@hussmartinez/audio-sdk 0.4.0 → 0.6.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/README.md +106 -23
- package/dist/assets/audio/audio.worker.js +1 -1
- package/dist/index.d.ts +795 -148
- package/dist/index.js +1737 -515
- package/dist/index.js.map +1 -1
- package/dist/lazy/inline-worker-D8bxbE-Q.js +30 -0
- package/dist/lazy/{inline-worker-BB2jwrIT.js.map → inline-worker-D8bxbE-Q.js.map} +1 -1
- package/formats/hm-audio-command/v2.schema.json +381 -0
- package/formats/hm-audio-plan/v2.schema.json +226 -0
- package/package.json +8 -6
- package/dist/lazy/inline-worker-BB2jwrIT.js +0 -30
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["locate","locateIn"],"sources":["../src/core/errors/audio-error.ts","../src/core/errors/abort.ts","../src/adapters/audio-worker/loader.ts","../src/adapters/peaks.ts","../src/adapters/web-audio/platform-decode.ts","../src/adapters/audio-engine.ts","../src/core/model/plan.ts","../src/core/model/envelope.ts","../src/adapters/web-audio/gain-automation.ts","../src/adapters/web-audio/play-graph.ts","../src/adapters/audio-output.ts","../src/adapters/wav/wav-writer.ts","../src/adapters/audio-processor.ts","../src/core/errors/audio-limits.ts","../src/core/operations/commands.ts","../src/core/format/plan-document.ts","../src/core/model/time.ts","../src/core/session/session.ts","../src/messages/en.ts"],"sourcesContent":["import { isSdkError, type SdkCoreErrorCode, SdkError } from \"@hussmartinez/sdk-core\";\n\n/**\n * Error codes of `@hussmartinez/audio-sdk`: sdk-core's own codes, such as\n * `ABORTED`, `WORKER_CRASHED` and `FILE_TOO_LARGE`, plus the audio SDK's\n * (ADR 0004). They never change meaning once released.\n *\n * - `INVALID_AUDIO`: the file is malformed, its headers claim more audio than\n * its packets carry, or it decodes to more than its bound allows.\n * - `UNSUPPORTED_FORMAT`: the container or codec isn't recognised, the file's\n * packets can't be walked to a bound, or the browser can't decode at its\n * sample rate.\n * - `DECODE_FAILED`: the browser couldn't decode a file the SDK probed,\n * usually because it lacks the codec. `details.codec` names it.\n * - `INVALID_COMMAND`: an edit command doesn't apply to the clip plan, such\n * as a range outside its source or an unknown clip key.\n * - `INVALID_DOCUMENT`: a plan document, such as a saved project, isn't\n * valid in its format.\n * - `DURATION_TOO_LONG`: a file exceeds the `maxDuration` limit.\n * - `TOO_MANY_CHANNELS`: a file exceeds the `maxChannels` limit.\n * - `SAMPLE_RATE_TOO_HIGH`: a file exceeds the `maxSampleRate` limit.\n * - `SESSION_TOO_LARGE`: the decoded audio the session holds exceeds the\n * `maxSessionSize` limit.\n * - `TOO_MANY_CLIPS`: the clip plan exceeds the `maxClips` limit.\n *\n * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`\n * value and the `unit`. Other codes' `details` name the container, codec or\n * sample rate involved, never data from the file.\n *\n * @public\n */\nexport type AudioErrorCode =\n | SdkCoreErrorCode\n | \"INVALID_AUDIO\"\n | \"UNSUPPORTED_FORMAT\"\n | \"DECODE_FAILED\"\n | \"INVALID_COMMAND\"\n | \"INVALID_DOCUMENT\"\n | \"DURATION_TOO_LONG\"\n | \"TOO_MANY_CHANNELS\"\n | \"SAMPLE_RATE_TOO_HIGH\"\n | \"SESSION_TOO_LARGE\"\n | \"TOO_MANY_CLIPS\";\n\n/**\n * The error `@hussmartinez/audio-sdk` throws and rejects with, with a stable\n * `code`, structured `details` and the underlying error as `cause`. Show\n * users the text for its code from {@link audioMessages}, never its\n * `message`, which is for developers and may contain text from the file.\n *\n * @example\n * ```ts\n * try {\n * await session.open(file);\n * } catch (error) {\n * if (isAudioError(error, \"DECODE_FAILED\")) {\n * suggestConvertingToWav();\n * } else {\n * show(messages.error(error));\n * }\n * }\n * ```\n *\n * @public\n */\nexport class AudioError extends SdkError<AudioErrorCode> {\n /** Always `\"AudioError\"`, which survives minification and worker boundaries. */\n override readonly name = \"AudioError\";\n}\n\n/**\n * Checks whether a value is an {@link AudioError}, optionally with a given\n * code.\n *\n * Unlike `instanceof`, it recognises errors from another copy of this\n * package or another realm, and errors rebuilt after crossing a worker\n * boundary.\n *\n * @param value - Any thrown value.\n * @param code - When given, the error must also have this code.\n * @public\n */\nexport function isAudioError<Code extends AudioErrorCode = AudioErrorCode>(\n value: unknown,\n code?: Code,\n): value is AudioError & { readonly code: Code } {\n return isSdkError(value, code) && value.name === \"AudioError\";\n}\n","import { createErrorHelpers } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"./audio-error.js\";\n\n/**\n * The audio SDK's error helpers, from sdk-core's `createErrorHelpers`, so\n * every SDK adapts failures and aborts the same way (ADR 0018, ADR 0020).\n *\n * - `asAudioError`: makes any failure an `AudioError`, as every port\n * promises. Another `SdkError`, such as the worker client's `ABORTED` or\n * `WORKER_CRASHED`, keeps its code, details and message, and anything else\n * becomes `UNKNOWN`, with the original as `cause`.\n * - `abortError`: the error an aborted call rejects with: the reason itself\n * when it's an `SdkError`, such as the file policy's\n * `PROCESSING_TIME_EXCEEDED`, `TIMEOUT` for a timeout, and `ABORTED`\n * otherwise.\n * - `throwIfAborted`: throws `abortError` if the signal has been aborted.\n *\n * @internal\n */\nexport const {\n adapt: asAudioError,\n abortError,\n throwIfAborted,\n} = /* @__PURE__ */ createErrorHelpers(AudioError, {\n fallbackCode: \"UNKNOWN\",\n fallbackMessage: \"Audio processing failed.\",\n});\n","import { resolveAssetsBase, type WorkerLike } from \"@hussmartinez/sdk-core\";\n\n/** Where the audio worker comes from, and the version it must announce. */\nexport interface AudioWorkerSource {\n /** Loads the worker's code, on the first call, and returns how to start it. */\n readonly loadWorker: () => Promise<() => WorkerLike>;\n /** The version the worker must announce: this package's (sdk-core ADR 0038). */\n readonly version: string;\n /** Where the worker comes from, for the version error's details. */\n readonly asset?: string;\n}\n\n/**\n * The audio worker, inlined by default or self-hosted under `assetsUrl`\n * (docs/adr/0002). The engine and the processor each start their own from\n * it.\n */\nexport function audioWorkerSource(assetsUrl: string | URL | undefined): AudioWorkerSource {\n const selfHosted =\n assetsUrl === undefined\n ? undefined\n : new URL(\"audio/audio.worker.js\", resolveAssetsBase(assetsUrl)).href;\n return {\n loadWorker: selfHosted\n ? async () => () => new Worker(selfHosted, { type: \"module\", name: \"hm-audio\" })\n : async () => (await import(\"./inline-worker.js\")).createInlineWorker,\n version: __AUDIO_SDK_VERSION__,\n ...(selfHosted ? { asset: selfHosted } : {}),\n };\n}\n","import type { AudioPeakLevel, AudioPeaks } from \"../core/model/source.js\";\n\n/**\n * Frames per bucket at the finest level of a waveform overview. Each coarser\n * level groups four buckets of the one before (docs/adr/0002).\n *\n * @internal\n */\nexport const FINEST_BUCKET = 256;\n\n/** How many buckets each coarser level combines. */\nconst LEVEL_FACTOR = 4;\n\n/** Each channel's minimum and maximum per bucket. */\nexport interface BucketPeaks {\n readonly min: Float32Array[];\n readonly max: Float32Array[];\n}\n\n/**\n * The minimum and maximum of each bucket of `bucket` frames, per channel.\n * Called on a block whose first frame starts a bucket; a last, shorter\n * bucket covers what's left.\n *\n * @internal\n */\nexport function blockPeaks(channels: readonly Float32Array[], bucket: number): BucketPeaks {\n const min: Float32Array[] = [];\n const max: Float32Array[] = [];\n for (const samples of channels) {\n const count = Math.ceil(samples.length / bucket);\n const low = new Float32Array(count);\n const high = new Float32Array(count);\n for (let b = 0; b < count; b += 1) {\n const end = Math.min(samples.length, (b + 1) * bucket);\n let lo = Number.POSITIVE_INFINITY;\n let hi = Number.NEGATIVE_INFINITY;\n for (let i = b * bucket; i < end; i += 1) {\n const sample = samples[i] as number;\n if (sample < lo) lo = sample;\n if (sample > hi) hi = sample;\n }\n low[b] = lo;\n high[b] = hi;\n }\n min.push(low);\n max.push(high);\n }\n return { min, max };\n}\n\n/**\n * Builds the whole pyramid from the finest level, each level combining four\n * buckets of the one before, until a level has one bucket.\n *\n * @internal\n */\nexport function buildPyramid(finest: BucketPeaks, bucket = FINEST_BUCKET): AudioPeaks {\n const levels: AudioPeakLevel[] = [];\n let current = finest;\n let framesPerBucket = bucket;\n for (;;) {\n levels.push({\n framesPerBucket,\n channels: current.min.map((min, c) => ({ min, max: current.max[c] as Float32Array })),\n });\n const count = current.min[0]?.length ?? 0;\n if (count <= 1) break;\n current = {\n min: current.min.map((values) => combine(values, Math.min)),\n max: current.max.map((values) => combine(values, Math.max)),\n };\n framesPerBucket *= LEVEL_FACTOR;\n }\n return { levels };\n}\n\nfunction combine(values: Float32Array, pick: (a: number, b: number) => number): Float32Array {\n const out = new Float32Array(Math.ceil(values.length / LEVEL_FACTOR));\n for (let i = 0; i < out.length; i += 1) {\n let value = values[i * LEVEL_FACTOR] as number;\n const end = Math.min(values.length, (i + 1) * LEVEL_FACTOR);\n for (let j = i * LEVEL_FACTOR + 1; j < end; j += 1) value = pick(value, values[j] as number);\n out[i] = value;\n }\n return out;\n}\n","import { abortError, throwIfAborted } from \"../../core/errors/abort.js\";\nimport { AudioError, isAudioError } from \"../../core/errors/audio-error.js\";\nimport type { AudioProbe, DecodedAudio } from \"../../core/model/source.js\";\n\n/**\n * Decodes a file's bytes with a platform decoder, at the given rate and\n * channel count. The SDK's is Web Audio's; tests pass their own.\n *\n * @internal\n */\nexport type PlatformDecoder = (\n bytes: ArrayBuffer,\n format: { readonly sampleRate: number; readonly channels: number },\n) => Promise<DecodedAudio>;\n\n/** A buffer the decoded audio can be copied into, when it must be shortened. */\nexport type CreateBuffer = (options: {\n numberOfChannels: number;\n length: number;\n sampleRate: number;\n}) => DecodedAudio & {\n copyToChannel(source: Float32Array, channel: number, startInChannel: number): void;\n};\n\n/**\n * Web Audio's decoder: `decodeAudioData` on a fresh `OfflineAudioContext` at\n * the file's probed rate, so nothing is resampled (docs/adr/0001). It exists\n * only on the page.\n *\n * @internal\n */\nexport const webAudioDecoder: PlatformDecoder = (bytes, { sampleRate, channels }) => {\n const Offline = (globalThis as { OfflineAudioContext?: typeof OfflineAudioContext })\n .OfflineAudioContext;\n if (typeof Offline !== \"function\") {\n throw new AudioError(\"UNSUPPORTED_ENVIRONMENT\", \"Web Audio isn't available.\", {\n details: { feature: \"OfflineAudioContext\" },\n });\n }\n let context: OfflineAudioContext;\n try {\n context = new Offline({ numberOfChannels: channels, length: 1, sampleRate });\n } catch (error) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", \"This browser can't decode at this rate.\", {\n details: { sampleRate },\n cause: error,\n });\n }\n return context.decodeAudioData(bytes);\n};\n\n/** Settles with the decode, or rejects as soon as the signal aborts. */\nfunction untilAborted<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n // A result that arrives after an abort is dropped, and so is a late\n // failure, which would otherwise be reported as unhandled.\n work.catch(() => {});\n if (!signal) return work;\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n work.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\n/**\n * Decodes a probed compressed file on the page, under sdk-core ADR 0031's\n * rules for platform decoders that only run there:\n *\n * - **Only probed files:** the caller passes the probe that walked this\n * file's packets, and the limits have been checked against its bound.\n * - **A fresh buffer:** the decoder gets bytes read from the `Blob` for it,\n * which it may detach; no caller-owned buffer is ever handed over.\n * - **The output is checked against the bound:** a different rate, more\n * channels than the probe allows, or more frames than the bound plus the\n * codec's tolerance,\n * fails with `INVALID_AUDIO`, and the output is discarded. A result within\n * the tolerance but past the bound is shortened to the bound.\n * - **Never the decoder's errors:** a failure becomes `DECODE_FAILED`, with\n * `details` naming the container and codec, never the browser's message,\n * which is kept only as the error's `cause`.\n * - **The time limit:** a page-side decode can't be terminated, so when the\n * signal aborts, as `maxProcessingTime` does, it stops waiting and rejects\n * with the abort's code, such as `PROCESSING_TIME_EXCEEDED`; the result is\n * discarded whenever it arrives.\n *\n * @internal\n */\nexport async function decodeOnPage(\n file: Blob,\n probe: AudioProbe,\n decoder: PlatformDecoder,\n createBuffer: CreateBuffer,\n signal?: AbortSignal,\n): Promise<DecodedAudio> {\n const { container, codec, sampleRate, channels, frameBound, frameTolerance } = probe;\n throwIfAborted(signal);\n const bytes = await untilAborted(file.arrayBuffer(), signal);\n\n let decoded: DecodedAudio;\n try {\n decoded = await untilAborted(\n Promise.resolve().then(() => decoder(bytes, { sampleRate, channels })),\n signal,\n );\n } catch (error) {\n if (isAudioError(error)) throw error;\n throw new AudioError(\"DECODE_FAILED\", \"The browser couldn't decode this file.\", {\n details: { container, codec },\n cause: error,\n });\n }\n\n // A decoder that \"succeeds\" with no audio, as WebKit does on some crafted\n // Opus, hasn't decoded the file.\n if (decoded.length === 0) {\n throw new AudioError(\"DECODE_FAILED\", \"The browser decoded no audio from this file.\", {\n details: { container, codec, reason: \"no audio decoded\" },\n });\n }\n\n const invalid = (reason: string) =>\n new AudioError(\"INVALID_AUDIO\", `The decoded audio ${reason}.`, {\n details: { container, codec, reason: `decoded ${reason}` },\n });\n if (decoded.sampleRate !== sampleRate) throw invalid(\"rate differs from the probe\");\n // The probe allows for the most channels a decoder may output, such as\n // stereo for mono AAC that may carry parametric stereo; fewer is fine.\n if (decoded.numberOfChannels > channels) throw invalid(\"channel count exceeds the probe\");\n if (decoded.length > frameBound + frameTolerance) throw invalid(\"length exceeds the bound\");\n if (decoded.length <= frameBound) return decoded;\n\n // Within the tolerance but past the bound: the source is the bound's length.\n const capped = createBuffer({\n numberOfChannels: decoded.numberOfChannels,\n length: frameBound,\n sampleRate,\n });\n for (let c = 0; c < decoded.numberOfChannels; c += 1) {\n capped.copyToChannel(decoded.getChannelData(c).subarray(0, frameBound), c, 0);\n }\n return capped;\n}\n","import { createWorkerClient, type WorkerClient, type WorkerLike } from \"@hussmartinez/sdk-core\";\nimport { asAudioError, throwIfAborted } from \"../core/errors/abort.js\";\nimport { AudioError } from \"../core/errors/audio-error.js\";\nimport type { AudioPeaks, AudioProbe, DecodedAudio } from \"../core/model/source.js\";\nimport type { AudioEngine } from \"../core/ports/audio-engine.js\";\nimport type { AudioWorkerContract } from \"./audio-worker/contract.js\";\nimport { audioWorkerSource } from \"./audio-worker/loader.js\";\nimport type { PcmLayout } from \"./pcm/layout.js\";\nimport { type BucketPeaks, buildPyramid, FINEST_BUCKET } from \"./peaks.js\";\nimport {\n decodeOnPage,\n type PlatformDecoder,\n webAudioDecoder,\n} from \"./web-audio/platform-decode.js\";\n\n/**\n * Frames per block between the page and the worker: at most 2¹⁶ per\n * channel (docs/adr/0002), and a whole number of finest peak buckets.\n */\nconst BLOCK_FRAMES = 65_536;\n\n/**\n * Options for {@link createAudioEngine}.\n *\n * @public\n */\nexport interface AudioEngineOptions {\n /**\n * Milliseconds without calls after which the worker stops. It starts again\n * on the next call. Defaults to sdk-core's 30 seconds.\n */\n readonly idleTimeout?: number;\n /**\n * Where the application serves the package's `dist/assets/` directory, to\n * load the worker from its own origin instead of a `blob:` URL. The worker\n * is then `audio/audio.worker.js` there, and a Content Security Policy\n * needs `worker-src 'self'` and no `blob:` (docs/adr/0002). Copy\n * `dist/assets` again after every upgrade: a worker from another version\n * is refused with `WORKER_START_FAILED`. By default the worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/** An `AudioBuffer`, or what tests use in its place. */\nexport interface WritableAudio extends DecodedAudio {\n copyToChannel(source: Float32Array, channel: number, startInChannel: number): void;\n}\n\n/** What the engine needs from its environment, replaceable in tests. */\nexport interface EngineEnvironment {\n /** Loads the worker's code, on the first call, and returns how to start it. */\n readonly loadWorker: () => Promise<() => WorkerLike>;\n /** Creates an empty buffer for a decoded source. Throws for a sample rate it can't hold. */\n readonly createBuffer: (options: {\n numberOfChannels: number;\n length: number;\n sampleRate: number;\n }) => WritableAudio;\n /** Decodes compressed files on the page (sdk-core ADR 0031). */\n readonly decodePlatform: PlatformDecoder;\n readonly idleTimeout?: number;\n /** The version the worker must announce: this package's (sdk-core ADR 0038). */\n readonly version: string;\n /** Where the worker comes from, for the version error's details. */\n readonly asset?: string;\n}\n\n/**\n * Creates the SDK's audio engine (docs/adr/0001, docs/adr/0002). It probes\n * files in its worker: WAV and AIFF, FLAC (native or in Ogg), MP3, AAC in\n * ADTS, AAC or ALAC in MP4, Opus or Vorbis in Ogg, and Opus, Vorbis, FLAC\n * or AAC in WebM and Matroska, walking every frame of a compressed file to\n * bound its decoded length. It parses WAV and AIFF block by block into an\n * `AudioBuffer`, building the waveform overview as it goes. It decodes\n * compressed files with the browser's own decoder, on the page, under\n * sdk-core ADR 0031's rules: only probed files, a fresh buffer, the output\n * checked against the probe's bound, errors by code, and the time limit of\n * the caller's signal. Other containers fail with `UNSUPPORTED_FORMAT`.\n *\n * Nothing starts until the first call. By default the worker is inlined,\n * which needs `worker-src blob:` in a Content Security Policy; with\n * `assetsUrl` it loads from your own origin, which needs `worker-src 'self'`\n * instead. Either way it makes no requests of its own.\n *\n * @example\n * ```ts\n * const engine = createAudioEngine();\n * const probe = await engine.probe(file);\n * policy.check(\"maxDuration\", (probe.frameBound / probe.sampleRate) * 1000);\n * const audio = await engine.decode(file, probe, { onProgress });\n * ```\n *\n * @public\n */\nexport function createAudioEngine(options: AudioEngineOptions = {}): AudioEngine {\n return createEngine({\n ...audioWorkerSource(options.assetsUrl),\n createBuffer: (bufferOptions) => new AudioBuffer(bufferOptions),\n decodePlatform: webAudioDecoder,\n ...(options.idleTimeout === undefined ? {} : { idleTimeout: options.idleTimeout }),\n });\n}\n\n/**\n * The engine, with its environment passed in.\n *\n * @internal\n */\nexport function createEngine(environment: EngineEnvironment): AudioEngine {\n let startWorker: (() => WorkerLike) | undefined;\n let destroyed = false;\n const layouts = new WeakMap<AudioProbe, PcmLayout>();\n /** Probes of compressed files this engine made, which decode can trust. */\n const compressedProbes = new WeakSet<AudioProbe>();\n const finestPeaks = new WeakMap<DecodedAudio, BucketPeaks>();\n\n const newClient = () =>\n createWorkerClient<AudioWorkerContract>({\n createWorker: () => {\n if (!startWorker) {\n throw new AudioError(\"WORKER_START_FAILED\", \"The audio worker hasn't loaded.\");\n }\n return startWorker();\n },\n errorClasses: { AudioError },\n // A self-hosted worker copied before an upgrade would speak the same\n // protocol but run other code, so the worker must announce this\n // package's version, or it's refused with WORKER_START_FAILED.\n packageVersion: environment.version,\n ...(environment.asset === undefined ? {} : { workerAsset: environment.asset }),\n ...(environment.idleTimeout === undefined ? {} : { idleTimeout: environment.idleTimeout }),\n });\n // Probing, parsing and exports run in order on one client; analysis, such\n // as peaks for audio the worker didn't parse, on another, so cancelling it\n // never fails them as collateral (docs/adr/0002).\n let main: WorkerClient<AudioWorkerContract> | undefined;\n let analysis: WorkerClient<AudioWorkerContract> | undefined;\n\n async function ready(): Promise<void> {\n if (destroyed) throw new Error(\"The audio engine has been destroyed.\");\n startWorker ??= await environment.loadWorker();\n }\n\n async function run<T>(work: () => Promise<T>): Promise<T> {\n try {\n return await work();\n } catch (error) {\n throw error instanceof RangeError || error instanceof TypeError ? error : asAudioError(error);\n }\n }\n\n /**\n * Probes the file again for a probe this engine didn't make, such as a\n * copy, and requires it to describe the same audio: a decoder only ever\n * runs on a file whose bound this engine established (sdk-core ADR 0031).\n */\n async function reprobe(file: Blob, probe: AudioProbe, signal?: AbortSignal) {\n main ??= newClient();\n const fresh = await main.call(\"probe\", { file }, signal ? { signal } : {});\n const same =\n fresh.probe.codec === probe.codec &&\n fresh.probe.sampleRate === probe.sampleRate &&\n fresh.probe.channels === probe.channels &&\n fresh.probe.frameBound === probe.frameBound;\n if (!same) {\n throw new AudioError(\"INVALID_AUDIO\", \"The probe doesn't describe this file.\", {\n details: { container: probe.container },\n });\n }\n return fresh.probe;\n }\n\n async function layoutOf(file: Blob, probe: AudioProbe, signal?: AbortSignal) {\n const known = layouts.get(probe);\n if (known) return known;\n // A probe the caller rebuilt or copied: read the header again, and make\n // sure it describes the same audio.\n main ??= newClient();\n const fresh = await main.call(\"probe\", { file }, signal ? { signal } : {});\n const same =\n fresh.probe.sampleRate === probe.sampleRate &&\n fresh.probe.channels === probe.channels &&\n fresh.probe.frameBound === probe.frameBound;\n if (!same) {\n throw new AudioError(\"INVALID_AUDIO\", \"The probe doesn't describe this file.\", {\n details: { container: probe.container },\n });\n }\n if (!fresh.layout) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", \"Compressed formats aren't supported yet.\", {\n details: { container: probe.container, codec: probe.codec },\n });\n }\n return fresh.layout;\n }\n\n return {\n probe(file, options = {}) {\n return run(async () => {\n throwIfAborted(options.signal);\n await ready();\n main ??= newClient();\n const result = await main.call(\n \"probe\",\n { file },\n options.signal ? { signal: options.signal } : {},\n );\n if (result.layout) layouts.set(result.probe, result.layout);\n else compressedProbes.add(result.probe);\n return result.probe;\n });\n },\n\n decode(file, probe, options = {}) {\n return run(async () => {\n throwIfAborted(options.signal);\n await ready();\n if (probe.codec !== \"pcm\") {\n const trusted = compressedProbes.has(probe)\n ? probe\n : await reprobe(file, probe, options.signal);\n const audio = await decodeOnPage(\n file,\n trusted,\n environment.decodePlatform,\n environment.createBuffer,\n options.signal,\n );\n options.onProgress?.(1);\n return audio;\n }\n const layout = await layoutOf(file, probe, options.signal);\n const { frames, channels, sampleRate } = layout;\n let buffer: WritableAudio;\n try {\n buffer = environment.createBuffer({\n numberOfChannels: channels,\n length: frames,\n sampleRate,\n });\n } catch (error) {\n throw new AudioError(\n \"UNSUPPORTED_FORMAT\",\n \"This browser can't hold audio at this rate.\",\n {\n details: { container: layout.container, sampleRate },\n cause: error,\n },\n );\n }\n\n const buckets = Math.ceil(frames / FINEST_BUCKET);\n const peaks: BucketPeaks = {\n min: Array.from({ length: channels }, () => new Float32Array(buckets)),\n max: Array.from({ length: channels }, () => new Float32Array(buckets)),\n };\n main ??= newClient();\n for (let start = 0; start < frames; start += BLOCK_FRAMES) {\n const block = await main.call(\n \"readBlock\",\n {\n file,\n layout,\n start,\n frames: Math.min(BLOCK_FRAMES, frames - start),\n bucket: FINEST_BUCKET,\n },\n options.signal ? { signal: options.signal } : {},\n );\n const at = start / FINEST_BUCKET;\n for (let c = 0; c < channels; c += 1) {\n buffer.copyToChannel(block.channels[c] as Float32Array, c, start);\n peaks.min[c]?.set(block.min[c] as Float32Array, at);\n peaks.max[c]?.set(block.max[c] as Float32Array, at);\n }\n options.onProgress?.(Math.min(start + BLOCK_FRAMES, frames) / frames);\n }\n if (frames === 0) options.onProgress?.(1);\n finestPeaks.set(buffer, peaks);\n return buffer;\n });\n },\n\n peaks(audio, options = {}) {\n return run(async (): Promise<AudioPeaks> => {\n throwIfAborted(options.signal);\n const known = finestPeaks.get(audio);\n if (known) return buildPyramid(known, FINEST_BUCKET);\n await ready();\n analysis ??= newClient();\n const buckets = Math.ceil(audio.length / FINEST_BUCKET);\n const peaks: BucketPeaks = {\n min: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),\n max: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),\n };\n for (let start = 0; start < audio.length; start += BLOCK_FRAMES) {\n const end = Math.min(audio.length, start + BLOCK_FRAMES);\n // Copies of one block, so the source is never transferred away.\n const channels = Array.from({ length: audio.numberOfChannels }, (_, c) =>\n audio.getChannelData(c).slice(start, end),\n );\n const block = await analysis.call(\n \"peaks\",\n { channels, bucket: FINEST_BUCKET },\n { transfer: true, ...(options.signal ? { signal: options.signal } : {}) },\n );\n const at = start / FINEST_BUCKET;\n for (let c = 0; c < audio.numberOfChannels; c += 1) {\n peaks.min[c]?.set(block.min[c] as Float32Array, at);\n peaks.max[c]?.set(block.max[c] as Float32Array, at);\n }\n }\n finestPeaks.set(audio, peaks);\n return buildPyramid(peaks, FINEST_BUCKET);\n });\n },\n\n async destroy() {\n destroyed = true;\n main?.destroy();\n analysis?.destroy();\n },\n };\n}\n","import { sequenceOffsets } from \"@hussmartinez/sdk-core\";\n\n/**\n * The shape of a fade: `linear` changes the gain at a constant rate, and\n * `equalPower` keeps the perceived loudness steadier, which suits crossfades.\n *\n * @public\n */\nexport type AudioFadeCurve = \"linear\" | \"equalPower\";\n\n/**\n * A fade at one end of a clip. `frames: 0` is no fade.\n *\n * @public\n */\nexport interface AudioFade {\n readonly frames: number;\n readonly curve: AudioFadeCurve;\n}\n\n/**\n * One piece of a source, played in the plan (ADR 0003).\n *\n * @public\n */\nexport interface AudioClip {\n /** Stable across edits, so selection and waveform tiles follow a clip that moves. */\n readonly key: string;\n /** The id of the source the clip plays. */\n readonly source: string;\n /** The first source frame the clip plays, inclusive. */\n readonly start: number;\n /** The source frame the clip stops before, exclusive. */\n readonly end: number;\n /** The clip's gain in decibels. 0 leaves it unchanged. */\n readonly gainDb: number;\n readonly fadeIn: AudioFade;\n readonly fadeOut: AudioFade;\n}\n\n/**\n * Metadata that export writes into the file (ADR 0001).\n *\n * @public\n */\nexport interface AudioMetadata {\n readonly title: string;\n readonly artist: string;\n readonly album: string;\n readonly year: string;\n readonly comment: string;\n}\n\n/**\n * The session's document: clips played back to back on one track, over\n * immutable sources, with the metadata (ADR 0003). Every position and length\n * is a whole number of frames at `sampleRate`.\n *\n * @public\n */\nexport interface AudioPlan {\n /** The session's sample rate, from its first source. */\n readonly sampleRate: number;\n /** The session's channel count, from its first source. */\n readonly channels: number;\n readonly clips: readonly AudioClip[];\n readonly metadata: AudioMetadata;\n}\n\n/**\n * Metadata with every field empty.\n *\n * @public\n */\nexport const EMPTY_METADATA: AudioMetadata = Object.freeze({\n title: \"\",\n artist: \"\",\n album: \"\",\n year: \"\",\n comment: \"\",\n});\n\n/**\n * No fade.\n *\n * @public\n */\nexport const NO_FADE: AudioFade = Object.freeze({ frames: 0, curve: \"linear\" });\n\n/**\n * A clip's length in frames.\n *\n * @public\n */\nexport function clipLength(clip: AudioClip): number {\n return clip.end - clip.start;\n}\n\n/**\n * The plan's length in frames: the sum of its clips' lengths.\n *\n * @public\n */\nexport function planLength(plan: AudioPlan): number {\n let total = 0;\n for (const clip of plan.clips) total += clipLength(clip);\n return total;\n}\n\n/**\n * Where each clip starts on the timeline, in frames. It's derived from the\n * clips before it, never stored, so it can't disagree with them (ADR 0003).\n *\n * @public\n */\nexport function clipOffsets(plan: AudioPlan): readonly number[] {\n return clipBoundaries(plan).slice(0, -1);\n}\n\n/**\n * Every clip boundary on the timeline, in frames: the clips' starts, then\n * the plan's length (sdk-core ADR 0042).\n *\n * @internal\n */\nexport function clipBoundaries(plan: AudioPlan): readonly number[] {\n return sequenceOffsets(plan.clips.map(clipLength));\n}\n\n/**\n * Why a clip isn't valid within its source, as a stable token: a value of\n * `details.reason` on `INVALID_COMMAND` (sdk-core ADR 0045).\n *\n * - `invalid-frames`: a position or fade length isn't a non-negative whole\n * number of frames.\n * - `clip-too-short`: the clip is shorter than one frame.\n * - `clip-outside-source`: it ends after its source's last frame.\n * - `gain-out-of-range`: the gain isn't a finite number from\n * {@link MIN_GAIN_DB} to {@link MAX_GAIN_DB}.\n * - `fades-too-long`: its fades together are longer than the clip.\n *\n * @public\n */\nexport type AudioClipProblem =\n | \"invalid-frames\"\n | \"clip-too-short\"\n | \"clip-outside-source\"\n | \"gain-out-of-range\"\n | \"fades-too-long\";\n\n/**\n * The lowest clip gain, in decibels: far below audibility, so it serves as\n * silence.\n *\n * @public\n */\nexport const MIN_GAIN_DB = -120;\n\n/**\n * The highest clip gain, in decibels: enough to normalize a very quiet\n * recording, while every gain stays a finite factor.\n *\n * @public\n */\nexport const MAX_GAIN_DB = 120;\n\nconst isFrames = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0;\n\n/**\n * What's wrong with a clip within a source of `sourceFrames` frames, or\n * `undefined` if it's valid: whole, non-negative frames, at least one frame\n * long, inside the source, with a gain in range and fades that fit the clip\n * together.\n *\n * @internal\n */\nexport function clipProblem(clip: AudioClip, sourceFrames: number): AudioClipProblem | undefined {\n if (![clip.start, clip.end, clip.fadeIn.frames, clip.fadeOut.frames].every(isFrames)) {\n return \"invalid-frames\";\n }\n if (clip.end <= clip.start) return \"clip-too-short\";\n if (clip.end > sourceFrames) return \"clip-outside-source\";\n if (\n typeof clip.gainDb !== \"number\" ||\n !(clip.gainDb >= MIN_GAIN_DB && clip.gainDb <= MAX_GAIN_DB)\n ) {\n return \"gain-out-of-range\";\n }\n if (clip.fadeIn.frames + clip.fadeOut.frames > clipLength(clip)) return \"fades-too-long\";\n return undefined;\n}\n\n/**\n * Throws `RangeError` unless the clip is valid within a source of\n * `sourceFrames` frames, as {@link clipProblem} checks.\n *\n * @internal\n */\nexport function assertClip(clip: AudioClip, sourceFrames: number): void {\n const problem = clipProblem(clip, sourceFrames);\n if (problem) throw new RangeError(`Clip ${clip.key} isn't valid: ${problem}.`);\n}\n","import type { AudioClip, AudioFadeCurve } from \"./plan.js\";\n\n/**\n * Converts decibels to a linear gain factor.\n *\n * @public\n */\nexport function dbToGain(db: number): number {\n return 10 ** (db / 20);\n}\n\n/** A fade's gain at `position`, from 0 (silent) to 1 (full). */\nfunction fadeShape(curve: AudioFadeCurve, position: number): number {\n return curve === \"equalPower\" ? Math.sin((position * Math.PI) / 2) : position;\n}\n\n/**\n * The gain at one frame of a clip, from its gain and its fades: the single\n * definition of the envelope, which export applies per sample and playback\n * samples into the clip's `GainNode` (ADR 0001).\n *\n * A fade in starts at silence on the clip's first frame, and a fade out\n * reaches silence on its last frame.\n *\n * @param clip - The clip.\n * @param frame - A frame within the clip, from 0 to its length minus one.\n * @public\n */\nexport function gainAt(clip: AudioClip, frame: number): number {\n const length = clip.end - clip.start;\n let gain = dbToGain(clip.gainDb);\n const { fadeIn, fadeOut } = clip;\n if (fadeIn.frames > 0 && frame < fadeIn.frames) {\n gain *= fadeShape(fadeIn.curve, frame / fadeIn.frames);\n }\n const fromEnd = length - 1 - frame;\n if (fadeOut.frames > 0 && fromEnd < fadeOut.frames) {\n gain *= fadeShape(fadeOut.curve, Math.max(0, fromEnd) / fadeOut.frames);\n }\n return gain;\n}\n","import { gainAt } from \"../../core/model/envelope.js\";\nimport { type AudioClip, clipLength } from \"../../core/model/plan.js\";\n\n/**\n * The most points a fade's curve gets: Web Audio interpolates linearly\n * between them, so a long fade is sampled, and a short one is exact.\n */\nexport const MAX_CURVE_POINTS = 1_024;\n\n/** One automation event of a clip's `GainNode`, in seconds from when the clip starts playing. */\nexport type GainEvent =\n | { readonly kind: \"set\"; readonly time: number; readonly value: number }\n | {\n readonly kind: \"curve\";\n readonly time: number;\n readonly duration: number;\n readonly values: Float32Array;\n };\n\n/** Samples `gainAt` from frame `from` to frame `to`, both included, at no more than the maximum points. */\nfunction curve(clip: AudioClip, from: number, to: number): Float32Array {\n const points = Math.min(MAX_CURVE_POINTS, to - from + 1);\n const values = new Float32Array(points);\n for (let i = 0; i < points; i += 1) {\n const frame = points === 1 ? from : from + ((to - from) * i) / (points - 1);\n values[i] = gainAt(clip, Math.round(frame));\n }\n return values;\n}\n\n/**\n * A clip's gain automation, played from frame `from` of the clip, as\n * `setValueAtTime` and `setValueCurveAtTime` events (docs/adr/0001): the\n * playback side of `gainAt`, which export applies per sample.\n *\n * - **Fade in:** a curve from `from` to the fade's last frame, then the\n * clip's gain.\n * - **Fade out:** a curve from its first frame to the clip's last, reaching\n * silence there.\n * - **No two events share a time,** and no event falls inside a curve, which\n * Web Audio refuses: a fade out that starts where the fade in ends follows\n * its curve directly.\n */\nexport function gainEvents(clip: AudioClip, from: number, sampleRate: number): GainEvent[] {\n const length = clipLength(clip);\n const fadeInEnd = clip.fadeIn.frames;\n const fadeOutStart = length - clip.fadeOut.frames;\n const at = (frame: number) => (frame - from) / sampleRate;\n const events: GainEvent[] = [];\n let cursor = from;\n\n if (from < fadeInEnd) {\n // Its last value, the clip's steady gain, holds after it.\n events.push({\n kind: \"curve\",\n time: 0,\n duration: at(fadeInEnd),\n values: curve(clip, from, fadeInEnd),\n });\n cursor = fadeInEnd;\n }\n const outFrom = Math.max(cursor, fadeOutStart);\n const fadingOut = clip.fadeOut.frames > 0 && outFrom < length - 1;\n // The steady gain from the start, unless a curve starts there.\n if (events.length === 0 && !(fadingOut && outFrom === from)) {\n events.push({ kind: \"set\", time: 0, value: gainAt(clip, from) });\n }\n if (fadingOut) {\n events.push({\n kind: \"curve\",\n time: at(outFrom),\n duration: at(length - 1) - at(outFrom),\n values: curve(clip, outFrom, length - 1),\n });\n } else if (clip.fadeOut.frames > 0 && outFrom > cursor) {\n // A fade out of the last frame alone, too short for a curve: silence there.\n events.push({ kind: \"set\", time: at(outFrom), value: gainAt(clip, outFrom) });\n }\n return events;\n}\n","import { type AudioPlan, clipLength, clipOffsets, planLength } from \"../../core/model/plan.js\";\nimport { gainEvents } from \"./gain-automation.js\";\n\n/** The nodes of a scheduled plan, to stop it. */\nexport interface ScheduledPlan {\n /** Stops every clip at once, and disconnects the graph. */\n stop(): void;\n}\n\n/**\n * Schedules a plan from timeline frame `from`, with that frame playing at\n * context time `at` (docs/adr/0002):\n *\n * - each clip is an `AudioBufferSourceNode` on its source, started at its\n * offset, through a `GainNode` automated from `gainAt` (docs/adr/0001);\n * - every clip feeds one bus with the plan's channel count and Web Audio's\n * `speakers` interpretation, so sources with other channel counts mix as\n * export mixes them.\n *\n * It works on any `BaseAudioContext`: the output plays through a realtime\n * one, and the tests render the same graph offline to compare with export.\n */\nexport function schedulePlan(\n context: BaseAudioContext,\n destination: AudioNode,\n plan: AudioPlan,\n buffer: (source: string) => AudioBuffer,\n from: number,\n at: number,\n): ScheduledPlan {\n const rate = plan.sampleRate;\n const bus = context.createGain();\n bus.channelCount = plan.channels;\n bus.channelCountMode = \"explicit\";\n bus.channelInterpretation = \"speakers\";\n bus.connect(destination);\n\n const nodes: { source: AudioBufferSourceNode; gain: GainNode }[] = [];\n const offsets = clipOffsets(plan);\n const end = planLength(plan);\n for (const [index, clip] of plan.clips.entries()) {\n const offset = offsets[index] as number;\n const length = clipLength(clip);\n if (offset + length <= from || offset >= end) continue;\n const within = Math.max(0, from - offset);\n const when = at + Math.max(0, offset - from) / rate;\n const source = context.createBufferSource();\n source.buffer = buffer(clip.source);\n const gain = context.createGain();\n for (const event of gainEvents(clip, within, rate)) {\n if (event.kind === \"set\") gain.gain.setValueAtTime(event.value, when + event.time);\n else gain.gain.setValueCurveAtTime(event.values, when + event.time, event.duration);\n }\n source.connect(gain).connect(bus);\n source.start(when, (clip.start + within) / rate, (length - within) / rate);\n nodes.push({ source, gain });\n }\n\n return {\n stop() {\n for (const { source, gain } of nodes) {\n try {\n source.stop();\n } catch {\n // Already stopped.\n }\n source.disconnect();\n gain.disconnect();\n }\n bus.disconnect();\n },\n };\n}\n","import { createStore } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"../core/errors/audio-error.js\";\nimport { type AudioPlan, planLength } from \"../core/model/plan.js\";\nimport type { DecodedAudio } from \"../core/model/source.js\";\nimport type {\n AudioOutput,\n AudioOutputSnapshot,\n AudioOutputState,\n} from \"../core/ports/audio-output.js\";\nimport { type ScheduledPlan, schedulePlan } from \"./web-audio/play-graph.js\";\n\n/**\n * How far ahead of the context's clock playback starts, in seconds, so the\n * first clip is scheduled in time.\n */\nexport const START_LEAD = 0.03;\n\n/**\n * How long `play()` waits for the context to run, in milliseconds. A\n * context stays suspended without a user gesture, or without a sound\n * server, as in Firefox in the browser test image (sdk-core ADR 0043).\n */\nexport const RESUME_TIMEOUT = 2_000;\n\n/**\n * What the output needs from the page, replaceable in tests.\n *\n * @internal\n */\nexport interface OutputEnvironment {\n readonly createContext: () => AudioContext;\n}\n\n/**\n * Creates the SDK's playback output (docs/adr/0002): it plays a plan\n * through Web Audio, from the playhead, and reschedules from the playhead\n * whenever the plan changes or it seeks, so an edit or a seek during\n * playback always takes effect.\n *\n * - **One `AudioContext`,** created on the first `play()`, which should be\n * a user gesture, as browsers' autoplay rules require. If the context\n * doesn't run within two seconds, `play()` rejects with\n * `UNSUPPORTED_ENVIRONMENT`, and the output stays as it was.\n * - **Each clip is an `AudioBufferSourceNode`** on its source, through a\n * `GainNode` automated from `gainAt`, so playback follows the envelope\n * export applies. Sources mix into the plan's channels by Web Audio's\n * speaker rules, as export does.\n * - **The playhead** is read from the audio clock by `position()`, which a\n * view polls on animation frames; it isn't in the snapshot.\n *\n * Sources should be `AudioBuffer`s, as `createAudioEngine` decodes them.\n * Others are copied into one once, on first use.\n *\n * @example\n * ```ts\n * const output = createAudioOutput();\n * output.load(plan, sources);\n * playButton.onclick = () => output.play();\n * requestAnimationFrame(function draw() {\n * drawPlayhead(output.position());\n * requestAnimationFrame(draw);\n * });\n * ```\n *\n * @public\n */\nexport function createAudioOutput(): AudioOutput {\n return createOutput({ createContext: () => new AudioContext() });\n}\n\n/**\n * The output, with its environment passed in.\n *\n * @internal\n */\nexport function createOutput(environment: OutputEnvironment): AudioOutput {\n const store = createStore<AudioOutputSnapshot>(Object.freeze({ state: \"stopped\" }));\n const copies = new WeakMap<DecodedAudio, AudioBuffer>();\n let context: AudioContext | undefined;\n let plan: AudioPlan | undefined;\n let sources: ReadonlyMap<string, DecodedAudio> = new Map();\n /** The playhead while not playing. */\n let playhead = 0;\n /** While playing: what's scheduled, and which frame plays at which context time. */\n let playing: { scheduled: ScheduledPlan; frame: number; time: number } | undefined;\n let endTimer: ReturnType<typeof setTimeout> | undefined;\n let destroyed = false;\n\n const length = () => (plan ? planLength(plan) : 0);\n const assertAlive = () => {\n if (destroyed) throw new Error(\"The audio output has been destroyed.\");\n };\n const setState = (state: AudioOutputState) => {\n if (store.getSnapshot().state !== state) store.set(Object.freeze({ state }));\n };\n\n /** A source as an `AudioBuffer`, copied into one once if it isn't. */\n function buffer(id: string): AudioBuffer {\n const audio = sources.get(id);\n if (!audio) throw new TypeError(`The plan's source ${id} isn't loaded.`);\n if (audio instanceof AudioBuffer) return audio;\n let copy = copies.get(audio);\n if (!copy) {\n copy = new AudioBuffer({\n length: audio.length,\n numberOfChannels: audio.numberOfChannels,\n sampleRate: audio.sampleRate,\n });\n for (let channel = 0; channel < audio.numberOfChannels; channel += 1) {\n copy.copyToChannel(Float32Array.from(audio.getChannelData(channel)), channel);\n }\n copies.set(audio, copy);\n }\n return copy;\n }\n\n /** Where the playhead is: from the audio clock while playing. */\n function position(): number {\n if (!playing || !context || !plan) return playhead;\n const elapsed = Math.max(0, context.currentTime - playing.time);\n return Math.min(length(), Math.floor(playing.frame + elapsed * plan.sampleRate));\n }\n\n /** Stops what's scheduled, keeping the playhead where it is now. */\n function unschedule(): void {\n if (!playing) return;\n playhead = position();\n playing.scheduled.stop();\n playing = undefined;\n clearTimeout(endTimer);\n endTimer = undefined;\n }\n\n /** Waits for the end of the plan, by the audio clock. */\n function watchEnd(): void {\n clearTimeout(endTimer);\n if (!playing || !context || !plan) return;\n const remaining =\n playing.time - context.currentTime + (length() - playing.frame) / plan.sampleRate;\n endTimer = setTimeout(\n () => {\n if (position() >= length()) {\n unschedule();\n playhead = length();\n setState(\"stopped\");\n } else {\n watchEnd();\n }\n },\n Math.max(0, remaining * 1_000) + 5,\n );\n }\n\n /** Schedules the plan from the playhead, on a running context. */\n function schedule(): void {\n if (!context || !plan) return;\n const time = context.currentTime + START_LEAD;\n playing = {\n scheduled: schedulePlan(context, context.destination, plan, buffer, playhead, time),\n frame: playhead,\n time,\n };\n watchEnd();\n }\n\n async function running(audio: AudioContext): Promise<boolean> {\n if (audio.state === \"running\") return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), RESUME_TIMEOUT);\n });\n try {\n await Promise.race([audio.resume().then(() => true), timedOut]);\n } finally {\n clearTimeout(timer);\n }\n // resume() changes the state while this waits, which TypeScript can't see.\n return (audio.state as AudioContextState) === \"running\";\n }\n\n return {\n getSnapshot: store.getSnapshot,\n subscribe: store.subscribe,\n position,\n\n load(next, nextSources) {\n assertAlive();\n const wasPlaying = playing !== undefined;\n unschedule();\n plan = next;\n sources = nextSources;\n playhead = Math.min(playhead, length());\n if (!wasPlaying) return;\n if (playhead >= length()) {\n playhead = length();\n setState(\"stopped\");\n } else {\n schedule();\n }\n },\n\n async play() {\n assertAlive();\n if (length() === 0 || playing) return;\n context ??= environment.createContext();\n if (!(await running(context))) {\n throw new AudioError(\n \"UNSUPPORTED_ENVIRONMENT\",\n \"The browser didn't start audio output. Play from a click or a key press.\",\n { details: { feature: \"audio-output\" } },\n );\n }\n // Another call may have started, or the plan changed, while waiting.\n if (destroyed || playing || length() === 0) return;\n if (playhead >= length()) playhead = 0;\n schedule();\n setState(\"playing\");\n },\n\n pause() {\n assertAlive();\n if (!playing) return;\n unschedule();\n setState(\"paused\");\n },\n\n stop() {\n assertAlive();\n unschedule();\n playhead = 0;\n setState(\"stopped\");\n },\n\n seek(frame) {\n assertAlive();\n const wasPlaying = playing !== undefined;\n unschedule();\n playhead = Math.max(0, Math.min(Math.round(frame), length()));\n if (wasPlaying && playhead < length()) schedule();\n else if (wasPlaying) setState(\"stopped\");\n },\n\n async destroy() {\n if (destroyed) return;\n destroyed = true;\n unschedule();\n setState(\"stopped\");\n await context?.close().catch(() => {});\n context = undefined;\n },\n };\n}\n","import type { AudioMetadata } from \"../../core/model/plan.js\";\nimport type { AudioSampleFormat } from \"../../core/ports/audio-processor.js\";\n\n/**\n * Writes WAV files for export (docs/adr/0001): the header, which the plan\n * fixes in advance, and the samples, block by block.\n *\n * - **Quantisation:** samples are clamped to [−1, 1], and a non-finite one\n * is silence. 16-bit and 24-bit PCM scale by 2ⁿ⁻¹, round half away from\n * zero, and clamp to [−2ⁿ⁻¹, 2ⁿ⁻¹ − 1], so +1.0 writes the largest\n * positive value. Readers that divide by 2ⁿ⁻¹, as this SDK's does, get\n * back the nearest representable value. There's no dither.\n * - **32-bit float** writes the clamped sample, rounded to the nearest\n * float32.\n * - **Layout:** `fmt ` is WAVE_FORMAT_EXTENSIBLE, with a speaker mask for\n * mono, stereo, quad and 5.1, when there are more than two channels or\n * more than 16 bits; float files also get a `fact` chunk. The metadata\n * goes in a `LIST`/`INFO` chunk before `data`, and is left out when every\n * field is empty. A file whose sizes don't fit 32 bits is RF64, with a\n * `ds64` chunk.\n */\n\nconst BYTES: Record<AudioSampleFormat, number> = { pcm16: 2, pcm24: 3, float32: 4 };\nconst WAVE_FORMAT_PCM = 0x0001;\nconst WAVE_FORMAT_IEEE_FLOAT = 0x0003;\nconst WAVE_FORMAT_EXTENSIBLE = 0xfffe;\n/** The tail every `KSDATAFORMAT_SUBTYPE_*` GUID shares after its format tag. */\nconst SUBTYPE_TAIL = [\n 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71,\n];\n/** Speaker masks for the layouts Web Audio's speaker rules know. */\nconst SPEAKERS: Readonly<Record<number, number>> = { 1: 0x4, 2: 0x3, 4: 0x33, 6: 0x3f };\nconst MAX_32 = 0xffffffff;\n/** The INFO ids of each metadata field, in the order they're written. */\nconst INFO_IDS: readonly [keyof AudioMetadata, string][] = [\n [\"title\", \"INAM\"],\n [\"artist\", \"IART\"],\n [\"album\", \"IPRD\"],\n [\"year\", \"ICRD\"],\n [\"comment\", \"ICMT\"],\n];\n\n/** What the header describes. */\nexport interface WavSpec {\n readonly sampleRate: number;\n readonly channels: number;\n readonly frames: number;\n readonly sampleFormat: AudioSampleFormat;\n readonly metadata: AudioMetadata;\n}\n\n/** Bytes per sample of a format. */\nexport function bytesPerSample(format: AudioSampleFormat): number {\n return BYTES[format];\n}\n\n/** The size of the samples, without the pad byte an odd size needs. */\nexport function dataSize(spec: Pick<WavSpec, \"channels\" | \"frames\" | \"sampleFormat\">): number {\n return spec.frames * spec.channels * BYTES[spec.sampleFormat];\n}\n\nclass Writer {\n readonly bytes: Uint8Array<ArrayBuffer>;\n readonly view: DataView;\n at = 0;\n\n constructor(size: number) {\n this.bytes = new Uint8Array(size);\n this.view = new DataView(this.bytes.buffer);\n }\n\n text(value: string): void {\n for (let i = 0; i < value.length; i += 1) this.bytes[this.at + i] = value.charCodeAt(i);\n this.at += value.length;\n }\n\n u16(value: number): void {\n this.view.setUint16(this.at, value, true);\n this.at += 2;\n }\n\n u32(value: number): void {\n this.view.setUint32(this.at, value, true);\n this.at += 4;\n }\n\n u64(value: number): void {\n this.u32(value % 2 ** 32);\n this.u32(Math.floor(value / 2 ** 32));\n }\n\n raw(value: Uint8Array): void {\n this.bytes.set(value, this.at);\n this.at += value.length;\n }\n}\n\n/** The `LIST`/`INFO` chunk's body, or nothing when every field is empty. */\nfunction infoBody(metadata: AudioMetadata): Uint8Array | undefined {\n const encoder = new TextEncoder();\n const fields = INFO_IDS.flatMap(([field, id]) => {\n const text = metadata[field];\n // UTF-8, NUL-terminated, and padded to an even size.\n return text === \"\" ? [] : [{ id, value: encoder.encode(`${text}\\0`) }];\n });\n if (fields.length === 0) return undefined;\n const size =\n 4 + fields.reduce((sum, { value }) => sum + 8 + value.length + (value.length % 2), 0);\n const writer = new Writer(size);\n writer.text(\"INFO\");\n for (const { id, value } of fields) {\n writer.text(id);\n writer.u32(value.length);\n writer.raw(value);\n if (value.length % 2 === 1) writer.at += 1;\n }\n return writer.bytes;\n}\n\n/**\n * The file's header: everything before the samples. The samples follow\n * directly, and an odd number of sample bytes then needs one pad byte.\n */\nexport function wavHeader(spec: WavSpec): Uint8Array<ArrayBuffer> {\n const { sampleRate, channels, frames, sampleFormat, metadata } = spec;\n const bytes = BYTES[sampleFormat];\n const float = sampleFormat === \"float32\";\n const extensible = channels > 2 || bytes > 2;\n const fmtSize = extensible ? 40 : float ? 18 : 16;\n const info = infoBody(metadata);\n const data = dataSize(spec);\n const pad = data % 2;\n const chunks = 8 + fmtSize + (float ? 12 : 0) + (info ? 8 + info.length : 0) + 8 + data + pad;\n const riffSize = 4 + chunks;\n const rf64 = riffSize > MAX_32 || data > MAX_32 || frames > MAX_32;\n const headerSize = 12 + (rf64 ? 36 : 0) + chunks - data - pad;\n\n const writer = new Writer(headerSize);\n writer.text(rf64 ? \"RF64\" : \"RIFF\");\n writer.u32(rf64 ? MAX_32 : riffSize);\n writer.text(\"WAVE\");\n if (rf64) {\n writer.text(\"ds64\");\n writer.u32(28);\n writer.u64(riffSize + 36);\n writer.u64(data);\n writer.u64(frames);\n writer.u32(0);\n }\n\n writer.text(\"fmt \");\n writer.u32(fmtSize);\n const tag = float ? WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM;\n writer.u16(extensible ? WAVE_FORMAT_EXTENSIBLE : tag);\n writer.u16(channels);\n writer.u32(sampleRate);\n writer.u32(sampleRate * channels * bytes);\n writer.u16(channels * bytes);\n writer.u16(bytes * 8);\n if (extensible) {\n writer.u16(22);\n writer.u16(bytes * 8);\n writer.u32(SPEAKERS[channels] ?? 0);\n writer.u16(tag);\n for (const byte of SUBTYPE_TAIL) writer.bytes[writer.at++] = byte;\n } else if (float) {\n writer.u16(0);\n }\n\n if (float) {\n writer.text(\"fact\");\n writer.u32(4);\n writer.u32(rf64 ? MAX_32 : frames);\n }\n if (info) {\n writer.text(\"LIST\");\n writer.u32(info.length);\n writer.raw(info);\n }\n writer.text(\"data\");\n writer.u32(rf64 ? MAX_32 : data);\n return writer.bytes;\n}\n\n/** Rounds half away from zero, as the PCM formats document. */\nfunction roundHalfAway(value: number): number {\n return value < 0 ? -Math.round(-value) : Math.round(value);\n}\n\n/**\n * A sample as stored: an integer for PCM, a float for float32, after\n * clamping as the module describes.\n */\nexport function quantise(sample: number, format: AudioSampleFormat): number {\n const clamped = Number.isFinite(sample) ? Math.max(-1, Math.min(1, sample)) : 0;\n if (format === \"float32\") return Math.fround(clamped);\n const scale = format === \"pcm16\" ? 0x8000 : 0x800000;\n // + 0 turns −0 into 0: an integer sample has no sign of zero.\n return Math.min(scale - 1, roundHalfAway(clamped * scale)) + 0;\n}\n\n/** Interleaves and quantises one block of samples, one array per channel. */\nexport function encodeSamples(\n channels: readonly Float32Array[],\n frames: number,\n format: AudioSampleFormat,\n): Uint8Array<ArrayBuffer> {\n const bytes = BYTES[format];\n const out = new Uint8Array(frames * channels.length * bytes);\n const view = new DataView(out.buffer);\n let at = 0;\n for (let frame = 0; frame < frames; frame += 1) {\n for (const channel of channels) {\n const value = quantise(channel[frame] ?? 0, format);\n if (format === \"float32\") view.setFloat32(at, value, true);\n else if (format === \"pcm16\") view.setInt16(at, value, true);\n else {\n view.setUint8(at, value & 0xff);\n view.setUint8(at + 1, (value >> 8) & 0xff);\n view.setUint8(at + 2, (value >> 16) & 0xff);\n }\n at += bytes;\n }\n }\n return out;\n}\n","import { createWorkerClient, type WorkerClient, type WorkerLike } from \"@hussmartinez/sdk-core\";\nimport { asAudioError, throwIfAborted } from \"../core/errors/abort.js\";\nimport { AudioError } from \"../core/errors/audio-error.js\";\nimport { assertClip, clipLength, clipOffsets, planLength } from \"../core/model/plan.js\";\nimport type {\n AudioProcessor,\n AudioRenderJob,\n AudioSampleFormat,\n} from \"../core/ports/audio-processor.js\";\nimport type { AudioWorkerContract } from \"./audio-worker/contract.js\";\nimport { type AudioWorkerSource, audioWorkerSource } from \"./audio-worker/loader.js\";\nimport type { BlockSegment } from \"./wav/render-block.js\";\nimport { dataSize } from \"./wav/wav-writer.js\";\n\n/**\n * Frames per output block between the page and the worker: at most 2¹⁶ per\n * channel (docs/adr/0002).\n */\nexport const EXPORT_BLOCK_FRAMES = 65_536;\n\nconst SAMPLE_FORMATS: ReadonlySet<string> = new Set<AudioSampleFormat>([\n \"pcm16\",\n \"pcm24\",\n \"float32\",\n]);\n\n/**\n * Options for {@link createAudioProcessor}.\n *\n * @public\n */\nexport interface AudioProcessorOptions {\n /**\n * Milliseconds without calls after which the worker stops. It starts again\n * on the next call. Defaults to sdk-core's 30 seconds.\n */\n readonly idleTimeout?: number;\n /**\n * Where the application serves the package's `dist/assets/` directory, as\n * for `createAudioEngine` (docs/adr/0002). By default the worker is\n * inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/** What the processor needs from its environment, replaceable in tests. */\nexport interface ProcessorEnvironment extends AudioWorkerSource {\n readonly idleTimeout?: number;\n}\n\n/**\n * Creates the SDK's processor (docs/adr/0003): it renders a plan's clips,\n * with their gain and fades, and encodes them as a WAV file, in its own\n * worker, block by block. The page sends each block's source samples, at\n * most 2¹⁶ frames per channel, and collects the encoded blocks into a\n * `Blob` of parts, so an export never holds the whole file in one buffer.\n *\n * Sources with another channel count mix into the plan's by Web Audio's\n * speaker rules, as playback does. Samples are clamped to full scale, and\n * 16-bit and 24-bit PCM round half away from zero, without dither. Files\n * whose sizes don't fit 32 bits are written as RF64.\n *\n * @example\n * ```ts\n * const processor = createAudioProcessor();\n * const wav = await processor.render(\n * { plan, sources, format: { container: \"wav\", sampleFormat: \"pcm24\" } },\n * { signal, onProgress },\n * );\n * ```\n *\n * @public\n */\nexport function createAudioProcessor(options: AudioProcessorOptions = {}): AudioProcessor {\n return createProcessor({\n ...audioWorkerSource(options.assetsUrl),\n ...(options.idleTimeout === undefined ? {} : { idleTimeout: options.idleTimeout }),\n });\n}\n\n/** Checks a job before any work, as the port promises. */\nfunction check(job: AudioRenderJob): AudioSampleFormat {\n const { plan, sources, format } = job;\n if (format.container !== \"wav\")\n throw new TypeError(`Can't export to ${String(format.container)}.`);\n const sampleFormat = format.sampleFormat ?? \"pcm16\";\n if (!SAMPLE_FORMATS.has(sampleFormat)) {\n throw new TypeError(`Unknown sample format ${String(sampleFormat)}.`);\n }\n if (!Number.isSafeInteger(plan.sampleRate) || plan.sampleRate < 1) {\n throw new RangeError(\"The plan's sample rate must be a whole number above 0.\");\n }\n if (!Number.isSafeInteger(plan.channels) || plan.channels < 1) {\n throw new RangeError(\"The plan's channel count must be a whole number above 0.\");\n }\n for (const clip of plan.clips) {\n const source = sources.get(clip.source);\n if (!source) throw new TypeError(`Clip ${clip.key}'s source ${clip.source} isn't in the job.`);\n assertClip(clip, source.length);\n }\n return sampleFormat;\n}\n\n/**\n * The processor, with its environment passed in.\n *\n * @internal\n */\nexport function createProcessor(environment: ProcessorEnvironment): AudioProcessor {\n let startWorker: (() => WorkerLike) | undefined;\n let client: WorkerClient<AudioWorkerContract> | undefined;\n let destroyed = false;\n\n async function ready(): Promise<WorkerClient<AudioWorkerContract>> {\n if (destroyed) throw new Error(\"The audio processor has been destroyed.\");\n startWorker ??= await environment.loadWorker();\n client ??= createWorkerClient<AudioWorkerContract>({\n createWorker: () => {\n if (!startWorker) {\n throw new AudioError(\"WORKER_START_FAILED\", \"The audio worker hasn't loaded.\");\n }\n return startWorker();\n },\n errorClasses: { AudioError },\n packageVersion: environment.version,\n ...(environment.asset === undefined ? {} : { workerAsset: environment.asset }),\n ...(environment.idleTimeout === undefined ? {} : { idleTimeout: environment.idleTimeout }),\n });\n return client;\n }\n\n async function render(\n job: AudioRenderJob,\n signal: AbortSignal | undefined,\n onProgress: ((fraction: number) => void) | undefined,\n ): Promise<Blob> {\n const { plan, sources } = job;\n const sampleFormat = check(job);\n throwIfAborted(signal);\n const worker = await ready();\n const call = signal ? { signal } : {};\n const frames = planLength(plan);\n const spec = { sampleRate: plan.sampleRate, channels: plan.channels, frames, sampleFormat };\n const parts: Uint8Array<ArrayBuffer>[] = [\n await worker.call(\"wavHeader\", { ...spec, metadata: { ...plan.metadata } }, call),\n ];\n const offsets = clipOffsets(plan);\n // The first clip that can overlap the next block, so each block looks\n // only at its own clips.\n let first = 0;\n for (let start = 0; start < frames; start += EXPORT_BLOCK_FRAMES) {\n throwIfAborted(signal);\n const length = Math.min(EXPORT_BLOCK_FRAMES, frames - start);\n const end = start + length;\n const segments: BlockSegment[] = [];\n while (first < plan.clips.length) {\n const clip = plan.clips[first];\n if (!clip || (offsets[first] as number) + clipLength(clip) > start) break;\n first += 1;\n }\n for (let index = first; index < plan.clips.length; index += 1) {\n const clip = plan.clips[index];\n const offset = offsets[index] as number;\n if (!clip || offset >= end) break;\n const from = Math.max(start, offset);\n const to = Math.min(end, offset + clipLength(clip));\n const within = from - offset;\n const source = sources.get(clip.source);\n if (!source) throw new TypeError(`Clip ${clip.key}'s source isn't in the job.`);\n const samples = Array.from({ length: source.numberOfChannels }, (_, channel) =>\n source\n .getChannelData(channel)\n .slice(clip.start + within, clip.start + within + (to - from)),\n );\n segments.push({ clip, within, at: from - start, samples, frames: to - from });\n }\n parts.push(\n await worker.call(\n \"renderBlock\",\n { channels: plan.channels, frames: length, sampleFormat, segments },\n call,\n ),\n );\n onProgress?.(end / frames);\n }\n // Chunks are padded to an even size.\n if (dataSize(spec) % 2 === 1) parts.push(new Uint8Array(1));\n if (frames === 0) onProgress?.(1);\n return new Blob(parts, { type: \"audio/wav\" });\n }\n\n return {\n async render(job, options = {}) {\n try {\n return await render(job, options.signal, options.onProgress);\n } catch (error) {\n if (error instanceof TypeError || error instanceof RangeError) throw error;\n throw asAudioError(error, \"The recording couldn't be exported.\");\n }\n },\n async destroy() {\n destroyed = true;\n client?.destroy();\n },\n };\n}\n","import {\n coreLimits,\n defineLimits,\n type FilePolicy,\n type FilePolicyOverrides,\n type Limits,\n} from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"./audio-error.js\";\n\n/**\n * The audio SDK's limit definitions: sdk-core's core limits with audio\n * defaults, plus five for audio (ADR 0004).\n *\n * | Limit | Code | Default maximum | Default warning |\n * |---|---|---|---|\n * | `maxFileSize` | `FILE_TOO_LARGE` | 1 GB | 250 MB |\n * | `maxFiles` | `TOO_MANY_FILES` | 20 | none |\n * | `maxDecodedSize` | `DECODED_SIZE_TOO_LARGE` | 1 GB | 400 MB |\n * | `maxProcessingTime` | `PROCESSING_TIME_EXCEEDED` | 120 s | none |\n * | `maxDuration` | `DURATION_TOO_LONG` | 3 hours | 1 hour |\n * | `maxChannels` | `TOO_MANY_CHANNELS` | 8 | none |\n * | `maxSampleRate` | `SAMPLE_RATE_TOO_HIGH` | 192 kHz | none |\n * | `maxSessionSize` | `SESSION_TOO_LARGE` | 1.5 GB | 750 MB |\n * | `maxClips` | `TOO_MANY_CLIPS` | 2,000 | none |\n *\n * Sizes are decimal: 1 MB is 1,000,000 bytes. Decoded sizes count 32-bit\n * floats: frames × channels × 4 bytes. `maxDuration` is in milliseconds, and\n * `maxSampleRate` is in hertz.\n *\n * @public\n */\nexport const audioLimitDefinitions = {\n ...coreLimits,\n maxFileSize: { ...coreLimits.maxFileSize, default: 1_000_000_000, warning: 250_000_000 },\n maxDecodedSize: { ...coreLimits.maxDecodedSize, default: 1_000_000_000, warning: 400_000_000 },\n maxDuration: {\n code: \"DURATION_TOO_LONG\",\n unit: \"milliseconds\",\n default: 3 * 60 * 60 * 1_000,\n warning: 60 * 60 * 1_000,\n },\n maxChannels: { code: \"TOO_MANY_CHANNELS\", unit: \"count\", default: 8 },\n maxSampleRate: { code: \"SAMPLE_RATE_TOO_HIGH\", unit: \"hertz\", default: 192_000 },\n maxSessionSize: {\n code: \"SESSION_TOO_LARGE\",\n unit: \"bytes\",\n default: 1_500_000_000,\n warning: 750_000_000,\n },\n maxClips: { code: \"TOO_MANY_CLIPS\", unit: \"count\", default: 2_000 },\n} as const;\n\n/**\n * The type of {@link audioLimitDefinitions}.\n *\n * @public\n */\nexport type AudioLimitDefinitions = typeof audioLimitDefinitions;\n\n/**\n * The names of the audio SDK's limits.\n *\n * @public\n */\nexport type AudioLimitName = keyof AudioLimitDefinitions;\n\n/**\n * A host's `filePolicy`: a new maximum, or `{ maximum, warning }`, for any of\n * the audio SDK's limits. `Infinity` disables a maximum, which removes a\n * protection against hostile files, or disables a warning. Unknown limit\n * names throw `TypeError` when the policy is resolved.\n *\n * @example\n * ```ts\n * // Long recordings: raise the decoded and session sizes together.\n * const filePolicy: AudioFilePolicyOverrides = {\n * maxDecodedSize: 2e9,\n * maxSessionSize: { maximum: 3e9, warning: 1.5e9 },\n * };\n * ```\n *\n * @public\n */\nexport type AudioFilePolicyOverrides = FilePolicyOverrides<AudioLimitDefinitions>;\n\n/**\n * A resolved file policy for the audio SDK. Violations throw\n * {@link AudioError}.\n *\n * @public\n */\nexport type AudioFilePolicy = FilePolicy<AudioLimitDefinitions>;\n\n/**\n * The audio SDK's limits, ready to resolve a host's `filePolicy`. Violations\n * are thrown as {@link AudioError}, with `details` naming the limit.\n *\n * @example\n * ```ts\n * const policy = audioLimits.resolve(props.filePolicy);\n * policy.check(\"maxChannels\", channels); // throws AudioError(\"TOO_MANY_CHANNELS\") above 8\n * ```\n *\n * @public\n */\nexport const audioLimits: Limits<AudioLimitDefinitions> = /* @__PURE__ */ defineLimits(\n audioLimitDefinitions,\n { errorClass: AudioError },\n);\n","import { locate as locateIn, type Reducer } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"../errors/audio-error.js\";\nimport {\n type AudioClip,\n type AudioClipProblem,\n type AudioFade,\n type AudioFadeCurve,\n type AudioMetadata,\n type AudioPlan,\n clipBoundaries,\n clipLength,\n clipProblem,\n EMPTY_METADATA,\n MAX_GAIN_DB,\n MIN_GAIN_DB,\n NO_FADE,\n planLength,\n} from \"../model/plan.js\";\n\n/**\n * Inserts clips at a timeline frame. When the frame falls inside a clip,\n * that clip is split there: its first part keeps its key, and its second\n * part takes `splitKey`.\n *\n * @public\n */\nexport interface AudioInsertClipsCommand {\n readonly type: \"audio.insertClips\";\n /** The timeline frame to insert at, from 0 to the plan's length. */\n readonly at: number;\n /** The clips, in order, with keys the plan doesn't have. */\n readonly clips: readonly AudioClip[];\n /** The key of the second part of a clip that `at` splits. Required only then. */\n readonly splitKey?: string;\n}\n\n/**\n * Removes clips. Their sources stay, so undo can bring them back.\n *\n * @public\n */\nexport interface AudioRemoveClipsCommand {\n readonly type: \"audio.removeClips\";\n readonly keys: readonly string[];\n}\n\n/**\n * Puts removed clips back at their indexes, with every field as it was.\n * It's what undoing a removal runs.\n *\n * @public\n */\nexport interface AudioRestoreClipsCommand {\n readonly type: \"audio.restoreClips\";\n /** Each clip, and the index it takes in the resulting plan, in increasing order. */\n readonly entries: readonly { readonly index: number; readonly clip: AudioClip }[];\n}\n\n/**\n * Replaces `count` clips from `index` with `clips`. It's what undoing an\n * insert, a split or a range deletion runs: those change a run of\n * neighbouring clips.\n *\n * @public\n */\nexport interface AudioReplaceClipsCommand {\n readonly type: \"audio.replaceClips\";\n readonly index: number;\n readonly count: number;\n readonly clips: readonly AudioClip[];\n}\n\n/**\n * Sets clips to new states, matched by key, with every field given. It's\n * what undoing a trim, a gain or a fade runs.\n *\n * @public\n */\nexport interface AudioUpdateClipsCommand {\n readonly type: \"audio.updateClips\";\n readonly clips: readonly AudioClip[];\n}\n\n/**\n * Removes the timeline range from `start` to `end`, trimming the clips at\n * its edges. A range inside one clip splits it: the part after the range\n * takes `newKey`.\n *\n * @public\n */\nexport interface AudioDeleteRangeCommand {\n readonly type: \"audio.deleteRange\";\n /** The first timeline frame removed, inclusive. */\n readonly start: number;\n /** The timeline frame the range stops before, exclusive. */\n readonly end: number;\n /** The key of the part after the range, when the range is inside one clip. Required only then. */\n readonly newKey?: string;\n}\n\n/**\n * Changes the range of its source a clip plays. Fades that no longer fit\n * are shortened in proportion.\n *\n * @public\n */\nexport interface AudioTrimClipCommand {\n readonly type: \"audio.trimClip\";\n readonly key: string;\n /** The first source frame, inclusive. */\n readonly start: number;\n /** The source frame the clip stops before, exclusive. */\n readonly end: number;\n}\n\n/**\n * Splits a clip in two at a timeline frame inside it. The first part keeps\n * the clip's key and fade in, and the second takes `newKey` and the fade out.\n *\n * @public\n */\nexport interface AudioSplitClipCommand {\n readonly type: \"audio.splitClip\";\n readonly key: string;\n /** A timeline frame strictly inside the clip. */\n readonly at: number;\n readonly newKey: string;\n}\n\n/**\n * Moves clips, keeping their relative order, so that the first of them\n * ends up at index `to` of the resulting plan.\n *\n * @public\n */\nexport interface AudioMoveClipsCommand {\n readonly type: \"audio.moveClips\";\n readonly keys: readonly string[];\n readonly to: number;\n}\n\n/**\n * Puts every clip in a new order, given as every key exactly once. It's\n * what undoing a move runs.\n *\n * @public\n */\nexport interface AudioReorderClipsCommand {\n readonly type: \"audio.reorderClips\";\n readonly order: readonly string[];\n}\n\n/**\n * Sets the gain of clips.\n *\n * @public\n */\nexport interface AudioSetGainCommand {\n readonly type: \"audio.setGain\";\n readonly keys: readonly string[];\n /** Decibels, from `MIN_GAIN_DB` to `MAX_GAIN_DB`. */\n readonly gainDb: number;\n}\n\n/**\n * Sets a clip's fade in or fade out. Together, the two fades must fit in\n * the clip.\n *\n * @public\n */\nexport interface AudioSetFadeCommand {\n readonly type: \"audio.setFade\";\n readonly key: string;\n readonly edge: \"in\" | \"out\";\n /** The fade's length in frames. 0 removes it. */\n readonly frames: number;\n readonly curve: AudioFadeCurve;\n}\n\n/**\n * Sets one metadata field, which export writes into the file.\n *\n * @public\n */\nexport interface AudioSetMetadataCommand {\n readonly type: \"audio.setMetadata\";\n readonly field: keyof AudioMetadata;\n /** At most {@link MAX_METADATA_LENGTH} code points. */\n readonly value: string;\n}\n\n/**\n * An edit to the clip plan (docs/adr/0003). Commands are plain,\n * structured-cloneable data, never carry samples, and each has an exact\n * inverse, which is how undo works (ADR 0010, ADR 0029).\n *\n * @public\n */\nexport type AudioCommand =\n | AudioInsertClipsCommand\n | AudioRemoveClipsCommand\n | AudioRestoreClipsCommand\n | AudioReplaceClipsCommand\n | AudioUpdateClipsCommand\n | AudioDeleteRangeCommand\n | AudioTrimClipCommand\n | AudioSplitClipCommand\n | AudioMoveClipsCommand\n | AudioReorderClipsCommand\n | AudioSetGainCommand\n | AudioSetFadeCommand\n | AudioSetMetadataCommand;\n\n/**\n * The longest metadata value, in Unicode code points, so that history steps\n * stay small. Code points are what JSON Schema's `maxLength` counts, and\n * what every language can count, so the limit is the same in every port\n * (sdk-core ADR 0045): 1,000 emoji fit, though they're 2,000 UTF-16 units.\n *\n * @public\n */\nexport const MAX_METADATA_LENGTH = 1_000;\n\n/**\n * Whether text has more than `max` code points, counted with `for…of`,\n * which walks code points, and stopping as soon as it knows.\n *\n * @internal\n */\nexport function longerThan(text: string, max: number): boolean {\n // Every code point is one or two UTF-16 units.\n if (text.length <= max) return false;\n let count = 0;\n for (const _ of text) {\n count += 1;\n if (count > max) return true;\n }\n return false;\n}\n\nconst CURVES: ReadonlySet<string> = new Set<AudioFadeCurve>([\"linear\", \"equalPower\"]);\n\n/**\n * The frames of each registered source, or `undefined` for an id the\n * session doesn't have. Sources never change, so the reducer stays pure.\n *\n * @internal\n */\nexport type SourceFrames = (source: string) => number | undefined;\n\n/**\n * Why the reducer refused a command, as a stable token: `details.reason` on\n * `INVALID_COMMAND`, which hosts and conformance vectors compare instead of\n * the message (sdk-core ADR 0045). Tokens never change meaning once\n * released.\n *\n * - The clip's own problems, {@link AudioClipProblem}.\n * - `malformed-command`: the command isn't shaped as its type says, such as\n * a list that isn't one, or a clip without a key or source.\n * - `unknown-command`: its `type` isn't one of {@link AudioCommand}'s.\n * - `unknown-source`: a clip names a source the session doesn't hold.\n * - `invalid-fade-curve`: a fade's curve isn't `linear` or `equalPower`.\n * - `no-clips`: the command needs at least one clip, and names none.\n * - `duplicate-key`: it names a clip twice, or gives two new clips one key.\n * - `key-taken`: a new clip's key is already in the plan.\n * - `unknown-clip`: it names a clip the plan doesn't have.\n * - `frame-outside-plan`: a timeline frame is outside the plan.\n * - `empty-range`: a range is shorter than one frame.\n * - `not-inside-clip`: a split frame isn't strictly inside its clip.\n * - `new-key-required`: it cuts a clip in two without the new part's key.\n * - `invalid-index`: an index or a run of clips is outside the plan.\n * - `empty-change`: it would change nothing at all.\n * - `invalid-order`: a new order doesn't list every clip exactly once.\n * - `invalid-edge`: a fade's edge isn't `in` or `out`.\n * - `unknown-metadata-field`: the metadata has no such field.\n * - `metadata-too-long`: a metadata value is over {@link MAX_METADATA_LENGTH}\n * code points.\n *\n * The session adds `no-recording`, for a command or an export with no\n * recording open, `not-plain-data`, for a command that can't be cloned, and\n * `empty-plan`, for an export of a plan with no clips.\n *\n * @public\n */\nexport type AudioCommandRejection =\n | AudioClipProblem\n | \"malformed-command\"\n | \"unknown-command\"\n | \"unknown-source\"\n | \"invalid-fade-curve\"\n | \"no-clips\"\n | \"duplicate-key\"\n | \"key-taken\"\n | \"unknown-clip\"\n | \"frame-outside-plan\"\n | \"empty-range\"\n | \"not-inside-clip\"\n | \"new-key-required\"\n | \"invalid-index\"\n | \"empty-change\"\n | \"invalid-order\"\n | \"invalid-edge\"\n | \"unknown-metadata-field\"\n | \"metadata-too-long\"\n | \"no-recording\"\n | \"not-plain-data\"\n | \"empty-plan\";\n\n/**\n * A refusal with its reason, before it becomes the caller's `AudioError`.\n *\n * @internal\n */\nexport class Invalid extends Error {\n readonly reason: AudioCommandRejection;\n\n constructor(reason: AudioCommandRejection, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\n/** @internal */\nexport function invalid(reason: AudioCommandRejection, message: string): never {\n throw new Invalid(reason, message);\n}\n\n/** An object whose fields, from a command that may have been stored or sent, are unchecked. */\nexport type Unchecked<T> = { readonly [Key in keyof T]?: unknown };\n\n/** @internal */\nexport function isRecord<T>(value: unknown): value is Unchecked<T> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** @internal */\nexport function isKey(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isIndex(value: unknown, max: number): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= max;\n}\n\nfunction fade(value: unknown, name: string): AudioFade {\n if (!isRecord<AudioFade>(value)) invalid(\"malformed-command\", `${name} isn't a fade`);\n onlyFields(value, FADE_FIELDS, name);\n if (typeof value.curve !== \"string\" || !CURVES.has(value.curve)) {\n invalid(\"invalid-fade-curve\", `${name}'s curve isn't linear or equalPower`);\n }\n return { frames: value.frames as number, curve: value.curve as AudioFadeCurve };\n}\n\n/**\n * The fields each command may have. Anything else fails as\n * `malformed-command`, as the format's JSON Schema refuses it, so that the\n * reducer accepts exactly what the schema does (sdk-core ADR 0045). A field\n * whose value is `undefined` counts as absent.\n */\nconst COMMAND_FIELDS: Readonly<Record<AudioCommand[\"type\"], readonly string[]>> = {\n \"audio.insertClips\": [\"at\", \"clips\", \"splitKey\"],\n \"audio.removeClips\": [\"keys\"],\n \"audio.restoreClips\": [\"entries\"],\n \"audio.replaceClips\": [\"index\", \"count\", \"clips\"],\n \"audio.updateClips\": [\"clips\"],\n \"audio.deleteRange\": [\"start\", \"end\", \"newKey\"],\n \"audio.trimClip\": [\"key\", \"start\", \"end\"],\n \"audio.splitClip\": [\"key\", \"at\", \"newKey\"],\n \"audio.moveClips\": [\"keys\", \"to\"],\n \"audio.reorderClips\": [\"order\"],\n \"audio.setGain\": [\"keys\", \"gainDb\"],\n \"audio.setFade\": [\"key\", \"edge\", \"frames\", \"curve\"],\n \"audio.setMetadata\": [\"field\", \"value\"],\n};\nconst CLIP_FIELDS = [\"key\", \"source\", \"start\", \"end\", \"gainDb\", \"fadeIn\", \"fadeOut\"];\nconst FADE_FIELDS = [\"frames\", \"curve\"];\nconst ENTRY_FIELDS = [\"index\", \"clip\"];\n\n/** Fails unless every field the object has is one of `allowed`. */\n/** @internal */\nexport function onlyFields(value: object, allowed: readonly string[], what: string): void {\n for (const [field, content] of Object.entries(value)) {\n if (content !== undefined && !allowed.includes(field)) {\n invalid(\"malformed-command\", `${what} has no field ${field}`);\n }\n }\n}\n\n/** Fails unless an optional key, when it's there, is a non-empty string. */\nfunction optionalKey(value: unknown, name: string): string | undefined {\n if (value !== undefined && !isKey(value)) {\n invalid(\"malformed-command\", `${name} must be a non-empty string`);\n }\n return value;\n}\n\n/**\n * A clean copy of a clip from a command, with only its own fields, or a\n * failure if it isn't valid within its source.\n */\n/** @internal */\nexport function checkClip(value: unknown, sourceFrames: SourceFrames): AudioClip {\n if (!isRecord<AudioClip>(value) || !isKey(value.key) || !isKey(value.source)) {\n invalid(\"malformed-command\", \"a clip needs a key and a source\");\n }\n onlyFields(value, CLIP_FIELDS, \"a clip\");\n const clip: AudioClip = {\n key: value.key,\n source: value.source,\n start: value.start as number,\n end: value.end as number,\n gainDb: value.gainDb as number,\n fadeIn: fade(value.fadeIn, \"fadeIn\"),\n fadeOut: fade(value.fadeOut, \"fadeOut\"),\n };\n const frames = sourceFrames(clip.source);\n if (frames === undefined) invalid(\"unknown-source\", `the session has no source ${clip.source}`);\n const problem = clipProblem(clip, frames);\n if (problem) invalid(problem, `clip ${clip.key} isn't valid within its source`);\n return clip;\n}\n\nfunction checkClips(values: unknown, sourceFrames: SourceFrames): AudioClip[] {\n if (!Array.isArray(values)) invalid(\"malformed-command\", \"clips must be a list\");\n return values.map((value) => checkClip(value, sourceFrames));\n}\n\n/** Fails unless every key is new: absent from `existing`, and not repeated. */\nfunction checkNewKeys(keys: readonly unknown[], existing: Iterable<string>): void {\n const taken = new Set(existing);\n const seen = new Set<string>();\n for (const key of keys) {\n if (!isKey(key)) invalid(\"malformed-command\", \"a key must be a non-empty string\");\n if (taken.has(key)) invalid(\"key-taken\", `the key ${key} is taken`);\n if (seen.has(key)) invalid(\"duplicate-key\", `the key ${key} appears twice`);\n seen.add(key);\n }\n}\n\n/** The indexes of the given keys, in plan order, failing on unknown or repeated keys. */\nfunction positions(plan: AudioPlan, keys: unknown): number[] {\n if (!Array.isArray(keys)) invalid(\"malformed-command\", \"keys must be a list\");\n if (keys.length === 0) invalid(\"no-clips\", \"it needs at least one clip\");\n const wanted = new Set<unknown>(keys);\n if (wanted.size !== keys.length) invalid(\"duplicate-key\", \"a clip appears twice\");\n const found: number[] = [];\n plan.clips.forEach((clip, index) => {\n if (wanted.has(clip.key)) found.push(index);\n });\n if (found.length !== wanted.size) invalid(\"unknown-clip\", \"the plan doesn't have every clip\");\n return found;\n}\n\nfunction position(plan: AudioPlan, key: unknown): number {\n return positions(plan, [key])[0] as number;\n}\n\n/**\n * Shortens fades that no longer fit their clip, in proportion, so that\n * neither reaches into the other.\n */\nfunction fitFades(clip: AudioClip): AudioClip {\n const length = clipLength(clip);\n const total = clip.fadeIn.frames + clip.fadeOut.frames;\n // A clip of no frames, or of invalid ones, is left for validation to\n // refuse with its own reason.\n if (total <= length || !(length > 0)) return clip;\n return {\n ...clip,\n fadeIn: { ...clip.fadeIn, frames: Math.floor((clip.fadeIn.frames * length) / total) },\n fadeOut: { ...clip.fadeOut, frames: Math.floor((clip.fadeOut.frames * length) / total) },\n };\n}\n\n/**\n * The part of a clip from `from` to `to`, in frames from its start. A part\n * keeps the fades of the edges it shares with the clip, and has none at a\n * cut.\n */\nfunction part(clip: AudioClip, from: number, to: number, key: string): AudioClip {\n const length = clipLength(clip);\n return fitFades({\n ...clip,\n key,\n start: clip.start + from,\n end: clip.start + to,\n fadeIn: from === 0 ? clip.fadeIn : NO_FADE,\n fadeOut: to === length ? clip.fadeOut : NO_FADE,\n });\n}\n\n/**\n * Where a timeline frame falls: the index of the clip that contains it and\n * the offset into that clip, or the index after the last clip, at offset 0,\n * for the plan's end.\n */\nfunction locate(plan: AudioPlan, frame: unknown): { index: number; offset: number } {\n if (!isIndex(frame, planLength(plan))) {\n invalid(\"frame-outside-plan\", \"the frame is outside the plan\");\n }\n // A valid frame past every clip is the plan's end, where locate finds none.\n const found = locateIn(clipBoundaries(plan), frame);\n return found\n ? { index: found.index, offset: found.within }\n : { index: plan.clips.length, offset: 0 };\n}\n\nfunction withClips(plan: AudioPlan, clips: readonly AudioClip[]): AudioPlan {\n return { ...plan, clips };\n}\n\nfunction splice(\n plan: AudioPlan,\n index: number,\n count: number,\n clips: readonly AudioClip[],\n): AudioPlan {\n return withClips(plan, [\n ...plan.clips.slice(0, index),\n ...clips,\n ...plan.clips.slice(index + count),\n ]);\n}\n\nfunction updateByKey(plan: AudioPlan, clips: readonly AudioClip[]): AudioPlan {\n const byKey = new Map(clips.map((clip) => [clip.key, clip]));\n return withClips(\n plan,\n plan.clips.map((clip) => byKey.get(clip.key) ?? clip),\n );\n}\n\ntype Applied = { state: AudioPlan; inverse: AudioCommand };\n\nfunction apply(plan: AudioPlan, command: AudioCommand, sourceFrames: SourceFrames): Applied {\n if (!isRecord<AudioCommand>(command)) invalid(\"malformed-command\", \"a command is an object\");\n const fields = Object.hasOwn(COMMAND_FIELDS, command.type as string)\n ? COMMAND_FIELDS[command.type as AudioCommand[\"type\"]]\n : undefined;\n if (!fields) invalid(\"unknown-command\", \"unknown command\");\n onlyFields(command, [\"type\", ...fields], command.type as string);\n switch (command.type) {\n case \"audio.insertClips\": {\n const clips = checkClips(command.clips, sourceFrames);\n if (clips.length === 0) invalid(\"no-clips\", \"it needs at least one clip\");\n const keys = clips.map((clip) => clip.key);\n checkNewKeys(\n keys,\n plan.clips.map((clip) => clip.key),\n );\n const splitKey = optionalKey(command.splitKey, \"splitKey\");\n const { index, offset } = locate(plan, command.at);\n if (offset === 0) {\n return {\n state: splice(plan, index, 0, clips),\n inverse: { type: \"audio.replaceClips\", index, count: clips.length, clips: [] },\n };\n }\n if (splitKey === undefined) {\n invalid(\"new-key-required\", \"inserting inside a clip needs a splitKey\");\n }\n checkNewKeys([splitKey], [...plan.clips.map((clip) => clip.key), ...keys]);\n const split = plan.clips[index] as AudioClip;\n const parts = [\n part(split, 0, offset, split.key),\n ...clips,\n part(split, offset, clipLength(split), splitKey),\n ];\n return {\n state: splice(plan, index, 1, parts),\n inverse: { type: \"audio.replaceClips\", index, count: parts.length, clips: [split] },\n };\n }\n\n case \"audio.removeClips\": {\n const at = positions(plan, command.keys);\n const removed = new Set(at);\n return {\n state: withClips(\n plan,\n plan.clips.filter((_, index) => !removed.has(index)),\n ),\n inverse: {\n type: \"audio.restoreClips\",\n entries: at.map((index) => ({ index, clip: plan.clips[index] as AudioClip })),\n },\n };\n }\n\n case \"audio.restoreClips\": {\n if (!Array.isArray(command.entries)) invalid(\"malformed-command\", \"entries must be a list\");\n if (command.entries.length === 0) invalid(\"no-clips\", \"it needs at least one clip\");\n const entries = command.entries.map((entry: unknown) => {\n if (!isRecord<{ index: number; clip: AudioClip }>(entry)) {\n invalid(\"malformed-command\", \"an entry needs an index and a clip\");\n }\n onlyFields(entry, ENTRY_FIELDS, \"an entry\");\n return { index: entry.index, clip: checkClip(entry.clip, sourceFrames) };\n });\n checkNewKeys(\n entries.map(({ clip }) => clip.key),\n plan.clips.map((clip) => clip.key),\n );\n const clips = [...plan.clips];\n let previous = -1;\n for (const { index, clip } of entries) {\n if (!isIndex(index, clips.length) || index <= previous) {\n invalid(\"invalid-index\", `clip ${clip.key} can't be restored at index ${String(index)}`);\n }\n clips.splice(index, 0, clip);\n previous = index;\n }\n return {\n state: withClips(plan, clips),\n inverse: { type: \"audio.removeClips\", keys: entries.map(({ clip }) => clip.key) },\n };\n }\n\n case \"audio.replaceClips\": {\n const { index, count } = command;\n if (!isIndex(index, plan.clips.length) || !isIndex(count, plan.clips.length - index)) {\n invalid(\"invalid-index\", \"the run of clips is outside the plan\");\n }\n const clips = checkClips(command.clips, sourceFrames);\n if (count === 0 && clips.length === 0) invalid(\"empty-change\", \"it changes nothing\");\n const removed = plan.clips.slice(index, index + count);\n checkNewKeys(\n clips.map((clip) => clip.key),\n [...plan.clips.slice(0, index), ...plan.clips.slice(index + count)].map((clip) => clip.key),\n );\n return {\n state: splice(plan, index, count, clips),\n inverse: { type: \"audio.replaceClips\", index, count: clips.length, clips: removed },\n };\n }\n\n case \"audio.updateClips\": {\n const clips = checkClips(command.clips, sourceFrames);\n const at = positions(\n plan,\n clips.map((clip) => clip.key),\n );\n return {\n state: updateByKey(plan, clips),\n inverse: {\n type: \"audio.updateClips\",\n clips: at.map((index) => plan.clips[index] as AudioClip),\n },\n };\n }\n\n case \"audio.deleteRange\": {\n const { start, end } = command;\n const newKey = optionalKey(command.newKey, \"newKey\");\n if (!isIndex(start, planLength(plan)) || !isIndex(end, planLength(plan))) {\n invalid(\"frame-outside-plan\", \"the range must be inside the plan\");\n }\n if (end <= start) invalid(\"empty-range\", \"the range must be at least one frame long\");\n const first = locate(plan, start);\n const last = locate(plan, end - 1);\n const firstClip = plan.clips[first.index] as AudioClip;\n const lastClip = plan.clips[last.index] as AudioClip;\n const kept: AudioClip[] = [];\n if (first.offset > 0) kept.push(part(firstClip, 0, first.offset, firstClip.key));\n if (last.offset + 1 < clipLength(lastClip)) {\n let key = lastClip.key;\n if (first.index === last.index && first.offset > 0) {\n if (newKey === undefined) {\n invalid(\"new-key-required\", \"deleting inside a clip needs a newKey\");\n }\n checkNewKeys(\n [newKey],\n plan.clips.map((clip) => clip.key),\n );\n key = newKey;\n }\n kept.push(part(lastClip, last.offset + 1, clipLength(lastClip), key));\n }\n const count = last.index - first.index + 1;\n return {\n state: splice(plan, first.index, count, kept),\n inverse: {\n type: \"audio.replaceClips\",\n index: first.index,\n count: kept.length,\n clips: plan.clips.slice(first.index, first.index + count),\n },\n };\n }\n\n case \"audio.trimClip\": {\n const index = position(plan, command.key);\n const clip = plan.clips[index] as AudioClip;\n const trimmed = checkClip(\n fitFades({ ...clip, start: command.start, end: command.end }),\n sourceFrames,\n );\n return {\n state: updateByKey(plan, [trimmed]),\n inverse: { type: \"audio.updateClips\", clips: [clip] },\n };\n }\n\n case \"audio.splitClip\": {\n const index = position(plan, command.key);\n const clip = plan.clips[index] as AudioClip;\n const { index: within, offset } = locate(plan, command.at);\n if (within !== index || offset === 0) {\n invalid(\"not-inside-clip\", \"the frame must be strictly inside the clip\");\n }\n checkNewKeys(\n [command.newKey],\n plan.clips.map((entry) => entry.key),\n );\n const parts = [\n part(clip, 0, offset, clip.key),\n part(clip, offset, clipLength(clip), command.newKey),\n ];\n return {\n state: splice(plan, index, 1, parts),\n inverse: { type: \"audio.replaceClips\", index, count: 2, clips: [clip] },\n };\n }\n\n case \"audio.moveClips\": {\n const moved = new Set(positions(plan, command.keys));\n const block = plan.clips.filter((_, index) => moved.has(index));\n const rest = plan.clips.filter((_, index) => !moved.has(index));\n if (!isIndex(command.to, rest.length)) invalid(\"invalid-index\", \"the clips can't move there\");\n return {\n state: withClips(plan, [...rest.slice(0, command.to), ...block, ...rest.slice(command.to)]),\n inverse: { type: \"audio.reorderClips\", order: plan.clips.map((clip) => clip.key) },\n };\n }\n\n case \"audio.reorderClips\": {\n const { order } = command;\n const byKey = new Map(plan.clips.map((clip) => [clip.key, clip]));\n if (\n !Array.isArray(order) ||\n order.length !== plan.clips.length ||\n new Set(order).size !== order.length ||\n order.some((key) => !byKey.has(key))\n ) {\n invalid(\"invalid-order\", \"the order must list every clip exactly once\");\n }\n return {\n state: withClips(\n plan,\n order.map((key) => byKey.get(key) as AudioClip),\n ),\n inverse: { type: \"audio.reorderClips\", order: plan.clips.map((clip) => clip.key) },\n };\n }\n\n case \"audio.setGain\": {\n const at = positions(plan, command.keys);\n const gainDb = command.gainDb;\n if (typeof gainDb !== \"number\" || !(gainDb >= MIN_GAIN_DB && gainDb <= MAX_GAIN_DB)) {\n invalid(\"gain-out-of-range\", `gain must be from ${MIN_GAIN_DB} to ${MAX_GAIN_DB} dB`);\n }\n const before = at.map((index) => plan.clips[index] as AudioClip);\n return {\n state: updateByKey(\n plan,\n before.map((clip) => ({ ...clip, gainDb })),\n ),\n inverse: { type: \"audio.updateClips\", clips: before },\n };\n }\n\n case \"audio.setFade\": {\n const clip = plan.clips[position(plan, command.key)] as AudioClip;\n const { edge, frames } = command;\n if (edge !== \"in\" && edge !== \"out\") invalid(\"invalid-edge\", \"the edge must be in or out\");\n const next = { frames, curve: fade({ frames, curve: command.curve }, \"the fade\").curve };\n const updated = checkClip(\n edge === \"in\" ? { ...clip, fadeIn: next } : { ...clip, fadeOut: next },\n sourceFrames,\n );\n return {\n state: updateByKey(plan, [updated]),\n inverse: { type: \"audio.updateClips\", clips: [clip] },\n };\n }\n\n case \"audio.setMetadata\": {\n const { field, value } = command;\n if (typeof field !== \"string\" || !Object.hasOwn(EMPTY_METADATA, field)) {\n invalid(\"unknown-metadata-field\", \"there's no such metadata field\");\n }\n if (typeof value !== \"string\") invalid(\"malformed-command\", \"a metadata value must be text\");\n if (longerThan(value, MAX_METADATA_LENGTH)) {\n invalid(\n \"metadata-too-long\",\n `a metadata value can have at most ${MAX_METADATA_LENGTH} code points`,\n );\n }\n return {\n state: { ...plan, metadata: { ...plan.metadata, [field]: value } },\n inverse: { type: \"audio.setMetadata\", field, value: plan.metadata[field] },\n };\n }\n\n default:\n return invalid(\"unknown-command\", \"unknown command\");\n }\n}\n\n/**\n * Creates the clip plan's reducer (docs/adr/0003): it applies one command\n * without changing the plan, and returns the new plan with the command's\n * inverse. Sources are looked up through `sourceFrames`, so commands never\n * carry samples. An invalid command throws `AudioError` with\n * `INVALID_COMMAND` and changes nothing: the reducer never corrects one.\n *\n * @internal\n */\nexport function createPlanReducer(sourceFrames: SourceFrames): Reducer<AudioPlan, AudioCommand> {\n return (plan, command) => {\n try {\n return apply(plan, command, sourceFrames);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const type =\n isRecord<AudioCommand>(command) && typeof command.type === \"string\" ? command.type : \"\";\n const known = type.startsWith(\"audio.\") && type.length <= 64;\n throw new AudioError(\n \"INVALID_COMMAND\",\n `Invalid ${known ? type : \"command\"}: ${error.message}.`,\n { details: known ? { command: type, reason: error.reason } : { reason: error.reason } },\n );\n }\n };\n}\n","import { AudioError } from \"../errors/audio-error.js\";\nimport type { AudioClip, AudioClipProblem, AudioMetadata, AudioPlan } from \"../model/plan.js\";\nimport {\n checkClip,\n Invalid,\n invalid,\n isKey,\n isRecord,\n longerThan,\n MAX_METADATA_LENGTH,\n onlyFields,\n} from \"../operations/commands.js\";\n\n/**\n * The name of the clip plan's portable format (sdk-core ADR 0045).\n *\n * @public\n */\nexport const AUDIO_PLAN_FORMAT = \"hm-audio-plan\";\n\n/**\n * The version of {@link AUDIO_PLAN_FORMAT} this release writes, and the\n * latest it reads.\n *\n * @public\n */\nexport const AUDIO_PLAN_VERSION = 1;\n\n/**\n * A content-addressed reference to binary data, such as a source's file\n * (sdk-core ADR 0045). Documents never inline bytes.\n *\n * @public\n */\nexport interface AudioAssetReference {\n /** `sha256:` and the lowercase hex SHA-256 of the bytes. */\n readonly asset: string;\n /** The bytes' media type, such as `audio/wav`, in lowercase. */\n readonly mediaType: string;\n /** The size of the bytes. */\n readonly size: number;\n}\n\n/**\n * A source, as a plan document records it: its length, which its clips must\n * lie within, and, once documents travel with their files, its content.\n *\n * @public\n */\nexport interface AudioPlanDocumentSource {\n /** The source's length in frames, at the plan's sample rate. */\n readonly frames: number;\n readonly asset?: AudioAssetReference;\n}\n\n/**\n * The clip plan as portable JSON: `hm-audio-plan` version 1, which\n * `formats/hm-audio-plan/v1.schema.json` describes (docs/formats/hm-audio-plan.md).\n * Every position is a whole number of frames, and sources are named by the\n * ids their clips use.\n *\n * @public\n */\nexport interface AudioPlanDocument {\n readonly format: typeof AUDIO_PLAN_FORMAT;\n readonly version: typeof AUDIO_PLAN_VERSION;\n readonly sampleRate: number;\n readonly channels: number;\n readonly sources: Readonly<Record<string, AudioPlanDocumentSource>>;\n readonly clips: readonly AudioClip[];\n readonly metadata: AudioMetadata;\n}\n\n/**\n * Why a plan document was refused, as a stable token: `details.reason` on\n * the error (sdk-core ADR 0045).\n *\n * - With `UNSUPPORTED_FORMAT`: `unknown-format`, a document of another\n * format, and `unknown-format-version`, a later version than this release\n * reads.\n * - With `INVALID_DOCUMENT`: `malformed-document`, a document that isn't\n * shaped as the schema says; `unknown-source`, a clip whose source the\n * document doesn't list; `duplicate-key`, two clips with one key;\n * `invalid-fade-curve` and `metadata-too-long`, as for commands; and a\n * clip's own problems, {@link AudioClipProblem}.\n *\n * @public\n */\nexport type AudioDocumentRejection =\n | AudioClipProblem\n | \"unknown-format\"\n | \"unknown-format-version\"\n | \"malformed-document\"\n | \"unknown-source\"\n | \"duplicate-key\"\n | \"invalid-fade-curve\"\n | \"metadata-too-long\";\n\nconst DOCUMENT_FIELDS = [\n \"format\",\n \"version\",\n \"sampleRate\",\n \"channels\",\n \"sources\",\n \"clips\",\n \"metadata\",\n];\nconst SOURCE_FIELDS = [\"frames\", \"asset\"];\nconst ASSET_FIELDS = [\"asset\", \"mediaType\", \"size\"];\nconst METADATA_FIELDS: readonly (keyof AudioMetadata)[] = [\n \"title\",\n \"artist\",\n \"album\",\n \"year\",\n \"comment\",\n];\n/** The patterns the schema uses too, so both accept the same documents. */\nconst ASSET_ID = /^sha256:[0-9a-f]{64}$/;\nconst MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;\n\nfunction malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\nconst isCount = (value: unknown, min: number): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min;\n\nfunction readAsset(value: unknown): AudioAssetReference {\n if (!isRecord<AudioAssetReference>(value)) malformed(\"an asset is an object\");\n onlyFields(value, ASSET_FIELDS, \"an asset\");\n const { asset, mediaType, size } = value;\n if (typeof asset !== \"string\" || !ASSET_ID.test(asset)) malformed(\"an asset id is sha256:<hex>\");\n if (typeof mediaType !== \"string\" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) {\n malformed(\"a media type is type/subtype, in lowercase\");\n }\n if (!isCount(size, 0)) malformed(\"an asset's size is a whole number of bytes\");\n return { asset, mediaType, size };\n}\n\nfunction readSources(value: unknown): Record<string, AudioPlanDocumentSource> {\n if (!isRecord<Record<string, unknown>>(value) || Array.isArray(value)) {\n malformed(\"sources is an object\");\n }\n return Object.fromEntries(\n Object.entries(value).map(([id, source]) => {\n if (!isKey(id)) malformed(\"a source id is a non-empty string\");\n if (!isRecord<AudioPlanDocumentSource>(source)) malformed(\"a source is an object\");\n onlyFields(source, SOURCE_FIELDS, \"a source\");\n if (!isCount(source.frames, 1)) malformed(\"a source's frames are a whole number above 0\");\n const entry: AudioPlanDocumentSource =\n source.asset === undefined\n ? { frames: source.frames }\n : { frames: source.frames, asset: readAsset(source.asset) };\n return [id, entry];\n }),\n );\n}\n\nfunction readMetadata(value: unknown): AudioMetadata {\n if (!isRecord<AudioMetadata>(value)) malformed(\"metadata is an object\");\n onlyFields(value, METADATA_FIELDS, \"metadata\");\n const fields = METADATA_FIELDS.map((field) => {\n const text = value[field];\n if (typeof text !== \"string\") malformed(`metadata.${field} is text`);\n if (longerThan(text, MAX_METADATA_LENGTH)) {\n invalid(\"metadata-too-long\", `metadata.${field} is over ${MAX_METADATA_LENGTH} code points`);\n }\n return [field, text] as const;\n });\n return Object.fromEntries(fields) as unknown as AudioMetadata;\n}\n\nfunction read(value: unknown): {\n plan: AudioPlan;\n sources: Record<string, AudioPlanDocumentSource>;\n} {\n if (!isRecord<AudioPlanDocument>(value) || Array.isArray(value)) {\n malformed(\"a document is an object\");\n }\n const { format, version } = value;\n if (typeof format !== \"string\") malformed(\"format is text\");\n if (format !== AUDIO_PLAN_FORMAT) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", `This isn't an ${AUDIO_PLAN_FORMAT} document.`, {\n details: { format: AUDIO_PLAN_FORMAT, reason: \"unknown-format\" },\n });\n }\n if (Number.isSafeInteger(version) && (version as number) > AUDIO_PLAN_VERSION) {\n throw new AudioError(\n \"UNSUPPORTED_FORMAT\",\n `This ${AUDIO_PLAN_FORMAT} document is a later version than this release reads.`,\n { details: { format: AUDIO_PLAN_FORMAT, reason: \"unknown-format-version\" } },\n );\n }\n if (version !== AUDIO_PLAN_VERSION) malformed(\"version is 1\");\n onlyFields(value, DOCUMENT_FIELDS, \"a document\");\n if (!isCount(value.sampleRate, 1)) malformed(\"sampleRate is a whole number above 0\");\n if (!isCount(value.channels, 1)) malformed(\"channels is a whole number above 0\");\n const sources = readSources(value.sources);\n if (!Array.isArray(value.clips)) malformed(\"clips is a list\");\n const lookup = (id: string) => (Object.hasOwn(sources, id) ? sources[id]?.frames : undefined);\n const clips = value.clips.map((clip: unknown) => checkClip(clip, lookup));\n const keys = new Set<string>();\n for (const { key } of clips) {\n if (keys.has(key)) invalid(\"duplicate-key\", `two clips have the key ${key}`);\n keys.add(key);\n }\n return {\n plan: {\n sampleRate: value.sampleRate,\n channels: value.channels,\n clips,\n metadata: readMetadata(value.metadata),\n },\n sources,\n };\n}\n\n/**\n * Reads a plan document, such as one parsed from JSON, checking it as\n * {@link AudioPlanDocument}'s schema does and more: every clip must lie\n * within a source the document lists, and keys must be unique. Unknown\n * fields are refused, never dropped.\n *\n * @param value - The parsed JSON.\n * @returns The plan, and its sources by id.\n * @throws `AudioError` with `UNSUPPORTED_FORMAT` for another format or a\n * later version, and `INVALID_DOCUMENT` for anything else that's wrong,\n * with a {@link AudioDocumentRejection} as `details.reason`.\n * @public\n */\nexport function readAudioPlanDocument(value: unknown): {\n readonly plan: AudioPlan;\n readonly sources: Readonly<Record<string, AudioPlanDocumentSource>>;\n} {\n try {\n return read(value);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const reason = error.reason === \"malformed-command\" ? \"malformed-document\" : error.reason;\n throw new AudioError(\n \"INVALID_DOCUMENT\",\n `Invalid ${AUDIO_PLAN_FORMAT} document: ${error.message}.`,\n {\n details: { format: AUDIO_PLAN_FORMAT, reason },\n },\n );\n }\n}\n\n/**\n * Writes a plan as an {@link AudioPlanDocument}, plain JSON-ready data.\n *\n * @param plan - The plan.\n * @param sources - The sources by id, with at least every source the plan's\n * clips use. They're written as given.\n * @throws `TypeError` if a clip's source is missing from `sources`.\n * @public\n */\nexport function toAudioPlanDocument(\n plan: AudioPlan,\n sources: Readonly<Record<string, AudioPlanDocumentSource>>,\n): AudioPlanDocument {\n for (const clip of plan.clips) {\n if (!Object.hasOwn(sources, clip.source)) {\n throw new TypeError(`The sources don't include ${clip.source}, which clip ${clip.key} uses.`);\n }\n }\n return {\n format: AUDIO_PLAN_FORMAT,\n version: AUDIO_PLAN_VERSION,\n sampleRate: plan.sampleRate,\n channels: plan.channels,\n sources: Object.fromEntries(\n Object.entries(sources).map(([id, { frames, asset }]) => [\n id,\n asset === undefined ? { frames } : { frames, asset: { ...asset } },\n ]),\n ),\n clips: plan.clips.map(({ key, source, start, end, gainDb, fadeIn, fadeOut }) => ({\n key,\n source,\n start,\n end,\n gainDb,\n fadeIn: { frames: fadeIn.frames, curve: fadeIn.curve },\n fadeOut: { frames: fadeOut.frames, curve: fadeOut.curve },\n })),\n metadata: { ...plan.metadata },\n };\n}\n","/**\n * Every position and length in the model is a whole number of frames, at the\n * session's sample rate (ADR 0003). A frame is one sample on every channel.\n * Seconds appear only at the edges: in the UI and in events.\n */\n\n/**\n * Converts frames to seconds, for display and events.\n *\n * @param frames - A whole number of frames.\n * @param sampleRate - Frames per second.\n * @public\n */\nexport function framesToSeconds(frames: number, sampleRate: number): number {\n return frames / sampleRate;\n}\n\n/**\n * Converts seconds to the nearest whole frame, for input from the UI, such\n * as a typed trim point.\n *\n * @param seconds - A time in seconds.\n * @param sampleRate - Frames per second.\n * @public\n */\nexport function secondsToFrames(seconds: number, sampleRate: number): number {\n return Math.round(seconds * sampleRate);\n}\n\n/**\n * Throws `RangeError` unless the value is a non-negative whole number of\n * frames.\n *\n * @internal\n */\nexport function assertFrames(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new RangeError(`${name} must be a non-negative whole number of frames, not ${value}.`);\n }\n}\n","import {\n applyCommands,\n checkFile,\n createHistory,\n createStore,\n type HistoryStep,\n withProcessingTime,\n} from \"@hussmartinez/sdk-core\";\nimport { abortError, asAudioError, throwIfAborted } from \"../errors/abort.js\";\nimport { AudioError } from \"../errors/audio-error.js\";\nimport {\n type AudioFilePolicyOverrides,\n type AudioLimitName,\n audioLimits,\n} from \"../errors/audio-limits.js\";\nimport {\n type AudioClip,\n type AudioPlan,\n EMPTY_METADATA,\n NO_FADE,\n planLength,\n} from \"../model/plan.js\";\nimport type { AudioPeaks, AudioProbe, AudioSourceInfo, DecodedAudio } from \"../model/source.js\";\nimport { framesToSeconds } from \"../model/time.js\";\nimport { type AudioCommand, createPlanReducer } from \"../operations/commands.js\";\nimport type { AudioEngine } from \"../ports/audio-engine.js\";\nimport type {\n AudioExportFormat,\n AudioProcessor,\n AudioSampleFormat,\n} from \"../ports/audio-processor.js\";\nimport type { AudioProgressOptions } from \"../ports/options.js\";\n\n/** Bytes per decoded sample: sources are held as 32-bit floats (docs/adr/0004). */\nconst BYTES_PER_SAMPLE = 4;\n\n/**\n * Something the user should know about the recordings open, though they\n * opened (docs/adr/0004). Show its text from `warnings.<limit>`, or from\n * `warnings.truncated`, in the message catalogue, with its fields as\n * parameters.\n *\n * - `limit`: a value at or above a limit's warning threshold, but within its\n * maximum. `source` names the recording it's about, unless it's about the\n * whole session, as `maxSessionSize` and `maxClips` are.\n * - `truncated`: an uncompressed recording holds fewer frames than its\n * header declares, as after an interrupted recording or download. It\n * opened with the frames it holds.\n *\n * @public\n */\nexport type AudioWarning =\n | {\n readonly type: \"limit\";\n readonly limit: AudioLimitName;\n readonly actual: number;\n readonly source?: string;\n }\n | {\n readonly type: \"truncated\";\n readonly source: string;\n /** The frames the recording holds. */\n readonly frames: number;\n /** The frames its header declares. */\n readonly declaredFrames: number;\n };\n\n/**\n * A range of the timeline, in frames: `start` inclusive and `end`\n * exclusive, at least one frame long.\n *\n * @public\n */\nexport interface AudioSelection {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * What the session is doing.\n *\n * - `empty`: no recording is open.\n * - `opening`: a recording is being opened, replacing any other.\n * - `ready`: a recording is open.\n * - `error`: no recording is open, because the last open failed; `error`\n * says why. A failed open while a recording is open keeps it, with the\n * status `ready` and `error` set.\n *\n * @public\n */\nexport type AudioSessionStatus = \"empty\" | \"opening\" | \"ready\" | \"error\";\n\n/**\n * The session's state at one moment (docs/adr/0003). Snapshots are\n * immutable: every change makes a new one, so `useSyncExternalStore` and\n * other subscribers can compare them by identity. The playhead isn't here:\n * it belongs to `AudioOutput`, which moves it sixty times a second.\n *\n * @public\n */\nexport interface AudioSessionSnapshot {\n readonly status: AudioSessionStatus;\n /** The recording being edited, or `undefined` when none is open. */\n readonly plan: AudioPlan | undefined;\n /** The sources the session holds: those the plan uses, and those undo or redo can bring back. */\n readonly sources: readonly AudioSourceInfo[];\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n /**\n * Whether undo steps were dropped since the recording opened, to make\n * room for an insert within `maxSessionSize`. Editors say so, because the\n * earliest edits can no longer be undone (ADR 0010).\n */\n readonly historyTrimmed: boolean;\n /** Whether a recording is being opened or inserted. */\n readonly busy: boolean;\n /** Why the last open or insert failed. Show its text by its code. */\n readonly error: AudioError | undefined;\n readonly warnings: readonly AudioWarning[];\n /**\n * The decoded bytes of every source the session holds, which the\n * `maxSessionSize` limit counts: frames × channels × 4.\n */\n readonly sessionBytes: number;\n /** The selected range of the timeline. View state: not undoable, and never in events. */\n readonly selection: AudioSelection | undefined;\n}\n\n/**\n * Anonymous usage events, for a host's analytics (docs/adr/0003). They\n * never contain file names, samples or metadata values. Durations are in\n * seconds, rounded to two significant figures, such as 3,500 for 3,456.7,\n * so that an exact length can't fingerprint a recording.\n *\n * @public\n */\nexport type AudioSessionEvent =\n | ({ readonly type: \"recording_opened\" | \"recording_inserted\" } & AudioRecordingFacts)\n | {\n readonly type: \"recording_exported\";\n readonly durationSeconds: number;\n readonly sampleRate: number;\n readonly channels: number;\n readonly sampleFormat: AudioSampleFormat;\n }\n | { readonly type: \"recording_closed\" }\n | { readonly type: \"command\"; readonly commands: readonly AudioCommand[\"type\"][] }\n | { readonly type: \"undo\" }\n | { readonly type: \"redo\" }\n | {\n readonly type: \"failed\";\n readonly operation: \"open\" | \"insert\" | \"command\" | \"export\";\n readonly code: string;\n };\n\n/**\n * What an event says about a recording: its format and size, never its\n * name or contents.\n *\n * @public\n */\nexport interface AudioRecordingFacts {\n /** Rounded to two significant figures. */\n readonly durationSeconds: number;\n readonly sampleRate: number;\n readonly channels: number;\n readonly container: AudioSourceInfo[\"container\"];\n readonly codec: AudioSourceInfo[\"codec\"];\n readonly truncated: boolean;\n}\n\n/**\n * Options for {@link createAudioSession}.\n *\n * @public\n */\nexport interface AudioSessionOptions {\n /** Probes, decodes and builds waveform peaks, such as `createAudioEngine()`. */\n readonly engine: AudioEngine;\n /** Limits for untrusted files (docs/adr/0004). Unknown names throw. */\n readonly filePolicy?: AudioFilePolicyOverrides;\n /** Renders and encodes exports, such as `createAudioProcessor()`. Needed for `export()`. */\n readonly processor?: AudioProcessor;\n /** Receives anonymous usage events. Errors it throws are ignored. */\n readonly onEvent?: (event: AudioSessionEvent) => void;\n}\n\n/**\n * Options for {@link AudioSession.export}.\n *\n * @public\n */\nexport interface AudioSessionExportOptions extends AudioProgressOptions {\n /** The file to write. Defaults to 16-bit PCM WAV. */\n readonly format?: AudioExportFormat;\n}\n\n/**\n * Options for {@link AudioSession.insert}.\n *\n * @public\n */\nexport interface AudioInsertOptions extends AudioProgressOptions {\n /**\n * The timeline frame to insert at, splitting the clip there if it's inside\n * one. Defaults to the end.\n */\n readonly at?: number;\n}\n\n/**\n * The recording being edited, as a framework-agnostic store (ADR 0008,\n * ADR 0029): a clip plan over decoded sources, edited with commands, with\n * undo and redo (docs/adr/0003). React binds to it with\n * `useSyncExternalStore`, and the element binds to the same store.\n *\n * @public\n */\nexport interface AudioSession {\n /** The current snapshot, the same object until something changes. */\n getSnapshot(): AudioSessionSnapshot;\n /** Calls the listener after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /**\n * Opens a recording, replacing the current one and its history once it\n * has opened. The file is checked against the file policy before it's\n * read, and its probe before it's decoded. Rejects with an `AudioError`,\n * which the snapshot also holds; the current recording, if any, stays\n * open.\n */\n open(file: Blob, options?: AudioProgressOptions): Promise<void>;\n /**\n * Inserts another recording at a timeline frame, as one undoable step. It\n * must have the session's sample rate; resampling comes later. If the\n * sources held would then exceed `maxSessionSize`, the session first drops\n * history steps, in sdk-core's `dropOrder`, as far as needed to release\n * sources only they refer to, and sets `historyTrimmed`. If even that\n * isn't enough, it rejects with `SESSION_TOO_LARGE` and changes nothing.\n */\n insert(file: Blob, options?: AudioInsertOptions): Promise<void>;\n /**\n * Runs one command, or several as one undoable step. A command that\n * doesn't apply throws `AudioError` with `INVALID_COMMAND`, and one that\n * would exceed `maxClips` throws `TOO_MANY_CLIPS`; either changes\n * nothing. The commands are copied, so changing them afterwards has no\n * effect.\n */\n execute(commands: AudioCommand | readonly AudioCommand[]): void;\n /**\n * Runs `fn`, and records the commands it executes as one undoable step,\n * for gestures such as dragging a trim handle.\n */\n group<T>(fn: () => T): T;\n /**\n * A clip key no clip has, in the plan or the history, for commands that\n * create clips, such as `newKey` in `audio.splitClip`.\n */\n createKey(): string;\n undo(): void;\n redo(): void;\n /**\n * Selects a range of the timeline, clamped to the plan, or clears the\n * selection with `undefined`. An empty range clears it too.\n */\n select(range: AudioSelection | undefined): void;\n /** A source's waveform overview, or `undefined` for a source the session doesn't hold. */\n getPeaks(source: string): AudioPeaks | undefined;\n /**\n * Renders and encodes the plan as it is now, with the session's\n * `processor`, under `maxProcessingTime`. It returns the file, and never\n * downloads it: the host decides what to do with it. Edits made while it\n * runs don't change it. Rejects with `INVALID_COMMAND` and the reason\n * `no-recording` or `empty-plan` when there's nothing to export, and\n * throws `TypeError` when the session has no processor.\n */\n export(options?: AudioSessionExportOptions): Promise<Blob>;\n /** Closes the recording and releases its sources. */\n close(): Promise<void>;\n}\n\ninterface Source {\n readonly info: AudioSourceInfo;\n readonly audio: DecodedAudio;\n readonly peaks: AudioPeaks;\n readonly bytes: number;\n readonly warnings: readonly AudioWarning[];\n}\n\n/** The clips a command or its inverse carries, which keep their sources alive. */\nfunction clipsOf(command: AudioCommand): readonly AudioClip[] {\n switch (command.type) {\n case \"audio.insertClips\":\n case \"audio.replaceClips\":\n case \"audio.updateClips\":\n return command.clips;\n case \"audio.restoreClips\":\n return command.entries.map((entry) => entry.clip);\n default:\n return [];\n }\n}\n\n/**\n * A duration as events report it: two significant figures, so it describes\n * a recording's length without identifying the recording.\n */\nfunction coarseSeconds(seconds: number): number {\n return seconds > 0 ? Number(seconds.toPrecision(2)) : 0;\n}\n\n/** Every clip key a command names, created or referred to. */\nfunction keysOf(command: AudioCommand): string[] {\n const keys = clipsOf(command).map((clip) => clip.key);\n if (\"newKey\" in command && typeof command.newKey === \"string\") keys.push(command.newKey);\n if (\"splitKey\" in command && typeof command.splitKey === \"string\") keys.push(command.splitKey);\n return keys;\n}\n\n/**\n * Creates an {@link AudioSession}. Pass the engine to use; the headless core\n * doesn't choose one.\n *\n * @example\n * ```ts\n * const session = createAudioSession({ engine: createAudioEngine() });\n * await session.open(file);\n * const [clip] = session.getSnapshot().plan?.clips ?? [];\n * session.execute({ type: \"audio.setGain\", keys: [clip.key], gainDb: -3 });\n * session.undo();\n * ```\n *\n * @public\n */\nexport function createAudioSession(options: AudioSessionOptions): AudioSession {\n const { engine } = options;\n const policy = audioLimits.resolve(options.filePolicy);\n const history = createHistory<AudioCommand>();\n const sources = new Map<string, Source>();\n const reducer = createPlanReducer((id) => sources.get(id)?.info.frames);\n let plan: AudioPlan | undefined;\n let status: AudioSessionStatus = \"empty\";\n let error: AudioError | undefined;\n let busy = 0;\n let selection: AudioSelection | undefined;\n let nextKey = 0;\n let nextSource = 0;\n /** The loads in progress, which a newer open or a close cancels. */\n const loading = new Set<AbortController>();\n const cancelLoads = (message: string) => {\n for (const controller of loading) controller.abort(new AudioError(\"ABORTED\", message));\n };\n /**\n * Counts opens and closes. A load that finishes after another open or a\n * close changes nothing, and reports nothing: that one reports.\n */\n let generation = 0;\n const superseded = (since: number) =>\n since !== generation\n ? new AudioError(\"ABORTED\", \"The recording was closed or replaced.\")\n : undefined;\n\n const heldBytes = (): number => {\n let total = 0;\n for (const source of sources.values()) total += source.bytes;\n return total;\n };\n\n /** The sources the plan and the given history steps refer to. */\n function referenced(steps: readonly HistoryStep<AudioCommand>[]): Set<string> {\n const ids = new Set(plan?.clips.map((clip) => clip.source));\n for (const { commands, inverses } of steps) {\n for (const command of [...commands, ...inverses]) {\n for (const clip of clipsOf(command)) ids.add(clip.source);\n }\n }\n return ids;\n }\n\n /** Releases the sources nothing refers to any more. */\n function collect(): void {\n const keep = referenced(history.steps);\n for (const id of sources.keys()) if (!keep.has(id)) sources.delete(id);\n }\n\n /**\n * How many history steps must be dropped, in drop order, for the held\n * sources plus `extra` bytes to fit `maxSessionSize`, or `undefined` if\n * dropping every step isn't enough.\n */\n function stepsToDrop(extra: number): number | undefined {\n const { maximum } = policy.limits.maxSessionSize;\n const order = history.dropOrder;\n for (let count = 0; count <= order.length; count += 1) {\n const kept = new Set(order.slice(count));\n const ids = referenced(history.steps.filter((entry) => kept.has(entry)));\n let total = extra;\n for (const id of ids) total += sources.get(id)?.bytes ?? 0;\n if (total <= maximum) return count;\n }\n return undefined;\n }\n\n /** The sources' own warnings, and the session's, which follow every change. */\n function sessionWarnings(): AudioWarning[] {\n const found = [...sources.values()].flatMap((source) => source.warnings);\n const bytes = heldBytes();\n if (bytes > 0 && bytes >= policy.limits.maxSessionSize.warning) {\n found.push({ type: \"limit\", limit: \"maxSessionSize\", actual: bytes });\n }\n const clips = plan?.clips.length ?? 0;\n if (clips > 0 && clips >= policy.limits.maxClips.warning) {\n found.push({ type: \"limit\", limit: \"maxClips\", actual: clips });\n }\n return found;\n }\n\n function makeSnapshot(): AudioSessionSnapshot {\n return Object.freeze({\n status,\n plan,\n sources: Object.freeze([...sources.values()].map((source) => source.info)),\n canUndo: history.canUndo,\n canRedo: history.canRedo,\n historyTrimmed: history.trimmed,\n busy: busy > 0,\n error,\n warnings: Object.freeze(sessionWarnings()),\n sessionBytes: heldBytes(),\n selection,\n });\n }\n\n const store = createStore<AudioSessionSnapshot>(makeSnapshot());\n\n function changed(): void {\n // The selection follows the plan: it can't reach past its end.\n if (selection) {\n const end = Math.min(selection.end, plan ? planLength(plan) : 0);\n selection = selection.start < end ? { start: selection.start, end } : undefined;\n }\n store.set(makeSnapshot());\n }\n\n function emit(event: AudioSessionEvent): void {\n try {\n options.onEvent?.(event);\n } catch {\n // A host's analytics must never break editing.\n }\n }\n\n function facts(source: Source): AudioRecordingFacts {\n const { info } = source;\n return {\n durationSeconds: coarseSeconds(framesToSeconds(info.frames, info.sampleRate)),\n sampleRate: info.sampleRate,\n channels: info.channels,\n container: info.container,\n codec: info.codec,\n truncated: source.warnings.some((warning) => warning.type === \"truncated\"),\n };\n }\n\n /**\n * Checks, probes, decodes and builds the peaks of one file, without\n * registering it. Every limit but the session's is checked here, and all\n * but the session size before decoding (docs/adr/0004).\n */\n async function load(\n file: Blob,\n signal: AbortSignal,\n onProgress: ((fraction: number) => void) | undefined,\n beforeDecode: (probe: AudioProbe) => void,\n ): Promise<Source> {\n if (!(file instanceof Blob)) throw new TypeError(\"A recording must be a Blob or a File.\");\n nextSource += 1;\n const id = `s${nextSource}`;\n const warnings: AudioWarning[] = [];\n const warnAt = (limit: AudioLimitName, actual: number) => {\n if (policy.check(limit, actual) === \"warning\") {\n warnings.push({ type: \"limit\", limit, actual, source: id });\n }\n };\n // The file size, before anything is read (ADR 0020).\n if (checkFile(policy, file) === \"warning\") {\n warnings.push({ type: \"limit\", limit: \"maxFileSize\", actual: file.size, source: id });\n }\n const probe = await withProcessingTime(\n policy,\n (limited) => engine.probe(file, { signal: limited }),\n { signal },\n );\n // The probe's bound and channels are maxima, so these checks hold for\n // whatever the decoder returns.\n warnAt(\"maxChannels\", probe.channels);\n warnAt(\"maxSampleRate\", probe.sampleRate);\n warnAt(\"maxDuration\", Math.ceil((probe.frameBound * 1_000) / probe.sampleRate));\n warnAt(\"maxDecodedSize\", probe.frameBound * probe.channels * BYTES_PER_SAMPLE);\n beforeDecode(probe);\n const audio = await withProcessingTime(\n policy,\n (limited) =>\n engine.decode(file, probe, { signal: limited, ...(onProgress ? { onProgress } : {}) }),\n { signal },\n );\n // The source is what the decoder returned, capped at the bound, with the\n // decoder's own channel count: mono AAC probes as two channels\n // (docs/adr/0004).\n const frames = Math.min(audio.length, probe.frameBound);\n const channels = audio.numberOfChannels;\n if (audio.sampleRate !== probe.sampleRate || channels < 1 || channels > probe.channels) {\n throw new AudioError(\"INVALID_AUDIO\", \"The decoder's output doesn't match the probe.\", {\n details: { container: probe.container, codec: probe.codec },\n });\n }\n if (frames < 1) {\n throw new AudioError(\"DECODE_FAILED\", \"The recording decoded to no audio.\", {\n details: { codec: probe.codec },\n });\n }\n const peaks = await withProcessingTime(\n policy,\n (limited) => engine.peaks(audio, { signal: limited }),\n { signal },\n );\n throwIfAborted(signal);\n if (probe.declaredFrames !== undefined && probe.declaredFrames > frames) {\n warnings.push({\n type: \"truncated\",\n source: id,\n frames,\n declaredFrames: probe.declaredFrames,\n });\n }\n return {\n info: Object.freeze({\n id,\n sampleRate: audio.sampleRate,\n channels,\n frames,\n container: probe.container,\n codec: probe.codec,\n }),\n audio,\n peaks,\n bytes: frames * channels * BYTES_PER_SAMPLE,\n warnings: Object.freeze(warnings),\n };\n }\n\n /** Runs a load, marking the session busy, and cancelling it if a newer open starts. */\n async function track<Value>(\n signal: AbortSignal | undefined,\n replaces: boolean,\n run: (signal: AbortSignal) => Promise<Value>,\n ): Promise<Value> {\n if (replaces) cancelLoads(\"A newer recording replaced this one.\");\n const controller = new AbortController();\n loading.add(controller);\n const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;\n busy += 1;\n changed();\n try {\n return await run(combined);\n } finally {\n busy -= 1;\n loading.delete(controller);\n changed();\n }\n }\n\n /** Applies commands to the plan, checking `maxClips`, without committing anything. */\n function applyChecked(\n current: AudioPlan,\n commands: readonly AudioCommand[],\n ): { state: AudioPlan; inverses: AudioCommand[] } {\n const result = applyCommands(reducer, current, commands);\n if (result.state.clips.length > current.clips.length) {\n policy.check(\"maxClips\", result.state.clips.length);\n }\n return result;\n }\n\n function commit(\n result: { state: AudioPlan; inverses: AudioCommand[] },\n commands: AudioCommand[],\n ) {\n plan = result.state;\n history.push({ commands, inverses: result.inverses });\n // A new step drops the redo steps, and the sources only they held.\n collect();\n }\n\n function newKey(): string {\n const used = new Set(plan?.clips.map((clip) => clip.key));\n for (const { commands, inverses } of history.steps) {\n for (const command of [...commands, ...inverses])\n for (const key of keysOf(command)) used.add(key);\n }\n let key: string;\n do {\n nextKey += 1;\n key = `c${nextKey}`;\n } while (used.has(key));\n return key;\n }\n\n return {\n getSnapshot: store.getSnapshot,\n subscribe: store.subscribe,\n\n async open(file, callOptions = {}) {\n generation += 1;\n const started = generation;\n status = \"opening\";\n error = undefined;\n try {\n const source = await track(callOptions.signal, true, (signal) =>\n load(file, signal, callOptions.onProgress, () => {}),\n );\n const replaced = superseded(started);\n if (replaced) throw replaced;\n // The open recording is released once this one opens, so this one\n // must fit on its own.\n policy.check(\"maxSessionSize\", source.bytes);\n sources.clear();\n history.clear();\n sources.set(source.info.id, source);\n plan = {\n sampleRate: source.info.sampleRate,\n channels: source.info.channels,\n clips: [\n {\n key: newKey(),\n source: source.info.id,\n start: 0,\n end: source.info.frames,\n gainDb: 0,\n fadeIn: NO_FADE,\n fadeOut: NO_FADE,\n },\n ],\n metadata: EMPTY_METADATA,\n };\n selection = undefined;\n status = \"ready\";\n changed();\n emit({ type: \"recording_opened\", ...facts(source) });\n } catch (reason) {\n const failure = asAudioError(reason, \"The recording couldn't be opened.\");\n // A newer open replaced this one, or a close cancelled it; that\n // reports its own outcome.\n if (started !== generation) throw failure;\n // A failed open keeps the recording that was already open, and its\n // history, so a bad file never costs the user their work.\n status = plan ? \"ready\" : \"error\";\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"open\", code: failure.code });\n throw failure;\n }\n },\n\n async insert(file, insertOptions = {}) {\n if (!plan || status !== \"ready\") {\n throw new AudioError(\"INVALID_COMMAND\", \"Open a recording before inserting another.\", {\n details: { reason: \"no-recording\" },\n });\n }\n const started = generation;\n error = undefined;\n try {\n const source = await track(insertOptions.signal, false, (signal) => {\n policy.check(\"maxFiles\", sources.size + 1);\n return load(file, signal, insertOptions.onProgress, (probe) => {\n const rate = plan?.sampleRate;\n if (probe.sampleRate !== rate) {\n throw new AudioError(\n \"UNSUPPORTED_FORMAT\",\n `Recordings at ${probe.sampleRate} Hz can't be inserted into a ${rate} Hz session yet.`,\n { details: { sampleRate: probe.sampleRate } },\n );\n }\n });\n });\n const replaced = superseded(started);\n if (replaced) throw replaced;\n const current = plan as AudioPlan;\n // Everything that can fail happens before anything changes.\n const drop = stepsToDrop(source.bytes);\n if (drop === undefined) throw policy.error(\"maxSessionSize\", heldBytes() + source.bytes);\n const commands: AudioCommand[] = [\n {\n type: \"audio.insertClips\",\n at: insertOptions.at ?? planLength(current),\n clips: [\n {\n key: newKey(),\n source: source.info.id,\n start: 0,\n end: source.info.frames,\n gainDb: 0,\n fadeIn: NO_FADE,\n fadeOut: NO_FADE,\n },\n ],\n splitKey: newKey(),\n },\n ];\n sources.set(source.info.id, source);\n let result: ReturnType<typeof applyChecked>;\n try {\n result = applyChecked(current, commands);\n } catch (reason) {\n sources.delete(source.info.id);\n throw reason;\n }\n history.drop(drop);\n commit(result, commands);\n changed();\n emit({ type: \"recording_inserted\", ...facts(source) });\n } catch (reason) {\n const failure = asAudioError(reason, \"The recording couldn't be inserted.\");\n if (started !== generation) throw failure;\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"insert\", code: failure.code });\n throw failure;\n }\n },\n\n execute(commands) {\n const list: AudioCommand[] = Array.isArray(commands)\n ? [...(commands as readonly AudioCommand[])]\n : [commands as AudioCommand];\n if (list.length === 0) return;\n try {\n if (!plan) {\n throw new AudioError(\"INVALID_COMMAND\", \"Open a recording before editing it.\", {\n details: { reason: \"no-recording\" },\n });\n }\n let copies: AudioCommand[];\n try {\n // The history keeps its own copies, which also proves they're\n // plain, serialisable data (ADR 0010).\n copies = structuredClone(list);\n } catch (reason) {\n throw new AudioError(\"INVALID_COMMAND\", \"Commands must be plain data.\", {\n cause: reason,\n details: { reason: \"not-plain-data\" },\n });\n }\n commit(applyChecked(plan, copies), copies);\n } catch (reason) {\n const failure = asAudioError(reason);\n emit({ type: \"failed\", operation: \"command\", code: failure.code });\n throw failure;\n }\n changed();\n emit({ type: \"command\", commands: list.map((command) => command.type) });\n },\n\n group: (fn) => history.group(fn),\n\n createKey: newKey,\n\n undo() {\n const current = plan;\n const entry = current && history.undo();\n if (!current || !entry) return;\n try {\n plan = applyCommands(reducer, current, entry.inverses).state;\n } catch (reason) {\n history.restore(\"undo\");\n throw reason;\n }\n changed();\n emit({ type: \"undo\" });\n },\n\n redo() {\n const current = plan;\n const entry = current && history.redo();\n if (!current || !entry) return;\n try {\n plan = applyCommands(reducer, current, entry.commands).state;\n } catch (reason) {\n history.restore(\"redo\");\n throw reason;\n }\n changed();\n emit({ type: \"redo\" });\n },\n\n select(range) {\n let next: AudioSelection | undefined;\n if (range) {\n const { start, end } = range;\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {\n throw new RangeError(\"A selection is a range of whole frames.\");\n }\n const length = plan ? planLength(plan) : 0;\n const from = Math.max(0, Math.min(start, end, length));\n const to = Math.min(length, Math.max(start, end, 0));\n next = from < to ? { start: from, end: to } : undefined;\n }\n if (next?.start === selection?.start && next?.end === selection?.end) return;\n selection = next;\n changed();\n },\n\n getPeaks: (id) => sources.get(id)?.peaks,\n\n async export(exportOptions = {}) {\n const current = plan;\n const format: AudioExportFormat = exportOptions.format ?? { container: \"wav\" };\n try {\n if (!current) {\n throw new AudioError(\"INVALID_COMMAND\", \"Open a recording before exporting it.\", {\n details: { reason: \"no-recording\" },\n });\n }\n if (current.clips.length === 0) {\n throw new AudioError(\"INVALID_COMMAND\", \"The recording has no clips to export.\", {\n details: { reason: \"empty-plan\" },\n });\n }\n const { processor } = options;\n if (!processor) throw new TypeError(\"Exporting needs a processor in createAudioSession.\");\n // The sources as they are now: an edit or a close during the export\n // can't change what it renders.\n const used = new Map<string, DecodedAudio>();\n for (const { source } of current.clips) {\n const held = sources.get(source);\n if (held) used.set(source, held.audio);\n }\n busy += 1;\n changed();\n try {\n const output = await withProcessingTime(\n policy,\n (signal) =>\n processor.render(\n { plan: current, sources: used, format },\n {\n signal,\n ...(exportOptions.onProgress ? { onProgress: exportOptions.onProgress } : {}),\n },\n ),\n exportOptions.signal ? { signal: exportOptions.signal } : {},\n );\n emit({\n type: \"recording_exported\",\n durationSeconds: coarseSeconds(\n framesToSeconds(planLength(current), current.sampleRate),\n ),\n sampleRate: current.sampleRate,\n channels: current.channels,\n sampleFormat: format.sampleFormat ?? \"pcm16\",\n });\n return output;\n } finally {\n busy -= 1;\n changed();\n }\n } catch (reason) {\n if (reason instanceof TypeError || reason instanceof RangeError) throw reason;\n // Whatever a processor rejects with once the caller has aborted, the\n // export was cancelled.\n const failure = exportOptions.signal?.aborted\n ? abortError(exportOptions.signal)\n : asAudioError(reason, \"The recording couldn't be exported.\");\n emit({ type: \"failed\", operation: \"export\", code: failure.code });\n throw failure;\n }\n },\n\n async close() {\n generation += 1;\n cancelLoads(\"The recording was closed.\");\n const hadRecording = plan !== undefined;\n sources.clear();\n history.clear();\n plan = undefined;\n selection = undefined;\n error = undefined;\n status = \"empty\";\n changed();\n if (hadRecording) emit({ type: \"recording_closed\" });\n },\n };\n}\n","import { defineMessages, type MessageValue, plural, sdkCoreMessages } from \"@hussmartinez/sdk-core\";\nimport type { AudioErrorCode } from \"../core/errors/audio-error.js\";\nimport type { AudioLimitName } from \"../core/errors/audio-limits.js\";\n\n/**\n * The audio SDK's English message catalogue: sdk-core's messages, and text\n * for every {@link AudioErrorCode} and every limit's warning. Pass it to\n * `createMessages` from `@hussmartinez/sdk-core`, with the host's locale and\n * overrides. The editor's text joins it as the editor arrives.\n *\n * Error text is looked up by code, with the error's `details` as\n * parameters, and never taken from `error.message` (ADR 0019).\n *\n * @example\n * ```ts\n * const messages = createMessages(audioMessages, { locale: \"en\", overrides: props.messages });\n * messages.error(error); // \"This recording has 12 channels, which is over the 8-channel limit.\"\n * messages.t(\"warnings.maxSessionSize\", { actual: 800e6 });\n * ```\n *\n * @public\n */\nexport const audioMessages = /* @__PURE__ */ defineMessages({\n ...sdkCoreMessages,\n \"errors.INVALID_AUDIO\": \"This file isn't valid audio, or it's too damaged to open.\",\n \"errors.UNSUPPORTED_FORMAT\":\n \"This audio format isn't supported. Try converting the file to WAV, then open it again.\",\n \"errors.DECODE_FAILED\":\n \"This browser can't play this kind of audio. Try another browser, or convert the file to WAV.\",\n \"errors.INVALID_COMMAND\": \"This edit couldn't be made. Please try again.\",\n \"errors.INVALID_DOCUMENT\": \"This project is damaged, or it isn't an audio project.\",\n \"errors.DURATION_TOO_LONG\":\n \"This recording is {actual, duration} long, which is over the {maximum, duration} limit.\",\n \"errors.TOO_MANY_CHANNELS\":\n \"This recording has {actual, number} channels, which is over the {maximum, number}-channel limit.\",\n \"errors.SAMPLE_RATE_TOO_HIGH\":\n \"This recording's sample rate is {actual, number} Hz, which is over the {maximum, number} Hz limit.\",\n \"errors.SESSION_TOO_LARGE\":\n \"The open recordings would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Remove a recording, or clear the undo history, and try again.\",\n \"errors.TOO_MANY_CLIPS\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"A recording can have {maximum} clip. Join or delete clips, and try again.\",\n other: \"A recording can have up to {maximum} clips. Join or delete clips, and try again.\",\n }),\n \"warnings.maxDuration\":\n \"This recording is {actual, duration} long, and may be slow to open and edit.\",\n \"warnings.maxChannels\": \"This recording has {actual, number} channels, and may be slow to edit.\",\n \"warnings.maxSampleRate\":\n \"This recording's sample rate is {actual, number} Hz, and it may be slow to edit.\",\n \"warnings.maxSessionSize\":\n \"The open recordings use {actual, fileSize} of memory. Clearing the undo history frees memory.\",\n \"warnings.maxClips\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This recording has {actual} clip. Many clips may be slow to play and export.\",\n other: \"This recording has {actual} clips. Many clips may be slow to play and export.\",\n }),\n \"warnings.truncated\":\n \"This recording looks incomplete, perhaps from an interrupted recording or download. It opened with the audio it holds.\",\n}) satisfies Record<`errors.${AudioErrorCode}`, MessageValue> &\n Record<`warnings.${AudioLimitName}` | \"warnings.truncated\", MessageValue>;\n\n/**\n * The type of {@link audioMessages}, for typing a host's overrides with\n * `MessageOverrides<AudioMessageCatalogue>`.\n *\n * @public\n */\nexport type AudioMessageCatalogue = typeof audioMessages;\n"],"mappings":";;AAiEA,IAAa,aAAb,cAAgC,SAAyB;CAEvD,OAAyB;AAC3B;AAcA,SAAgB,aACd,OACA,MAC+C;CAC/C,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,SAAS;AACnD;;ACpEA,IAAa,EACX,OAAO,cACP,YACA,mBACkB,mCAAmB,YAAY;CACjD,cAAc;CACd,iBAAiB;AACnB,CAAC;;ACTD,SAAgB,kBAAkB,WAAwD;CACxF,MAAM,aACJ,cAAc,KAAA,IACV,KAAA,IACA,IAAI,IAAI,yBAAyB,kBAAkB,SAAS,CAAC,CAAC,CAAC;CACrE,OAAO;EACL,YAAY,aACR,kBAAkB,IAAI,OAAO,YAAY;GAAE,MAAM;GAAU,MAAM;EAAW,CAAC,IAC7E,aAAa,MAAM,OAAO,oCAAA,CAAuB;EACrD,SAAA;EACA,GAAI,aAAa,EAAE,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AAM,QAAQ;IAAK,CAAC;IAChE,MAAM;GACR;EACF;EAEA,MAAM,QAAQ;GACZ,cAAc;GACd,YAAY,2BAA2B;GACvC,MAAM,eAAe,SAAS,KAAA;GAC9B,QAAQ,MAAM;GACd,QAAQ,MAAM;GACd,OAAO,KAAA;GACP,YAAY,KAAA;GACZ,QAAQ,KAAA;GACR,SAAS;GACT,QAAQ;GACR,IAAI,cAAc,KAAK,EAAE,MAAM,mBAAmB,CAAC;EACrD;CACF;AACF;;ACt2BA,IAAa,gBAAgC,+BAAe;CAC1D,GAAG;CACH,wBAAwB;CACxB,6BACE;CACF,wBACE;CACF,0BAA0B;CAC1B,2BAA2B;CAC3B,4BACE;CACF,4BACE;CACF,+BACE;CACF,4BACE;CACF,yBAAyC,uBAAO,WAAW;EACzD,KAAK;EACL,OAAO;CACT,CAAC;CACD,wBACE;CACF,wBAAwB;CACxB,0BACE;CACF,2BACE;CACF,qBAAqC,uBAAO,UAAU;EACpD,KAAK;EACL,OAAO;CACT,CAAC;CACD,sBACE;AACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["isWhole","isFrames","keysOf","DOCUMENT_FIELDS","catalogue"],"sources":["../src/core/errors/audio-error.ts","../src/core/errors/abort.ts","../src/adapters/audio-worker/loader.ts","../src/adapters/peaks.ts","../src/adapters/resample/resample.ts","../src/adapters/web-audio/platform-decode.ts","../src/adapters/audio-engine.ts","../src/core/model/plan.ts","../src/core/model/envelope.ts","../src/adapters/web-audio/gain-automation.ts","../src/adapters/web-audio/play-graph.ts","../src/adapters/audio-output.ts","../src/core/model/mix.ts","../src/adapters/wav/wav-writer.ts","../src/adapters/audio-processor.ts","../src/adapters/audio-adapters.ts","../src/core/errors/audio-limits.ts","../src/core/operations/checks.ts","../src/core/format/document-parts.ts","../src/core/operations/commands.ts","../src/core/format/version-1.ts","../src/core/format/plan-document.ts","../src/core/model/peaks.ts","../src/core/model/source.ts","../src/core/model/time.ts","../src/core/session/connect-output.ts","../src/core/session/source-name.ts","../src/core/session/session.ts","../src/core/session/watch-playhead.ts","../src/messages/en.ts","../src/messages/text.ts"],"sourcesContent":["import { isSdkError, type SdkCoreErrorCode, SdkError } from \"@hussmartinez/sdk-core\";\n\n/**\n * Error codes of `@hussmartinez/audio-sdk`: sdk-core's own codes, such as\n * `ABORTED`, `WORKER_CRASHED` and `FILE_TOO_LARGE`, plus the audio SDK's\n * (ADR 0004). They never change meaning once released.\n *\n * - `INVALID_AUDIO`: the file is malformed, its headers claim more audio than\n * its packets carry, or it decodes to more than its bound allows.\n * - `UNSUPPORTED_FORMAT`: the container or codec isn't recognised, the file's\n * packets can't be walked to a bound, or the browser can't decode at its\n * sample rate.\n * - `DECODE_FAILED`: the browser couldn't decode a file the SDK probed,\n * usually because it lacks the codec. `details.codec` names it.\n * - `INVALID_COMMAND`: an edit command doesn't apply to the clip plan, such\n * as a range outside its source or an unknown clip key.\n * - `INVALID_DOCUMENT`: a plan document, such as a saved project, isn't\n * valid in its format.\n * - `DURATION_TOO_LONG`: a file, or the plan an edit would give, exceeds the\n * `maxDuration` limit.\n * - `TOO_MANY_CHANNELS`: a file exceeds the `maxChannels` limit.\n * - `SAMPLE_RATE_TOO_HIGH`: a file exceeds the `maxSampleRate` limit.\n * - `SESSION_TOO_LARGE`: the decoded audio the session holds exceeds the\n * `maxSessionSize` limit.\n * - `TOO_MANY_CLIPS`: the plan exceeds the `maxClips` limit, over all its\n * tracks.\n * - `TOO_MANY_TRACKS`: the plan exceeds the `maxTracks` limit.\n *\n * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`\n * value and the `unit`. Other codes' `details` name the container, codec or\n * sample rate involved, never data from the file.\n *\n * @public\n */\nexport type AudioErrorCode =\n | SdkCoreErrorCode\n | \"INVALID_AUDIO\"\n | \"UNSUPPORTED_FORMAT\"\n | \"DECODE_FAILED\"\n | \"INVALID_COMMAND\"\n | \"INVALID_DOCUMENT\"\n | \"DURATION_TOO_LONG\"\n | \"TOO_MANY_CHANNELS\"\n | \"SAMPLE_RATE_TOO_HIGH\"\n | \"SESSION_TOO_LARGE\"\n | \"TOO_MANY_CLIPS\"\n | \"TOO_MANY_TRACKS\";\n\n/**\n * The error `@hussmartinez/audio-sdk` throws and rejects with, with a stable\n * `code`, structured `details` and the underlying error as `cause`. Show\n * users the text for its code from {@link audioMessages}, never its\n * `message`, which is for developers and may contain text from the file.\n *\n * @example\n * ```ts\n * try {\n * await session.open(file);\n * } catch (error) {\n * if (isAudioError(error, \"DECODE_FAILED\")) {\n * suggestConvertingToWav();\n * } else {\n * show(messages.error(error));\n * }\n * }\n * ```\n *\n * @public\n */\nexport class AudioError extends SdkError<AudioErrorCode> {\n /** Always `\"AudioError\"`, which survives minification and worker boundaries. */\n override readonly name = \"AudioError\";\n}\n\n/**\n * Checks whether a value is an {@link AudioError}, optionally with a given\n * code.\n *\n * Unlike `instanceof`, it recognises errors from another copy of this\n * package or another realm, and errors rebuilt after crossing a worker\n * boundary.\n *\n * @param value - Any thrown value.\n * @param code - When given, the error must also have this code.\n * @public\n */\nexport function isAudioError<Code extends AudioErrorCode = AudioErrorCode>(\n value: unknown,\n code?: Code,\n): value is AudioError & { readonly code: Code } {\n return isSdkError(value, code) && value.name === \"AudioError\";\n}\n","import { createErrorHelpers } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"./audio-error.js\";\n\n/**\n * The audio SDK's error helpers, from sdk-core's `createErrorHelpers`, so\n * every SDK adapts failures and aborts the same way (ADR 0018, ADR 0020).\n *\n * - `asAudioError`: makes any failure an `AudioError`, as every port\n * promises. Another `SdkError`, such as the worker client's `ABORTED` or\n * `WORKER_CRASHED`, keeps its code, details and message, and anything else\n * becomes `UNKNOWN`, with the original as `cause`.\n * - `abortError`: the error an aborted call rejects with: the reason itself\n * when it's an `SdkError`, such as the file policy's\n * `PROCESSING_TIME_EXCEEDED`, `TIMEOUT` for a timeout, and `ABORTED`\n * otherwise.\n * - `throwIfAborted`: throws `abortError` if the signal has been aborted.\n *\n * @internal\n */\nexport const {\n adapt: asAudioError,\n abortError,\n throwIfAborted,\n} = /* @__PURE__ */ createErrorHelpers(AudioError, {\n fallbackCode: \"UNKNOWN\",\n fallbackMessage: \"Audio processing failed.\",\n});\n","import { resolveAssetsBase, type WorkerLike } from \"@hussmartinez/sdk-core\";\n\n/** Where the audio worker comes from, and the version it must announce. */\nexport interface AudioWorkerSource {\n /** Loads the worker's code, on the first call, and returns how to start it. */\n readonly loadWorker: () => Promise<() => WorkerLike>;\n /** The version the worker must announce: this package's (sdk-core ADR 0038). */\n readonly version: string;\n /** Where the worker comes from, for the version error's details. */\n readonly asset?: string;\n}\n\n/**\n * The audio worker, inlined by default or self-hosted under `assetsUrl`\n * (docs/adr/0002). The engine and the processor each start their own from\n * it.\n */\nexport function audioWorkerSource(assetsUrl: string | URL | undefined): AudioWorkerSource {\n const selfHosted =\n assetsUrl === undefined\n ? undefined\n : new URL(\"audio/audio.worker.js\", resolveAssetsBase(assetsUrl)).href;\n return {\n loadWorker: selfHosted\n ? async () => () => new Worker(selfHosted, { type: \"module\", name: \"hm-audio\" })\n : async () => (await import(\"./inline-worker.js\")).createInlineWorker,\n version: __AUDIO_SDK_VERSION__,\n ...(selfHosted ? { asset: selfHosted } : {}),\n };\n}\n","import type { AudioPeakLevel, AudioPeaks } from \"../core/model/source.js\";\n\n/**\n * Frames per bucket at the finest level of a waveform overview. Each coarser\n * level groups four buckets of the one before (docs/adr/0002).\n *\n * @internal\n */\nexport const FINEST_BUCKET = 256;\n\n/** How many buckets each coarser level combines. */\nconst LEVEL_FACTOR = 4;\n\n/** Each channel's minimum and maximum per bucket. */\nexport interface BucketPeaks {\n readonly min: Float32Array[];\n readonly max: Float32Array[];\n}\n\n/**\n * The minimum and maximum of each bucket of `bucket` frames, per channel.\n * Called on a block whose first frame starts a bucket; a last, shorter\n * bucket covers what's left.\n *\n * @internal\n */\nexport function blockPeaks(channels: readonly Float32Array[], bucket: number): BucketPeaks {\n const min: Float32Array[] = [];\n const max: Float32Array[] = [];\n for (const samples of channels) {\n const count = Math.ceil(samples.length / bucket);\n const low = new Float32Array(count);\n const high = new Float32Array(count);\n for (let b = 0; b < count; b += 1) {\n const end = Math.min(samples.length, (b + 1) * bucket);\n let lo = Number.POSITIVE_INFINITY;\n let hi = Number.NEGATIVE_INFINITY;\n for (let i = b * bucket; i < end; i += 1) {\n const sample = samples[i] as number;\n if (sample < lo) lo = sample;\n if (sample > hi) hi = sample;\n }\n low[b] = lo;\n high[b] = hi;\n }\n min.push(low);\n max.push(high);\n }\n return { min, max };\n}\n\n/**\n * Builds the whole pyramid from the finest level, each level combining four\n * buckets of the one before, until a level has one bucket.\n *\n * @internal\n */\nexport function buildPyramid(finest: BucketPeaks, bucket = FINEST_BUCKET): AudioPeaks {\n const levels: AudioPeakLevel[] = [];\n let current = finest;\n let framesPerBucket = bucket;\n for (;;) {\n levels.push({\n framesPerBucket,\n channels: current.min.map((min, c) => ({ min, max: current.max[c] as Float32Array })),\n });\n const count = current.min[0]?.length ?? 0;\n if (count <= 1) break;\n current = {\n min: current.min.map((values) => combine(values, Math.min)),\n max: current.max.map((values) => combine(values, Math.max)),\n };\n framesPerBucket *= LEVEL_FACTOR;\n }\n return { levels };\n}\n\nfunction combine(values: Float32Array, pick: (a: number, b: number) => number): Float32Array {\n const out = new Float32Array(Math.ceil(values.length / LEVEL_FACTOR));\n for (let i = 0; i < out.length; i += 1) {\n let value = values[i * LEVEL_FACTOR] as number;\n const end = Math.min(values.length, (i + 1) * LEVEL_FACTOR);\n for (let j = i * LEVEL_FACTOR + 1; j < end; j += 1) value = pick(value, values[j] as number);\n out[i] = value;\n }\n return out;\n}\n","/**\n * Sample-rate conversion with a windowed sinc (docs/adr/0006): band-limited\n * interpolation, so that a source at another rate keeps its pitch and length\n * in the session, without the aliasing that picking or averaging samples\n * leaves.\n *\n * It runs in the worker, block by block. It's our own, not Web Audio's,\n * because the browsers' resamplers differ from each other, can't report\n * progress and can't be cancelled; this one gives the same samples in every\n * engine, whatever the blocks.\n */\n\n/** Zero crossings of the sinc on each side of its centre. More is sharper and slower. */\nconst ZERO_CROSSINGS = 16;\n\n/** Table entries per zero crossing. The filter is read between them linearly. */\nconst TABLE_RESOLUTION = 512;\n\n/** The Kaiser window's shape: about 90 dB of stop-band attenuation. */\nconst KAISER_BETA = 9;\n\n/**\n * How much of the band below the lower Nyquist frequency passes: the rest is\n * the filter's transition, kept below Nyquist so nothing aliases.\n */\nconst PASS_BAND = 0.945;\n\n/** The zeroth-order modified Bessel function of the first kind, by its power series. */\nfunction bessel0(x: number): number {\n let sum = 1;\n let term = 1;\n const quarter = (x * x) / 4;\n for (let k = 1; term > sum * 1e-17; k += 1) {\n term *= quarter / (k * k);\n sum += term;\n }\n return sum;\n}\n\nlet table: Float64Array | undefined;\n\n/**\n * The windowed sinc from its centre to its last zero crossing, in units of\n * zero crossings, so one table serves every pair of rates.\n */\nfunction filterTable(): Float64Array {\n if (table) return table;\n const size = ZERO_CROSSINGS * TABLE_RESOLUTION;\n // One entry past the end, zero, so reading between entries never overruns.\n const built = new Float64Array(size + 2);\n const scale = bessel0(KAISER_BETA);\n for (let i = 0; i <= size; i += 1) {\n const u = i / TABLE_RESOLUTION;\n const sinc = i === 0 ? 1 : Math.sin(Math.PI * u) / (Math.PI * u);\n const position = u / ZERO_CROSSINGS;\n const window = bessel0(KAISER_BETA * Math.sqrt(Math.max(0, 1 - position * position))) / scale;\n built[i] = sinc * window;\n }\n built[size] = 0;\n table = built;\n return built;\n}\n\n/** Whether a value is a whole number of at least `least`. */\nconst isWhole = (value: number, least: number) => Number.isSafeInteger(value) && value >= least;\n\n/**\n * How many frames `frames` at `fromRate` become at `toRate`: enough to cover\n * the same time, rounded up.\n *\n * @internal\n */\nexport function resampledLength(frames: number, fromRate: number, toRate: number): number {\n if (!isWhole(frames, 0) || !isWhole(fromRate, 1) || !isWhole(toRate, 1)) {\n throw new RangeError(\"Frames and rates must be whole numbers, and rates positive.\");\n }\n const length = Math.ceil((frames * toRate) / fromRate);\n if (!Number.isSafeInteger(length)) throw new RangeError(\"The resampled length is too large.\");\n return length;\n}\n\n/**\n * How many input frames the filter reads on each side of an output frame's\n * position.\n *\n * @internal\n */\nexport function resampleReach(fromRate: number, toRate: number): number {\n return Math.ceil(ZERO_CROSSINGS / (Math.min(1, toRate / fromRate) * PASS_BAND));\n}\n\n/**\n * The input frames that the output frames `[start, start + frames)` read,\n * as `[first, end)`, clipped to an input of `inputFrames`.\n *\n * @internal\n */\nexport function resampleWindow(\n start: number,\n frames: number,\n fromRate: number,\n toRate: number,\n inputFrames: number,\n): { readonly first: number; readonly end: number } {\n const reach = resampleReach(fromRate, toRate);\n const clip = (frame: number) => Math.min(inputFrames, Math.max(0, frame));\n return {\n first: clip(Math.floor((start * fromRate) / toRate) - reach),\n end: clip(Math.floor(((start + frames - 1) * fromRate) / toRate) + reach + 1),\n };\n}\n\n/**\n * One block of a conversion: which output frames to compute, and the input\n * they need.\n *\n * @internal\n */\nexport interface ResampleBlockInput {\n /** The input samples of one channel, from the input frame `inputStart`. */\n readonly input: Float32Array;\n /** The input frame `input` begins at. Frames outside `input` count as silence. */\n readonly inputStart: number;\n readonly fromRate: number;\n readonly toRate: number;\n /** The first output frame to compute. */\n readonly start: number;\n /** How many output frames to compute. */\n readonly frames: number;\n}\n\n/**\n * Computes a run of output frames of one channel. Each frame depends only\n * on its own index and the input around it, so the result doesn't depend on\n * how the output is cut into blocks. Pass at least the input that\n * {@link resampleWindow} names; frames outside it are silence, as before\n * the recording's start and after its end.\n *\n * @internal\n */\nexport function resampleBlock(block: ResampleBlockInput): Float32Array<ArrayBuffer> {\n const { input, inputStart, fromRate, toRate, start, frames } = block;\n if (\n !isWhole(fromRate, 1) ||\n !isWhole(toRate, 1) ||\n !isWhole(start, 0) ||\n !isWhole(frames, 0) ||\n !isWhole(inputStart, 0) ||\n !Number.isSafeInteger((start + frames) * fromRate)\n ) {\n throw new RangeError(\"Rates and positions must be whole numbers, and rates positive.\");\n }\n const filter = filterTable();\n // Below 1 when the rate falls: the filter widens to cut what the lower\n // rate can't carry.\n const cutoff = Math.min(1, toRate / fromRate) * PASS_BAND;\n const reach = resampleReach(fromRate, toRate);\n const step = cutoff * TABLE_RESOLUTION;\n const taps = 2 * reach;\n const output = new Float32Array(frames);\n const available = input.length;\n\n // An output frame's place between two input frames is one of a few\n // phases, toRate / gcd of them, such as 160 from 44.1 to 48 kHz. Each\n // phase's weights are worked out once, the first time a frame needs them.\n const phases = toRate / gcd(fromRate, toRate);\n const phaseStep = toRate / phases;\n const rows: (Float64Array | undefined)[] = [];\n\n /** The weights of the input frames around a position, for one phase. They sum to 1. */\n const weightsOf = (phase: number): Float64Array => {\n const row = new Float64Array(taps);\n const fraction = phase / phases;\n let total = 0;\n for (let tap = 0; tap < taps; tap += 1) {\n // The tap's input frame is `tap - reach + 1` frames from the position's whole frame.\n const at = Math.abs(fraction - (tap - reach + 1)) * step;\n const index = Math.floor(at);\n if (index >= filter.length - 1) continue;\n const low = filter[index] as number;\n const weight = low + ((filter[index + 1] as number) - low) * (at - index);\n row[tap] = weight;\n total += weight;\n }\n // Every tap counts towards the gain, over silence or not, so a steady\n // signal keeps its level and the ends fade into the silence around them.\n for (let tap = 0; tap < taps; tap += 1) row[tap] = (row[tap] as number) / total;\n return row;\n };\n\n for (let n = 0; n < frames; n += 1) {\n // The output frame's position in the input, as a whole frame and a\n // remainder, in whole numbers so that it's exact.\n const scaled = (start + n) * fromRate;\n const whole = Math.floor(scaled / toRate);\n const phase = (scaled - whole * toRate) / phaseStep;\n let row = rows[phase];\n if (!row) {\n row = weightsOf(phase);\n rows[phase] = row;\n }\n // The first tap's input frame, as an index into `input`.\n const base = whole - reach + 1 - inputStart;\n const from = Math.max(0, -base);\n const to = Math.min(taps, available - base);\n let sum = 0;\n for (let tap = from; tap < to; tap += 1) {\n sum += (input[base + tap] as number) * (row[tap] as number);\n }\n output[n] = sum;\n }\n return output;\n}\n\n/** The greatest common divisor of two positive whole numbers. */\nfunction gcd(a: number, b: number): number {\n let [x, y] = [a, b];\n while (y !== 0) [x, y] = [y, x % y];\n return x;\n}\n","import { abortError, throwIfAborted } from \"../../core/errors/abort.js\";\nimport { AudioError, isAudioError } from \"../../core/errors/audio-error.js\";\nimport type { AudioProbe, DecodedAudio } from \"../../core/model/source.js\";\n\n/**\n * Decodes a file's bytes with a platform decoder, at the given rate and\n * channel count. The SDK's is Web Audio's; tests pass their own.\n *\n * @internal\n */\nexport type PlatformDecoder = (\n bytes: ArrayBuffer,\n format: { readonly sampleRate: number; readonly channels: number },\n) => Promise<DecodedAudio>;\n\n/** A buffer the decoded audio can be copied into, when it must be shortened. */\nexport type CreateBuffer = (options: {\n numberOfChannels: number;\n length: number;\n sampleRate: number;\n}) => DecodedAudio & {\n copyToChannel(source: Float32Array, channel: number, startInChannel: number): void;\n};\n\n/**\n * Web Audio's decoder: `decodeAudioData` on a fresh `OfflineAudioContext` at\n * the file's probed rate, so nothing is resampled (docs/adr/0001). It exists\n * only on the page.\n *\n * @internal\n */\nexport const webAudioDecoder: PlatformDecoder = (bytes, { sampleRate, channels }) => {\n const Offline = (globalThis as { OfflineAudioContext?: typeof OfflineAudioContext })\n .OfflineAudioContext;\n if (typeof Offline !== \"function\") {\n throw new AudioError(\"UNSUPPORTED_ENVIRONMENT\", \"Web Audio isn't available.\", {\n details: { feature: \"OfflineAudioContext\" },\n });\n }\n let context: OfflineAudioContext;\n try {\n context = new Offline({ numberOfChannels: channels, length: 1, sampleRate });\n } catch (error) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", \"This browser can't decode at this rate.\", {\n details: { sampleRate },\n cause: error,\n });\n }\n return context.decodeAudioData(bytes);\n};\n\n/** Settles with the decode, or rejects as soon as the signal aborts. */\nfunction untilAborted<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n // A result that arrives after an abort is dropped, and so is a late\n // failure, which would otherwise be reported as unhandled.\n work.catch(() => {});\n if (!signal) return work;\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n work.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\n/**\n * Decodes a probed compressed file on the page, under sdk-core ADR 0031's\n * rules for platform decoders that only run there:\n *\n * - **Only probed files:** the caller passes the probe that walked this\n * file's packets, and the limits have been checked against its bound.\n * - **A fresh buffer:** the decoder gets bytes read from the `Blob` for it,\n * which it may detach; no caller-owned buffer is ever handed over.\n * - **The output is checked against the bound:** a different rate, more\n * channels than the probe allows, or more frames than the bound plus the\n * codec's tolerance,\n * fails with `INVALID_AUDIO`, and the output is discarded. A result within\n * the tolerance but past the bound is shortened to the bound.\n * - **Never the decoder's errors:** a failure becomes `DECODE_FAILED`, with\n * `details` naming the container and codec, never the browser's message,\n * which is kept only as the error's `cause`.\n * - **The time limit:** a page-side decode can't be terminated, so when the\n * signal aborts, as `maxProcessingTime` does, it stops waiting and rejects\n * with the abort's code, such as `PROCESSING_TIME_EXCEEDED`; the result is\n * discarded whenever it arrives.\n *\n * @internal\n */\nexport async function decodeOnPage(\n file: Blob,\n probe: AudioProbe,\n decoder: PlatformDecoder,\n createBuffer: CreateBuffer,\n signal?: AbortSignal,\n): Promise<DecodedAudio> {\n const { container, codec, sampleRate, channels, frameBound, frameTolerance } = probe;\n throwIfAborted(signal);\n const bytes = await untilAborted(file.arrayBuffer(), signal);\n\n let decoded: DecodedAudio;\n try {\n decoded = await untilAborted(\n Promise.resolve().then(() => decoder(bytes, { sampleRate, channels })),\n signal,\n );\n } catch (error) {\n if (isAudioError(error)) throw error;\n throw new AudioError(\"DECODE_FAILED\", \"The browser couldn't decode this file.\", {\n details: { container, codec },\n cause: error,\n });\n }\n\n // A decoder that \"succeeds\" with no audio, as WebKit does on some crafted\n // Opus, hasn't decoded the file.\n if (decoded.length === 0) {\n throw new AudioError(\"DECODE_FAILED\", \"The browser decoded no audio from this file.\", {\n details: { container, codec, reason: \"no audio decoded\" },\n });\n }\n\n const invalid = (reason: string) =>\n new AudioError(\"INVALID_AUDIO\", `The decoded audio ${reason}.`, {\n details: { container, codec, reason: `decoded ${reason}` },\n });\n if (decoded.sampleRate !== sampleRate) throw invalid(\"rate differs from the probe\");\n // The probe allows for the most channels a decoder may output, such as\n // stereo for mono AAC that may carry parametric stereo; fewer is fine.\n if (decoded.numberOfChannels > channels) throw invalid(\"channel count exceeds the probe\");\n if (decoded.length > frameBound + frameTolerance) throw invalid(\"length exceeds the bound\");\n if (decoded.length <= frameBound) return decoded;\n\n // Within the tolerance but past the bound: the source is the bound's length.\n const capped = createBuffer({\n numberOfChannels: decoded.numberOfChannels,\n length: frameBound,\n sampleRate,\n });\n for (let c = 0; c < decoded.numberOfChannels; c += 1) {\n capped.copyToChannel(decoded.getChannelData(c).subarray(0, frameBound), c, 0);\n }\n return capped;\n}\n","import { createWorkerClient, type WorkerClient, type WorkerLike } from \"@hussmartinez/sdk-core\";\nimport { asAudioError, throwIfAborted } from \"../core/errors/abort.js\";\nimport { AudioError } from \"../core/errors/audio-error.js\";\nimport type { AudioPeaks, AudioProbe, DecodedAudio } from \"../core/model/source.js\";\nimport type { AudioEngine } from \"../core/ports/audio-engine.js\";\nimport type { AudioWorkerContract } from \"./audio-worker/contract.js\";\nimport { audioWorkerSource } from \"./audio-worker/loader.js\";\nimport type { PcmLayout } from \"./pcm/layout.js\";\nimport { type BucketPeaks, buildPyramid, FINEST_BUCKET } from \"./peaks.js\";\nimport { resampledLength, resampleReach, resampleWindow } from \"./resample/resample.js\";\nimport {\n decodeOnPage,\n type PlatformDecoder,\n webAudioDecoder,\n} from \"./web-audio/platform-decode.js\";\n\n/**\n * Frames per block between the page and the worker: at most 2¹⁶ per\n * channel (docs/adr/0002), and a whole number of finest peak buckets.\n */\nconst BLOCK_FRAMES = 65_536;\n\n/**\n * Options for {@link createAudioEngine}.\n *\n * @public\n */\nexport interface AudioEngineOptions {\n /**\n * Milliseconds without calls after which the worker stops. It starts again\n * on the next call. Defaults to sdk-core's 30 seconds.\n */\n readonly idleTimeout?: number;\n /**\n * Where the application serves the package's `dist/assets/` directory, to\n * load the worker from its own origin instead of a `blob:` URL. The worker\n * is then `audio/audio.worker.js` there, and a Content Security Policy\n * needs `worker-src 'self'` and no `blob:` (docs/adr/0002). Copy\n * `dist/assets` again after every upgrade: a worker from another version\n * is refused with `WORKER_START_FAILED`. By default the worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/** An `AudioBuffer`, or what tests use in its place. */\nexport interface WritableAudio extends DecodedAudio {\n copyToChannel(source: Float32Array, channel: number, startInChannel: number): void;\n}\n\n/** What the engine needs from its environment, replaceable in tests. */\nexport interface EngineEnvironment {\n /** Loads the worker's code, on the first call, and returns how to start it. */\n readonly loadWorker: () => Promise<() => WorkerLike>;\n /** Creates an empty buffer for a decoded source. Throws for a sample rate it can't hold. */\n readonly createBuffer: (options: {\n numberOfChannels: number;\n length: number;\n sampleRate: number;\n }) => WritableAudio;\n /** Decodes compressed files on the page (sdk-core ADR 0031). */\n readonly decodePlatform: PlatformDecoder;\n readonly idleTimeout?: number;\n /** The version the worker must announce: this package's (sdk-core ADR 0038). */\n readonly version: string;\n /** Where the worker comes from, for the version error's details. */\n readonly asset?: string;\n}\n\n/**\n * Creates the SDK's audio engine (docs/adr/0001, docs/adr/0002). It probes\n * files in its worker: WAV and AIFF, FLAC (native or in Ogg), MP3, AAC in\n * ADTS, AAC or ALAC in MP4, Opus or Vorbis in Ogg, and Opus, Vorbis, FLAC\n * or AAC in WebM and Matroska, walking every frame of a compressed file to\n * bound its decoded length. It parses WAV and AIFF block by block into an\n * `AudioBuffer`, building the waveform overview as it goes. It decodes\n * compressed files with the browser's own decoder, on the page, under\n * sdk-core ADR 0031's rules: only probed files, a fresh buffer, the output\n * checked against the probe's bound, errors by code, and the time limit of\n * the caller's signal. Other containers fail with `UNSUPPORTED_FORMAT`.\n *\n * Asked for another sample rate than a file's, it converts the decoded\n * audio in its worker, block by block, with a windowed sinc, so every\n * browser gives the same samples (docs/adr/0006).\n *\n * Nothing starts until the first call. By default the worker is inlined,\n * which needs `worker-src blob:` in a Content Security Policy; with\n * `assetsUrl` it loads from your own origin, which needs `worker-src 'self'`\n * instead. Either way it makes no requests of its own.\n *\n * @example\n * ```ts\n * const engine = createAudioEngine();\n * const probe = await engine.probe(file);\n * policy.check(\"maxDuration\", (probe.frameBound / probe.sampleRate) * 1000);\n * const audio = await engine.decode(file, probe, { onProgress });\n * ```\n *\n * @public\n */\nexport function createAudioEngine(options: AudioEngineOptions = {}): AudioEngine {\n return createEngine({\n ...audioWorkerSource(options.assetsUrl),\n createBuffer: (bufferOptions) => new AudioBuffer(bufferOptions),\n decodePlatform: webAudioDecoder,\n ...(options.idleTimeout === undefined ? {} : { idleTimeout: options.idleTimeout }),\n });\n}\n\n/**\n * The engine, with its environment passed in.\n *\n * @internal\n */\nexport function createEngine(environment: EngineEnvironment): AudioEngine {\n let startWorker: (() => WorkerLike) | undefined;\n let destroyed = false;\n const layouts = new WeakMap<AudioProbe, PcmLayout>();\n /** Probes of compressed files this engine made, which decode can trust. */\n const compressedProbes = new WeakSet<AudioProbe>();\n const finestPeaks = new WeakMap<DecodedAudio, BucketPeaks>();\n\n const newClient = () =>\n createWorkerClient<AudioWorkerContract>({\n createWorker: () => {\n if (!startWorker) {\n throw new AudioError(\"WORKER_START_FAILED\", \"The audio worker hasn't loaded.\");\n }\n return startWorker();\n },\n errorClasses: { AudioError },\n // A self-hosted worker copied before an upgrade would speak the same\n // protocol but run other code, so the worker must announce this\n // package's version, or it's refused with WORKER_START_FAILED.\n packageVersion: environment.version,\n ...(environment.asset === undefined ? {} : { workerAsset: environment.asset }),\n ...(environment.idleTimeout === undefined ? {} : { idleTimeout: environment.idleTimeout }),\n });\n // Probing, parsing and exports run in order on one client; analysis, such\n // as peaks for audio the worker didn't parse, on another, so cancelling it\n // never fails them as collateral (docs/adr/0002).\n let main: WorkerClient<AudioWorkerContract> | undefined;\n let analysis: WorkerClient<AudioWorkerContract> | undefined;\n\n async function ready(): Promise<void> {\n if (destroyed) throw new Error(\"The audio engine has been destroyed.\");\n startWorker ??= await environment.loadWorker();\n }\n\n async function run<T>(work: () => Promise<T>): Promise<T> {\n try {\n return await work();\n } catch (error) {\n throw error instanceof RangeError || error instanceof TypeError ? error : asAudioError(error);\n }\n }\n\n /**\n * Probes the file again for a probe this engine didn't make, such as a\n * copy, and requires it to describe the same audio: a decoder only ever\n * runs on a file whose bound this engine established (sdk-core ADR 0031).\n */\n async function reprobe(file: Blob, probe: AudioProbe, signal?: AbortSignal) {\n main ??= newClient();\n const fresh = await main.call(\"probe\", { file }, signal ? { signal } : {});\n const same =\n fresh.probe.codec === probe.codec &&\n fresh.probe.sampleRate === probe.sampleRate &&\n fresh.probe.channels === probe.channels &&\n fresh.probe.frameBound === probe.frameBound;\n if (!same) {\n throw new AudioError(\"INVALID_AUDIO\", \"The probe doesn't describe this file.\", {\n details: { container: probe.container },\n });\n }\n return fresh.probe;\n }\n\n async function layoutOf(file: Blob, probe: AudioProbe, signal?: AbortSignal) {\n const known = layouts.get(probe);\n if (known) return known;\n // A probe the caller rebuilt or copied: read the header again, and make\n // sure it describes the same audio.\n main ??= newClient();\n const fresh = await main.call(\"probe\", { file }, signal ? { signal } : {});\n const same =\n fresh.probe.sampleRate === probe.sampleRate &&\n fresh.probe.channels === probe.channels &&\n fresh.probe.frameBound === probe.frameBound;\n if (!same) {\n throw new AudioError(\"INVALID_AUDIO\", \"The probe doesn't describe this file.\", {\n details: { container: probe.container },\n });\n }\n if (!fresh.layout) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", \"Compressed formats aren't supported yet.\", {\n details: { container: probe.container, codec: probe.codec },\n });\n }\n return fresh.layout;\n }\n\n /** A buffer for decoded audio, or `UNSUPPORTED_FORMAT` for a rate the browser can't hold. */\n function bufferFor(\n numberOfChannels: number,\n length: number,\n sampleRate: number,\n container: AudioProbe[\"container\"],\n ): WritableAudio {\n try {\n return environment.createBuffer({ numberOfChannels, length, sampleRate });\n } catch (error) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", \"This browser can't hold audio at this rate.\", {\n details: { container, sampleRate },\n cause: error,\n });\n }\n }\n\n /**\n * Converts decoded audio to another sample rate, in the worker\n * (docs/adr/0006). Each block carries the input its output frames read,\n * at most a block's worth, copied so the source is never transferred away.\n */\n async function resample(\n audio: DecodedAudio,\n toRate: number,\n container: AudioProbe[\"container\"],\n signal: AbortSignal | undefined,\n onProgress: ((fraction: number) => void) | undefined,\n ): Promise<DecodedAudio> {\n const fromRate = audio.sampleRate;\n const length = resampledLength(audio.length, fromRate, toRate);\n const buffer = bufferFor(audio.numberOfChannels, length, toRate, container);\n const room = BLOCK_FRAMES - 2 * resampleReach(fromRate, toRate);\n const blockFrames = Math.max(1, Math.min(BLOCK_FRAMES, Math.floor((room * toRate) / fromRate)));\n main ??= newClient();\n for (let start = 0; start < length; start += blockFrames) {\n const frames = Math.min(blockFrames, length - start);\n const { first, end } = resampleWindow(start, frames, fromRate, toRate, audio.length);\n const channels = Array.from({ length: audio.numberOfChannels }, (_, c) =>\n audio.getChannelData(c).slice(first, end),\n );\n const block = await main.call(\n \"resample\",\n { channels, inputStart: first, fromRate, toRate, start, frames },\n { transfer: true, ...(signal ? { signal } : {}) },\n );\n for (let c = 0; c < audio.numberOfChannels; c += 1) {\n buffer.copyToChannel(block[c] as Float32Array, c, start);\n }\n onProgress?.((start + frames) / length);\n }\n if (length === 0) onProgress?.(1);\n return buffer;\n }\n\n /** Decodes a probed file at its own rate. */\n async function decodeAtOwnRate(\n file: Blob,\n probe: AudioProbe,\n signal: AbortSignal | undefined,\n onProgress: ((fraction: number) => void) | undefined,\n ): Promise<DecodedAudio> {\n if (probe.codec !== \"pcm\") {\n const trusted = compressedProbes.has(probe) ? probe : await reprobe(file, probe, signal);\n const audio = await decodeOnPage(\n file,\n trusted,\n environment.decodePlatform,\n environment.createBuffer,\n signal,\n );\n onProgress?.(1);\n return audio;\n }\n const layout = await layoutOf(file, probe, signal);\n const { frames, channels, sampleRate } = layout;\n const buffer = bufferFor(channels, frames, sampleRate, layout.container);\n\n const buckets = Math.ceil(frames / FINEST_BUCKET);\n const peaks: BucketPeaks = {\n min: Array.from({ length: channels }, () => new Float32Array(buckets)),\n max: Array.from({ length: channels }, () => new Float32Array(buckets)),\n };\n main ??= newClient();\n for (let start = 0; start < frames; start += BLOCK_FRAMES) {\n const block = await main.call(\n \"readBlock\",\n {\n file,\n layout,\n start,\n frames: Math.min(BLOCK_FRAMES, frames - start),\n bucket: FINEST_BUCKET,\n },\n signal ? { signal } : {},\n );\n const at = start / FINEST_BUCKET;\n for (let c = 0; c < channels; c += 1) {\n buffer.copyToChannel(block.channels[c] as Float32Array, c, start);\n peaks.min[c]?.set(block.min[c] as Float32Array, at);\n peaks.max[c]?.set(block.max[c] as Float32Array, at);\n }\n onProgress?.(Math.min(start + BLOCK_FRAMES, frames) / frames);\n }\n if (frames === 0) onProgress?.(1);\n finestPeaks.set(buffer, peaks);\n return buffer;\n }\n\n return {\n probe(file, options = {}) {\n return run(async () => {\n throwIfAborted(options.signal);\n await ready();\n main ??= newClient();\n const result = await main.call(\n \"probe\",\n { file },\n options.signal ? { signal: options.signal } : {},\n );\n if (result.layout) layouts.set(result.probe, result.layout);\n else compressedProbes.add(result.probe);\n return result.probe;\n });\n },\n\n decode(file, probe, options = {}) {\n return run(async () => {\n throwIfAborted(options.signal);\n const { signal, onProgress, sampleRate = probe.sampleRate } = options;\n // A rate that isn't a positive whole number is refused before\n // anything is decoded.\n if (!Number.isSafeInteger(sampleRate) || sampleRate < 1) {\n throw new RangeError(\"The sample rate must be a positive whole number of hertz.\");\n }\n await ready();\n if (sampleRate === probe.sampleRate) {\n return decodeAtOwnRate(file, probe, signal, onProgress);\n }\n // Decoding, then converting: each is half of the progress.\n const half = (from: number) =>\n onProgress && ((fraction: number) => onProgress(from + fraction / 2));\n const audio = await decodeAtOwnRate(file, probe, signal, half(0));\n return resample(audio, sampleRate, probe.container, signal, half(0.5));\n });\n },\n\n peaks(audio, options = {}) {\n return run(async (): Promise<AudioPeaks> => {\n throwIfAborted(options.signal);\n const known = finestPeaks.get(audio);\n if (known) return buildPyramid(known, FINEST_BUCKET);\n await ready();\n analysis ??= newClient();\n const buckets = Math.ceil(audio.length / FINEST_BUCKET);\n const peaks: BucketPeaks = {\n min: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),\n max: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),\n };\n for (let start = 0; start < audio.length; start += BLOCK_FRAMES) {\n const end = Math.min(audio.length, start + BLOCK_FRAMES);\n // Copies of one block, so the source is never transferred away.\n const channels = Array.from({ length: audio.numberOfChannels }, (_, c) =>\n audio.getChannelData(c).slice(start, end),\n );\n const block = await analysis.call(\n \"peaks\",\n { channels, bucket: FINEST_BUCKET },\n { transfer: true, ...(options.signal ? { signal: options.signal } : {}) },\n );\n const at = start / FINEST_BUCKET;\n for (let c = 0; c < audio.numberOfChannels; c += 1) {\n peaks.min[c]?.set(block.min[c] as Float32Array, at);\n peaks.max[c]?.set(block.max[c] as Float32Array, at);\n }\n }\n finestPeaks.set(audio, peaks);\n return buildPyramid(peaks, FINEST_BUCKET);\n });\n },\n\n async destroy() {\n destroyed = true;\n main?.destroy();\n analysis?.destroy();\n },\n };\n}\n","/**\n * The shape of a fade: `linear` changes the gain at a constant rate, and\n * `equalPower` keeps the perceived loudness steadier, which suits crossfades.\n *\n * @public\n */\nexport type AudioFadeCurve = \"linear\" | \"equalPower\";\n\n/**\n * A fade at one end of a clip. `frames: 0` is no fade.\n *\n * @public\n */\nexport interface AudioFade {\n readonly frames: number;\n readonly curve: AudioFadeCurve;\n}\n\n/**\n * A range of a source with its gain and fades: a clip without its place on\n * the timeline, which is what version 1 of the plan called a clip.\n *\n * @public\n */\nexport interface AudioClipBody {\n /** Stable across edits, so selection and waveform tiles follow a clip that moves. */\n readonly key: string;\n /** The id of the source the clip plays. */\n readonly source: string;\n /** The first source frame the clip plays, inclusive. */\n readonly start: number;\n /** The source frame the clip stops before, exclusive. */\n readonly end: number;\n /** The clip's gain in decibels. 0 leaves it unchanged. */\n readonly gainDb: number;\n readonly fadeIn: AudioFade;\n readonly fadeOut: AudioFade;\n}\n\n/**\n * A clip on a track (docs/adr/0006): a range of a source, starting on the\n * timeline frame `at`. A clip's position is stored, so an edit on one track\n * leaves every other clip where it is.\n *\n * @public\n */\nexport interface AudioClip extends AudioClipBody {\n /** The timeline frame the clip starts on. */\n readonly at: number;\n}\n\n/**\n * One track: clips in time order that never overlap, with the track's\n * name, gain, mute and solo (docs/adr/0006).\n *\n * @public\n */\nexport interface AudioTrack {\n /** Stable across edits. Tracks and clips share one namespace of keys. */\n readonly key: string;\n /**\n * The name people gave it, at most {@link MAX_TRACK_NAME_LENGTH} code\n * points. Empty means none, and an editor shows \"Track 2\". It's\n * untrusted text: render it as text, never as HTML.\n */\n readonly name: string;\n /** The track's gain in decibels. */\n readonly gainDb: number;\n readonly muted: boolean;\n readonly soloed: boolean;\n /** Sorted by `at`, each ending at or before the next one starts. */\n readonly clips: readonly AudioClip[];\n}\n\n/**\n * Metadata that export writes into the file (ADR 0001).\n *\n * @public\n */\nexport interface AudioMetadata {\n readonly title: string;\n readonly artist: string;\n readonly album: string;\n readonly year: string;\n readonly comment: string;\n}\n\n/**\n * The session's document (docs/adr/0003, docs/adr/0006): tracks of clips\n * positioned in time, over immutable sources, mixed on playback and export,\n * with the metadata. Every position and length is a whole number of frames\n * at `sampleRate`.\n *\n * @public\n */\nexport interface AudioPlan {\n /** The session's sample rate, from its first source. */\n readonly sampleRate: number;\n /** The session's channel count: its first source's, raised by a wider one. */\n readonly channels: number;\n /** The master gain in decibels, applied to the mix. */\n readonly gainDb: number;\n /** From top to bottom. A plan always has at least one. */\n readonly tracks: readonly AudioTrack[];\n readonly metadata: AudioMetadata;\n}\n\n/**\n * Metadata with every field empty.\n *\n * @public\n */\nexport const EMPTY_METADATA: AudioMetadata = Object.freeze({\n title: \"\",\n artist: \"\",\n album: \"\",\n year: \"\",\n comment: \"\",\n});\n\n/**\n * No fade.\n *\n * @public\n */\nexport const NO_FADE: AudioFade = Object.freeze({ frames: 0, curve: \"linear\" });\n\n/**\n * The longest track name, in Unicode code points, as JSON Schema's\n * `maxLength` counts them (sdk-core ADR 0045).\n *\n * @public\n */\nexport const MAX_TRACK_NAME_LENGTH = 100;\n\n/**\n * A clip's length in frames.\n *\n * @public\n */\nexport function clipLength(clip: AudioClipBody): number {\n return clip.end - clip.start;\n}\n\n/**\n * The timeline frame a clip stops before.\n *\n * @public\n */\nexport function clipEnd(clip: AudioClip): number {\n return clip.at + clipLength(clip);\n}\n\n/**\n * A track's length in frames: where its last clip ends.\n *\n * @public\n */\nexport function trackLength(track: AudioTrack): number {\n const last = track.clips.at(-1);\n return last ? clipEnd(last) : 0;\n}\n\n/**\n * The plan's length in frames: where the last clip on any track ends.\n * Silence before the first clip is part of the plan.\n *\n * @public\n */\nexport function planLength(plan: AudioPlan): number {\n let length = 0;\n for (const track of plan.tracks) length = Math.max(length, trackLength(track));\n return length;\n}\n\n/**\n * The tracks that sound: those that aren't muted and, when any track is\n * soloed, are soloed themselves. It's the one definition that playback,\n * export and an editor's dimming all follow.\n *\n * @public\n */\nexport function audibleTracks(plan: AudioPlan): readonly AudioTrack[] {\n const solo = plan.tracks.some((track) => track.soloed);\n return plan.tracks.filter((track) => !track.muted && (!solo || track.soloed));\n}\n\n/**\n * What's wrong with the order of a track's clips, or `undefined`:\n *\n * - `clips-out-of-order`: a clip starts before the one listed before it;\n * - `clips-overlap`: a clip starts before the one before it has ended.\n *\n * @internal\n */\nexport function orderProblem(\n clips: readonly AudioClip[],\n): \"clips-out-of-order\" | \"clips-overlap\" | undefined {\n for (let i = 1; i < clips.length; i += 1) {\n const before = clips[i - 1] as AudioClip;\n const clip = clips[i] as AudioClip;\n if (clip.at < before.at) return \"clips-out-of-order\";\n if (clip.at < clipEnd(before)) return \"clips-overlap\";\n }\n return undefined;\n}\n\n/**\n * The index of the first clip that ends after `frame`: the clip that plays\n * the frame, when it has started by then, and otherwise the next one. It's\n * the clips' length when every clip ends at or before the frame. A binary\n * search, because clips are sorted and never overlap.\n *\n * @internal\n */\nexport function clipIndexAt(clips: readonly AudioClip[], frame: number): number {\n let low = 0;\n let high = clips.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (clipEnd(clips[middle] as AudioClip) > frame) high = middle;\n else low = middle + 1;\n }\n return low;\n}\n\n/**\n * The clip that plays a timeline frame on a track, or `undefined` in\n * silence.\n *\n * @public\n */\nexport function clipAt(track: AudioTrack, frame: number): AudioClip | undefined {\n const clip = track.clips[clipIndexAt(track.clips, frame)];\n return clip && clip.at <= frame ? clip : undefined;\n}\n\n/**\n * Why a clip isn't valid within its source, as a stable token: a value of\n * `details.reason` on `INVALID_COMMAND` (sdk-core ADR 0045).\n *\n * - `invalid-frames`: a position or fade length isn't a non-negative whole\n * number of frames.\n * - `clip-too-short`: the clip is shorter than one frame.\n * - `clip-outside-source`: it ends after its source's last frame.\n * - `gain-out-of-range`: the gain isn't a finite number from\n * {@link MIN_GAIN_DB} to {@link MAX_GAIN_DB}.\n * - `fades-too-long`: its fades together are longer than the clip.\n *\n * @public\n */\nexport type AudioClipProblem =\n | \"invalid-frames\"\n | \"clip-too-short\"\n | \"clip-outside-source\"\n | \"gain-out-of-range\"\n | \"fades-too-long\";\n\n/**\n * The lowest clip gain, in decibels: far below audibility, so it serves as\n * silence.\n *\n * @public\n */\nexport const MIN_GAIN_DB = -120;\n\n/**\n * The highest clip gain, in decibels: enough to normalize a very quiet\n * recording, while every gain stays a finite factor.\n *\n * @public\n */\nexport const MAX_GAIN_DB = 120;\n\nconst isFrames = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0;\n\n/**\n * What's wrong with a clip within a source of `sourceFrames` frames, or\n * `undefined` if it's valid: whole, non-negative frames, at least one frame\n * long, inside the source, with a gain in range and fades that fit the clip\n * together.\n *\n * @internal\n */\nexport function clipProblem(\n clip: AudioClipBody,\n sourceFrames: number,\n): AudioClipProblem | undefined {\n if (![clip.start, clip.end, clip.fadeIn.frames, clip.fadeOut.frames].every(isFrames)) {\n return \"invalid-frames\";\n }\n if (clip.end <= clip.start) return \"clip-too-short\";\n if (clip.end > sourceFrames) return \"clip-outside-source\";\n if (\n typeof clip.gainDb !== \"number\" ||\n !(clip.gainDb >= MIN_GAIN_DB && clip.gainDb <= MAX_GAIN_DB)\n ) {\n return \"gain-out-of-range\";\n }\n if (clip.fadeIn.frames + clip.fadeOut.frames > clipLength(clip)) return \"fades-too-long\";\n return undefined;\n}\n\n/**\n * Throws `RangeError` unless the clip is valid within a source of\n * `sourceFrames` frames, as {@link clipProblem} checks.\n *\n * @internal\n */\nexport function assertClip(clip: AudioClipBody, sourceFrames: number): void {\n const problem = clipProblem(clip, sourceFrames);\n if (problem) throw new RangeError(`Clip ${clip.key} isn't valid: ${problem}.`);\n}\n","import type { AudioClipBody, AudioFadeCurve } from \"./plan.js\";\n\n/**\n * Converts decibels to a linear gain factor.\n *\n * @public\n */\nexport function dbToGain(db: number): number {\n return 10 ** (db / 20);\n}\n\n/** A fade's gain at `position`, from 0 (silent) to 1 (full). */\nfunction fadeShape(curve: AudioFadeCurve, position: number): number {\n return curve === \"equalPower\" ? Math.sin((position * Math.PI) / 2) : position;\n}\n\n/**\n * The gain at one frame of a clip, from its gain and its fades: the single\n * definition of the envelope, which export applies per sample and playback\n * samples into the clip's `GainNode` (ADR 0001).\n *\n * A fade in starts at silence on the clip's first frame, and a fade out\n * reaches silence on its last frame.\n *\n * @param clip - The clip.\n * @param frame - A frame within the clip, from 0 to its length minus one.\n * @public\n */\nexport function gainAt(clip: AudioClipBody, frame: number): number {\n const length = clip.end - clip.start;\n let gain = dbToGain(clip.gainDb);\n const { fadeIn, fadeOut } = clip;\n if (fadeIn.frames > 0 && frame < fadeIn.frames) {\n gain *= fadeShape(fadeIn.curve, frame / fadeIn.frames);\n }\n const fromEnd = length - 1 - frame;\n if (fadeOut.frames > 0 && fromEnd < fadeOut.frames) {\n gain *= fadeShape(fadeOut.curve, Math.max(0, fromEnd) / fadeOut.frames);\n }\n return gain;\n}\n","import { gainAt } from \"../../core/model/envelope.js\";\nimport { type AudioClipBody, clipLength } from \"../../core/model/plan.js\";\n\n/**\n * The most points a fade's curve gets: Web Audio interpolates linearly\n * between them, so a long fade is sampled, and a short one is exact.\n */\nexport const MAX_CURVE_POINTS = 1_024;\n\n/** One automation event of a clip's `GainNode`, in seconds from when the clip starts playing. */\nexport type GainEvent =\n | { readonly kind: \"set\"; readonly time: number; readonly value: number }\n | {\n readonly kind: \"curve\";\n readonly time: number;\n readonly duration: number;\n readonly values: Float32Array;\n };\n\n/** Samples `gainAt` from frame `from` to frame `to`, both included, at no more than the maximum points. */\nfunction curve(clip: AudioClipBody, from: number, to: number): Float32Array {\n const points = Math.min(MAX_CURVE_POINTS, to - from + 1);\n const values = new Float32Array(points);\n for (let i = 0; i < points; i += 1) {\n const frame = points === 1 ? from : from + ((to - from) * i) / (points - 1);\n values[i] = gainAt(clip, Math.round(frame));\n }\n return values;\n}\n\n/**\n * A clip's gain automation, played from frame `from` of the clip, as\n * `setValueAtTime` and `setValueCurveAtTime` events (docs/adr/0001): the\n * playback side of `gainAt`, which export applies per sample.\n *\n * - **Fade in:** a curve from `from` to the fade's last frame, then the\n * clip's gain.\n * - **Fade out:** a curve from its first frame to the clip's last, reaching\n * silence there.\n * - **No two events share a time,** and no event falls inside a curve, which\n * Web Audio refuses: a fade out that starts where the fade in ends follows\n * its curve directly.\n */\nexport function gainEvents(clip: AudioClipBody, from: number, sampleRate: number): GainEvent[] {\n const length = clipLength(clip);\n const fadeInEnd = clip.fadeIn.frames;\n const fadeOutStart = length - clip.fadeOut.frames;\n const at = (frame: number) => (frame - from) / sampleRate;\n const events: GainEvent[] = [];\n let cursor = from;\n\n if (from < fadeInEnd) {\n // Its last value, the clip's steady gain, holds after it.\n events.push({\n kind: \"curve\",\n time: 0,\n duration: at(fadeInEnd),\n values: curve(clip, from, fadeInEnd),\n });\n cursor = fadeInEnd;\n }\n const outFrom = Math.max(cursor, fadeOutStart);\n const fadingOut = clip.fadeOut.frames > 0 && outFrom < length - 1;\n // The steady gain from the start, unless a curve starts there.\n if (events.length === 0 && !(fadingOut && outFrom === from)) {\n events.push({ kind: \"set\", time: 0, value: gainAt(clip, from) });\n }\n if (fadingOut) {\n events.push({\n kind: \"curve\",\n time: at(outFrom),\n duration: at(length - 1) - at(outFrom),\n values: curve(clip, outFrom, length - 1),\n });\n } else if (clip.fadeOut.frames > 0 && outFrom > cursor) {\n // A fade out of the last frame alone, too short for a curve: silence there.\n events.push({ kind: \"set\", time: at(outFrom), value: gainAt(clip, outFrom) });\n }\n return events;\n}\n","import { dbToGain } from \"../../core/model/envelope.js\";\nimport {\n type AudioClip,\n type AudioPlan,\n type AudioTrack,\n audibleTracks,\n clipLength,\n} from \"../../core/model/plan.js\";\nimport { gainEvents } from \"./gain-automation.js\";\n\n/**\n * How long a change of a track's gain, mute or solo, or of the master gain,\n * takes to reach its new level during playback, in seconds: short enough to\n * feel immediate, and long enough not to click (docs/adr/0006).\n */\nexport const GAIN_RAMP = 0.005;\n\n/** The nodes of a scheduled plan, to change its levels and to stop it. */\nexport interface ScheduledPlan {\n /**\n * Moves the tracks' gains and the master gain to a plan's, from context\n * time `at`, over {@link GAIN_RAMP}. The plan must have the same clips as\n * the one scheduled, as {@link sameClips} checks: nothing is rescheduled.\n */\n setLevels(plan: AudioPlan, at: number): void;\n /** Stops every clip at once, and disconnects the graph. */\n stop(): void;\n}\n\n/** The tracks that have clips, by key. */\nfunction tracksWithClips(plan: AudioPlan): Map<string, readonly AudioClip[]> {\n const found = new Map<string, readonly AudioClip[]>();\n for (const track of plan.tracks) if (track.clips.length > 0) found.set(track.key, track.clips);\n return found;\n}\n\n/**\n * Whether two plans schedule the same audio: the same rate and channels,\n * and the same clips on the same tracks, compared by identity, as the\n * reducer keeps a track's clips when only its settings change. Then only\n * levels differ, the tracks' gain, mute and solo and the master gain, and\n * the order of the tracks, which isn't heard. An empty track isn't heard\n * either, so adding or removing one changes nothing here.\n */\nexport function sameClips(a: AudioPlan, b: AudioPlan): boolean {\n if (a.sampleRate !== b.sampleRate || a.channels !== b.channels) return false;\n const before = tracksWithClips(a);\n const after = tracksWithClips(b);\n if (before.size !== after.size) return false;\n for (const [key, clips] of before) if (after.get(key) !== clips) return false;\n return true;\n}\n\n/** Each track's level as a factor: its gain when it's audible, and silence when it isn't. */\nfunction trackLevels(plan: AudioPlan): Map<string, number> {\n const audible = new Set<AudioTrack>(audibleTracks(plan));\n return new Map(\n plan.tracks.map((track) => [track.key, audible.has(track) ? dbToGain(track.gainDb) : 0]),\n );\n}\n\n/**\n * Schedules a plan from timeline frame `from`, with that frame playing at\n * context time `at` (docs/adr/0002):\n *\n * - each clip is an `AudioBufferSourceNode` on its source, started at its\n * place on the timeline, through a `GainNode` automated from `gainAt`\n * (docs/adr/0001);\n * - a track's clips feed the track's `GainNode`, at the track's gain, or at\n * silence when the track is muted or left out by a solo. So a mute, a\n * solo or a gain is one node's level, changed without rescheduling a\n * clip (docs/adr/0006);\n * - the tracks feed one bus, at the master gain, with the plan's channel\n * count and Web Audio's `speakers` interpretation, so sources with other\n * channel counts mix as export mixes them.\n *\n * It works on any `BaseAudioContext`: the output plays through a realtime\n * one, and the tests render the same graph offline to compare with export.\n */\nexport function schedulePlan(\n context: BaseAudioContext,\n destination: AudioNode,\n plan: AudioPlan,\n buffer: (source: string) => AudioBuffer,\n from: number,\n at: number,\n): ScheduledPlan {\n const rate = plan.sampleRate;\n const bus = context.createGain();\n bus.gain.value = dbToGain(plan.gainDb);\n bus.channelCount = plan.channels;\n bus.channelCountMode = \"explicit\";\n bus.channelInterpretation = \"speakers\";\n bus.connect(destination);\n\n const nodes: { source: AudioBufferSourceNode; gain: GainNode }[] = [];\n const tracks = new Map<string, GainNode>();\n // The level each node was last sent to, which a ramp starts from.\n const levels = trackLevels(plan);\n let master = dbToGain(plan.gainDb);\n for (const track of plan.tracks) {\n // A track with no clips has nothing to play, at any level.\n if (track.clips.length === 0) continue;\n const output = context.createGain();\n output.gain.value = levels.get(track.key) ?? 0;\n output.channelCount = plan.channels;\n output.channelCountMode = \"explicit\";\n output.channelInterpretation = \"speakers\";\n output.connect(bus);\n tracks.set(track.key, output);\n for (const clip of track.clips) {\n const length = clipLength(clip);\n if (clip.at + length <= from) continue;\n const within = Math.max(0, from - clip.at);\n const when = at + Math.max(0, clip.at - from) / rate;\n const source = context.createBufferSource();\n source.buffer = buffer(clip.source);\n const gain = context.createGain();\n for (const event of gainEvents(clip, within, rate)) {\n if (event.kind === \"set\") gain.gain.setValueAtTime(event.value, when + event.time);\n else gain.gain.setValueCurveAtTime(event.values, when + event.time, event.duration);\n }\n source.connect(gain).connect(output);\n source.start(when, (clip.start + within) / rate, (length - within) / rate);\n nodes.push({ source, gain });\n }\n }\n\n /** Sends a level to a new value, from where it was last sent, over the ramp. */\n const ramp = (param: AudioParam, from: number, to: number, time: number) => {\n if (from === to) return;\n param.setValueAtTime(from, time);\n param.linearRampToValueAtTime(to, time + GAIN_RAMP);\n };\n\n return {\n setLevels(next, time) {\n const targets = trackLevels(next);\n for (const [key, output] of tracks) {\n const target = targets.get(key) ?? 0;\n ramp(output.gain, levels.get(key) ?? 0, target, time);\n levels.set(key, target);\n }\n const target = dbToGain(next.gainDb);\n ramp(bus.gain, master, target, time);\n master = target;\n },\n stop() {\n for (const { source, gain } of nodes) {\n try {\n source.stop();\n } catch {\n // Already stopped.\n }\n source.disconnect();\n gain.disconnect();\n }\n for (const output of tracks.values()) output.disconnect();\n bus.disconnect();\n },\n };\n}\n","import { createStore } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"../core/errors/audio-error.js\";\nimport { type AudioPlan, planLength } from \"../core/model/plan.js\";\nimport type { DecodedAudio } from \"../core/model/source.js\";\nimport type {\n AudioOutput,\n AudioOutputSnapshot,\n AudioOutputState,\n} from \"../core/ports/audio-output.js\";\nimport { type ScheduledPlan, sameClips, schedulePlan } from \"./web-audio/play-graph.js\";\n\n/**\n * How far ahead of the context's clock playback starts, in seconds, so the\n * first clip is scheduled in time.\n */\nexport const START_LEAD = 0.03;\n\n/**\n * How long `play()` waits for the context to run, in milliseconds. A\n * context stays suspended without a user gesture, or without a sound\n * server, as in Firefox in the browser test image (sdk-core ADR 0043).\n */\nexport const RESUME_TIMEOUT = 2_000;\n\n/**\n * What the output needs from the page, replaceable in tests.\n *\n * @internal\n */\nexport interface OutputEnvironment {\n readonly createContext: () => AudioContext;\n}\n\n/**\n * Creates the SDK's playback output (docs/adr/0002): it plays a plan\n * through Web Audio, from the playhead, and reschedules from the playhead\n * whenever the plan changes or it seeks, so an edit or a seek during\n * playback always takes effect.\n *\n * - **One `AudioContext`,** created on the first `play()`, which should be\n * a user gesture, as browsers' autoplay rules require. If the context\n * doesn't run within two seconds, `play()` rejects with\n * `UNSUPPORTED_ENVIRONMENT` and `details.reason` `\"autoplay-blocked\"`,\n * and the output stays as it was.\n * - **Each clip is an `AudioBufferSourceNode`** on its source, through a\n * `GainNode` automated from `gainAt`, so playback follows the envelope\n * export applies. Sources mix into the plan's channels by Web Audio's\n * speaker rules, as export does.\n * - **Each track is a `GainNode`** its clips feed, at the track's gain, or\n * at silence when it's muted or left out by a solo, and the tracks feed\n * one at the master gain. Loading a plan that differs only in those\n * levels moves the nodes there over 5 ms, and reschedules nothing, so a\n * mute, a solo or a gain is heard at once, without a gap or a click\n * (docs/adr/0006).\n * - **The playhead** is read from the audio clock by `position()`, which a\n * view polls on animation frames; it isn't in the snapshot.\n *\n * Sources should be `AudioBuffer`s, as `createAudioEngine` decodes them.\n * Others are copied into one once, on first use.\n *\n * @example\n * ```ts\n * const output = createAudioOutput();\n * output.load(plan, sources);\n * playButton.onclick = () => output.play();\n * requestAnimationFrame(function draw() {\n * drawPlayhead(output.position());\n * requestAnimationFrame(draw);\n * });\n * ```\n *\n * @public\n */\nexport function createAudioOutput(): AudioOutput {\n return createOutput({ createContext: () => new AudioContext() });\n}\n\n/**\n * The output, with its environment passed in.\n *\n * @internal\n */\nexport function createOutput(environment: OutputEnvironment): AudioOutput {\n const store = createStore<AudioOutputSnapshot>(Object.freeze({ state: \"stopped\" }));\n const copies = new WeakMap<DecodedAudio, AudioBuffer>();\n let context: AudioContext | undefined;\n let plan: AudioPlan | undefined;\n let sources: ReadonlyMap<string, DecodedAudio> = new Map();\n /** The playhead while not playing. */\n let playhead = 0;\n /** While playing: what's scheduled, and which frame plays at which context time. */\n let playing: { scheduled: ScheduledPlan; frame: number; time: number } | undefined;\n let endTimer: ReturnType<typeof setTimeout> | undefined;\n let destroyed = false;\n\n const length = () => (plan ? planLength(plan) : 0);\n const assertAlive = () => {\n if (destroyed) throw new Error(\"The audio output has been destroyed.\");\n };\n const setState = (state: AudioOutputState) => {\n if (store.getSnapshot().state !== state) store.set(Object.freeze({ state }));\n };\n /**\n * Tells subscribers the playhead jumped, with a new snapshot in the same\n * state, so a view that reads `position()` on changes catches a seek, a\n * stop, or a plan that moves it, even while paused (point 8 of #54).\n */\n const jumped = () => store.set(Object.freeze({ state: store.getSnapshot().state }));\n\n /** A source as an `AudioBuffer`, copied into one once if it isn't. */\n function buffer(id: string): AudioBuffer {\n const audio = sources.get(id);\n if (!audio) throw new TypeError(`The plan's source ${id} isn't loaded.`);\n if (audio instanceof AudioBuffer) return audio;\n let copy = copies.get(audio);\n if (!copy) {\n copy = new AudioBuffer({\n length: audio.length,\n numberOfChannels: audio.numberOfChannels,\n sampleRate: audio.sampleRate,\n });\n for (let channel = 0; channel < audio.numberOfChannels; channel += 1) {\n copy.copyToChannel(Float32Array.from(audio.getChannelData(channel)), channel);\n }\n copies.set(audio, copy);\n }\n return copy;\n }\n\n /** Where the playhead is: from the audio clock while playing. */\n function position(): number {\n if (!playing || !context || !plan) return playhead;\n const elapsed = Math.max(0, context.currentTime - playing.time);\n return Math.min(length(), Math.floor(playing.frame + elapsed * plan.sampleRate));\n }\n\n /** Stops what's scheduled, keeping the playhead where it is now. */\n function unschedule(): void {\n if (!playing) return;\n playhead = position();\n playing.scheduled.stop();\n playing = undefined;\n clearTimeout(endTimer);\n endTimer = undefined;\n }\n\n /** Waits for the end of the plan, by the audio clock. */\n function watchEnd(): void {\n clearTimeout(endTimer);\n if (!playing || !context || !plan) return;\n const remaining =\n playing.time - context.currentTime + (length() - playing.frame) / plan.sampleRate;\n endTimer = setTimeout(\n () => {\n if (position() >= length()) {\n unschedule();\n playhead = length();\n setState(\"stopped\");\n } else {\n watchEnd();\n }\n },\n Math.max(0, remaining * 1_000) + 5,\n );\n }\n\n /** Schedules the plan from the playhead, on a running context. */\n function schedule(): void {\n if (!context || !plan) return;\n const time = context.currentTime + START_LEAD;\n playing = {\n scheduled: schedulePlan(context, context.destination, plan, buffer, playhead, time),\n frame: playhead,\n time,\n };\n watchEnd();\n }\n\n async function running(audio: AudioContext): Promise<boolean> {\n if (audio.state === \"running\") return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), RESUME_TIMEOUT);\n });\n try {\n await Promise.race([audio.resume().then(() => true), timedOut]);\n } finally {\n clearTimeout(timer);\n }\n // resume() changes the state while this waits, which TypeScript can't see.\n return (audio.state as AudioContextState) === \"running\";\n }\n\n return {\n getSnapshot: store.getSnapshot,\n subscribe: store.subscribe,\n position,\n\n load(next, nextSources) {\n assertAlive();\n // A plan with the same clips differs only in levels: a track's gain,\n // mute or solo, or the master gain. Those are set on what's playing,\n // without rescheduling a clip (docs/adr/0006).\n if (playing && context && plan && sameClips(plan, next)) {\n plan = next;\n sources = nextSources;\n playing.scheduled.setLevels(next, context.currentTime);\n return;\n }\n const wasPlaying = playing !== undefined;\n unschedule();\n plan = next;\n sources = nextSources;\n const before = playhead;\n playhead = Math.min(playhead, length());\n if (!wasPlaying) {\n if (playhead !== before) jumped();\n return;\n }\n if (playhead >= length()) {\n playhead = length();\n setState(\"stopped\");\n } else {\n schedule();\n }\n },\n\n async play() {\n assertAlive();\n if (length() === 0 || playing) return;\n context ??= environment.createContext();\n if (!(await running(context))) {\n throw new AudioError(\n \"UNSUPPORTED_ENVIRONMENT\",\n \"The browser didn't start audio output. Play from a click or a key press.\",\n // Most often a browser's autoplay rule, which a click lifts\n // (point 9 of #54): the reason lets an editor say so.\n { details: { feature: \"audio-output\", reason: \"autoplay-blocked\" } },\n );\n }\n // Another call may have started, or the plan changed, while waiting.\n if (destroyed || playing || length() === 0) return;\n if (playhead >= length()) playhead = 0;\n schedule();\n setState(\"playing\");\n },\n\n pause() {\n assertAlive();\n if (!playing) return;\n unschedule();\n setState(\"paused\");\n },\n\n stop() {\n assertAlive();\n unschedule();\n const before = playhead;\n playhead = 0;\n if (store.getSnapshot().state !== \"stopped\") setState(\"stopped\");\n else if (before !== 0) jumped();\n },\n\n seek(frame) {\n assertAlive();\n const wasPlaying = playing !== undefined;\n const before = position();\n unschedule();\n playhead = Math.max(0, Math.min(Math.round(frame), length()));\n if (wasPlaying && playhead < length()) schedule();\n if (wasPlaying && playhead >= length()) setState(\"stopped\");\n else if (playhead !== before) jumped();\n },\n\n async destroy() {\n if (destroyed) return;\n destroyed = true;\n unschedule();\n setState(\"stopped\");\n await context?.close().catch(() => {});\n context = undefined;\n },\n };\n}\n","import { dbToGain, gainAt } from \"./envelope.js\";\nimport {\n type AudioClipBody,\n type AudioPlan,\n audibleTracks,\n clipEnd,\n clipIndexAt,\n trackLength,\n} from \"./plan.js\";\nimport type { DecodedAudio } from \"./source.js\";\n\n/**\n * How a source's channels mix into the plan's, as Web Audio's `speakers`\n * channel interpretation does, so that playback and export agree\n * (docs/adr/0003). Mono, stereo, quad (L, R, SL, SR) and 5.1 (L, R, C, LFE,\n * SL, SR) mix by the Web Audio specification's up-mix and down-mix rules;\n * any other pair of counts mixes discretely: channel by channel, with extra\n * outputs silent and extra inputs dropped.\n *\n * The result is a matrix: `matrix[output][input]` is the weight of input\n * channel `input` in output channel `output`.\n *\n * @see https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixing\n * @internal\n */\nexport function channelMix(from: number, to: number): readonly (readonly number[])[] {\n const matrix = Array.from({ length: to }, () => new Array<number>(from).fill(0));\n const set = (output: number, input: number, weight: number) => {\n (matrix[output] as number[])[input] = weight;\n };\n const half = Math.SQRT1_2;\n const key = `${from}>${to}`;\n switch (key) {\n // Up-mixing.\n case \"1>2\":\n set(0, 0, 1);\n set(1, 0, 1);\n break;\n case \"1>4\":\n set(0, 0, 1);\n set(1, 0, 1);\n break;\n case \"1>6\":\n set(2, 0, 1);\n break;\n case \"2>4\":\n case \"2>6\":\n set(0, 0, 1);\n set(1, 1, 1);\n break;\n case \"4>6\":\n set(0, 0, 1);\n set(1, 1, 1);\n set(4, 2, 1);\n set(5, 3, 1);\n break;\n // Down-mixing.\n case \"2>1\":\n set(0, 0, 0.5);\n set(0, 1, 0.5);\n break;\n case \"4>1\":\n for (let input = 0; input < 4; input += 1) set(0, input, 0.25);\n break;\n case \"6>1\":\n set(0, 0, half);\n set(0, 1, half);\n set(0, 2, 1);\n set(0, 4, 0.5);\n set(0, 5, 0.5);\n break;\n case \"4>2\":\n set(0, 0, 0.5);\n set(0, 2, 0.5);\n set(1, 1, 0.5);\n set(1, 3, 0.5);\n break;\n case \"6>2\":\n set(0, 0, 1);\n set(0, 2, half);\n set(0, 4, half);\n set(1, 1, 1);\n set(1, 2, half);\n set(1, 5, half);\n break;\n case \"6>4\":\n set(0, 0, 1);\n set(0, 2, half);\n set(1, 1, 1);\n set(1, 2, half);\n set(2, 4, 1);\n set(3, 5, 1);\n break;\n default:\n // The same count, or a pair the speaker rules don't cover: discrete.\n for (let channel = 0; channel < Math.min(from, to); channel += 1) set(channel, channel, 1);\n }\n return matrix;\n}\n\n/**\n * The length of what sounds, in frames: where the last clip on any audible\n * track ends. It's what an export writes, so a muted track never pads the\n * file with silence (docs/adr/0006).\n *\n * @public\n */\nexport function mixLength(plan: AudioPlan): number {\n let length = 0;\n for (const track of audibleTracks(plan)) length = Math.max(length, trackLength(track));\n return length;\n}\n\n/**\n * One clip's part of a block of the mix: its source's samples for the\n * frames it covers there.\n *\n * @internal\n */\nexport interface MixSegment {\n /** The clip, for its gain and fades. */\n readonly clip: AudioClipBody;\n /** The gain of the clip's track, as a factor. */\n readonly gain: number;\n /** The first frame, counted from the clip's start. */\n readonly within: number;\n /** The frame of the block the segment starts at. */\n readonly at: number;\n /** The source's samples, one array per source channel, each `frames` long. */\n readonly samples: readonly Float32Array[];\n readonly frames: number;\n}\n\n/**\n * A block of the mix to compute.\n *\n * @internal\n */\nexport interface MixBlock {\n /** The plan's channel count. */\n readonly channels: number;\n /** The block's length in frames. */\n readonly frames: number;\n /** The master gain, as a factor. */\n readonly gain: number;\n readonly segments: readonly MixSegment[];\n}\n\n/**\n * A mixed block: its samples, clamped to full scale, and what clamping did.\n *\n * @internal\n */\nexport interface MixedBlock {\n /** One array per channel of the plan. */\n readonly channels: Float32Array<ArrayBuffer>[];\n /** The largest absolute sample before clamping. 1 is full scale. */\n readonly peak: number;\n /** How many frames had a sample over full scale, which was clamped. */\n readonly clipped: number;\n}\n\n/**\n * The parts of the plan's audible clips that fall in the frames\n * `[start, start + frames)`, with copies of their source samples: what\n * {@link mixBlock} needs for that block. Tracks are taken in plan order, and\n * muted and unsoloed tracks are left out, so they cost nothing.\n *\n * @throws `TypeError` if a clip's source isn't in `sources`.\n * @internal\n */\nexport function gatherSegments(\n plan: AudioPlan,\n sources: ReadonlyMap<string, DecodedAudio>,\n start: number,\n frames: number,\n): MixSegment[] {\n const end = start + frames;\n const segments: MixSegment[] = [];\n for (const track of audibleTracks(plan)) {\n const gain = dbToGain(track.gainDb);\n for (let index = clipIndexAt(track.clips, start); index < track.clips.length; index += 1) {\n const clip = track.clips[index];\n if (!clip || clip.at >= end) break;\n const from = Math.max(start, clip.at);\n const to = Math.min(end, clipEnd(clip));\n const within = from - clip.at;\n const source = sources.get(clip.source);\n if (!source) throw new TypeError(`Clip ${clip.key}'s source ${clip.source} isn't given.`);\n const samples = Array.from({ length: source.numberOfChannels }, (_, channel) =>\n source.getChannelData(channel).slice(clip.start + within, clip.start + within + to - from),\n );\n segments.push({ clip, gain, within, at: from - start, samples, frames: to - from });\n }\n }\n return segments;\n}\n\n/**\n * Mixes one block (docs/adr/0006), the one definition that export follows\n * and playback's graph reproduces:\n *\n * `out = clamp(master × Σ tracks (track gain × clip's gainAt × its source's frame, mixed to the plan's channels))`\n *\n * Tracks sum at unity, in the order given, in double precision, so every\n * engine adds in the same order. Frames no segment covers are silent.\n *\n * @internal\n */\nexport function mixBlock(block: MixBlock): MixedBlock {\n const { channels, frames, segments } = block;\n const sums = Array.from({ length: channels }, () => new Float64Array(frames));\n for (const segment of segments) {\n const matrix = channelMix(segment.samples.length, channels);\n for (let input = 0; input < segment.samples.length; input += 1) {\n const samples = segment.samples[input] as Float32Array;\n for (let output = 0; output < channels; output += 1) {\n const weight = (matrix[output] as number[])[input] as number;\n if (weight === 0) continue;\n const sum = sums[output] as Float64Array;\n for (let i = 0; i < segment.frames; i += 1) {\n const gain = gainAt(segment.clip, segment.within + i) * segment.gain;\n sum[segment.at + i] =\n (sum[segment.at + i] as number) + weight * (samples[i] as number) * gain;\n }\n }\n }\n }\n const out = Array.from({ length: channels }, () => new Float32Array(frames));\n let peak = 0;\n let clipped = 0;\n for (let i = 0; i < frames; i += 1) {\n let over = false;\n for (let channel = 0; channel < channels; channel += 1) {\n const value = ((sums[channel] as Float64Array)[i] as number) * block.gain;\n const size = Math.abs(value);\n if (size > peak) peak = size;\n if (size > 1) over = true;\n (out[channel] as Float32Array)[i] = Math.max(-1, Math.min(1, value));\n }\n if (over) clipped += 1;\n }\n return { channels: out, peak, clipped };\n}\n","import type { AudioMetadata } from \"../../core/model/plan.js\";\nimport type { AudioSampleFormat } from \"../../core/ports/audio-processor.js\";\n\n/**\n * Writes WAV files for export (docs/adr/0001): the header, which the plan\n * fixes in advance, and the samples, block by block.\n *\n * - **Quantisation:** samples are clamped to [−1, 1], and a non-finite one\n * is silence. 16-bit and 24-bit PCM scale by 2ⁿ⁻¹, round half away from\n * zero, and clamp to [−2ⁿ⁻¹, 2ⁿ⁻¹ − 1], so +1.0 writes the largest\n * positive value. Readers that divide by 2ⁿ⁻¹, as this SDK's does, get\n * back the nearest representable value. There's no dither.\n * - **32-bit float** writes the clamped sample, rounded to the nearest\n * float32.\n * - **Layout:** `fmt ` is WAVE_FORMAT_EXTENSIBLE, with a speaker mask for\n * mono, stereo, quad and 5.1, when there are more than two channels or\n * more than 16 bits; float files also get a `fact` chunk. The metadata\n * goes in a `LIST`/`INFO` chunk before `data`, and is left out when every\n * field is empty. A file whose sizes don't fit 32 bits is RF64, with a\n * `ds64` chunk.\n */\n\nconst BYTES: Record<AudioSampleFormat, number> = { pcm16: 2, pcm24: 3, float32: 4 };\nconst WAVE_FORMAT_PCM = 0x0001;\nconst WAVE_FORMAT_IEEE_FLOAT = 0x0003;\nconst WAVE_FORMAT_EXTENSIBLE = 0xfffe;\n/** The tail every `KSDATAFORMAT_SUBTYPE_*` GUID shares after its format tag. */\nconst SUBTYPE_TAIL = [\n 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71,\n];\n/** Speaker masks for the layouts Web Audio's speaker rules know. */\nconst SPEAKERS: Readonly<Record<number, number>> = { 1: 0x4, 2: 0x3, 4: 0x33, 6: 0x3f };\nconst MAX_32 = 0xffffffff;\n/** The INFO ids of each metadata field, in the order they're written. */\nconst INFO_IDS: readonly [keyof AudioMetadata, string][] = [\n [\"title\", \"INAM\"],\n [\"artist\", \"IART\"],\n [\"album\", \"IPRD\"],\n [\"year\", \"ICRD\"],\n [\"comment\", \"ICMT\"],\n];\n\n/** What the header describes. */\nexport interface WavSpec {\n readonly sampleRate: number;\n readonly channels: number;\n readonly frames: number;\n readonly sampleFormat: AudioSampleFormat;\n readonly metadata: AudioMetadata;\n}\n\n/** Bytes per sample of a format. */\nexport function bytesPerSample(format: AudioSampleFormat): number {\n return BYTES[format];\n}\n\n/** The size of the samples, without the pad byte an odd size needs. */\nexport function dataSize(spec: Pick<WavSpec, \"channels\" | \"frames\" | \"sampleFormat\">): number {\n return spec.frames * spec.channels * BYTES[spec.sampleFormat];\n}\n\nclass Writer {\n readonly bytes: Uint8Array<ArrayBuffer>;\n readonly view: DataView;\n at = 0;\n\n constructor(size: number) {\n this.bytes = new Uint8Array(size);\n this.view = new DataView(this.bytes.buffer);\n }\n\n text(value: string): void {\n for (let i = 0; i < value.length; i += 1) this.bytes[this.at + i] = value.charCodeAt(i);\n this.at += value.length;\n }\n\n u16(value: number): void {\n this.view.setUint16(this.at, value, true);\n this.at += 2;\n }\n\n u32(value: number): void {\n this.view.setUint32(this.at, value, true);\n this.at += 4;\n }\n\n u64(value: number): void {\n this.u32(value % 2 ** 32);\n this.u32(Math.floor(value / 2 ** 32));\n }\n\n raw(value: Uint8Array): void {\n this.bytes.set(value, this.at);\n this.at += value.length;\n }\n}\n\n/** The `LIST`/`INFO` chunk's body, or nothing when every field is empty. */\nfunction infoBody(metadata: AudioMetadata): Uint8Array | undefined {\n const encoder = new TextEncoder();\n const fields = INFO_IDS.flatMap(([field, id]) => {\n const text = metadata[field];\n // UTF-8, NUL-terminated, and padded to an even size.\n return text === \"\" ? [] : [{ id, value: encoder.encode(`${text}\\0`) }];\n });\n if (fields.length === 0) return undefined;\n const size =\n 4 + fields.reduce((sum, { value }) => sum + 8 + value.length + (value.length % 2), 0);\n const writer = new Writer(size);\n writer.text(\"INFO\");\n for (const { id, value } of fields) {\n writer.text(id);\n writer.u32(value.length);\n writer.raw(value);\n if (value.length % 2 === 1) writer.at += 1;\n }\n return writer.bytes;\n}\n\n/**\n * The file's header: everything before the samples. The samples follow\n * directly, and an odd number of sample bytes then needs one pad byte.\n */\nexport function wavHeader(spec: WavSpec): Uint8Array<ArrayBuffer> {\n const { sampleRate, channels, frames, sampleFormat, metadata } = spec;\n const bytes = BYTES[sampleFormat];\n const float = sampleFormat === \"float32\";\n const extensible = channels > 2 || bytes > 2;\n const fmtSize = extensible ? 40 : float ? 18 : 16;\n const info = infoBody(metadata);\n const data = dataSize(spec);\n const pad = data % 2;\n const chunks = 8 + fmtSize + (float ? 12 : 0) + (info ? 8 + info.length : 0) + 8 + data + pad;\n const riffSize = 4 + chunks;\n const rf64 = riffSize > MAX_32 || data > MAX_32 || frames > MAX_32;\n const headerSize = 12 + (rf64 ? 36 : 0) + chunks - data - pad;\n\n const writer = new Writer(headerSize);\n writer.text(rf64 ? \"RF64\" : \"RIFF\");\n writer.u32(rf64 ? MAX_32 : riffSize);\n writer.text(\"WAVE\");\n if (rf64) {\n writer.text(\"ds64\");\n writer.u32(28);\n writer.u64(riffSize + 36);\n writer.u64(data);\n writer.u64(frames);\n writer.u32(0);\n }\n\n writer.text(\"fmt \");\n writer.u32(fmtSize);\n const tag = float ? WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM;\n writer.u16(extensible ? WAVE_FORMAT_EXTENSIBLE : tag);\n writer.u16(channels);\n writer.u32(sampleRate);\n writer.u32(sampleRate * channels * bytes);\n writer.u16(channels * bytes);\n writer.u16(bytes * 8);\n if (extensible) {\n writer.u16(22);\n writer.u16(bytes * 8);\n writer.u32(SPEAKERS[channels] ?? 0);\n writer.u16(tag);\n for (const byte of SUBTYPE_TAIL) writer.bytes[writer.at++] = byte;\n } else if (float) {\n writer.u16(0);\n }\n\n if (float) {\n writer.text(\"fact\");\n writer.u32(4);\n writer.u32(rf64 ? MAX_32 : frames);\n }\n if (info) {\n writer.text(\"LIST\");\n writer.u32(info.length);\n writer.raw(info);\n }\n writer.text(\"data\");\n writer.u32(rf64 ? MAX_32 : data);\n return writer.bytes;\n}\n\n/** Rounds half away from zero, as the PCM formats document. */\nfunction roundHalfAway(value: number): number {\n return value < 0 ? -Math.round(-value) : Math.round(value);\n}\n\n/**\n * A sample as stored: an integer for PCM, a float for float32, after\n * clamping as the module describes.\n */\nexport function quantise(sample: number, format: AudioSampleFormat): number {\n const clamped = Number.isFinite(sample) ? Math.max(-1, Math.min(1, sample)) : 0;\n if (format === \"float32\") return Math.fround(clamped);\n const scale = format === \"pcm16\" ? 0x8000 : 0x800000;\n // + 0 turns −0 into 0: an integer sample has no sign of zero.\n return Math.min(scale - 1, roundHalfAway(clamped * scale)) + 0;\n}\n\n/** Interleaves and quantises one block of samples, one array per channel. */\nexport function encodeSamples(\n channels: readonly Float32Array[],\n frames: number,\n format: AudioSampleFormat,\n): Uint8Array<ArrayBuffer> {\n const bytes = BYTES[format];\n const out = new Uint8Array(frames * channels.length * bytes);\n const view = new DataView(out.buffer);\n let at = 0;\n for (let frame = 0; frame < frames; frame += 1) {\n for (const channel of channels) {\n const value = quantise(channel[frame] ?? 0, format);\n if (format === \"float32\") view.setFloat32(at, value, true);\n else if (format === \"pcm16\") view.setInt16(at, value, true);\n else {\n view.setUint8(at, value & 0xff);\n view.setUint8(at + 1, (value >> 8) & 0xff);\n view.setUint8(at + 2, (value >> 16) & 0xff);\n }\n at += bytes;\n }\n }\n return out;\n}\n","import { createWorkerClient, type WorkerClient, type WorkerLike } from \"@hussmartinez/sdk-core\";\nimport { asAudioError, throwIfAborted } from \"../core/errors/abort.js\";\nimport { AudioError } from \"../core/errors/audio-error.js\";\nimport { dbToGain } from \"../core/model/envelope.js\";\nimport { gatherSegments, mixLength } from \"../core/model/mix.js\";\nimport { assertClip } from \"../core/model/plan.js\";\nimport type {\n AudioProcessor,\n AudioRenderJob,\n AudioRenderResult,\n AudioSampleFormat,\n} from \"../core/ports/audio-processor.js\";\nimport type { AudioWorkerContract } from \"./audio-worker/contract.js\";\nimport { type AudioWorkerSource, audioWorkerSource } from \"./audio-worker/loader.js\";\nimport { dataSize } from \"./wav/wav-writer.js\";\n\n/**\n * Frames per output block between the page and the worker: at most 2¹⁶ per\n * channel (docs/adr/0002).\n */\nexport const EXPORT_BLOCK_FRAMES = 65_536;\n\nconst SAMPLE_FORMATS: ReadonlySet<string> = new Set<AudioSampleFormat>([\n \"pcm16\",\n \"pcm24\",\n \"float32\",\n]);\n\n/**\n * Options for {@link createAudioProcessor}.\n *\n * @public\n */\nexport interface AudioProcessorOptions {\n /**\n * Milliseconds without calls after which the worker stops. It starts again\n * on the next call. Defaults to sdk-core's 30 seconds.\n */\n readonly idleTimeout?: number;\n /**\n * Where the application serves the package's `dist/assets/` directory, as\n * for `createAudioEngine` (docs/adr/0002). By default the worker is\n * inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/** What the processor needs from its environment, replaceable in tests. */\nexport interface ProcessorEnvironment extends AudioWorkerSource {\n readonly idleTimeout?: number;\n}\n\n/**\n * Creates the SDK's processor (docs/adr/0003, docs/adr/0006): it mixes a\n * plan's audible tracks, with their clips' gain and fades, the tracks' gains\n * and the master gain, and encodes the mix as a WAV file, in its own\n * worker, block by block. The page sends each block's source samples, at\n * most 2¹⁶ frames per channel, and collects the encoded blocks into a\n * `Blob` of parts, so an export never holds the whole file in one buffer.\n *\n * Sources with another channel count mix into the plan's by Web Audio's\n * speaker rules, as playback does. Tracks sum at unity. Samples are clamped\n * to full scale, and the result gives the mix's peak and how many frames\n * were clamped;\n * 16-bit and 24-bit PCM round half away from zero, without dither. Files\n * whose sizes don't fit 32 bits are written as RF64.\n *\n * @example\n * ```ts\n * const processor = createAudioProcessor();\n * const { blob, peakDb, clippedFrames } = await processor.render(\n * { plan, sources, format: { container: \"wav\", sampleFormat: \"pcm24\" } },\n * { signal, onProgress },\n * );\n * ```\n *\n * @public\n */\nexport function createAudioProcessor(options: AudioProcessorOptions = {}): AudioProcessor {\n return createProcessor({\n ...audioWorkerSource(options.assetsUrl),\n ...(options.idleTimeout === undefined ? {} : { idleTimeout: options.idleTimeout }),\n });\n}\n\n/** Checks a job before any work, as the port promises. */\nfunction check(job: AudioRenderJob): AudioSampleFormat {\n const { plan, sources, format } = job;\n if (format.container !== \"wav\")\n throw new TypeError(`Can't export to ${String(format.container)}.`);\n const sampleFormat = format.sampleFormat ?? \"pcm16\";\n if (!SAMPLE_FORMATS.has(sampleFormat)) {\n throw new TypeError(`Unknown sample format ${String(sampleFormat)}.`);\n }\n if (!Number.isSafeInteger(plan.sampleRate) || plan.sampleRate < 1) {\n throw new RangeError(\"The plan's sample rate must be a whole number above 0.\");\n }\n if (!Number.isSafeInteger(plan.channels) || plan.channels < 1) {\n throw new RangeError(\"The plan's channel count must be a whole number above 0.\");\n }\n for (const track of plan.tracks) {\n for (const clip of track.clips) {\n const source = sources.get(clip.source);\n if (!source) {\n throw new TypeError(`Clip ${clip.key}'s source ${clip.source} isn't in the job.`);\n }\n assertClip(clip, source.length);\n }\n }\n return sampleFormat;\n}\n\n/**\n * The processor, with its environment passed in.\n *\n * @internal\n */\nexport function createProcessor(environment: ProcessorEnvironment): AudioProcessor {\n let startWorker: (() => WorkerLike) | undefined;\n let client: WorkerClient<AudioWorkerContract> | undefined;\n let destroyed = false;\n\n async function ready(): Promise<WorkerClient<AudioWorkerContract>> {\n if (destroyed) throw new Error(\"The audio processor has been destroyed.\");\n startWorker ??= await environment.loadWorker();\n client ??= createWorkerClient<AudioWorkerContract>({\n createWorker: () => {\n if (!startWorker) {\n throw new AudioError(\"WORKER_START_FAILED\", \"The audio worker hasn't loaded.\");\n }\n return startWorker();\n },\n errorClasses: { AudioError },\n packageVersion: environment.version,\n ...(environment.asset === undefined ? {} : { workerAsset: environment.asset }),\n ...(environment.idleTimeout === undefined ? {} : { idleTimeout: environment.idleTimeout }),\n });\n return client;\n }\n\n async function render(\n job: AudioRenderJob,\n signal: AbortSignal | undefined,\n onProgress: ((fraction: number) => void) | undefined,\n ): Promise<AudioRenderResult> {\n const { plan, sources } = job;\n const sampleFormat = check(job);\n throwIfAborted(signal);\n const worker = await ready();\n const call = signal ? { signal } : {};\n // What sounds: a muted track neither plays nor pads the file.\n const frames = mixLength(plan);\n const gain = dbToGain(plan.gainDb);\n const spec = { sampleRate: plan.sampleRate, channels: plan.channels, frames, sampleFormat };\n const parts: Uint8Array<ArrayBuffer>[] = [\n await worker.call(\"wavHeader\", { ...spec, metadata: { ...plan.metadata } }, call),\n ];\n let peak = 0;\n let clippedFrames = 0;\n for (let start = 0; start < frames; start += EXPORT_BLOCK_FRAMES) {\n throwIfAborted(signal);\n const length = Math.min(EXPORT_BLOCK_FRAMES, frames - start);\n // Copies of each audible clip's part of the block, which the worker\n // then owns: the sources are never transferred away.\n const segments = gatherSegments(plan, sources, start, length);\n const block = await worker.call(\n \"renderBlock\",\n { channels: plan.channels, frames: length, gain, sampleFormat, segments },\n { ...call, transfer: true },\n );\n parts.push(block.bytes);\n peak = Math.max(peak, block.peak);\n clippedFrames += block.clipped;\n onProgress?.((start + length) / frames);\n }\n // Chunks are padded to an even size.\n if (dataSize(spec) % 2 === 1) parts.push(new Uint8Array(1));\n if (frames === 0) onProgress?.(1);\n return {\n blob: new Blob(parts, { type: \"audio/wav\" }),\n peakDb: 20 * Math.log10(peak),\n clippedFrames,\n };\n }\n\n return {\n async render(job, options = {}) {\n try {\n return await render(job, options.signal, options.onProgress);\n } catch (error) {\n if (error instanceof TypeError || error instanceof RangeError) throw error;\n throw asAudioError(error, \"The recording couldn't be exported.\");\n }\n },\n async destroy() {\n destroyed = true;\n client?.destroy();\n },\n };\n}\n","import type { AudioEngine } from \"../core/ports/audio-engine.js\";\nimport type { AudioOutput } from \"../core/ports/audio-output.js\";\nimport type { AudioProcessor } from \"../core/ports/audio-processor.js\";\nimport { createAudioEngine } from \"./audio-engine.js\";\nimport { createAudioOutput } from \"./audio-output.js\";\nimport { createAudioProcessor } from \"./audio-processor.js\";\n\n/**\n * Options for {@link createAudioAdapters}.\n *\n * @public\n */\nexport interface AudioAdaptersOptions {\n /**\n * Where the application serves the package's `dist/assets/` directory, for\n * the engine's and the processor's worker alike (docs/adr/0002). By\n * default the worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n /** Milliseconds without calls after which each worker stops. Defaults to sdk-core's 30 seconds. */\n readonly idleTimeout?: number;\n}\n\n/**\n * The SDK's own adapters, made together: what a session and its playback\n * need. You own them: the session never destroys what it's given, so call\n * {@link AudioAdapters.destroy} after closing the session.\n *\n * @public\n */\nexport interface AudioAdapters {\n readonly engine: AudioEngine;\n readonly processor: AudioProcessor;\n readonly output: AudioOutput;\n /** Destroys the engine, the processor and the output, waiting for each. */\n destroy(): Promise<void>;\n}\n\n/**\n * Creates the SDK's engine, processor and output with one set of options,\n * so a self-hosted worker's `assetsUrl` is given once (docs/adr/0006).\n * Nothing starts until it's used: no worker, and no `AudioContext` until\n * the first `play()`.\n *\n * @example\n * ```ts\n * const adapters = createAudioAdapters({ assetsUrl: \"/audio-sdk/\" });\n * const session = createAudioSession({ engine: adapters.engine, processor: adapters.processor });\n * const disconnect = connectOutput(session, adapters.output);\n * // …\n * disconnect();\n * await session.close();\n * await adapters.destroy();\n * ```\n *\n * @public\n */\nexport function createAudioAdapters(options: AudioAdaptersOptions = {}): AudioAdapters {\n const worker = {\n ...(options.assetsUrl === undefined ? {} : { assetsUrl: options.assetsUrl }),\n ...(options.idleTimeout === undefined ? {} : { idleTimeout: options.idleTimeout }),\n };\n const engine = createAudioEngine(worker);\n const processor = createAudioProcessor(worker);\n const output = createAudioOutput();\n return {\n engine,\n processor,\n output,\n async destroy() {\n await Promise.all([engine.destroy(), processor.destroy(), output.destroy()]);\n },\n };\n}\n","import {\n coreLimits,\n defineLimits,\n type FilePolicy,\n type FilePolicyOverrides,\n type Limits,\n} from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"./audio-error.js\";\n\n/**\n * The audio SDK's limit definitions: sdk-core's core limits with audio\n * defaults, plus six for audio (ADR 0004, docs/adr/0006).\n *\n * | Limit | Code | Default maximum | Default warning |\n * |---|---|---|---|\n * | `maxFileSize` | `FILE_TOO_LARGE` | 1 GB | 250 MB |\n * | `maxFiles` | `TOO_MANY_FILES` | 20 | none |\n * | `maxDecodedSize` | `DECODED_SIZE_TOO_LARGE` | 1 GB | 400 MB |\n * | `maxProcessingTime` | `PROCESSING_TIME_EXCEEDED` | 120 s | none |\n * | `maxDuration` | `DURATION_TOO_LONG` | 3 hours | 1 hour |\n * | `maxChannels` | `TOO_MANY_CHANNELS` | 8 | none |\n * | `maxSampleRate` | `SAMPLE_RATE_TOO_HIGH` | 192 kHz | none |\n * | `maxSessionSize` | `SESSION_TOO_LARGE` | 1.5 GB | 750 MB |\n * | `maxClips` | `TOO_MANY_CLIPS` | 2,000 | none |\n * | `maxTracks` | `TOO_MANY_TRACKS` | 16 | none |\n *\n * Sizes are decimal: 1 MB is 1,000,000 bytes. Decoded sizes count 32-bit\n * floats: frames × channels × 4 bytes. `maxDuration` is in milliseconds, and\n * `maxSampleRate` is in hertz. `maxDuration` bounds each file, and the plan's\n * length too: positions are free, so no file's limit keeps a clip from being\n * placed hours in. `maxClips` counts the clips of every track together.\n *\n * @public\n */\nexport const audioLimitDefinitions = {\n ...coreLimits,\n maxFileSize: { ...coreLimits.maxFileSize, default: 1_000_000_000, warning: 250_000_000 },\n maxDecodedSize: { ...coreLimits.maxDecodedSize, default: 1_000_000_000, warning: 400_000_000 },\n maxDuration: {\n code: \"DURATION_TOO_LONG\",\n unit: \"milliseconds\",\n default: 3 * 60 * 60 * 1_000,\n warning: 60 * 60 * 1_000,\n },\n maxChannels: { code: \"TOO_MANY_CHANNELS\", unit: \"count\", default: 8 },\n maxSampleRate: { code: \"SAMPLE_RATE_TOO_HIGH\", unit: \"hertz\", default: 192_000 },\n maxSessionSize: {\n code: \"SESSION_TOO_LARGE\",\n unit: \"bytes\",\n default: 1_500_000_000,\n warning: 750_000_000,\n },\n maxClips: { code: \"TOO_MANY_CLIPS\", unit: \"count\", default: 2_000 },\n maxTracks: { code: \"TOO_MANY_TRACKS\", unit: \"count\", default: 16 },\n} as const;\n\n/**\n * The type of {@link audioLimitDefinitions}.\n *\n * @public\n */\nexport type AudioLimitDefinitions = typeof audioLimitDefinitions;\n\n/**\n * The names of the audio SDK's limits.\n *\n * @public\n */\nexport type AudioLimitName = keyof AudioLimitDefinitions;\n\n/**\n * A host's `filePolicy`: a new maximum, or `{ maximum, warning }`, for any of\n * the audio SDK's limits. `Infinity` disables a maximum, which removes a\n * protection against hostile files, or disables a warning. Unknown limit\n * names throw `TypeError` when the policy is resolved.\n *\n * @example\n * ```ts\n * // Long recordings: raise the decoded and session sizes together.\n * const filePolicy: AudioFilePolicyOverrides = {\n * maxDecodedSize: 2e9,\n * maxSessionSize: { maximum: 3e9, warning: 1.5e9 },\n * };\n * ```\n *\n * @public\n */\nexport type AudioFilePolicyOverrides = FilePolicyOverrides<AudioLimitDefinitions>;\n\n/**\n * A resolved file policy for the audio SDK. Violations throw\n * {@link AudioError}.\n *\n * @public\n */\nexport type AudioFilePolicy = FilePolicy<AudioLimitDefinitions>;\n\n/**\n * The audio SDK's limits, ready to resolve a host's `filePolicy`. Violations\n * are thrown as {@link AudioError}, with `details` naming the limit.\n *\n * @example\n * ```ts\n * const policy = audioLimits.resolve(props.filePolicy);\n * policy.check(\"maxChannels\", channels); // throws AudioError(\"TOO_MANY_CHANNELS\") above 8\n * ```\n *\n * @public\n */\nexport const audioLimits: Limits<AudioLimitDefinitions> = /* @__PURE__ */ defineLimits(\n audioLimitDefinitions,\n { errorClass: AudioError },\n);\n","import {\n type AudioClipBody,\n type AudioFade,\n type AudioFadeCurve,\n clipLength,\n clipProblem,\n} from \"../model/plan.js\";\n\n/**\n * Checks the reducer and the document readers share: shapes, keys, fades\n * and clips, each failing with a stable reason (sdk-core ADR 0045).\n */\n\n/**\n * The longest metadata value, in Unicode code points, so that history steps\n * stay small. Code points are what JSON Schema's `maxLength` counts, and\n * what every language can count, so the limit is the same in every port\n * (sdk-core ADR 0045): 1,000 emoji fit, though they're 2,000 UTF-16 units.\n *\n * @public\n */\nexport const MAX_METADATA_LENGTH = 1_000;\n\n/**\n * Whether text has more than `max` code points, counted with `for…of`,\n * which walks code points, and stopping as soon as it knows.\n *\n * @internal\n */\nexport function longerThan(text: string, max: number): boolean {\n // Every code point is one or two UTF-16 units.\n if (text.length <= max) return false;\n let count = 0;\n for (const _ of text) {\n count += 1;\n if (count > max) return true;\n }\n return false;\n}\n\nconst CURVES: ReadonlySet<string> = new Set<AudioFadeCurve>([\"linear\", \"equalPower\"]);\n\n/**\n * The frames of each registered source, or `undefined` for an id the\n * session doesn't have. Sources never change, so the reducer stays pure.\n *\n * @internal\n */\nexport type SourceFrames = (source: string) => number | undefined;\n\n/**\n * A refusal with its reason, before it becomes the caller's `AudioError`.\n *\n * @internal\n */\nexport class Invalid extends Error {\n /** A rejection token, such as `unknown-clip`. */\n readonly reason: string;\n\n constructor(reason: string, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\n/** @internal */\nexport function invalid(reason: string, message: string): never {\n throw new Invalid(reason, message);\n}\n\n/** An object whose fields, from a command that may have been stored or sent, are unchecked. */\nexport type Unchecked<T> = { readonly [Key in keyof T]?: unknown };\n\n/** @internal */\nexport function isRecord<T>(value: unknown): value is Unchecked<T> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** @internal */\nexport function isKey(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/** @internal */\nexport function isIndex(value: unknown, max: number): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= max;\n}\n\n/** @internal */\nexport function fade(value: unknown, name: string): AudioFade {\n if (!isRecord<AudioFade>(value)) invalid(\"malformed-command\", `${name} isn't a fade`);\n onlyFields(value, FADE_FIELDS, name);\n if (typeof value.curve !== \"string\" || !CURVES.has(value.curve)) {\n invalid(\"invalid-fade-curve\", `${name}'s curve isn't linear or equalPower`);\n }\n return { frames: value.frames as number, curve: value.curve as AudioFadeCurve };\n}\n\nconst CLIP_FIELDS = [\"key\", \"source\", \"start\", \"end\", \"gainDb\", \"fadeIn\", \"fadeOut\"];\nconst FADE_FIELDS = [\"frames\", \"curve\"];\n\n/** Fails unless every field the object has is one of `allowed`. */\n/** @internal */\nexport function onlyFields(value: object, allowed: readonly string[], what: string): void {\n for (const [field, content] of Object.entries(value)) {\n if (content !== undefined && !allowed.includes(field)) {\n invalid(\"malformed-command\", `${what} has no field ${field}`);\n }\n }\n}\n\n/**\n * A clean copy of a clip's range, gain and fades, with only those fields,\n * or a failure if it isn't valid within its source.\n */\n/** @internal */\nexport function checkClipBody(value: unknown, sourceFrames: SourceFrames): AudioClipBody {\n if (!isRecord<AudioClipBody>(value) || !isKey(value.key) || !isKey(value.source)) {\n invalid(\"malformed-command\", \"a clip needs a key and a source\");\n }\n onlyFields(value, CLIP_FIELDS, \"a clip\");\n const clip: AudioClipBody = {\n key: value.key,\n source: value.source,\n start: value.start as number,\n end: value.end as number,\n gainDb: value.gainDb as number,\n fadeIn: fade(value.fadeIn, \"fadeIn\"),\n fadeOut: fade(value.fadeOut, \"fadeOut\"),\n };\n const frames = sourceFrames(clip.source);\n if (frames === undefined) invalid(\"unknown-source\", `the session has no source ${clip.source}`);\n const problem = clipProblem(clip, frames);\n if (problem) invalid(problem, `clip ${clip.key} isn't valid within its source`);\n return clip;\n}\n\n/**\n * Shortens fades that no longer fit their clip, in proportion, so that\n * neither reaches into the other.\n */\n/** @internal */\nexport function fitFades<Clip extends AudioClipBody>(clip: Clip): Clip {\n const length = clipLength(clip);\n const total = clip.fadeIn.frames + clip.fadeOut.frames;\n // A clip of no frames, or of invalid ones, is left for validation to\n // refuse with its own reason.\n if (total <= length || !(length > 0)) return clip;\n return {\n ...clip,\n fadeIn: { ...clip.fadeIn, frames: Math.floor((clip.fadeIn.frames * length) / total) },\n fadeOut: { ...clip.fadeOut, frames: Math.floor((clip.fadeOut.frames * length) / total) },\n };\n}\n","import type { AudioMetadata } from \"../model/plan.js\";\nimport {\n invalid,\n isKey,\n isRecord,\n longerThan,\n MAX_METADATA_LENGTH,\n onlyFields,\n} from \"../operations/checks.js\";\n\n/**\n * The parts every version of a plan document has (sdk-core ADR 0045): the\n * format's name, sources with their assets, and the metadata.\n */\n\n/**\n * The name of the clip plan's portable format (sdk-core ADR 0045).\n *\n * @public\n */\nexport const AUDIO_PLAN_FORMAT = \"hm-audio-plan\";\n\n/**\n * A content-addressed reference to binary data, such as a source's file\n * (sdk-core ADR 0045). Documents never inline bytes.\n *\n * @public\n */\nexport interface AudioAssetReference {\n /** `sha256:` and the lowercase hex SHA-256 of the bytes. */\n readonly asset: string;\n /** The bytes' media type, such as `audio/wav`, in lowercase. */\n readonly mediaType: string;\n /** The size of the bytes. */\n readonly size: number;\n}\n\n/**\n * A source, as a plan document records it: its length, which its clips must\n * lie within, and, once documents travel with their files, its content.\n *\n * @public\n */\nexport interface AudioPlanDocumentSource {\n /** The source's length in frames, at the plan's sample rate. */\n readonly frames: number;\n readonly asset?: AudioAssetReference;\n}\n\nconst SOURCE_FIELDS = [\"frames\", \"asset\"];\nconst ASSET_FIELDS = [\"asset\", \"mediaType\", \"size\"];\nconst METADATA_FIELDS: readonly (keyof AudioMetadata)[] = [\n \"title\",\n \"artist\",\n \"album\",\n \"year\",\n \"comment\",\n];\n/** The patterns the schema uses too, so both accept the same documents. */\nconst ASSET_ID = /^sha256:[0-9a-f]{64}$/;\nconst MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;\n\n/** @internal */\nexport function malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\n/** @internal */\nexport const isCount = (value: unknown, min: number): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min;\n\nfunction readAsset(value: unknown): AudioAssetReference {\n if (!isRecord<AudioAssetReference>(value)) malformed(\"an asset is an object\");\n onlyFields(value, ASSET_FIELDS, \"an asset\");\n const { asset, mediaType, size } = value;\n if (typeof asset !== \"string\" || !ASSET_ID.test(asset)) malformed(\"an asset id is sha256:<hex>\");\n if (typeof mediaType !== \"string\" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) {\n malformed(\"a media type is type/subtype, in lowercase\");\n }\n if (!isCount(size, 0)) malformed(\"an asset's size is a whole number of bytes\");\n return { asset, mediaType, size };\n}\n\n/** @internal */\nexport function readSources(value: unknown): Record<string, AudioPlanDocumentSource> {\n if (!isRecord<Record<string, unknown>>(value) || Array.isArray(value)) {\n malformed(\"sources is an object\");\n }\n return Object.fromEntries(\n Object.entries(value).map(([id, source]) => {\n if (!isKey(id)) malformed(\"a source id is a non-empty string\");\n if (!isRecord<AudioPlanDocumentSource>(source)) malformed(\"a source is an object\");\n onlyFields(source, SOURCE_FIELDS, \"a source\");\n if (!isCount(source.frames, 1)) malformed(\"a source's frames are a whole number above 0\");\n const entry: AudioPlanDocumentSource =\n source.asset === undefined\n ? { frames: source.frames }\n : { frames: source.frames, asset: readAsset(source.asset) };\n return [id, entry];\n }),\n );\n}\n\n/** @internal */\nexport function readMetadata(value: unknown): AudioMetadata {\n if (!isRecord<AudioMetadata>(value)) malformed(\"metadata is an object\");\n onlyFields(value, METADATA_FIELDS, \"metadata\");\n const fields = METADATA_FIELDS.map((field) => {\n const text = value[field];\n if (typeof text !== \"string\") malformed(`metadata.${field} is text`);\n if (longerThan(text, MAX_METADATA_LENGTH)) {\n invalid(\"metadata-too-long\", `metadata.${field} is over ${MAX_METADATA_LENGTH} code points`);\n }\n return [field, text] as const;\n });\n return Object.fromEntries(fields) as unknown as AudioMetadata;\n}\n","import type { Reducer } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"../errors/audio-error.js\";\nimport {\n type AudioClip,\n type AudioClipProblem,\n type AudioFadeCurve,\n type AudioMetadata,\n type AudioPlan,\n type AudioTrack,\n clipEnd,\n clipIndexAt,\n EMPTY_METADATA,\n MAX_GAIN_DB,\n MAX_TRACK_NAME_LENGTH,\n MIN_GAIN_DB,\n NO_FADE,\n orderProblem,\n planLength,\n} from \"../model/plan.js\";\nimport {\n checkClipBody,\n fade,\n fitFades,\n Invalid,\n isIndex,\n isKey,\n isRecord,\n longerThan,\n MAX_METADATA_LENGTH,\n onlyFields,\n type SourceFrames,\n type Unchecked,\n} from \"./checks.js\";\n\n/**\n * The plan's commands and reducer (docs/adr/0003, docs/adr/0006).\n *\n * Edits are of two kinds. **Clip edits never move another clip:** they fail\n * with `clips-overlap` rather than push a neighbour. **Time edits add or\n * remove time on the tracks they name,** and move everything after it on\n * those tracks.\n */\n\n/**\n * Adds clips to a track, each at its own `at`, in free space.\n *\n * @public\n */\nexport interface AudioInsertClipsCommand {\n readonly type: \"audio.insertClips\";\n readonly track: string;\n /** The clips, in any order, with keys the plan doesn't have. */\n readonly clips: readonly AudioClip[];\n}\n\n/**\n * Removes clips, on any tracks, leaving silence where they were.\n *\n * @public\n */\nexport interface AudioRemoveClipsCommand {\n readonly type: \"audio.removeClips\";\n readonly keys: readonly string[];\n}\n\n/**\n * Changes the range of its source a clip plays. The audio stays where it is\n * on the timeline: moving `start` moves the clip's `at` by the same amount.\n * Fades that no longer fit are shortened in proportion.\n *\n * @public\n */\nexport interface AudioTrimClipCommand {\n readonly type: \"audio.trimClip\";\n readonly key: string;\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * Splits a clip in two at a timeline frame strictly inside it. The first\n * part keeps the key and the fade in; the second takes `newKey` and the\n * fade out.\n *\n * @public\n */\nexport interface AudioSplitClipCommand {\n readonly type: \"audio.splitClip\";\n readonly key: string;\n readonly at: number;\n /**\n * The second part's key. `session.execute` gives one from\n * `session.createKey()` when it's left out; a stored command, and the\n * format, always carry it.\n */\n readonly newKey?: string;\n}\n\n/**\n * Moves clips by a signed number of frames, and to another track when one is named.\n *\n * @public\n */\nexport interface AudioMoveClipsCommand {\n readonly type: \"audio.moveClips\";\n readonly keys: readonly string[];\n /** Frames to move by: negative is earlier. */\n readonly by: number;\n /** The track every clip moves to. Without it, each stays on its own. */\n readonly track?: string;\n}\n\n/**\n * Sets the gain of clips.\n *\n * @public\n */\nexport interface AudioSetGainCommand {\n readonly type: \"audio.setGain\";\n readonly keys: readonly string[];\n readonly gainDb: number;\n}\n\n/**\n * Sets a clip's fade in or fade out. Together, the two must fit in the clip.\n *\n * @public\n */\nexport interface AudioSetFadeCommand {\n readonly type: \"audio.setFade\";\n readonly key: string;\n readonly edge: \"in\" | \"out\";\n readonly frames: number;\n readonly curve: AudioFadeCurve;\n}\n\n/**\n * Removes a range of time from the named tracks, trimming the clips at its\n * edges. With `ripple`, later clips on those tracks move earlier by the\n * range's length; without, silence stays.\n *\n * @public\n */\nexport interface AudioDeleteRangeCommand {\n readonly type: \"audio.deleteRange\";\n readonly start: number;\n readonly end: number;\n readonly tracks: readonly string[];\n readonly ripple: boolean;\n /**\n * By track key: the key of the part after the range, on a track where the\n * range lies inside one clip. A track that doesn't need its key ignores it.\n * `session.execute` gives a key to every track named without one.\n */\n readonly newKeys?: Readonly<Record<string, string>>;\n}\n\n/**\n * Removes everything outside a range, on every track, and moves what's kept to the start.\n *\n * @public\n */\nexport interface AudioKeepRangeCommand {\n readonly type: \"audio.keepRange\";\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * Opens `frames` of silence at a timeline frame on the named tracks. A clip\n * that lies across the frame is split there, and everything after moves\n * later.\n *\n * @public\n */\nexport interface AudioInsertTimeCommand {\n readonly type: \"audio.insertTime\";\n readonly at: number;\n readonly frames: number;\n readonly tracks: readonly string[];\n /**\n * By track key: the key of the second part of a clip the frame splits.\n * `session.execute` gives a key to every track named without one.\n */\n readonly newKeys?: Readonly<Record<string, string>>;\n}\n\n/**\n * Adds an empty track at an index.\n *\n * @public\n */\nexport interface AudioAddTrackCommand {\n readonly type: \"audio.addTrack\";\n /**\n * The new track's key. `session.execute` gives one from\n * `session.createKey()` when it's left out; a stored command, and the\n * format, always carry it.\n */\n readonly key?: string;\n readonly index: number;\n readonly name?: string;\n}\n\n/**\n * Removes tracks, with their clips. A plan keeps at least one track.\n *\n * @public\n */\nexport interface AudioRemoveTracksCommand {\n readonly type: \"audio.removeTracks\";\n readonly keys: readonly string[];\n}\n\n/**\n * Moves a track to an index of the resulting plan.\n *\n * @public\n */\nexport interface AudioMoveTrackCommand {\n readonly type: \"audio.moveTrack\";\n readonly key: string;\n readonly to: number;\n}\n\n/**\n * Sets the fields given of a track, at least one.\n *\n * @public\n */\nexport interface AudioSetTrackCommand {\n readonly type: \"audio.setTrack\";\n readonly key: string;\n readonly name?: string;\n readonly gainDb?: number;\n readonly muted?: boolean;\n readonly soloed?: boolean;\n}\n\n/**\n * Sets the master gain.\n *\n * @public\n */\nexport interface AudioSetMasterGainCommand {\n readonly type: \"audio.setMasterGain\";\n readonly gainDb: number;\n}\n\n/**\n * Sets the plan's channel count.\n *\n * @public\n */\nexport interface AudioSetChannelsCommand {\n readonly type: \"audio.setChannels\";\n readonly channels: number;\n}\n\n/**\n * Sets one metadata field.\n *\n * @public\n */\nexport interface AudioSetMetadataCommand {\n readonly type: \"audio.setMetadata\";\n readonly field: keyof AudioMetadata;\n readonly value: string;\n}\n\n/**\n * Puts removed clips back on their tracks. A clip's `at` says where. Undo's, for a removal.\n *\n * @public\n */\nexport interface AudioRestoreClipsCommand {\n readonly type: \"audio.restoreClips\";\n readonly entries: readonly { readonly track: string; readonly clip: AudioClip }[];\n}\n\n/**\n * Sets clips, matched by key, to states with every field given. Undo's, for a trim, a gain or a fade.\n *\n * @public\n */\nexport interface AudioUpdateClipsCommand {\n readonly type: \"audio.updateClips\";\n readonly clips: readonly AudioClip[];\n}\n\n/**\n * Puts clips on tracks and positions. Undo's, for a move, and its own inverse.\n *\n * @public\n */\nexport interface AudioPlaceClipsCommand {\n readonly type: \"audio.placeClips\";\n readonly entries: readonly {\n readonly key: string;\n readonly track: string;\n readonly at: number;\n }[];\n}\n\n/**\n * One track's part of {@link AudioReplaceClipsCommand}.\n *\n * @public\n */\nexport interface AudioClipsEdit {\n readonly track: string;\n /** The first clip of the run to replace. */\n readonly index: number;\n /** How many clips the run has. */\n readonly count: number;\n /** What takes the run's place. */\n readonly clips: readonly AudioClip[];\n /** Frames every clip after the run moves by: negative is earlier. */\n readonly shift: number;\n}\n\n/**\n * On each named track, replaces a run of neighbouring clips, then moves\n * every clip after the run by `shift` frames. Undo's, for a split and for\n * the time edits, and its own inverse: a ripple that moved a thousand clips\n * is undone by one number.\n *\n * @public\n */\nexport interface AudioReplaceClipsCommand {\n readonly type: \"audio.replaceClips\";\n readonly edits: readonly AudioClipsEdit[];\n}\n\n/**\n * Puts removed tracks back at their indexes, with their clips and settings. Undo's.\n *\n * @public\n */\nexport interface AudioRestoreTracksCommand {\n readonly type: \"audio.restoreTracks\";\n /** Each track, and the index it takes in the resulting plan, in increasing order. */\n readonly entries: readonly { readonly index: number; readonly track: AudioTrack }[];\n}\n\n/**\n * The edits a user makes: `hm-audio-command` version 2\n * (docs/formats/hm-audio-plan.md).\n *\n * @public\n */\nexport type AudioUserCommand =\n | AudioInsertClipsCommand\n | AudioRemoveClipsCommand\n | AudioTrimClipCommand\n | AudioSplitClipCommand\n | AudioMoveClipsCommand\n | AudioSetGainCommand\n | AudioSetFadeCommand\n | AudioDeleteRangeCommand\n | AudioKeepRangeCommand\n | AudioInsertTimeCommand\n | AudioAddTrackCommand\n | AudioRemoveTracksCommand\n | AudioMoveTrackCommand\n | AudioSetTrackCommand\n | AudioSetMasterGainCommand\n | AudioSetChannelsCommand\n | AudioSetMetadataCommand;\n\n/**\n * An edit to the plan (docs/adr/0003, docs/adr/0006): the user's commands,\n * and the inverses that only undo runs, which aren't part of the portable\n * format. Commands are plain, structured-cloneable data, never carry\n * samples, and each has an exact inverse, which is how undo works\n * (ADR 0010, ADR 0029).\n *\n * @public\n */\nexport type AudioCommand =\n | AudioUserCommand\n | AudioRestoreClipsCommand\n | AudioUpdateClipsCommand\n | AudioPlaceClipsCommand\n | AudioReplaceClipsCommand\n | AudioRestoreTracksCommand;\n\n/**\n * Why the reducer refused a command, as a stable token: `details.reason` on\n * `INVALID_COMMAND`, which hosts and conformance vectors compare instead of\n * the message (sdk-core ADR 0045). Tokens never change meaning once\n * released.\n *\n * - A clip's own problems, {@link AudioClipProblem}.\n * - `malformed-command`: the command isn't shaped as its type says.\n * - `unknown-command`: its `type` isn't one of {@link AudioCommand}'s.\n * - `unknown-source`: a clip names a source the session doesn't hold.\n * - `invalid-fade-curve`: a fade's curve isn't `linear` or `equalPower`.\n * - `no-clips`, `no-tracks`: the command needs at least one, and names none.\n * - `duplicate-key`: it names a clip or a track twice, or two things would\n * share a key.\n * - `key-taken`: a new clip's or track's key is already in the plan.\n * - `unknown-clip`, `unknown-track`: it names one the plan doesn't have.\n * - `frame-outside-plan`: a timeline frame is outside the plan, or a clip\n * would start before the timeline does.\n * - `empty-range`: a range is shorter than one frame.\n * - `not-inside-clip`: a split frame isn't strictly inside its clip.\n * - `new-key-required`: it cuts a clip in two without the new part's key.\n * - `invalid-index`: an index or a run is outside the plan or the track.\n * - `empty-change`: `audio.setTrack` sets nothing.\n * - `invalid-edge`: a fade's edge isn't `in` or `out`.\n * - `unknown-metadata-field`: the metadata has no such field.\n * - `metadata-too-long`, `name-too-long`: a metadata value is over\n * {@link MAX_METADATA_LENGTH} code points, or a track's name over\n * {@link MAX_TRACK_NAME_LENGTH}.\n * - `clips-overlap`: a clip would start before the one before it has ended.\n * - `clips-out-of-order`: a list of a track's clips isn't in time order.\n * - `last-track`: it would leave the plan without a track.\n *\n * The session adds `no-recording`, for a command or an export with no\n * recording open, `not-plain-data`, for a command that can't be cloned,\n * `empty-plan`, for an export of a plan with no clips, and\n * `nothing-audible`, for an export in which no track with clips sounds.\n *\n * @public\n */\nexport type AudioCommandRejection =\n | AudioClipProblem\n | \"malformed-command\"\n | \"unknown-command\"\n | \"unknown-source\"\n | \"invalid-fade-curve\"\n | \"no-clips\"\n | \"no-tracks\"\n | \"duplicate-key\"\n | \"key-taken\"\n | \"unknown-clip\"\n | \"unknown-track\"\n | \"frame-outside-plan\"\n | \"empty-range\"\n | \"not-inside-clip\"\n | \"new-key-required\"\n | \"invalid-index\"\n | \"empty-change\"\n | \"invalid-edge\"\n | \"unknown-metadata-field\"\n | \"metadata-too-long\"\n | \"name-too-long\"\n | \"clips-overlap\"\n | \"clips-out-of-order\"\n | \"last-track\"\n | \"no-recording\"\n | \"not-plain-data\"\n | \"empty-plan\"\n | \"nothing-audible\";\n\n/** @internal */\nexport function refuse(reason: AudioCommandRejection, message: string): never {\n throw new Invalid(reason, message);\n}\n\nconst COMMAND_FIELDS: Readonly<Record<AudioCommand[\"type\"], readonly string[]>> = {\n \"audio.insertClips\": [\"track\", \"clips\"],\n \"audio.removeClips\": [\"keys\"],\n \"audio.trimClip\": [\"key\", \"start\", \"end\"],\n \"audio.splitClip\": [\"key\", \"at\", \"newKey\"],\n \"audio.moveClips\": [\"keys\", \"by\", \"track\"],\n \"audio.setGain\": [\"keys\", \"gainDb\"],\n \"audio.setFade\": [\"key\", \"edge\", \"frames\", \"curve\"],\n \"audio.deleteRange\": [\"start\", \"end\", \"tracks\", \"ripple\", \"newKeys\"],\n \"audio.keepRange\": [\"start\", \"end\"],\n \"audio.insertTime\": [\"at\", \"frames\", \"tracks\", \"newKeys\"],\n \"audio.addTrack\": [\"key\", \"index\", \"name\"],\n \"audio.removeTracks\": [\"keys\"],\n \"audio.moveTrack\": [\"key\", \"to\"],\n \"audio.setTrack\": [\"key\", \"name\", \"gainDb\", \"muted\", \"soloed\"],\n \"audio.setMasterGain\": [\"gainDb\"],\n \"audio.setChannels\": [\"channels\"],\n \"audio.setMetadata\": [\"field\", \"value\"],\n \"audio.restoreClips\": [\"entries\"],\n \"audio.updateClips\": [\"clips\"],\n \"audio.placeClips\": [\"entries\"],\n \"audio.replaceClips\": [\"edits\"],\n \"audio.restoreTracks\": [\"entries\"],\n};\nconst TRACK_FIELDS = [\"key\", \"name\", \"gainDb\", \"muted\", \"soloed\", \"clips\"];\n\nconst isFrames = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) >= 0;\n\n/** A gain in range, or a failure. */\nfunction checkGain(value: unknown): number {\n if (typeof value !== \"number\" || !(value >= MIN_GAIN_DB && value <= MAX_GAIN_DB)) {\n refuse(\"gain-out-of-range\", `gain must be from ${MIN_GAIN_DB} to ${MAX_GAIN_DB} dB`);\n }\n return value;\n}\n\n/** A track's name, or a failure. */\nfunction checkName(value: unknown): string {\n if (typeof value !== \"string\") refuse(\"malformed-command\", \"a track's name must be text\");\n if (longerThan(value, MAX_TRACK_NAME_LENGTH)) {\n refuse(\"name-too-long\", `a track's name can have at most ${MAX_TRACK_NAME_LENGTH} code points`);\n }\n return value;\n}\n\nfunction checkFlag(value: unknown, name: string): boolean {\n if (typeof value !== \"boolean\") refuse(\"malformed-command\", `${name} must be true or false`);\n return value;\n}\n\n/**\n * A clean copy of a positioned clip, with only its own fields, or a failure\n * if it isn't valid within its source or its position isn't whole frames.\n *\n * @internal\n */\nexport function checkClip(value: unknown, sourceFrames: SourceFrames): AudioClip {\n if (!isRecord<AudioClip>(value)) refuse(\"malformed-command\", \"a clip is an object\");\n // The clip without its position is a single-track clip, checked as one.\n const clip = checkClipBody({ ...value, at: undefined }, sourceFrames);\n const { at } = value;\n if (!isFrames(at) || !Number.isSafeInteger(at + (clip.end - clip.start))) {\n refuse(\"invalid-frames\", `clip ${clip.key}'s position isn't a whole number of frames`);\n }\n return {\n key: clip.key,\n at,\n source: clip.source,\n start: clip.start,\n end: clip.end,\n gainDb: clip.gainDb,\n fadeIn: clip.fadeIn,\n fadeOut: clip.fadeOut,\n };\n}\n\nfunction checkClips(values: unknown, sourceFrames: SourceFrames): AudioClip[] {\n if (!Array.isArray(values)) refuse(\"malformed-command\", \"clips must be a list\");\n return values.map((value) => checkClip(value, sourceFrames));\n}\n\n/** Fails unless a track's clips are in time order and don't overlap. */\nfunction checkOrder(clips: readonly AudioClip[]): void {\n const problem = orderProblem(clips);\n if (problem === \"clips-overlap\") refuse(problem, \"two clips on a track would overlap\");\n if (problem) refuse(problem, \"a track's clips must be in time order\");\n}\n\n/** Clips in time order. Clips that start together stay as they were, and fail as overlapping. */\nfunction sorted(clips: readonly AudioClip[]): AudioClip[] {\n return [...clips].sort((a, b) => a.at - b.at);\n}\n\n/**\n * A clean copy of a whole track, or a failure. Its keys aren't compared\n * with any other track's here.\n *\n * @internal\n */\nexport function checkTrack(value: unknown, sourceFrames: SourceFrames): AudioTrack {\n if (!isRecord<AudioTrack>(value) || !isKey(value.key)) {\n refuse(\"malformed-command\", \"a track needs a key\");\n }\n onlyFields(value, TRACK_FIELDS, \"a track\");\n const clips = checkClips(value.clips, sourceFrames);\n checkOrder(clips);\n return {\n key: value.key,\n name: checkName(value.name),\n gainDb: checkGain(value.gainDb),\n muted: checkFlag(value.muted, \"muted\"),\n soloed: checkFlag(value.soloed, \"soloed\"),\n clips,\n };\n}\n\n/** Every key in the plan: its tracks' and its clips'. */\nfunction keysOf(plan: AudioPlan): Set<string> {\n const keys = new Set<string>();\n for (const track of plan.tracks) {\n keys.add(track.key);\n for (const clip of track.clips) keys.add(clip.key);\n }\n return keys;\n}\n\n/**\n * Fails unless every key in the plan is there once.\n *\n * @internal\n */\nexport function checkUniqueKeys(plan: AudioPlan): void {\n const seen = new Set<string>();\n const once = (key: string) => {\n if (seen.has(key)) refuse(\"duplicate-key\", `the key ${key} appears twice`);\n seen.add(key);\n };\n for (const track of plan.tracks) {\n once(track.key);\n for (const clip of track.clips) once(clip.key);\n }\n}\n\n/** Fails unless every key is new: absent from `taken`, which it then joins. */\nfunction claim(keys: readonly unknown[], taken: Set<string>): void {\n const before = new Set(taken);\n for (const key of keys) {\n if (!isKey(key)) refuse(\"malformed-command\", \"a key must be a non-empty string\");\n if (before.has(key)) refuse(\"key-taken\", `the key ${key} is taken`);\n if (taken.has(key)) refuse(\"duplicate-key\", `the key ${key} appears twice`);\n taken.add(key);\n }\n}\n\n/** A list of keys, each once, or a failure with `empty` when there are none. */\nfunction keyList(value: unknown, empty: \"no-clips\" | \"no-tracks\"): string[] {\n if (!Array.isArray(value)) refuse(\"malformed-command\", \"keys must be a list\");\n if (value.length === 0) refuse(empty, \"it needs at least one\");\n const seen = new Set<string>();\n for (const key of value) {\n if (!isKey(key)) refuse(\"malformed-command\", \"a key must be a non-empty string\");\n if (seen.has(key)) refuse(\"duplicate-key\", `the key ${key} appears twice`);\n seen.add(key);\n }\n return value as string[];\n}\n\n/** The index of a track, by key. */\nfunction trackIndex(plan: AudioPlan, key: unknown): number {\n if (!isKey(key)) refuse(\"malformed-command\", \"a track is named by its key\");\n const index = plan.tracks.findIndex((track) => track.key === key);\n if (index < 0) refuse(\"unknown-track\", `the plan has no track ${key}`);\n return index;\n}\n\n/** The indexes of tracks, by key, in the order given. */\nfunction trackIndexes(plan: AudioPlan, keys: unknown): number[] {\n return keyList(keys, \"no-tracks\").map((key) => trackIndex(plan, key));\n}\n\ninterface Located {\n /** The index of the clip's track. */\n readonly track: number;\n readonly clip: AudioClip;\n}\n\n/** Where the named clips are, in plan order. */\nfunction locateClips(plan: AudioPlan, keys: unknown): Located[] {\n const wanted = new Set(keyList(keys, \"no-clips\"));\n const found: Located[] = [];\n plan.tracks.forEach((track, index) => {\n for (const clip of track.clips) {\n if (wanted.has(clip.key)) found.push({ track: index, clip });\n }\n });\n if (found.length !== wanted.size) refuse(\"unknown-clip\", \"the plan doesn't have every clip\");\n return found;\n}\n\nfunction locateClip(plan: AudioPlan, key: unknown): Located {\n return locateClips(plan, [key])[0] as Located;\n}\n\n/** The plan with some tracks' clips replaced, by track index. */\nfunction withClips(plan: AudioPlan, changes: ReadonlyMap<number, readonly AudioClip[]>): AudioPlan {\n if (changes.size === 0) return plan;\n return {\n ...plan,\n tracks: plan.tracks.map((track, index) => {\n const clips = changes.get(index);\n return clips ? { ...track, clips } : track;\n }),\n };\n}\n\n/** The plan with clips replaced by new states of themselves, each staying on its track. */\nfunction withUpdated(plan: AudioPlan, clips: readonly AudioClip[]): AudioPlan {\n const byKey = new Map(clips.map((clip) => [clip.key, clip]));\n const changes = new Map<number, AudioClip[]>();\n plan.tracks.forEach((track, index) => {\n if (track.clips.some((clip) => byKey.has(clip.key))) {\n const next = track.clips.map((clip) => byKey.get(clip.key) ?? clip);\n checkOrder(next);\n changes.set(index, next);\n }\n });\n return withClips(plan, changes);\n}\n\n/**\n * The part of a clip from `from` to `to`, in frames from its start, placed\n * at `at`. A part keeps the fades of the edges it shares with the clip, and\n * has none at a cut.\n */\nfunction cut(clip: AudioClip, from: number, to: number, key: string, at: number): AudioClip {\n return fitFades({\n ...clip,\n key,\n at,\n start: clip.start + from,\n end: clip.start + to,\n fadeIn: from === 0 ? clip.fadeIn : NO_FADE,\n fadeOut: to === clip.end - clip.start ? clip.fadeOut : NO_FADE,\n });\n}\n\n/** Clips moved by a signed number of frames, or a failure if one would leave the timeline. */\nfunction shifted(clips: readonly AudioClip[], by: number): AudioClip[] {\n if (by === 0) return [...clips];\n return clips.map((clip) => {\n const at = clip.at + by;\n if (at < 0) refuse(\"frame-outside-plan\", \"a clip can't start before the timeline does\");\n if (!Number.isSafeInteger(at + (clip.end - clip.start))) {\n refuse(\"invalid-frames\", \"a clip's position isn't a whole number of frames\");\n }\n return { ...clip, at };\n });\n}\n\n/** A range of the timeline inside the plan, at least one frame long. */\nfunction checkRange(plan: AudioPlan, start: unknown, end: unknown): [number, number] {\n const length = planLength(plan);\n if (!isIndex(start, length) || !isIndex(end, length)) {\n refuse(\"frame-outside-plan\", \"the range must be inside the plan\");\n }\n if (end <= start) refuse(\"empty-range\", \"the range must be at least one frame long\");\n return [start, end];\n}\n\n/**\n * The optional keys of a time edit, by the key of the track each is for.\n * Read as own fields, so a track keyed `__proto__` is a track like any other.\n */\nfunction newKeysFor(value: unknown, tracks: readonly string[]): ReadonlyMap<string, string> {\n const keys = new Map<string, string>();\n if (value === undefined) return keys;\n if (!isRecord<Record<string, unknown>>(value) || Array.isArray(value)) {\n refuse(\"malformed-command\", \"newKeys is an object of keys, by track\");\n }\n for (const [track, key] of Object.entries(value)) {\n if (!isKey(track) || !isKey(key)) {\n refuse(\"malformed-command\", \"newKeys is an object of keys, by track\");\n }\n if (!tracks.includes(track)) refuse(\"unknown-track\", `the command doesn't edit track ${track}`);\n keys.set(track, key);\n }\n return keys;\n}\n\n/** Puts clips on tracks and positions, keeping each touched track in time order. */\nfunction place(\n plan: AudioPlan,\n placements: ReadonlyMap<string, { readonly track: number; readonly at: number }>,\n): AudioPlan {\n const arriving = new Map<number, AudioClip[]>();\n const changes = new Map<number, AudioClip[]>();\n plan.tracks.forEach((track, index) => {\n const staying: AudioClip[] = [];\n for (const clip of track.clips) {\n const to = placements.get(clip.key);\n if (!to) {\n staying.push(clip);\n continue;\n }\n const moved = shifted([clip], to.at - clip.at);\n arriving.set(to.track, [...(arriving.get(to.track) ?? []), ...moved]);\n }\n if (staying.length !== track.clips.length) changes.set(index, staying);\n });\n for (const [index, clips] of arriving) {\n const base = changes.get(index) ?? (plan.tracks[index] as AudioTrack).clips;\n changes.set(index, sorted([...base, ...clips]));\n }\n for (const clips of changes.values()) checkOrder(clips);\n return withClips(plan, changes);\n}\n\ntype Applied = { state: AudioPlan; inverse: AudioCommand };\n\n/** A time edit's result: the tracks' new clips, and the edits that undo them. */\ninterface TimeEdit {\n readonly changes: Map<number, AudioClip[]>;\n readonly undo: AudioClipsEdit[];\n}\n\nfunction timeEdit(plan: AudioPlan, edit: TimeEdit): Applied {\n return {\n state: withClips(plan, edit.changes),\n inverse: { type: \"audio.replaceClips\", edits: edit.undo },\n };\n}\n\nfunction apply(plan: AudioPlan, command: AudioCommand, sourceFrames: SourceFrames): Applied {\n if (!isRecord<AudioCommand>(command)) refuse(\"malformed-command\", \"a command is an object\");\n const fields = Object.hasOwn(COMMAND_FIELDS, command.type as string)\n ? COMMAND_FIELDS[command.type as AudioCommand[\"type\"]]\n : undefined;\n if (!fields) refuse(\"unknown-command\", \"unknown command\");\n onlyFields(command, [\"type\", ...fields], command.type as string);\n\n // Each command checks what its schema states, such as a gain's range,\n // before what depends on the plan, so a command a schema refuses is\n // refused here for the schema's reason.\n switch (command.type) {\n case \"audio.insertClips\": {\n const index = trackIndex(plan, command.track);\n const clips = checkClips(command.clips, sourceFrames);\n if (clips.length === 0) refuse(\"no-clips\", \"it needs at least one clip\");\n const keys = clips.map((clip) => clip.key);\n claim(keys, keysOf(plan));\n const next = sorted([...(plan.tracks[index] as AudioTrack).clips, ...clips]);\n checkOrder(next);\n return {\n state: withClips(plan, new Map([[index, next]])),\n inverse: { type: \"audio.removeClips\", keys },\n };\n }\n\n case \"audio.removeClips\": {\n const found = locateClips(plan, command.keys);\n const removed = new Set(found.map(({ clip }) => clip.key));\n const changes = new Map<number, AudioClip[]>();\n for (const { track } of found) {\n changes.set(\n track,\n (plan.tracks[track] as AudioTrack).clips.filter((clip) => !removed.has(clip.key)),\n );\n }\n return {\n state: withClips(plan, changes),\n inverse: {\n type: \"audio.restoreClips\",\n entries: found.map(({ track, clip }) => ({\n track: (plan.tracks[track] as AudioTrack).key,\n clip,\n })),\n },\n };\n }\n\n case \"audio.restoreClips\": {\n if (!Array.isArray(command.entries)) refuse(\"malformed-command\", \"entries must be a list\");\n if (command.entries.length === 0) refuse(\"no-clips\", \"it needs at least one clip\");\n const arriving = new Map<number, AudioClip[]>();\n const keys: string[] = [];\n for (const entry of command.entries as unknown[]) {\n if (!isRecord<{ track: string; clip: AudioClip }>(entry)) {\n refuse(\"malformed-command\", \"an entry needs a track and a clip\");\n }\n onlyFields(entry, [\"track\", \"clip\"], \"an entry\");\n const index = trackIndex(plan, entry.track);\n const clip = checkClip(entry.clip, sourceFrames);\n keys.push(clip.key);\n arriving.set(index, [...(arriving.get(index) ?? []), clip]);\n }\n claim(keys, keysOf(plan));\n const changes = new Map<number, AudioClip[]>();\n for (const [index, clips] of arriving) {\n const next = sorted([...(plan.tracks[index] as AudioTrack).clips, ...clips]);\n checkOrder(next);\n changes.set(index, next);\n }\n return {\n state: withClips(plan, changes),\n inverse: { type: \"audio.removeClips\", keys },\n };\n }\n\n case \"audio.updateClips\": {\n const clips = checkClips(command.clips, sourceFrames);\n const before = locateClips(\n plan,\n clips.map((clip) => clip.key),\n ).map(({ clip }) => clip);\n return {\n state: withUpdated(plan, clips),\n inverse: { type: \"audio.updateClips\", clips: before },\n };\n }\n\n case \"audio.placeClips\": {\n if (!Array.isArray(command.entries)) refuse(\"malformed-command\", \"entries must be a list\");\n const placements = new Map<string, { track: number; at: number }>();\n const keys: unknown[] = [];\n for (const entry of command.entries as unknown[]) {\n if (!isRecord<{ key: string; track: string; at: number }>(entry)) {\n refuse(\"malformed-command\", \"an entry needs a key, a track and a position\");\n }\n onlyFields(entry, [\"key\", \"track\", \"at\"], \"an entry\");\n if (!isFrames(entry.at)) refuse(\"invalid-frames\", \"a position is a whole number of frames\");\n keys.push(entry.key);\n if (isKey(entry.key)) {\n placements.set(entry.key, { track: trackIndex(plan, entry.track), at: entry.at });\n }\n }\n const found = locateClips(plan, keys);\n return {\n state: place(plan, placements),\n inverse: {\n type: \"audio.placeClips\",\n entries: found.map(({ track, clip }) => ({\n key: clip.key,\n track: (plan.tracks[track] as AudioTrack).key,\n at: clip.at,\n })),\n },\n };\n }\n\n case \"audio.moveClips\": {\n const { by } = command;\n if (!Number.isSafeInteger(by)) refuse(\"malformed-command\", \"by is a whole number of frames\");\n const found = locateClips(plan, command.keys);\n const to = command.track === undefined ? undefined : trackIndex(plan, command.track);\n const placements = new Map(\n found.map(({ track, clip }) => [\n clip.key,\n { track: to ?? track, at: clip.at + (by as number) },\n ]),\n );\n return {\n state: place(plan, placements),\n inverse: {\n type: \"audio.placeClips\",\n entries: found.map(({ track, clip }) => ({\n key: clip.key,\n track: (plan.tracks[track] as AudioTrack).key,\n at: clip.at,\n })),\n },\n };\n }\n\n case \"audio.trimClip\": {\n const { track, clip } = locateClip(plan, command.key);\n const { start, end } = command;\n // The audio stays where it is: the position moves with the start.\n const at = isFrames(start) ? clip.at + (start - clip.start) : clip.at;\n if (at < 0) refuse(\"frame-outside-plan\", \"a clip can't start before the timeline does\");\n const trimmed = checkClip(\n fitFades({ ...clip, at, start: start as number, end: end as number }),\n sourceFrames,\n );\n const clips = sorted(\n (plan.tracks[track] as AudioTrack).clips.map((entry) =>\n entry.key === clip.key ? trimmed : entry,\n ),\n );\n checkOrder(clips);\n return {\n state: withClips(plan, new Map([[track, clips]])),\n inverse: { type: \"audio.updateClips\", clips: [clip] },\n };\n }\n\n case \"audio.splitClip\": {\n const { track, clip } = locateClip(plan, command.key);\n const { at } = command;\n if (!isIndex(at, planLength(plan))) {\n refuse(\"frame-outside-plan\", \"the frame is outside the plan\");\n }\n if (at <= clip.at || at >= clipEnd(clip)) {\n refuse(\"not-inside-clip\", \"the frame must be strictly inside the clip\");\n }\n // The reducer needs every key it creates: the session fills it in.\n claim([command.newKey], keysOf(plan));\n const newKey = command.newKey as string;\n const length = clip.end - clip.start;\n const parts = [\n cut(clip, 0, at - clip.at, clip.key, clip.at),\n cut(clip, at - clip.at, length, newKey, at),\n ];\n const clips = (plan.tracks[track] as AudioTrack).clips;\n const index = clips.indexOf(clip);\n return {\n state: withClips(\n plan,\n new Map([[track, [...clips.slice(0, index), ...parts, ...clips.slice(index + 1)]]]),\n ),\n inverse: {\n type: \"audio.replaceClips\",\n edits: [\n {\n track: (plan.tracks[track] as AudioTrack).key,\n index,\n count: 2,\n clips: [clip],\n shift: 0,\n },\n ],\n },\n };\n }\n\n case \"audio.setGain\": {\n const gainDb = checkGain(command.gainDb);\n const before = locateClips(plan, command.keys).map(({ clip }) => clip);\n return {\n state: withUpdated(\n plan,\n before.map((clip) => ({ ...clip, gainDb })),\n ),\n inverse: { type: \"audio.updateClips\", clips: before },\n };\n }\n\n case \"audio.setFade\": {\n const { clip } = locateClip(plan, command.key);\n const { edge, frames } = command;\n if (edge !== \"in\" && edge !== \"out\") refuse(\"invalid-edge\", \"the edge must be in or out\");\n const next = { frames, curve: fade({ frames, curve: command.curve }, \"the fade\").curve };\n const updated = checkClip(\n edge === \"in\" ? { ...clip, fadeIn: next } : { ...clip, fadeOut: next },\n sourceFrames,\n );\n return {\n state: withUpdated(plan, [updated]),\n inverse: { type: \"audio.updateClips\", clips: [clip] },\n };\n }\n\n case \"audio.deleteRange\": {\n const [start, end] = checkRange(plan, command.start, command.end);\n const indexes = trackIndexes(plan, command.tracks);\n const ripple = checkFlag(command.ripple, \"ripple\");\n const newKeys = newKeysFor(command.newKeys, command.tracks as string[]);\n const taken = keysOf(plan);\n const edit: TimeEdit = { changes: new Map(), undo: [] };\n indexes.forEach((index) => {\n const track = plan.tracks[index] as AudioTrack;\n const { clips } = track;\n // The run of clips the range touches: from the first that ends\n // after its start, up to the first that starts at or after its end.\n const first = clipIndexAt(clips, start);\n let after = first;\n while (after < clips.length && (clips[after] as AudioClip).at < end) after += 1;\n const kept: AudioClip[] = [];\n if (after > first) {\n const head = clips[first] as AudioClip;\n const tail = clips[after - 1] as AudioClip;\n if (head.at < start) kept.push(cut(head, 0, start - head.at, head.key, head.at));\n if (clipEnd(tail) > end) {\n let key = tail.key;\n if (kept.length > 0 && tail === head) {\n const newKey = newKeys.get(track.key);\n if (newKey === undefined) {\n refuse(\"new-key-required\", \"deleting inside a clip needs a new key for its track\");\n }\n claim([newKey], taken);\n key = newKey;\n }\n kept.push(cut(tail, end - tail.at, tail.end - tail.start, key, ripple ? start : end));\n }\n }\n const rest = clips.slice(after);\n const shift = ripple && rest.length > 0 ? start - end : 0;\n if (after === first && shift === 0) return;\n edit.changes.set(index, [...clips.slice(0, first), ...kept, ...shifted(rest, shift)]);\n edit.undo.push({\n track: track.key,\n index: first,\n count: kept.length,\n clips: clips.slice(first, after),\n shift: shift === 0 ? 0 : -shift,\n });\n });\n return timeEdit(plan, edit);\n }\n\n case \"audio.keepRange\": {\n const [start, end] = checkRange(plan, command.start, command.end);\n const edit: TimeEdit = { changes: new Map(), undo: [] };\n plan.tracks.forEach((track, index) => {\n const { clips } = track;\n if (clips.length === 0) return;\n const kept: AudioClip[] = [];\n for (const clip of clips) {\n const from = Math.max(clip.at, start);\n const to = Math.min(clipEnd(clip), end);\n if (to > from) kept.push(cut(clip, from - clip.at, to - clip.at, clip.key, from - start));\n }\n edit.changes.set(index, kept);\n edit.undo.push({ track: track.key, index: 0, count: kept.length, clips, shift: 0 });\n });\n return timeEdit(plan, edit);\n }\n\n case \"audio.insertTime\": {\n const { at, frames } = command;\n if (!isFrames(frames) || frames < 1) {\n refuse(\"invalid-frames\", \"the time to insert is a whole number of frames, at least one\");\n }\n if (!isIndex(at, planLength(plan))) {\n refuse(\"frame-outside-plan\", \"the frame is outside the plan\");\n }\n const indexes = trackIndexes(plan, command.tracks);\n const newKeys = newKeysFor(command.newKeys, command.tracks as string[]);\n const taken = keysOf(plan);\n const edit: TimeEdit = { changes: new Map(), undo: [] };\n indexes.forEach((index) => {\n const track = plan.tracks[index] as AudioTrack;\n const { clips } = track;\n const first = clipIndexAt(clips, at);\n const across = clips[first];\n if (across && across.at < at) {\n const newKey = newKeys.get(track.key);\n if (newKey === undefined) {\n refuse(\n \"new-key-required\",\n \"inserting time inside a clip needs a new key for its track\",\n );\n }\n claim([newKey], taken);\n const parts = [\n cut(across, 0, at - across.at, across.key, across.at),\n ...shifted(\n [cut(across, at - across.at, across.end - across.start, newKey, at)],\n frames,\n ),\n ];\n edit.changes.set(index, [\n ...clips.slice(0, first),\n ...parts,\n ...shifted(clips.slice(first + 1), frames),\n ]);\n edit.undo.push({\n track: track.key,\n index: first,\n count: 2,\n clips: [across],\n shift: -frames,\n });\n return;\n }\n const rest = clips.slice(first);\n if (rest.length === 0) return;\n edit.changes.set(index, [...clips.slice(0, first), ...shifted(rest, frames)]);\n edit.undo.push({ track: track.key, index: first, count: 0, clips: [], shift: -frames });\n });\n return timeEdit(plan, edit);\n }\n\n case \"audio.replaceClips\": {\n if (!Array.isArray(command.edits)) refuse(\"malformed-command\", \"edits must be a list\");\n const edit: TimeEdit = { changes: new Map(), undo: [] };\n for (const value of command.edits as unknown[]) {\n if (!isRecord<AudioClipsEdit>(value)) refuse(\"malformed-command\", \"an edit is an object\");\n onlyFields(value, [\"track\", \"index\", \"count\", \"clips\", \"shift\"], \"an edit\");\n const index = trackIndex(plan, value.track);\n if (edit.changes.has(index)) refuse(\"duplicate-key\", \"a track is edited twice\");\n const track = plan.tracks[index] as AudioTrack;\n const { index: from, count, shift } = value;\n if (!isIndex(from, track.clips.length) || !isIndex(count, track.clips.length - from)) {\n refuse(\"invalid-index\", \"the run of clips is outside the track\");\n }\n if (!Number.isSafeInteger(shift)) {\n refuse(\"malformed-command\", \"shift is a whole number of frames\");\n }\n const clips = checkClips(value.clips, sourceFrames);\n const next = [\n ...track.clips.slice(0, from),\n ...clips,\n ...shifted(track.clips.slice(from + count), shift as number),\n ];\n checkOrder(next);\n edit.changes.set(index, next);\n edit.undo.push({\n track: track.key,\n index: from,\n count: clips.length,\n clips: track.clips.slice(from, from + count),\n shift: shift === 0 ? 0 : -(shift as number),\n });\n }\n const applied = timeEdit(plan, edit);\n checkUniqueKeys(applied.state);\n return applied;\n }\n\n case \"audio.addTrack\": {\n const { key, index } = command;\n const name = command.name === undefined ? \"\" : checkName(command.name);\n claim([key], keysOf(plan));\n if (!isIndex(index, plan.tracks.length)) refuse(\"invalid-index\", \"the track can't go there\");\n const track: AudioTrack = {\n key: key as string,\n name,\n gainDb: 0,\n muted: false,\n soloed: false,\n clips: [],\n };\n return {\n state: {\n ...plan,\n tracks: [...plan.tracks.slice(0, index), track, ...plan.tracks.slice(index)],\n },\n inverse: { type: \"audio.removeTracks\", keys: [track.key] },\n };\n }\n\n case \"audio.removeTracks\": {\n const removed = new Set(trackIndexes(plan, command.keys));\n if (removed.size === plan.tracks.length) {\n refuse(\"last-track\", \"a plan keeps at least one track\");\n }\n return {\n state: { ...plan, tracks: plan.tracks.filter((_, index) => !removed.has(index)) },\n inverse: {\n type: \"audio.restoreTracks\",\n entries: [...removed]\n .sort((a, b) => a - b)\n .map((index) => ({ index, track: plan.tracks[index] as AudioTrack })),\n },\n };\n }\n\n case \"audio.restoreTracks\": {\n if (!Array.isArray(command.entries)) refuse(\"malformed-command\", \"entries must be a list\");\n if (command.entries.length === 0) refuse(\"no-tracks\", \"it needs at least one track\");\n const tracks = [...plan.tracks];\n const keys: string[] = [];\n let previous = -1;\n for (const entry of command.entries as unknown[]) {\n if (!isRecord<{ index: number; track: AudioTrack }>(entry)) {\n refuse(\"malformed-command\", \"an entry needs an index and a track\");\n }\n onlyFields(entry, [\"index\", \"track\"], \"an entry\");\n const track = checkTrack(entry.track, sourceFrames);\n const { index } = entry;\n if (!isIndex(index, tracks.length) || index <= previous) {\n refuse(\"invalid-index\", `track ${track.key} can't be restored at that index`);\n }\n tracks.splice(index, 0, track);\n keys.push(track.key);\n previous = index;\n }\n const state = { ...plan, tracks };\n checkUniqueKeys(state);\n return { state, inverse: { type: \"audio.removeTracks\", keys } };\n }\n\n case \"audio.moveTrack\": {\n const from = trackIndex(plan, command.key);\n const { to } = command;\n if (!isIndex(to, plan.tracks.length - 1)) refuse(\"invalid-index\", \"the track can't go there\");\n const tracks = plan.tracks.filter((_, index) => index !== from);\n tracks.splice(to, 0, plan.tracks[from] as AudioTrack);\n return {\n state: { ...plan, tracks },\n inverse: { type: \"audio.moveTrack\", key: command.key as string, to: from },\n };\n }\n\n case \"audio.setTrack\": {\n const { name, gainDb, muted, soloed } = command as Unchecked<AudioSetTrackCommand>;\n const next = {\n ...(name === undefined ? {} : { name: checkName(name) }),\n ...(gainDb === undefined ? {} : { gainDb: checkGain(gainDb) }),\n ...(muted === undefined ? {} : { muted: checkFlag(muted, \"muted\") }),\n ...(soloed === undefined ? {} : { soloed: checkFlag(soloed, \"soloed\") }),\n };\n const changed = Object.keys(next) as (keyof typeof next)[];\n if (changed.length === 0) refuse(\"empty-change\", \"it sets nothing\");\n const index = trackIndex(plan, command.key);\n const track = plan.tracks[index] as AudioTrack;\n const before = Object.fromEntries(changed.map((field) => [field, track[field]]));\n return {\n state: {\n ...plan,\n tracks: plan.tracks.map((entry, at) => (at === index ? { ...track, ...next } : entry)),\n },\n inverse: { type: \"audio.setTrack\", key: track.key, ...before },\n };\n }\n\n case \"audio.setMasterGain\":\n return {\n state: { ...plan, gainDb: checkGain(command.gainDb) },\n inverse: { type: \"audio.setMasterGain\", gainDb: plan.gainDb },\n };\n\n case \"audio.setChannels\": {\n const { channels } = command;\n if (!isFrames(channels) || channels < 1) {\n refuse(\"malformed-command\", \"channels is a whole number, at least one\");\n }\n return {\n state: { ...plan, channels },\n inverse: { type: \"audio.setChannels\", channels: plan.channels },\n };\n }\n\n case \"audio.setMetadata\": {\n const { field, value } = command;\n if (typeof field !== \"string\" || !Object.hasOwn(EMPTY_METADATA, field)) {\n refuse(\"unknown-metadata-field\", \"there's no such metadata field\");\n }\n if (typeof value !== \"string\") refuse(\"malformed-command\", \"a metadata value must be text\");\n if (longerThan(value, MAX_METADATA_LENGTH)) {\n refuse(\n \"metadata-too-long\",\n `a metadata value can have at most ${MAX_METADATA_LENGTH} code points`,\n );\n }\n return {\n state: { ...plan, metadata: { ...plan.metadata, [field]: value } },\n inverse: { type: \"audio.setMetadata\", field, value: plan.metadata[field] },\n };\n }\n\n default:\n return refuse(\"unknown-command\", \"unknown command\");\n }\n}\n\n/**\n * Creates the plan's reducer (docs/adr/0003, docs/adr/0006): it applies one\n * command without changing the plan, and returns the new plan with the\n * command's exact inverse. An invalid command throws `AudioError` with\n * `INVALID_COMMAND` and a {@link AudioCommandRejection} as\n * `details.reason`, and changes nothing.\n *\n * @internal\n */\nexport function createPlanReducer(sourceFrames: SourceFrames): Reducer<AudioPlan, AudioCommand> {\n return (plan, command) => {\n try {\n return apply(plan, command, sourceFrames);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const type =\n isRecord<AudioCommand>(command) && typeof command.type === \"string\" ? command.type : \"\";\n const known = type.startsWith(\"audio.\") && type.length <= 64;\n throw new AudioError(\n \"INVALID_COMMAND\",\n `Invalid ${known ? type : \"command\"}: ${error.message}.`,\n { details: known ? { command: type, reason: error.reason } : { reason: error.reason } },\n );\n }\n };\n}\n","import { AudioError } from \"../errors/audio-error.js\";\nimport type {\n AudioClip,\n AudioClipBody,\n AudioMetadata,\n AudioPlan,\n AudioTrack,\n} from \"../model/plan.js\";\nimport {\n checkClipBody,\n Invalid,\n invalid,\n isKey,\n isRecord,\n onlyFields,\n} from \"../operations/checks.js\";\nimport { type AudioUserCommand, refuse } from \"../operations/commands.js\";\nimport {\n AUDIO_PLAN_FORMAT,\n type AudioPlanDocumentSource,\n isCount,\n malformed,\n readMetadata,\n readSources,\n} from \"./document-parts.js\";\n\n/**\n * Version 1 of the plan (docs/adr/0003): one track of clips played back to\n * back. The package reads version 1 documents and commands, and migrates\n * them to version 2 (docs/adr/0006, docs/formats/hm-audio-plan.md). It\n * writes version 2 only.\n */\n\n/**\n * A clip of a version 1 plan: a range of a source, with no position of its\n * own. Its place was the sum of the lengths of the clips before it.\n *\n * @public\n */\nexport type AudioClipV1 = AudioClipBody;\n\n/**\n * A version 1 plan: clips played back to back on one track.\n *\n * @public\n */\nexport interface AudioPlanV1 {\n readonly sampleRate: number;\n readonly channels: number;\n readonly clips: readonly AudioClipV1[];\n readonly metadata: AudioMetadata;\n}\n\n/** `hm-audio-plan` version 1, which `formats/hm-audio-plan/v1.schema.json` describes. */\ninterface AudioPlanDocumentV1 extends AudioPlanV1 {\n readonly format: typeof AUDIO_PLAN_FORMAT;\n readonly version: 1;\n readonly sources: Readonly<Record<string, AudioPlanDocumentSource>>;\n}\n\nconst DOCUMENT_FIELDS = [\n \"format\",\n \"version\",\n \"sampleRate\",\n \"channels\",\n \"sources\",\n \"clips\",\n \"metadata\",\n];\n\nfunction readVersion1(value: unknown): {\n plan: AudioPlanV1;\n sources: Record<string, AudioPlanDocumentSource>;\n} {\n if (!isRecord<AudioPlanDocumentV1>(value) || Array.isArray(value)) {\n malformed(\"a document is an object\");\n }\n const { format, version } = value;\n if (typeof format !== \"string\") malformed(\"format is text\");\n if (format !== AUDIO_PLAN_FORMAT) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", `This isn't an ${AUDIO_PLAN_FORMAT} document.`, {\n details: { format: AUDIO_PLAN_FORMAT, reason: \"unknown-format\" },\n });\n }\n if (Number.isSafeInteger(version) && (version as number) > 1) {\n throw new AudioError(\n \"UNSUPPORTED_FORMAT\",\n `This ${AUDIO_PLAN_FORMAT} document is a later version than this release reads.`,\n { details: { format: AUDIO_PLAN_FORMAT, reason: \"unknown-format-version\" } },\n );\n }\n if (version !== 1) malformed(\"version is 1\");\n onlyFields(value, DOCUMENT_FIELDS, \"a document\");\n if (!isCount(value.sampleRate, 1)) malformed(\"sampleRate is a whole number above 0\");\n if (!isCount(value.channels, 1)) malformed(\"channels is a whole number above 0\");\n const sources = readSources(value.sources);\n if (!Array.isArray(value.clips)) malformed(\"clips is a list\");\n const lookup = (id: string) => (Object.hasOwn(sources, id) ? sources[id]?.frames : undefined);\n const clips = value.clips.map((clip: unknown) => checkClipBody(clip, lookup));\n const keys = new Set<string>();\n for (const { key } of clips) {\n if (keys.has(key)) invalid(\"duplicate-key\", `two clips have the key ${key}`);\n keys.add(key);\n }\n return {\n plan: {\n sampleRate: value.sampleRate,\n channels: value.channels,\n clips,\n metadata: readMetadata(value.metadata),\n },\n sources,\n };\n}\n\n/**\n * Reads a version 1 document, checked as version 1's schema does and more.\n *\n * @throws `AudioError` with `INVALID_DOCUMENT`, as the version 2 reader.\n * @internal\n */\nexport function readPlanDocumentV1(value: unknown): {\n readonly plan: AudioPlanV1;\n readonly sources: Readonly<Record<string, AudioPlanDocumentSource>>;\n} {\n try {\n return readVersion1(value);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const reason = error.reason === \"malformed-command\" ? \"malformed-document\" : error.reason;\n throw new AudioError(\n \"INVALID_DOCUMENT\",\n `Invalid ${AUDIO_PLAN_FORMAT} document: ${error.message}.`,\n { details: { format: AUDIO_PLAN_FORMAT, reason } },\n );\n }\n}\n\n/** The key a migrated plan's one track takes: `t1`, or the first of `t2`, `t3`… that no clip has. */\nfunction trackKeyFor(clips: readonly AudioClipV1[]): string {\n const taken = new Set(clips.map((clip) => clip.key));\n let number = 1;\n while (taken.has(`t${number}`)) number += 1;\n return `t${number}`;\n}\n\n/**\n * Migrates a version 1 plan: one track, unnamed, at 0 dB, holding the clips\n * back to back from the start, as version 1 played them, under a master\n * gain of 0 dB. It's pure and total: every version 1 plan has exactly one\n * version 2 plan.\n *\n * @public\n */\nexport function migratePlan(plan: AudioPlanV1): AudioPlan {\n let at = 0;\n const clips = plan.clips.map((clip): AudioClip => {\n const placed = {\n key: clip.key,\n at,\n source: clip.source,\n start: clip.start,\n end: clip.end,\n gainDb: clip.gainDb,\n fadeIn: clip.fadeIn,\n fadeOut: clip.fadeOut,\n };\n at += clip.end - clip.start;\n return placed;\n });\n return {\n sampleRate: plan.sampleRate,\n channels: plan.channels,\n gainDb: 0,\n tracks: [\n { key: trackKeyFor(plan.clips), name: \"\", gainDb: 0, muted: false, soloed: false, clips },\n ],\n metadata: plan.metadata,\n };\n}\n\n/** The shapes of version 1's user commands, as far as migrating them needs. */\ntype AudioCommandV1 =\n | { type: \"audio.insertClips\"; at: number; clips: readonly AudioClipV1[]; splitKey?: string }\n | { type: \"audio.removeClips\"; keys: readonly string[] }\n | { type: \"audio.deleteRange\"; start: number; end: number; newKey?: string }\n | { type: \"audio.trimClip\"; key: string; start: number; end: number }\n | { type: \"audio.splitClip\"; key: string; at: number; newKey: string }\n | { type: \"audio.moveClips\"; keys: readonly string[]; to: number }\n | Extract<AudioUserCommand, { type: \"audio.setGain\" | \"audio.setFade\" | \"audio.setMetadata\" }>;\n\nconst isWhole = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) >= 0;\n\n/**\n * Migrates a version 1 command to the version 2 commands with the same\n * effect, on the plan a version 1 document migrates to: its first track\n * holds what version 1's single track held.\n *\n * Version 1's commands closed gaps as they went, and version 2's clip edits\n * never move another clip. So an edit that changed a clip's length, or the\n * clips' order, becomes that edit with the time edits that close or open\n * the gap: `audio.insertTime`, and `audio.deleteRange` with `ripple`. Run\n * the result as one undo step.\n *\n * A command the plan can't take is returned as the nearest version 2\n * command, which the reducer then refuses, or refused here with\n * `INVALID_COMMAND` when it names clips the plan doesn't have.\n *\n * @public\n */\nexport function migrateAudioCommand(command: unknown, plan: AudioPlan): AudioUserCommand[] {\n try {\n return migrate(command, plan);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n throw new AudioError(\"INVALID_COMMAND\", `Invalid command: ${error.message}.`, {\n details: { reason: error.reason },\n });\n }\n}\n\nfunction migrate(value: unknown, plan: AudioPlan): AudioUserCommand[] {\n if (!isRecord<AudioCommandV1>(value)) refuse(\"malformed-command\", \"a command is an object\");\n const track = plan.tracks[0] as AudioTrack;\n const tracks = [track.key];\n const command = value as AudioCommandV1;\n const ripple = (start: number, end: number, newKey?: string): AudioUserCommand => ({\n type: \"audio.deleteRange\",\n start,\n end,\n tracks,\n ripple: true,\n ...(newKey === undefined ? {} : { newKeys: Object.fromEntries([[track.key, newKey]]) }),\n });\n const open = (at: number, frames: number, newKey?: string): AudioUserCommand => ({\n type: \"audio.insertTime\",\n at,\n frames,\n tracks,\n ...(newKey === undefined ? {} : { newKeys: Object.fromEntries([[track.key, newKey]]) }),\n });\n /** The named clips, in time order, or a failure. */\n const find = (keys: unknown): AudioClip[] => {\n if (!Array.isArray(keys)) refuse(\"malformed-command\", \"keys must be a list\");\n if (keys.length === 0) refuse(\"no-clips\", \"it needs at least one clip\");\n if (new Set(keys).size !== keys.length) refuse(\"duplicate-key\", \"a clip appears twice\");\n const found = track.clips.filter((clip) => keys.includes(clip.key));\n if (found.length !== keys.length) refuse(\"unknown-clip\", \"the plan doesn't have every clip\");\n return found;\n };\n const lengthOf = (clip: AudioClipBody) => clip.end - clip.start;\n\n switch (command.type) {\n case \"audio.insertClips\": {\n const { at, clips, splitKey } = command as { at: unknown; clips: unknown; splitKey?: string };\n onlyFields(command, [\"type\", \"at\", \"clips\", \"splitKey\"], command.type);\n if (splitKey !== undefined && !isKey(splitKey)) {\n refuse(\"malformed-command\", \"splitKey must be a non-empty string\");\n }\n if (!Array.isArray(clips)) refuse(\"malformed-command\", \"clips must be a list\");\n if (clips.length === 0) refuse(\"no-clips\", \"it needs at least one clip\");\n // The clips go back to back from the frame, in the room opened for\n // them. Clips that aren't valid are left for the reducer to refuse.\n let next = isWhole(at) ? at : 0;\n let total = 0;\n const placed = clips.map((clip: unknown) => {\n const length =\n isRecord<AudioClipBody>(clip) && isWhole(clip.start) && isWhole(clip.end)\n ? Math.max(0, clip.end - clip.start)\n : 0;\n const positioned = { ...(clip as object), at: next };\n next += length;\n total += length;\n return positioned as AudioClip;\n });\n const insert: AudioUserCommand = {\n type: \"audio.insertClips\",\n track: track.key,\n clips: placed,\n };\n // A frame inside a clip splits it; at a boundary the key isn't used.\n return total > 0 ? [open(at as number, total, splitKey), insert] : [insert];\n }\n\n case \"audio.removeClips\": {\n onlyFields(command, [\"type\", \"keys\"], command.type);\n // From the last to the first, so each range is still where it was.\n return find(command.keys)\n .reverse()\n .map((clip) => ripple(clip.at, clip.at + lengthOf(clip)));\n }\n\n case \"audio.deleteRange\": {\n onlyFields(command, [\"type\", \"start\", \"end\", \"newKey\"], command.type);\n return [ripple(command.start, command.end, command.newKey)];\n }\n\n case \"audio.trimClip\": {\n onlyFields(command, [\"type\", \"key\", \"start\", \"end\"], command.type);\n const { key, start, end } = command;\n const trim: AudioUserCommand = { type: \"audio.trimClip\", key, start, end };\n const clip = track.clips.find((entry) => entry.key === key);\n if (!clip || !isWhole(start) || !isWhole(end) || end <= start) return [trim];\n // Version 1 kept the clip's place and moved what came after it.\n // Version 2 keeps the audio's place. So: open room where the clip\n // grows, trim once, then close the gaps where it shrank.\n const earlier = clip.start - start;\n const later = end - clip.end;\n const length = end - start;\n const last = track.clips.at(-1) === clip;\n const before: AudioUserCommand[] = [];\n const after: AudioUserCommand[] = [];\n if (earlier > 0) before.push(open(clip.at, earlier));\n if (later > 0 && !last) {\n before.push(open(clip.at + Math.max(earlier, 0) + lengthOf(clip), later));\n }\n if (earlier < 0) after.push(ripple(clip.at, clip.at - earlier));\n if (later < 0 && !last) after.push(ripple(clip.at + length, clip.at + length - later));\n return [...before, trim, ...after];\n }\n\n case \"audio.splitClip\": {\n onlyFields(command, [\"type\", \"key\", \"at\", \"newKey\"], command.type);\n const { key, at, newKey } = command;\n return [{ type: \"audio.splitClip\", key, at, newKey }];\n }\n\n case \"audio.moveClips\": {\n onlyFields(command, [\"type\", \"keys\", \"to\"], command.type);\n const moved = find(command.keys);\n const rest = track.clips.filter((clip) => !moved.includes(clip));\n const { to } = command;\n if (!isWhole(to) || to > rest.length) refuse(\"invalid-index\", \"the clips can't move there\");\n // Take the clips out, closing the gaps, then open room for them\n // where they go, and put them there back to back.\n const removals = [...moved]\n .reverse()\n .map((clip) => ripple(clip.at, clip.at + lengthOf(clip)));\n let at = rest.slice(0, to).reduce((sum, clip) => sum + lengthOf(clip), 0);\n const from = at;\n const placed = moved.map((clip) => {\n const positioned = { ...clip, at };\n at += lengthOf(clip);\n return positioned;\n });\n return [\n ...removals,\n open(from, at - from),\n { type: \"audio.insertClips\", track: track.key, clips: placed },\n ];\n }\n\n case \"audio.setGain\":\n case \"audio.setFade\":\n case \"audio.setMetadata\":\n // The same in both versions.\n return [command];\n\n default:\n return refuse(\"unknown-command\", \"not a version 1 user command\");\n }\n}\n","import { AudioError } from \"../errors/audio-error.js\";\nimport type { AudioClipProblem, AudioMetadata, AudioPlan, AudioTrack } from \"../model/plan.js\";\nimport { Invalid, isRecord, onlyFields } from \"../operations/checks.js\";\nimport { checkTrack, checkUniqueKeys, refuse } from \"../operations/commands.js\";\nimport {\n AUDIO_PLAN_FORMAT,\n type AudioPlanDocumentSource,\n isCount,\n malformed,\n readMetadata,\n readSources,\n} from \"./document-parts.js\";\nimport { migratePlan, readPlanDocumentV1 } from \"./version-1.js\";\n\n/**\n * The version of {@link AUDIO_PLAN_FORMAT} this release writes, and the\n * latest it reads. It reads version 1 too, by migrating it.\n *\n * @public\n */\nexport const AUDIO_PLAN_VERSION = 2;\n\n/**\n * The plan as portable JSON: `hm-audio-plan` version 2, which\n * `formats/hm-audio-plan/v2.schema.json` describes\n * (docs/formats/hm-audio-plan.md). Every position is a whole number of\n * frames, and sources are named by the ids their clips use.\n *\n * @public\n */\nexport interface AudioPlanDocument {\n readonly format: typeof AUDIO_PLAN_FORMAT;\n readonly version: typeof AUDIO_PLAN_VERSION;\n readonly sampleRate: number;\n readonly channels: number;\n readonly gainDb: number;\n readonly sources: Readonly<Record<string, AudioPlanDocumentSource>>;\n readonly tracks: readonly AudioTrack[];\n readonly metadata: AudioMetadata;\n}\n\n/**\n * Why a plan document was refused, as a stable token: `details.reason` on\n * the error (sdk-core ADR 0045).\n *\n * - With `UNSUPPORTED_FORMAT`: `unknown-format`, a document of another\n * format, and `unknown-format-version`, a later version than this release\n * reads.\n * - With `INVALID_DOCUMENT`: `malformed-document`, a document that isn't\n * shaped as the schema says; `unknown-source`, a clip whose source the\n * document doesn't list; `duplicate-key`, a key used twice among tracks\n * and clips; `clips-overlap` and `clips-out-of-order`, a track whose\n * clips aren't in time order without overlap; `no-tracks`, a plan with\n * none; `invalid-fade-curve`, `metadata-too-long`, `name-too-long` and\n * `gain-out-of-range`, as for commands; and a clip's own problems,\n * {@link AudioClipProblem}.\n *\n * @public\n */\nexport type AudioDocumentRejection =\n | AudioClipProblem\n | \"unknown-format\"\n | \"unknown-format-version\"\n | \"malformed-document\"\n | \"unknown-source\"\n | \"duplicate-key\"\n | \"invalid-fade-curve\"\n | \"metadata-too-long\"\n | \"name-too-long\"\n | \"clips-overlap\"\n | \"clips-out-of-order\"\n | \"no-tracks\";\n\nconst DOCUMENT_FIELDS = [\n \"format\",\n \"version\",\n \"sampleRate\",\n \"channels\",\n \"gainDb\",\n \"sources\",\n \"tracks\",\n \"metadata\",\n];\n\nfunction read(value: unknown): {\n plan: AudioPlan;\n sources: Readonly<Record<string, AudioPlanDocumentSource>>;\n} {\n if (!isRecord<AudioPlanDocument>(value) || Array.isArray(value)) {\n malformed(\"a document is an object\");\n }\n const { format, version } = value;\n if (typeof format !== \"string\") malformed(\"format is text\");\n if (format !== AUDIO_PLAN_FORMAT) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", `This isn't an ${AUDIO_PLAN_FORMAT} document.`, {\n details: { format: AUDIO_PLAN_FORMAT, reason: \"unknown-format\" },\n });\n }\n if (Number.isSafeInteger(version) && (version as number) > AUDIO_PLAN_VERSION) {\n throw new AudioError(\n \"UNSUPPORTED_FORMAT\",\n `This ${AUDIO_PLAN_FORMAT} document is a later version than this release reads.`,\n { details: { format: AUDIO_PLAN_FORMAT, reason: \"unknown-format-version\" } },\n );\n }\n if (version === 1) {\n // Version 1's own reader checks it, and its plan migrates.\n const earlier = readPlanDocumentV1(value);\n return { plan: migratePlan(earlier.plan), sources: earlier.sources };\n }\n if (version !== AUDIO_PLAN_VERSION) malformed(\"version is 1 or 2\");\n onlyFields(value, DOCUMENT_FIELDS, \"a document\");\n if (!isCount(value.sampleRate, 1)) malformed(\"sampleRate is a whole number above 0\");\n if (!isCount(value.channels, 1)) malformed(\"channels is a whole number above 0\");\n const { gainDb } = value;\n if (typeof gainDb !== \"number\" || !(gainDb >= -120 && gainDb <= 120)) {\n refuse(\"gain-out-of-range\", \"the master gain must be from -120 to 120 dB\");\n }\n const sources = readSources(value.sources);\n if (!Array.isArray(value.tracks)) malformed(\"tracks is a list\");\n if (value.tracks.length === 0) refuse(\"no-tracks\", \"a plan has at least one track\");\n const lookup = (id: string) => (Object.hasOwn(sources, id) ? sources[id]?.frames : undefined);\n const plan: AudioPlan = {\n sampleRate: value.sampleRate,\n channels: value.channels,\n gainDb,\n tracks: value.tracks.map((track: unknown) => checkTrack(track, lookup)),\n metadata: readMetadata(value.metadata),\n };\n checkUniqueKeys(plan);\n return { plan, sources };\n}\n\n/**\n * Reads a plan document of version 1 or 2, and returns a multitrack plan:\n * a version 1 document migrates with {@link migratePlan}. It checks what\n * the schemas do and more: every clip lies within a source the document\n * lists, each track's clips are in time order and don't overlap, and keys\n * are unique. Unknown fields are refused, never dropped.\n *\n * @throws `AudioError` with `UNSUPPORTED_FORMAT` for another format or a\n * later version, and `INVALID_DOCUMENT` for anything else that's wrong,\n * with a {@link AudioDocumentRejection} as `details.reason`.\n * @public\n */\nexport function readAudioPlanDocument(value: unknown): {\n readonly plan: AudioPlan;\n readonly sources: Readonly<Record<string, AudioPlanDocumentSource>>;\n} {\n try {\n return read(value);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const reason = error.reason === \"malformed-command\" ? \"malformed-document\" : error.reason;\n throw new AudioError(\n \"INVALID_DOCUMENT\",\n `Invalid ${AUDIO_PLAN_FORMAT} document: ${error.message}.`,\n { details: { format: AUDIO_PLAN_FORMAT, reason } },\n );\n }\n}\n\n/**\n * Writes a multitrack plan as a version 2 document, plain JSON-ready data.\n *\n * @throws `TypeError` if a clip's source is missing from `sources`.\n * @public\n */\nexport function toAudioPlanDocument(\n plan: AudioPlan,\n sources: Readonly<Record<string, AudioPlanDocumentSource>>,\n): AudioPlanDocument {\n return {\n format: AUDIO_PLAN_FORMAT,\n version: AUDIO_PLAN_VERSION,\n sampleRate: plan.sampleRate,\n channels: plan.channels,\n gainDb: plan.gainDb,\n sources: Object.fromEntries(\n Object.entries(sources).map(([id, { frames, asset }]) => [\n id,\n asset === undefined ? { frames } : { frames, asset: { ...asset } },\n ]),\n ),\n tracks: plan.tracks.map((track) => ({\n key: track.key,\n name: track.name,\n gainDb: track.gainDb,\n muted: track.muted,\n soloed: track.soloed,\n clips: track.clips.map((clip) => {\n if (!Object.hasOwn(sources, clip.source)) {\n throw new TypeError(\n `The sources don't include ${clip.source}, which clip ${clip.key} uses.`,\n );\n }\n return {\n key: clip.key,\n at: clip.at,\n source: clip.source,\n start: clip.start,\n end: clip.end,\n gainDb: clip.gainDb,\n fadeIn: { frames: clip.fadeIn.frames, curve: clip.fadeIn.curve },\n fadeOut: { frames: clip.fadeOut.frames, curve: clip.fadeOut.curve },\n };\n }),\n })),\n metadata: { ...plan.metadata },\n };\n}\n","import type { AudioPeakLevel, AudioPeaks } from \"./source.js\";\n\n/**\n * The lowest and highest sample of each column of a waveform, over every\n * channel, as {@link peakColumns} gives them.\n *\n * @public\n */\nexport interface AudioPeakColumns {\n readonly min: Float32Array<ArrayBuffer>;\n readonly max: Float32Array<ArrayBuffer>;\n}\n\n/**\n * Options for {@link peakColumns}: the source frames to draw, and how many\n * columns to draw them in.\n *\n * @public\n */\nexport interface AudioPeakColumnsOptions {\n /** The first source frame, inclusive. */\n readonly from: number;\n /** The source frame to stop before. */\n readonly to: number;\n /** How many columns, such as device pixels, a whole number from 1. */\n readonly columns: number;\n}\n\n/**\n * The level to draw from: the coarsest whose buckets are no wider than a\n * column, so every column has at least one bucket of its own, and the\n * finest when columns are narrower than its buckets.\n */\nfunction levelFor(peaks: AudioPeaks, framesPerColumn: number): AudioPeakLevel | undefined {\n let chosen: AudioPeakLevel | undefined;\n for (const level of peaks.levels) {\n if (level.framesPerBucket <= framesPerColumn) chosen = level;\n }\n return chosen ?? peaks.levels[0];\n}\n\n/**\n * A waveform's columns, drawn from a source's peaks, never from its samples\n * (point 13 of #54, docs/adr/0005): for each of `columns` equal parts of the\n * source frames from `from` to `to`, the lowest and highest sample of every\n * channel, from the level of the overview whose buckets best fit a column.\n * Levels step by four, so a column reads at most a few buckets, and drawing\n * costs the same for an hour as for a minute. Frames past the source's end\n * are silent, 0.\n *\n * @throws `RangeError` for frames that aren't whole numbers from 0 with\n * `from` before `to`, or `columns` that isn't a whole number from 1.\n * @public\n */\nexport function peakColumns(peaks: AudioPeaks, options: AudioPeakColumnsOptions): AudioPeakColumns {\n const { from, to, columns } = options;\n if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to <= from) {\n throw new RangeError(\"from and to are whole frames, with from at 0 or more and before to.\");\n }\n if (!Number.isSafeInteger(columns) || columns < 1) {\n throw new RangeError(\"columns is a whole number from 1.\");\n }\n const min = new Float32Array(columns);\n const max = new Float32Array(columns);\n const framesPerColumn = (to - from) / columns;\n const level = levelFor(peaks, framesPerColumn);\n if (!level) return { min, max };\n const { framesPerBucket, channels } = level;\n const buckets = channels[0]?.min.length ?? 0;\n for (let column = 0; column < columns; column += 1) {\n const start = from + column * framesPerColumn;\n const end = from + (column + 1) * framesPerColumn;\n const first = Math.floor(start / framesPerBucket);\n // At least the bucket the column starts in, when columns are narrower.\n const last = Math.min(buckets, Math.max(first + 1, Math.ceil(end / framesPerBucket)));\n let low = 0;\n let high = 0;\n for (const channel of channels) {\n for (let bucket = first; bucket < last; bucket += 1) {\n low = Math.min(low, channel.min[bucket] as number);\n high = Math.max(high, channel.max[bucket] as number);\n }\n }\n min[column] = low;\n max[column] = high;\n }\n return { min, max };\n}\n","/**\n * The containers the probe recognises (ADR 0001).\n *\n * @public\n */\nexport type AudioContainer = \"wav\" | \"aiff\" | \"flac\" | \"ogg\" | \"mp3\" | \"adts\" | \"mp4\" | \"webm\";\n\n/**\n * The codecs the probe recognises (ADR 0001). `pcm` covers integer and\n * floating-point samples in WAV and AIFF.\n *\n * @public\n */\nexport type AudioCodec = \"pcm\" | \"mp3\" | \"aac\" | \"alac\" | \"opus\" | \"vorbis\" | \"flac\";\n\n/**\n * What the probe learned about a file before anything decodes it (ADR 0001,\n * ADR 0004). Limits are checked against it.\n *\n * @public\n */\nexport interface AudioProbe {\n readonly container: AudioContainer;\n readonly codec: AudioCodec;\n /** The sample rate the decoder will output, which can differ from the header's, as for Opus. */\n readonly sampleRate: number;\n /** The channel count the decoder will output, which can differ from the header's. */\n readonly channels: number;\n /**\n * The most frames the decoder can output, at {@link AudioProbe.sampleRate}\n * and {@link AudioProbe.channels}: the exact length of an uncompressed\n * file, or the sum over every packet of a compressed one, never a count\n * declared in a header. A packet that could decode to more channels, or\n * at a lower rate that's then resampled, counts as the frames that cover\n * it, so `frameBound × channels × 4` bounds the decoded bytes.\n */\n readonly frameBound: number;\n /**\n * The expected length in frames: a header's count when it's within\n * {@link AudioProbe.frameBound}, otherwise the bound itself.\n */\n readonly expectedFrames: number;\n /**\n * For a truncated uncompressed file, as from an interrupted recording or\n * download, the frames its header declares. The file opens with the\n * frames it holds, which are fewer; hosts can say that it's incomplete.\n * Compressed files whose headers claim more than their packets carry fail\n * instead (docs/adr/0001).\n */\n readonly declaredFrames?: number;\n /**\n * How many frames beyond {@link AudioProbe.frameBound} a decoder may\n * legitimately return, such as one or two codec frames for encoder delay,\n * priming or pre-skip. A longer result fails with `INVALID_AUDIO`.\n */\n readonly frameTolerance: number;\n}\n\n/**\n * Decoded audio, as 32-bit float samples per channel. A Web Audio\n * `AudioBuffer` is one, and tests can supply their own.\n *\n * @public\n */\nexport interface DecodedAudio {\n readonly sampleRate: number;\n /** The length in frames. */\n readonly length: number;\n readonly numberOfChannels: number;\n /** The samples of one channel. The caller must not modify them. */\n getChannelData(channel: number): Float32Array;\n}\n\n/**\n * One level of a waveform overview: the lowest and highest sample of each\n * bucket of frames, per channel.\n *\n * @public\n */\nexport interface AudioPeakLevel {\n /** How many frames each bucket covers. */\n readonly framesPerBucket: number;\n /** For each channel, the minimum and maximum sample of each bucket. */\n readonly channels: readonly { readonly min: Float32Array; readonly max: Float32Array }[];\n}\n\n/**\n * A source's waveform overview, a min/max pyramid at several zoom levels,\n * computed once so that drawing the waveform never scans samples (ADR 0002).\n * Levels are ordered from the finest to the coarsest.\n *\n * @public\n */\nexport interface AudioPeaks {\n readonly levels: readonly AudioPeakLevel[];\n}\n\n/**\n * A source the session holds, without its samples: what the snapshot shows\n * (ADR 0003).\n *\n * @public\n */\nexport interface AudioSourceInfo {\n /** Unique within the session, and never reused, even after the source is released. */\n readonly id: string;\n readonly sampleRate: number;\n readonly channels: number;\n /** The length in frames: the decoded length, capped at the probe's bound (ADR 0004). */\n readonly frames: number;\n readonly container: AudioContainer;\n readonly codec: AudioCodec;\n /**\n * The file's own sample rate, in hertz, when the source was converted to\n * the session's as it was inserted (docs/adr/0006). `sampleRate` and\n * `frames` describe the converted audio.\n */\n readonly resampledFrom?: number;\n /**\n * The name the host gave the recording, or its file's name, to show\n * people, cleaned as pdf-sdk ADR 0009 decides: its last path segment, with\n * no control or bidirectional formatting characters, none that Windows\n * refuses, no leading dots or surrounding space, in NFC, and at most\n * {@link MAX_SOURCE_NAME_LENGTH} code points. It's never in events, the\n * plan or a document. Show it as text, never as HTML.\n */\n readonly name?: string;\n}\n\n/**\n * The longest source name, in Unicode code points. A longer one is cut,\n * never in the middle of a character. The same as pdf-sdk's (its ADR 0009),\n * since a name may become a download's.\n *\n * @public\n */\nexport const MAX_SOURCE_NAME_LENGTH = 128;\n","/**\n * Every position and length in the model is a whole number of frames, at the\n * session's sample rate (ADR 0003). A frame is one sample on every channel.\n * Seconds appear only at the edges: in the UI and in events.\n */\n\n/**\n * Converts frames to seconds, for display and events.\n *\n * @param frames - A whole number of frames.\n * @param sampleRate - Frames per second.\n * @public\n */\nexport function framesToSeconds(frames: number, sampleRate: number): number {\n return frames / sampleRate;\n}\n\n/**\n * Converts seconds to the nearest whole frame, for input from the UI, such\n * as a typed trim point.\n *\n * @param seconds - A time in seconds.\n * @param sampleRate - Frames per second.\n * @public\n */\nexport function secondsToFrames(seconds: number, sampleRate: number): number {\n return Math.round(seconds * sampleRate);\n}\n\n/**\n * Throws `RangeError` unless the value is a non-negative whole number of\n * frames.\n *\n * @internal\n */\nexport function assertFrames(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new RangeError(`${name} must be a non-negative whole number of frames, not ${value}.`);\n }\n}\n\n/**\n * A timeline position as an editor shows it (docs/adr/0005): minutes,\n * seconds and hundredths, as `0:12.40`, with hours from an hour on, as\n * `1:02:05.00` (point 11 of #54). Hundredths are rounded down, so the time\n * shown is never ahead of what's heard. The digits and separators are the\n * same in every locale, as a timecode's are.\n *\n * @param frames - A non-negative whole number of frames.\n * @param sampleRate - Frames per second, a positive whole number.\n * @throws `RangeError` for frames or a rate that aren't whole numbers, or a\n * rate of 0.\n * @public\n */\nexport function formatTimecode(frames: number, sampleRate: number): string {\n assertFrames(\"frames\", frames);\n if (!Number.isSafeInteger(sampleRate) || sampleRate < 1) {\n throw new RangeError(`The sample rate must be a positive whole number, not ${sampleRate}.`);\n }\n const hundredths = Math.floor((frames * 100) / sampleRate);\n const two = (value: number) => String(value).padStart(2, \"0\");\n const fraction = two(hundredths % 100);\n const seconds = Math.floor(hundredths / 100) % 60;\n const minutes = Math.floor(hundredths / 6_000) % 60;\n const hours = Math.floor(hundredths / 360_000);\n return hours > 0\n ? `${hours}:${two(minutes)}:${two(seconds)}.${fraction}`\n : `${minutes}:${two(seconds)}.${fraction}`;\n}\n","import type { AudioPlan } from \"../model/plan.js\";\nimport type { DecodedAudio } from \"../model/source.js\";\nimport type { AudioOutput } from \"../ports/audio-output.js\";\nimport type { AudioSession } from \"./session.js\";\n\n/**\n * Keeps an output playing what the session holds (docs/adr/0003), so an\n * editor's playback follows every edit, undo and insert:\n *\n * - **on every change of the plan,** the output loads it, with the decoded\n * sources its clips use. While playing, it carries on from the playhead\n * with the new plan, as the output port promises;\n * - **when the recording is closed,** or replaced by another, the output\n * stops, and the playhead goes back to the start. A recording that\n * replaces another shares none of its sources, because source ids are\n * never reused; an insert keeps the sources already there.\n *\n * The output stays outside the session's snapshot: its playhead changes on\n * every audio frame, and the session's subscribers shouldn't re-render with\n * it. Returns a function that disconnects them, leaving the output as it is.\n *\n * @example\n * ```ts\n * const session = createAudioSession({ engine, processor });\n * const output = createAudioOutput();\n * const disconnect = connectOutput(session, output);\n * await session.open(file);\n * playButton.onclick = () => output.play();\n * ```\n *\n * @public\n */\nexport function connectOutput(session: AudioSession, output: AudioOutput): () => void {\n let plan: AudioPlan | undefined;\n /** The source ids the session held at the last change. */\n let held = new Set<string>();\n\n function sync(): void {\n const snapshot = session.getSnapshot();\n const next = snapshot.plan;\n const ids = new Set(snapshot.sources.map((source) => source.id));\n if (next === plan) {\n held = ids;\n return;\n }\n const clips = next ? next.tracks.flatMap((track) => track.clips) : [];\n const replaced =\n next === undefined || (plan !== undefined && !clips.some((clip) => held.has(clip.source)));\n if (replaced && plan !== undefined) output.stop();\n plan = next;\n held = ids;\n if (!next) return;\n const sources = new Map<string, DecodedAudio>();\n for (const { source } of clips) {\n const audio = session.getAudio(source);\n if (audio) sources.set(source, audio);\n }\n output.load(next, sources);\n }\n\n sync();\n return session.subscribe(sync);\n}\n","import { MAX_SOURCE_NAME_LENGTH as MAX_NAME_LENGTH } from \"../model/source.js\";\n\n/*\n * pdf-sdk's `src/core/session/source-name.ts`, with the same rules, steps\n * and tests, which only its length constant's import differs from. The\n * family cleans a file name one way, as pdf-sdk ADR 0009 decides, because\n * the same name may become a download's in either editor (docs/adr/0006).\n * It moves to sdk-core once that has it.\n */\n\nexport { MAX_NAME_LENGTH };\n\n/** Control characters (Unicode category Cc: C0, DEL and C1). */\nconst CONTROL = /\\p{Cc}/gu;\n/** Bidirectional formatting characters, which can disguise an extension. */\nconst BIDI = /[\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/gu;\n/** Characters Windows refuses in file names. Separators are handled first. */\nconst REFUSED = /[<>:\"|?*]/gu;\n\n/**\n * Cleans a file name chosen by whoever made the file, which is hostile input\n * (pdf-sdk ADR 0009). The result is safe as text content and as a download's\n * name: one path segment, with no control or bidirectional formatting\n * characters, no characters Windows refuses, no leading dots and at most\n * {@link MAX_NAME_LENGTH} code points. Returns `undefined` when nothing is\n * left, or for anything that isn't a string.\n */\nexport function cleanFileName(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n let name = raw.replace(CONTROL, \"\").replace(BIDI, \"\");\n name = name.slice(Math.max(name.lastIndexOf(\"/\"), name.lastIndexOf(\"\\\\\")) + 1);\n // Normalised after the removals, which could leave a base letter and its\n // combining mark side by side.\n name = name.replace(REFUSED, \"\").normalize(\"NFC\");\n // Leading dots would hide the file on some systems, or leave only an\n // extension; whitespace at either end is never meant.\n name = name.replace(/^[\\s.]+/u, \"\").trimEnd();\n // Array.from splits by code points, so no surrogate pair is cut in half.\n const points = Array.from(name);\n if (points.length > MAX_NAME_LENGTH) {\n name = points.slice(0, MAX_NAME_LENGTH).join(\"\").trimEnd();\n }\n return name === \"\" ? undefined : name;\n}\n","import {\n applyCommands,\n checkFile,\n createHistory,\n createStore,\n type HistoryStep,\n withProcessingTime,\n} from \"@hussmartinez/sdk-core\";\nimport { abortError, asAudioError, throwIfAborted } from \"../errors/abort.js\";\nimport { AudioError, isAudioError } from \"../errors/audio-error.js\";\nimport {\n type AudioFilePolicyOverrides,\n type AudioLimitName,\n audioLimits,\n} from \"../errors/audio-limits.js\";\nimport { mixLength } from \"../model/mix.js\";\nimport {\n type AudioClip,\n type AudioPlan,\n type AudioTrack,\n EMPTY_METADATA,\n NO_FADE,\n planLength,\n} from \"../model/plan.js\";\nimport type { AudioPeaks, AudioSourceInfo, DecodedAudio } from \"../model/source.js\";\nimport { framesToSeconds } from \"../model/time.js\";\nimport { type AudioCommand, createPlanReducer } from \"../operations/commands.js\";\nimport type { AudioEngine } from \"../ports/audio-engine.js\";\nimport type {\n AudioExportFormat,\n AudioProcessor,\n AudioRenderResult,\n AudioSampleFormat,\n} from \"../ports/audio-processor.js\";\nimport type { AudioProgressOptions } from \"../ports/options.js\";\nimport { cleanFileName } from \"./source-name.js\";\n\n/** Bytes per decoded sample: sources are held as 32-bit floats (docs/adr/0004). */\nconst BYTES_PER_SAMPLE = 4;\n\n/**\n * Something the user should know about the recordings open, though they\n * opened (docs/adr/0004). Show its text from `warnings.<limit>`, or from\n * `warnings.truncated`, in the message catalogue, with its fields as\n * parameters.\n *\n * - `limit`: a value at or above a limit's warning threshold, but within its\n * maximum. `source` names the recording it's about, unless it's about the\n * whole session, as `maxSessionSize` and `maxClips` are.\n * - `truncated`: an uncompressed recording holds fewer frames than its\n * header declares, as after an interrupted recording or download. It\n * opened with the frames it holds.\n *\n * @public\n */\nexport type AudioWarning =\n | {\n readonly type: \"limit\";\n readonly limit: AudioLimitName;\n readonly actual: number;\n readonly source?: string;\n }\n | {\n readonly type: \"truncated\";\n readonly source: string;\n /** The frames the recording holds. */\n readonly frames: number;\n /** The frames its header declares. */\n readonly declaredFrames: number;\n };\n\n/**\n * A selected range of the timeline, on some tracks (docs/adr/0006): frames\n * from `start` inclusive to `end` exclusive, and the keys of the tracks it\n * covers, in plan order.\n *\n * @public\n */\nexport interface AudioSelection {\n readonly start: number;\n readonly end: number;\n /** The tracks the range covers, at least one. */\n readonly tracks: readonly string[];\n}\n\n/**\n * What the session is doing.\n *\n * - `empty`: no recording is open.\n * - `opening`: a recording is being opened, replacing any other.\n * - `ready`: a recording is open.\n * - `error`: no recording is open, because the last open failed; `error`\n * says why. A failed open while a recording is open keeps it, with the\n * status `ready` and `error` set.\n *\n * @public\n */\nexport type AudioSessionStatus = \"empty\" | \"opening\" | \"ready\" | \"error\";\n\n/**\n * The session's state at one moment (docs/adr/0003). Snapshots are\n * immutable: every change makes a new one, so `useSyncExternalStore` and\n * other subscribers can compare them by identity. The playhead isn't here:\n * it belongs to `AudioOutput`, which moves it sixty times a second.\n *\n * @public\n */\nexport interface AudioSessionSnapshot {\n readonly status: AudioSessionStatus;\n /** The recording being edited, or `undefined` when none is open. */\n readonly plan: AudioPlan | undefined;\n /** The sources the session holds: those the plan uses, and those undo or redo can bring back. */\n readonly sources: readonly AudioSourceInfo[];\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n /**\n * Whether undo steps were dropped since the recording opened, to make\n * room for an insert within `maxSessionSize`. Editors say so, because the\n * earliest edits can no longer be undone (ADR 0010).\n */\n readonly historyTrimmed: boolean;\n /** Whether a recording is being opened or inserted. */\n readonly busy: boolean;\n /** Why the last open or insert failed. Show its text by its code. */\n readonly error: AudioError | undefined;\n readonly warnings: readonly AudioWarning[];\n /**\n * The decoded bytes of every source the session holds, which the\n * `maxSessionSize` limit counts: frames × channels × 4.\n */\n readonly sessionBytes: number;\n /** The selected range of the timeline. View state: not undoable, and never in events. */\n readonly selection: AudioSelection | undefined;\n}\n\n/**\n * Anonymous usage events, for a host's analytics (docs/adr/0003). They\n * never contain file names, samples or metadata values. Durations are in\n * seconds, rounded to two significant figures, such as 3,500 for 3,456.7,\n * so that an exact length can't fingerprint a recording.\n *\n * @public\n */\nexport type AudioSessionEvent =\n | ({ readonly type: \"recording_opened\" | \"recording_inserted\" } & AudioRecordingFacts)\n | {\n readonly type: \"recording_exported\";\n readonly durationSeconds: number;\n readonly sampleRate: number;\n readonly channels: number;\n readonly sampleFormat: AudioSampleFormat;\n }\n | { readonly type: \"recording_closed\" }\n | { readonly type: \"command\"; readonly commands: readonly AudioCommand[\"type\"][] }\n | { readonly type: \"undo\" }\n | { readonly type: \"redo\" }\n | {\n readonly type: \"failed\";\n readonly operation: \"open\" | \"insert\" | \"command\" | \"export\";\n readonly code: string;\n };\n\n/**\n * What an event says about a recording: its format and size, never its\n * name or contents.\n *\n * @public\n */\nexport interface AudioRecordingFacts {\n /** Rounded to two significant figures. */\n readonly durationSeconds: number;\n readonly sampleRate: number;\n readonly channels: number;\n readonly container: AudioSourceInfo[\"container\"];\n readonly codec: AudioSourceInfo[\"codec\"];\n readonly truncated: boolean;\n}\n\n/**\n * Options for {@link createAudioSession}.\n *\n * @public\n */\nexport interface AudioSessionOptions {\n /** Probes, decodes and builds waveform peaks, such as `createAudioEngine()`. */\n readonly engine: AudioEngine;\n /** Limits for untrusted files (docs/adr/0004). Unknown names throw. */\n readonly filePolicy?: AudioFilePolicyOverrides;\n /** Renders and encodes exports, such as `createAudioProcessor()`. Needed for `export()`. */\n readonly processor?: AudioProcessor;\n /** Receives anonymous usage events. Errors it throws are ignored. */\n readonly onEvent?: (event: AudioSessionEvent) => void;\n}\n\n/**\n * Options for {@link AudioSession.export}.\n *\n * @public\n */\nexport interface AudioSessionExportOptions extends AudioProgressOptions {\n /** The file to write. Defaults to 16-bit PCM WAV. */\n readonly format?: AudioExportFormat;\n}\n\n/**\n * Options for {@link AudioSession.insert}.\n *\n * @public\n */\nexport interface AudioOpenOptions extends AudioProgressOptions {\n /**\n * A name for the recording, to show people, such as its file's. It wins\n * over a `File`'s own name, which is used without it. It's cleaned as\n * pdf-sdk ADR 0009 decides, and kept on the source in `snapshot.sources`,\n * never in events, the plan or a document.\n */\n readonly name?: string;\n}\n\n/**\n * Options for {@link AudioSession.insert}.\n *\n * @public\n */\nexport interface AudioInsertOptions extends AudioOpenOptions {\n /**\n * The key of the track the recording goes on, where it needs free space.\n * Without it, the recording gets a new track of its own, below the\n * others: laying one recording under another is the common case.\n */\n readonly track?: string;\n /** The timeline frame the recording starts on. Defaults to 0. */\n readonly at?: number;\n}\n\n/**\n * The recording being edited, as a framework-agnostic store (ADR 0008,\n * ADR 0029): a clip plan over decoded sources, edited with commands, with\n * undo and redo (docs/adr/0003). React binds to it with\n * `useSyncExternalStore`, and the element binds to the same store.\n *\n * @public\n */\nexport interface AudioSession {\n /** The current snapshot, the same object until something changes. */\n getSnapshot(): AudioSessionSnapshot;\n /** Calls the listener after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /**\n * Opens a recording, replacing the current one and its history once it\n * has opened. The file is checked against the file policy before it's\n * read, and its probe before it's decoded. Rejects with an `AudioError`,\n * which the snapshot also holds; the current recording, if any, stays\n * open.\n */\n open(file: Blob, options?: AudioOpenOptions): Promise<void>;\n /**\n * Adds another recording, as one undoable step: on a new track of its\n * own, below the others, or on the track `options.track` names, where it\n * needs free space. It starts at `options.at`, or at the start. A\n * recording at another sample rate is converted to the session's, and its\n * source says so in `resampledFrom`; one with more channels than the plan\n * raises the plan's channel count to its own, in the same step. If the\n * sources held would then exceed `maxSessionSize`, the session first drops\n * history steps, in sdk-core's `dropOrder`, as far as needed to release\n * sources only they refer to, and sets `historyTrimmed`. If even that\n * isn't enough, it rejects with `SESSION_TOO_LARGE` and changes nothing.\n */\n insert(file: Blob, options?: AudioInsertOptions): Promise<void>;\n /**\n * Runs one command, or several as one undoable step. A command that\n * doesn't apply throws `AudioError` with `INVALID_COMMAND`, and one that\n * would exceed a limit throws its code: `TOO_MANY_CLIPS` for `maxClips`,\n * `TOO_MANY_TRACKS` for `maxTracks`, and `DURATION_TOO_LONG` when the plan\n * would become longer than `maxDuration`. Any of them changes\n * nothing. The commands are copied, so changing them afterwards has no\n * effect.\n */\n execute(commands: AudioCommand | readonly AudioCommand[]): void;\n /**\n * Runs `fn`, and records the commands it executes as one undoable step,\n * for gestures such as dragging a trim handle.\n */\n group<T>(fn: () => T): T;\n /**\n * A key no track or clip has, in the plan or the history, for commands\n * that create them, such as `newKey` in `audio.splitClip` or `key` in\n * `audio.addTrack`.\n */\n createKey(): string;\n undo(): void;\n redo(): void;\n /**\n * Selects a range of the timeline on the tracks named, or on every track\n * without `tracks`, clamped to the plan, or clears the selection with\n * `undefined`. An empty range clears it too, as does one that names no\n * track the plan has.\n */\n select(\n range:\n | { readonly start: number; readonly end: number; readonly tracks?: readonly string[] }\n | undefined,\n ): void;\n /** A source's waveform overview, or `undefined` for a source the session doesn't hold. */\n getPeaks(source: string): AudioPeaks | undefined;\n /**\n * A source's decoded audio, for playback, or `undefined` for a source the\n * session doesn't hold. Don't modify it: sources never change.\n */\n getAudio(source: string): DecodedAudio | undefined;\n /**\n * Mixes and encodes the plan's audible tracks as they are now, with the\n * session's `processor`, under `maxProcessingTime`. It returns the file\n * with the mix's peak and the frames that clipped, and never downloads\n * it: the host decides what to do with it. Edits made while it runs don't\n * change it. Rejects with `INVALID_COMMAND` and the reason `no-recording`,\n * `empty-plan` or `nothing-audible` when there's nothing to export, and\n * throws `TypeError` when the session has no processor.\n */\n export(options?: AudioSessionExportOptions): Promise<AudioRenderResult>;\n /** Closes the recording and releases its sources. */\n close(): Promise<void>;\n}\n\ninterface Source {\n readonly info: AudioSourceInfo;\n readonly audio: DecodedAudio;\n readonly peaks: AudioPeaks;\n readonly bytes: number;\n readonly warnings: readonly AudioWarning[];\n}\n\n/** The clips a command or its inverse carries, which keep their sources alive. */\nfunction clipsOf(command: AudioCommand): readonly AudioClip[] {\n switch (command.type) {\n case \"audio.insertClips\":\n case \"audio.updateClips\":\n return command.clips;\n case \"audio.restoreClips\":\n return command.entries.map((entry) => entry.clip);\n case \"audio.replaceClips\":\n return command.edits.flatMap((edit) => edit.clips);\n case \"audio.restoreTracks\":\n return command.entries.flatMap((entry) => entry.track.clips);\n default:\n return [];\n }\n}\n\n/**\n * A duration as events report it: two significant figures, so it describes\n * a recording's length without identifying the recording.\n */\nfunction coarseSeconds(seconds: number): number {\n return seconds > 0 ? Number(seconds.toPrecision(2)) : 0;\n}\n\n/** Every key a command creates or carries: its clips', its tracks' and its new parts'. */\nfunction keysOf(command: AudioCommand): string[] {\n const keys = clipsOf(command).map((clip) => clip.key);\n if (\"newKey\" in command && typeof command.newKey === \"string\") keys.push(command.newKey);\n if (\"newKeys\" in command && command.newKeys) keys.push(...Object.values(command.newKeys));\n if (command.type === \"audio.addTrack\" && typeof command.key === \"string\") keys.push(command.key);\n if (command.type === \"audio.restoreTracks\") {\n keys.push(...command.entries.map((entry) => entry.track.key));\n }\n return keys;\n}\n\n/** The edits that add or remove time, and so move what's after them. */\nconst TIME_EDITS: ReadonlySet<AudioCommand[\"type\"]> = new Set([\n \"audio.deleteRange\",\n \"audio.keepRange\",\n \"audio.insertTime\",\n]);\n\n/** Whether two values of plain data are equal: the same fields, holding equal values. */\nfunction equalData(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n return keys.every(\n (key) =>\n Object.hasOwn(b, key) &&\n equalData((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n );\n}\n\n/** Every clip of a plan, track by track. */\nfunction clipsIn(plan: AudioPlan | undefined): AudioClip[] {\n return plan ? plan.tracks.flatMap((track) => track.clips) : [];\n}\n\n/** A clip that plays the whole of a source, from a timeline frame. */\nfunction wholeClip(key: string, source: AudioSourceInfo, at: number): AudioClip {\n return {\n key,\n at,\n source: source.id,\n start: 0,\n end: source.frames,\n gainDb: 0,\n fadeIn: NO_FADE,\n fadeOut: NO_FADE,\n };\n}\n\n/**\n * Creates an {@link AudioSession}. Pass the engine to use; the headless core\n * doesn't choose one.\n *\n * @example\n * ```ts\n * const session = createAudioSession({ engine: createAudioEngine() });\n * await session.open(file);\n * const [clip] = session.getSnapshot().plan?.tracks[0]?.clips ?? [];\n * session.execute({ type: \"audio.setGain\", keys: [clip.key], gainDb: -3 });\n * session.undo();\n * ```\n *\n * @public\n */\nexport function createAudioSession(options: AudioSessionOptions): AudioSession {\n const { engine } = options;\n const policy = audioLimits.resolve(options.filePolicy);\n const history = createHistory<AudioCommand>();\n const sources = new Map<string, Source>();\n const reducer = createPlanReducer((id) => sources.get(id)?.info.frames);\n let plan: AudioPlan | undefined;\n let status: AudioSessionStatus = \"empty\";\n let error: AudioError | undefined;\n let busy = 0;\n let selection: AudioSelection | undefined;\n let nextKey = 0;\n let nextSource = 0;\n /** The loads in progress, which a newer open or a close cancels. */\n const loading = new Set<AbortController>();\n const cancelLoads = (message: string) => {\n for (const controller of loading) controller.abort(new AudioError(\"ABORTED\", message));\n };\n /**\n * Counts opens and closes. A load that finishes after another open or a\n * close changes nothing, and reports nothing: that one reports.\n */\n let generation = 0;\n const superseded = (since: number) =>\n since !== generation\n ? new AudioError(\"ABORTED\", \"The recording was closed or replaced.\")\n : undefined;\n\n const heldBytes = (): number => {\n let total = 0;\n for (const source of sources.values()) total += source.bytes;\n return total;\n };\n\n /** The sources the plan and the given history steps refer to. */\n function referenced(steps: readonly HistoryStep<AudioCommand>[]): Set<string> {\n const ids = new Set(clipsIn(plan).map((clip) => clip.source));\n for (const { commands, inverses } of steps) {\n for (const command of [...commands, ...inverses]) {\n for (const clip of clipsOf(command)) ids.add(clip.source);\n }\n }\n return ids;\n }\n\n /** Releases the sources nothing refers to any more. */\n function collect(): void {\n const keep = referenced(history.steps);\n for (const id of sources.keys()) if (!keep.has(id)) sources.delete(id);\n }\n\n /**\n * How many history steps must be dropped, in drop order, for the held\n * sources plus `extra` bytes to fit `maxSessionSize`, or `undefined` if\n * dropping every step isn't enough.\n */\n function stepsToDrop(extra: number): number | undefined {\n const { maximum } = policy.limits.maxSessionSize;\n const order = history.dropOrder;\n for (let count = 0; count <= order.length; count += 1) {\n const kept = new Set(order.slice(count));\n const ids = referenced(history.steps.filter((entry) => kept.has(entry)));\n let total = extra;\n for (const id of ids) total += sources.get(id)?.bytes ?? 0;\n if (total <= maximum) return count;\n }\n return undefined;\n }\n\n /** The sources' own warnings, and the session's, which follow every change. */\n function sessionWarnings(): AudioWarning[] {\n const found = [...sources.values()].flatMap((source) => source.warnings);\n const bytes = heldBytes();\n if (bytes > 0 && bytes >= policy.limits.maxSessionSize.warning) {\n found.push({ type: \"limit\", limit: \"maxSessionSize\", actual: bytes });\n }\n const clips = clipsIn(plan).length;\n if (clips > 0 && clips >= policy.limits.maxClips.warning) {\n found.push({ type: \"limit\", limit: \"maxClips\", actual: clips });\n }\n const tracks = plan?.tracks.length ?? 0;\n if (tracks > 0 && tracks >= policy.limits.maxTracks.warning) {\n found.push({ type: \"limit\", limit: \"maxTracks\", actual: tracks });\n }\n return found;\n }\n\n function makeSnapshot(): AudioSessionSnapshot {\n return Object.freeze({\n status,\n plan,\n sources: Object.freeze([...sources.values()].map((source) => source.info)),\n canUndo: history.canUndo,\n canRedo: history.canRedo,\n historyTrimmed: history.trimmed,\n busy: busy > 0,\n error,\n warnings: Object.freeze(sessionWarnings()),\n sessionBytes: heldBytes(),\n selection,\n });\n }\n\n const store = createStore<AudioSessionSnapshot>(makeSnapshot());\n\n function changed(): void {\n // The selection follows the plan: it can't reach past its end, or\n // cover a track that's gone.\n if (selection) {\n const end = Math.min(selection.end, plan ? planLength(plan) : 0);\n const tracks = (plan?.tracks ?? [])\n .map((track) => track.key)\n .filter((key) => selection?.tracks.includes(key));\n if (selection.start >= end || tracks.length === 0) selection = undefined;\n else if (end !== selection.end || tracks.length !== selection.tracks.length) {\n selection = Object.freeze({ start: selection.start, end, tracks: Object.freeze(tracks) });\n }\n }\n store.set(makeSnapshot());\n }\n\n function emit(event: AudioSessionEvent): void {\n try {\n options.onEvent?.(event);\n } catch {\n // A host's analytics must never break editing.\n }\n }\n\n function facts(source: Source): AudioRecordingFacts {\n const { info } = source;\n return {\n durationSeconds: coarseSeconds(framesToSeconds(info.frames, info.sampleRate)),\n sampleRate: info.sampleRate,\n channels: info.channels,\n container: info.container,\n codec: info.codec,\n truncated: source.warnings.some((warning) => warning.type === \"truncated\"),\n };\n }\n\n /**\n * Checks, probes, decodes and builds the peaks of one file, without\n * registering it. Every limit but the session's is checked here, and all\n * but the session size before decoding (docs/adr/0004).\n */\n async function load(\n file: Blob,\n signal: AbortSignal,\n onProgress: ((fraction: number) => void) | undefined,\n /** The session's rate, for an insert: a file at another rate is converted to it. */\n rate: number | undefined,\n /** The host's name for it, or the file's. */\n givenName: string | undefined,\n ): Promise<Source> {\n if (!(file instanceof Blob)) throw new TypeError(\"A recording must be a Blob or a File.\");\n const name = cleanFileName(\n givenName ?? (typeof File === \"function\" && file instanceof File ? file.name : undefined),\n );\n nextSource += 1;\n const id = `s${nextSource}`;\n const warnings: AudioWarning[] = [];\n const warnAt = (limit: AudioLimitName, actual: number) => {\n if (policy.check(limit, actual) === \"warning\") {\n warnings.push({ type: \"limit\", limit, actual, source: id });\n }\n };\n // The file size, before anything is read (ADR 0020).\n if (checkFile(policy, file) === \"warning\") {\n warnings.push({ type: \"limit\", limit: \"maxFileSize\", actual: file.size, source: id });\n }\n const probe = await withProcessingTime(\n policy,\n (limited) => engine.probe(file, { signal: limited }),\n { signal },\n );\n // The probe's bound and channels are maxima, so these checks hold for\n // whatever the decoder returns.\n warnAt(\"maxChannels\", probe.channels);\n warnAt(\"maxSampleRate\", probe.sampleRate);\n warnAt(\"maxDuration\", Math.ceil((probe.frameBound * 1_000) / probe.sampleRate));\n warnAt(\"maxDecodedSize\", probe.frameBound * probe.channels * BYTES_PER_SAMPLE);\n // A file at another rate is decoded at its own, then converted, so both\n // sizes are checked before anything is decoded (docs/adr/0004). The\n // bound scales with the rate, as the frames do.\n const sampleRate = rate ?? probe.sampleRate;\n const converts = sampleRate !== probe.sampleRate;\n const frameBound = Math.ceil((probe.frameBound * sampleRate) / probe.sampleRate);\n if (converts) warnAt(\"maxDecodedSize\", frameBound * probe.channels * BYTES_PER_SAMPLE);\n const audio = await withProcessingTime(\n policy,\n (limited) =>\n engine.decode(file, probe, {\n signal: limited,\n ...(onProgress ? { onProgress } : {}),\n ...(converts ? { sampleRate } : {}),\n }),\n { signal },\n );\n // The source is what the decoder returned, capped at the bound, with the\n // decoder's own channel count: mono AAC probes as two channels\n // (docs/adr/0004).\n const frames = Math.min(audio.length, frameBound);\n const channels = audio.numberOfChannels;\n if (audio.sampleRate !== sampleRate || channels < 1 || channels > probe.channels) {\n throw new AudioError(\"INVALID_AUDIO\", \"The decoder's output doesn't match the probe.\", {\n details: { container: probe.container, codec: probe.codec },\n });\n }\n if (frames < 1) {\n throw new AudioError(\"DECODE_FAILED\", \"The recording decoded to no audio.\", {\n details: { codec: probe.codec },\n });\n }\n const peaks = await withProcessingTime(\n policy,\n (limited) => engine.peaks(audio, { signal: limited }),\n { signal },\n );\n throwIfAborted(signal);\n if (probe.declaredFrames !== undefined && probe.declaredFrames > frames) {\n warnings.push({\n type: \"truncated\",\n source: id,\n frames,\n declaredFrames: probe.declaredFrames,\n });\n }\n return {\n info: Object.freeze({\n id,\n sampleRate: audio.sampleRate,\n channels,\n frames,\n container: probe.container,\n codec: probe.codec,\n ...(converts ? { resampledFrom: probe.sampleRate } : {}),\n ...(name === undefined ? {} : { name }),\n }),\n audio,\n peaks,\n bytes: frames * channels * BYTES_PER_SAMPLE,\n warnings: Object.freeze(warnings),\n };\n }\n\n /** Runs a load, marking the session busy, and cancelling it if a newer open starts. */\n async function track<Value>(\n signal: AbortSignal | undefined,\n replaces: boolean,\n run: (signal: AbortSignal) => Promise<Value>,\n ): Promise<Value> {\n if (replaces) cancelLoads(\"A newer recording replaced this one.\");\n const controller = new AbortController();\n loading.add(controller);\n const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;\n busy += 1;\n changed();\n try {\n return await run(combined);\n } finally {\n busy -= 1;\n loading.delete(controller);\n changed();\n }\n }\n\n /**\n * Applies commands to the plan, checking `maxClips`, `maxTracks` and the\n * plan's length against `maxDuration`, without committing anything.\n */\n function applyChecked(\n current: AudioPlan,\n commands: readonly AudioCommand[],\n ): { state: AudioPlan; inverses: AudioCommand[] } {\n const result = applyCommands(reducer, current, commands);\n const next = result.state;\n // Each limit is checked when the plan grows past where it was, so a\n // plan already over a lowered limit can still be edited and shrunk.\n const clips = clipsIn(next).length;\n if (clips > clipsIn(current).length) policy.check(\"maxClips\", clips);\n if (next.tracks.length > current.tracks.length) {\n policy.check(\"maxTracks\", next.tracks.length);\n }\n // Positions are free, so a clip can be placed hours in, which no\n // file's limit catches: the plan's own length has one (docs/adr/0006).\n const length = planLength(next);\n if (length > planLength(current)) {\n try {\n policy.check(\"maxDuration\", Math.ceil((length * 1_000) / next.sampleRate));\n } catch (error) {\n // The plan, not a file, would be too long: a reason of its own, so\n // its text can say so (docs/adr/0006).\n if (!isAudioError(error, \"DURATION_TOO_LONG\")) throw error;\n throw new AudioError(\"DURATION_TOO_LONG\", \"The plan would be longer than maxDuration.\", {\n details: { ...error.details, reason: \"plan-too-long\" },\n });\n }\n }\n return result;\n }\n\n function commit(\n result: { state: AudioPlan; inverses: AudioCommand[] },\n commands: AudioCommand[],\n ) {\n plan = result.state;\n history.push({ commands, inverses: result.inverses });\n // A new step drops the redo steps, and the sources only they held.\n collect();\n }\n\n function newKey(also: ReadonlySet<string> = new Set()): string {\n const used = new Set(clipsIn(plan).map((clip) => clip.key));\n for (const key of also) used.add(key);\n for (const track of plan?.tracks ?? []) used.add(track.key);\n for (const { commands, inverses } of history.steps) {\n for (const command of [...commands, ...inverses])\n for (const key of keysOf(command)) used.add(key);\n }\n let key: string;\n do {\n nextKey += 1;\n key = `c${nextKey}`;\n } while (used.has(key));\n return key;\n }\n\n /**\n * Gives commands the keys they need and don't have (docs/adr/0006, point 2\n * of #54): a split's new part, a new track, and the parts a time edit\n * leaves after a cut, one for every track it names, which the reducer\n * ignores where a track doesn't need it. The history then records the\n * keys, so undo and redo stay exact, and the reducer stays pure.\n */\n function fillKeys(commands: AudioCommand[]): void {\n const taken = new Set(commands.flatMap(keysOf));\n const fresh = () => {\n const key = newKey(taken);\n taken.add(key);\n return key;\n };\n commands.forEach((command, index) => {\n if (command.type === \"audio.splitClip\" && command.newKey === undefined) {\n commands[index] = { ...command, newKey: fresh() };\n } else if (command.type === \"audio.addTrack\" && command.key === undefined) {\n commands[index] = { ...command, key: fresh() };\n } else if (\n (command.type === \"audio.deleteRange\" || command.type === \"audio.insertTime\") &&\n Array.isArray(command.tracks)\n ) {\n const given = command.newKeys ?? {};\n const missing = command.tracks.filter(\n (track) => typeof track === \"string\" && !Object.hasOwn(given, track),\n );\n if (missing.length === 0) return;\n const newKeys: Record<string, string> = { ...given };\n for (const track of missing) {\n // An own field, even for a track keyed `__proto__`.\n Object.defineProperty(newKeys, track, {\n value: fresh(),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n commands[index] = { ...command, newKeys };\n }\n });\n }\n\n return {\n getSnapshot: store.getSnapshot,\n subscribe: store.subscribe,\n\n async open(file, callOptions = {}) {\n generation += 1;\n const started = generation;\n status = \"opening\";\n error = undefined;\n try {\n const source = await track(callOptions.signal, true, (signal) =>\n load(file, signal, callOptions.onProgress, undefined, callOptions.name),\n );\n const replaced = superseded(started);\n if (replaced) throw replaced;\n // The open recording is released once this one opens, so this one\n // must fit on its own.\n policy.check(\"maxSessionSize\", source.bytes);\n sources.clear();\n history.clear();\n sources.set(source.info.id, source);\n // No plan yet, so the two keys only have to differ from each other.\n plan = undefined;\n const first: AudioTrack = {\n key: newKey(),\n name: \"\",\n gainDb: 0,\n muted: false,\n soloed: false,\n clips: [wholeClip(newKey(), source.info, 0)],\n };\n plan = {\n sampleRate: source.info.sampleRate,\n channels: source.info.channels,\n gainDb: 0,\n tracks: [first],\n metadata: EMPTY_METADATA,\n };\n selection = undefined;\n status = \"ready\";\n changed();\n emit({ type: \"recording_opened\", ...facts(source) });\n } catch (reason) {\n const failure = asAudioError(reason, \"The recording couldn't be opened.\");\n // A newer open replaced this one, or a close cancelled it; that\n // reports its own outcome.\n if (started !== generation) throw failure;\n // A failed open keeps the recording that was already open, and its\n // history, so a bad file never costs the user their work.\n status = plan ? \"ready\" : \"error\";\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"open\", code: failure.code });\n throw failure;\n }\n },\n\n async insert(file, insertOptions = {}) {\n if (!plan || status !== \"ready\") {\n throw new AudioError(\"INVALID_COMMAND\", \"Open a recording before inserting another.\", {\n details: { reason: \"no-recording\" },\n });\n }\n const started = generation;\n error = undefined;\n try {\n const source = await track(insertOptions.signal, false, (signal) => {\n policy.check(\"maxFiles\", sources.size + 1);\n return load(file, signal, insertOptions.onProgress, plan?.sampleRate, insertOptions.name);\n });\n const replaced = superseded(started);\n if (replaced) throw replaced;\n const current = plan as AudioPlan;\n // Everything that can fail happens before anything changes.\n const drop = stepsToDrop(source.bytes);\n if (drop === undefined) throw policy.error(\"maxSessionSize\", heldBytes() + source.bytes);\n const clip = wholeClip(newKey(), source.info, insertOptions.at ?? 0);\n const commands: AudioCommand[] = [];\n // A wider recording widens the plan, so a mono voice opened first\n // doesn't fold stereo music to mono (docs/adr/0006). Never narrower.\n if (source.info.channels > current.channels) {\n commands.push({ type: \"audio.setChannels\", channels: source.info.channels });\n }\n let target = insertOptions.track;\n if (target === undefined) {\n target = newKey();\n commands.push({ type: \"audio.addTrack\", key: target, index: current.tracks.length });\n }\n commands.push({ type: \"audio.insertClips\", track: target, clips: [clip] });\n sources.set(source.info.id, source);\n let result: ReturnType<typeof applyChecked>;\n try {\n result = applyChecked(current, commands);\n } catch (reason) {\n sources.delete(source.info.id);\n throw reason;\n }\n history.drop(drop);\n commit(result, commands);\n changed();\n emit({ type: \"recording_inserted\", ...facts(source) });\n } catch (reason) {\n const failure = asAudioError(reason, \"The recording couldn't be inserted.\");\n if (started !== generation) throw failure;\n error = failure;\n changed();\n emit({ type: \"failed\", operation: \"insert\", code: failure.code });\n throw failure;\n }\n },\n\n execute(commands) {\n const list: AudioCommand[] = Array.isArray(commands)\n ? [...(commands as readonly AudioCommand[])]\n : [commands as AudioCommand];\n if (list.length === 0) return;\n try {\n if (!plan) {\n throw new AudioError(\"INVALID_COMMAND\", \"Open a recording before editing it.\", {\n details: { reason: \"no-recording\" },\n });\n }\n let copies: AudioCommand[];\n try {\n // The history keeps its own copies, which also proves they're\n // plain, serialisable data (ADR 0010).\n copies = structuredClone(list);\n } catch (reason) {\n throw new AudioError(\"INVALID_COMMAND\", \"Commands must be plain data.\", {\n cause: reason,\n details: { reason: \"not-plain-data\" },\n });\n }\n fillKeys(copies);\n const result = applyChecked(plan, copies);\n // A command that changes nothing, such as a gain that's already set,\n // succeeds without an undo step (point 4 of #54).\n if (equalData(result.state, plan)) return;\n commit(result, copies);\n // A time edit moves what's after it, so a selected range no longer\n // covers what was selected. Other edits keep it (point 5 of #54).\n if (copies.some((command) => TIME_EDITS.has(command.type))) selection = undefined;\n } catch (reason) {\n const failure = asAudioError(reason);\n emit({ type: \"failed\", operation: \"command\", code: failure.code });\n throw failure;\n }\n changed();\n emit({ type: \"command\", commands: list.map((command) => command.type) });\n },\n\n group: (fn) => history.group(fn),\n\n createKey: newKey,\n\n undo() {\n const current = plan;\n const entry = current && history.undo();\n if (!current || !entry) return;\n try {\n plan = applyCommands(reducer, current, entry.inverses).state;\n } catch (reason) {\n history.restore(\"undo\");\n throw reason;\n }\n changed();\n emit({ type: \"undo\" });\n },\n\n redo() {\n const current = plan;\n const entry = current && history.redo();\n if (!current || !entry) return;\n try {\n plan = applyCommands(reducer, current, entry.commands).state;\n } catch (reason) {\n history.restore(\"redo\");\n throw reason;\n }\n changed();\n emit({ type: \"redo\" });\n },\n\n select(range) {\n let next: AudioSelection | undefined;\n if (range) {\n const { start, end } = range;\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {\n throw new RangeError(\"A selection is a range of whole frames.\");\n }\n const length = plan ? planLength(plan) : 0;\n const from = Math.max(0, Math.min(start, end, length));\n const to = Math.min(length, Math.max(start, end, 0));\n // The plan's tracks the range names, in plan order; every track by default.\n const tracks = (plan?.tracks ?? [])\n .map((track) => track.key)\n .filter((key) => range.tracks === undefined || range.tracks.includes(key));\n if (from < to && tracks.length > 0) {\n next = Object.freeze({ start: from, end: to, tracks: Object.freeze(tracks) });\n }\n }\n const same =\n next?.start === selection?.start &&\n next?.end === selection?.end &&\n next?.tracks.join(\"\\n\") === selection?.tracks.join(\"\\n\");\n if (same) return;\n selection = next;\n changed();\n },\n\n getPeaks: (id) => sources.get(id)?.peaks,\n\n getAudio: (id) => sources.get(id)?.audio,\n\n async export(exportOptions = {}) {\n const current = plan;\n const format: AudioExportFormat = exportOptions.format ?? { container: \"wav\" };\n try {\n if (!current) {\n throw new AudioError(\"INVALID_COMMAND\", \"Open a recording before exporting it.\", {\n details: { reason: \"no-recording\" },\n });\n }\n const clips = clipsIn(current);\n if (clips.length === 0) {\n throw new AudioError(\"INVALID_COMMAND\", \"The recording has no clips to export.\", {\n details: { reason: \"empty-plan\" },\n });\n }\n if (mixLength(current) === 0) {\n throw new AudioError(\"INVALID_COMMAND\", \"No track with clips is audible.\", {\n details: { reason: \"nothing-audible\" },\n });\n }\n const { processor } = options;\n if (!processor) throw new TypeError(\"Exporting needs a processor in createAudioSession.\");\n // The sources as they are now: an edit or a close during the export\n // can't change what it renders.\n const used = new Map<string, DecodedAudio>();\n for (const { source } of clips) {\n const held = sources.get(source);\n if (held) used.set(source, held.audio);\n }\n busy += 1;\n changed();\n try {\n const output = await withProcessingTime(\n policy,\n (signal) =>\n processor.render(\n { plan: current, sources: used, format },\n {\n signal,\n ...(exportOptions.onProgress ? { onProgress: exportOptions.onProgress } : {}),\n },\n ),\n exportOptions.signal ? { signal: exportOptions.signal } : {},\n );\n emit({\n type: \"recording_exported\",\n durationSeconds: coarseSeconds(framesToSeconds(mixLength(current), current.sampleRate)),\n sampleRate: current.sampleRate,\n channels: current.channels,\n sampleFormat: format.sampleFormat ?? \"pcm16\",\n });\n return output;\n } finally {\n busy -= 1;\n changed();\n }\n } catch (reason) {\n if (reason instanceof TypeError || reason instanceof RangeError) throw reason;\n // Whatever a processor rejects with once the caller has aborted, the\n // export was cancelled.\n const failure = exportOptions.signal?.aborted\n ? abortError(exportOptions.signal)\n : asAudioError(reason, \"The recording couldn't be exported.\");\n emit({ type: \"failed\", operation: \"export\", code: failure.code });\n throw failure;\n }\n },\n\n async close() {\n generation += 1;\n cancelLoads(\"The recording was closed.\");\n const hadRecording = plan !== undefined;\n sources.clear();\n history.clear();\n plan = undefined;\n selection = undefined;\n error = undefined;\n status = \"empty\";\n changed();\n if (hadRecording) emit({ type: \"recording_closed\" });\n },\n };\n}\n","import type { AudioOutput } from \"../ports/audio-output.js\";\n\n/**\n * How {@link watchPlayhead} waits for the next frame to draw: the page's\n * `requestAnimationFrame` by default.\n *\n * @public\n */\nexport interface AudioFrameScheduler {\n request(callback: () => void): unknown;\n cancel(handle: unknown): void;\n}\n\n/** The page's animation frames, or a timer at about the same rate where there are none. */\nfunction pageFrames(): AudioFrameScheduler {\n const page = globalThis as {\n requestAnimationFrame?: (callback: () => void) => number;\n cancelAnimationFrame?: (handle: number) => void;\n };\n if (page.requestAnimationFrame && page.cancelAnimationFrame) {\n const { requestAnimationFrame: request, cancelAnimationFrame: cancel } = page;\n return {\n request: (callback) => request(callback),\n cancel: (handle) => cancel(handle as number),\n };\n }\n return {\n request: (callback) => setTimeout(callback, 16),\n cancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n };\n}\n\n/**\n * Follows an output's playhead (point 8 of #54), without a framework: calls\n * `listener` with the playhead, in whole frames, now, whenever it jumps, as\n * after a seek or a stop, and on every animation frame while playing. It\n * calls only when the frame differs from the last one it gave, and asks for\n * no frames while nothing plays. Returns a function that stops it.\n *\n * It reads the page's `requestAnimationFrame` when it's called, never on\n * import, so the entry stays server-safe.\n *\n * @example\n * ```ts\n * const stop = watchPlayhead(output, (frame) => {\n * playhead.textContent = formatTimecode(frame, plan.sampleRate);\n * });\n * ```\n *\n * @public\n */\nexport function watchPlayhead(\n output: AudioOutput,\n listener: (frame: number) => void,\n frames: AudioFrameScheduler = pageFrames(),\n): () => void {\n let last: number | undefined;\n let pending: unknown;\n let stopped = false;\n\n const report = () => {\n const frame = output.position();\n if (frame === last) return;\n last = frame;\n listener(frame);\n };\n const tick = () => {\n pending = undefined;\n if (stopped) return;\n report();\n if (output.getSnapshot().state === \"playing\") pending = frames.request(tick);\n };\n const changed = () => {\n if (stopped) return;\n report();\n if (output.getSnapshot().state === \"playing\") {\n pending ??= frames.request(tick);\n } else if (pending !== undefined) {\n frames.cancel(pending);\n pending = undefined;\n }\n };\n\n const unsubscribe = output.subscribe(changed);\n changed();\n return () => {\n stopped = true;\n unsubscribe();\n if (pending !== undefined) frames.cancel(pending);\n pending = undefined;\n };\n}\n","import { defineMessages, type MessageValue, plural, sdkCoreMessages } from \"@hussmartinez/sdk-core\";\nimport type { AudioErrorCode } from \"../core/errors/audio-error.js\";\nimport type { AudioLimitName } from \"../core/errors/audio-limits.js\";\n\n/**\n * The audio SDK's English message catalogue: sdk-core's messages, and text\n * for every {@link AudioErrorCode} and every limit's warning. Pass it to\n * `createMessages` from `@hussmartinez/sdk-core`, with the host's locale and\n * overrides. The editor's text joins it as the editor arrives.\n *\n * Error text is looked up by code, with the error's `details` as\n * parameters, and never taken from `error.message` (ADR 0019).\n *\n * @example\n * ```ts\n * const messages = createMessages(audioMessages, { locale: \"en\", overrides: props.messages });\n * messages.error(error); // \"This recording has 12 channels, which is over the 8-channel limit.\"\n * messages.t(\"warnings.maxSessionSize\", { actual: 800e6 });\n * ```\n *\n * @public\n */\nexport const audioMessages = /* @__PURE__ */ defineMessages({\n ...sdkCoreMessages,\n \"errors.INVALID_AUDIO\": \"This file isn't valid audio, or it's too damaged to open.\",\n \"errors.UNSUPPORTED_FORMAT\":\n \"This audio format isn't supported. Try converting the file to WAV, then open it again.\",\n \"errors.DECODE_FAILED\":\n \"This browser can't play this kind of audio. Try another browser, or convert the file to WAV.\",\n \"errors.INVALID_COMMAND\": \"This edit couldn't be made. Please try again.\",\n \"errors.INVALID_DOCUMENT\": \"This project is damaged, or it isn't an audio project.\",\n \"errors.DURATION_TOO_LONG\":\n \"This recording is {actual, duration} long, which is over the {maximum, duration} limit.\",\n \"errors.TOO_MANY_CHANNELS\":\n \"This recording has {actual, number} channels, which is over the {maximum, number}-channel limit.\",\n \"errors.SAMPLE_RATE_TOO_HIGH\":\n \"This recording's sample rate is {actual, number} Hz, which is over the {maximum, number} Hz limit.\",\n \"errors.SESSION_TOO_LARGE\":\n \"The open recordings would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Remove a recording, or clear the undo history, and try again.\",\n \"errors.TOO_MANY_CLIPS\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"A recording can have {maximum} clip. Join or delete clips, and try again.\",\n other: \"A recording can have up to {maximum} clips. Join or delete clips, and try again.\",\n }),\n \"errors.TOO_MANY_TRACKS\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"A recording can have {maximum} track. Remove a track, and try again.\",\n other: \"A recording can have up to {maximum} tracks. Remove a track, and try again.\",\n }),\n \"warnings.maxDuration\":\n \"This recording is {actual, duration} long, and may be slow to open and edit.\",\n \"warnings.maxChannels\": \"This recording has {actual, number} channels, and may be slow to edit.\",\n \"warnings.maxSampleRate\":\n \"This recording's sample rate is {actual, number} Hz, and it may be slow to edit.\",\n \"warnings.maxSessionSize\":\n \"The open recordings use {actual, fileSize} of memory. Clearing the undo history frees memory.\",\n \"warnings.maxClips\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This recording has {actual} clip. Many clips may be slow to play and export.\",\n other: \"This recording has {actual} clips. Many clips may be slow to play and export.\",\n }),\n \"warnings.maxTracks\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This recording has {actual} track. Many tracks may be slow to play and export.\",\n other: \"This recording has {actual} tracks. Many tracks may be slow to play and export.\",\n }),\n // Texts for one reason of a code, which take its place when the error\n // carries that reason: see audioErrorText.\n \"errors.UNSUPPORTED_ENVIRONMENT.autoplay-blocked\":\n \"The browser didn't let sound start. Press Play to start it.\",\n \"errors.DURATION_TOO_LONG.plan-too-long\":\n \"This would make the recording {actual, duration} long, which is over the {maximum, duration} limit.\",\n \"warnings.truncated\":\n \"This recording looks incomplete, perhaps from an interrupted recording or download. It opened with the audio it holds.\",\n}) satisfies Record<`errors.${AudioErrorCode}`, MessageValue> &\n Record<`warnings.${AudioLimitName}` | \"warnings.truncated\", MessageValue>;\n\n/**\n * The type of {@link audioMessages}, for typing a host's overrides with\n * `MessageOverrides<AudioMessageCatalogue>`.\n *\n * @public\n */\nexport type AudioMessageCatalogue = typeof audioMessages;\n","import { isSdkError, type Messages } from \"@hussmartinez/sdk-core\";\nimport type { AudioWarning } from \"../core/session/session.js\";\nimport { type AudioMessageCatalogue, audioMessages } from \"./en.js\";\n\n/**\n * The user-facing text for an error: the catalogue's text for its code and\n * `details.reason` together, `errors.<CODE>.<reason>`, when there is one,\n * and otherwise `messages.error(error)`, the text for its code. So a blocked\n * `play()` says that sound needs a press of Play, rather than that the\n * browser lacks a feature (point 9 of #54).\n *\n * sdk-core's `messages.error()` may take over this fallback for the family;\n * until then, use this one.\n *\n * @example\n * ```ts\n * const messages = createMessages(audioMessages, { locale: \"en\" });\n * showError(audioErrorText(messages, error));\n * ```\n *\n * @public\n */\nexport function audioErrorText(messages: Messages<AudioMessageCatalogue>, error: unknown): string {\n if (isSdkError(error)) {\n const details = (error.details ?? {}) as { readonly reason?: unknown };\n if (typeof details.reason === \"string\") {\n const key = `errors.${error.code}.${details.reason}`;\n if (Object.hasOwn(audioMessages, key)) {\n // The key is one of the catalogue's, whose parameters come from the\n // same details as its code's text.\n const catalogue = messages as unknown as { t(key: string, params: object): string };\n return catalogue.t(key, details);\n }\n }\n }\n return messages.error(error);\n}\n\n/**\n * The user-facing text for one of the snapshot's warnings, from\n * `warnings.<limit>` or `warnings.truncated`, with the parameters each needs\n * (point 12 of #54). A limit's name is known only at run time, which\n * `messages.t()` can't type, so this does it once.\n *\n * @example\n * ```ts\n * for (const warning of snapshot.warnings) show(audioWarningText(messages, warning));\n * ```\n *\n * @public\n */\nexport function audioWarningText(\n messages: Messages<AudioMessageCatalogue>,\n warning: AudioWarning,\n): string {\n if (warning.type === \"truncated\") return messages.t(\"warnings.truncated\");\n // Every limit's warning takes `actual`, or nothing, which ignores it.\n const catalogue = messages as unknown as { t(key: string, params: object): string };\n return catalogue.t(`warnings.${warning.limit}`, { actual: warning.actual });\n}\n"],"mappings":";;AAqEA,IAAa,aAAb,cAAgC,SAAyB;CAEvD,OAAyB;AAC3B;AAcA,SAAgB,aACd,OACA,MAC+C;CAC/C,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,SAAS;AACnD;;ACxEA,IAAa,EACX,OAAO,cACP,YACA,mBACkB,mCAAmB,YAAY;CACjD,cAAc;CACd,iBAAiB;AACnB,CAAC;;ACTD,SAAgB,kBAAkB,WAAwD;CACxF,MAAM,aACJ,cAAc,KAAA,IACV,KAAA,IACA,IAAI,IAAI,yBAAyB,kBAAkB,SAAS,CAAC,CAAC,CAAC;CACrE,OAAO;EACL,YAAY,aACR,kBAAkB,IAAI,OAAO,YAAY;GAAE,MAAM;GAAU,MAAM;EAAW,CAAC,IAC7E,aAAa,MAAM,OAAO,oCAAA,CAAuB;EACrD,SAAA;EACA,GAAI,aAAa,EAAE,OAAO,WAAW,IAAI,CAAC;CAC5C;AACF;AClBA,IAAM,eAAe;AA8CrB,SAAgB,aAAa,QAAqB,SAAA,KAAoC;CACpF,MAAM,SAA2B,CAAC;CAClC,IAAI,UAAU;CACd,IAAI,kBAAkB;CACtB,SAAS;EACP,OAAO,KAAK;GACV;GACA,UAAU,QAAQ,IAAI,KAAK,KAAK,OAAO;IAAE;IAAK,KAAK,QAAQ,IAAI;GAAmB,EAAE;EACtF,CAAC;EAED,KADc,QAAQ,IAAI,E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