@hussmartinez/audio-sdk 0.2.1 → 0.3.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/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/peaks.ts","../src/adapters/web-audio/platform-decode.ts","../src/adapters/audio-engine.ts","../src/core/errors/audio-limits.ts","../src/core/model/plan.ts","../src/core/operations/commands.ts","../src/core/format/plan-document.ts","../src/core/model/envelope.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 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 {\n createWorkerClient,\n resolveAssetsBase,\n type WorkerClient,\n type WorkerLike,\n} 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 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 const selfHosted =\n options.assetsUrl === undefined\n ? undefined\n : new URL(\"audio/audio.worker.js\", resolveAssetsBase(options.assetsUrl)).href;\n return createEngine({\n loadWorker: selfHosted\n ? async () => () => new Worker(selfHosted, { type: \"module\", name: \"hm-audio\" })\n : async () => (await import(\"./audio-worker/inline-worker.js\")).createInlineWorker,\n version: __AUDIO_SDK_VERSION__,\n ...(selfHosted ? { asset: selfHosted } : {}),\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 {\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 { 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 { 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} characters. */\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 UTF-16 code units, so that history steps\n * stay small.\n *\n * @public\n */\nexport const MAX_METADATA_LENGTH = 1_000;\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 * characters.\n *\n * The session adds `no-recording`, for a command with no recording open,\n * and `not-plain-data`, for a command that can't be cloned.\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\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 (value.length > MAX_METADATA_LENGTH) {\n invalid(\n \"metadata-too-long\",\n `a metadata value can have at most ${MAX_METADATA_LENGTH} characters`,\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 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 (text.length > MAX_METADATA_LENGTH) {\n invalid(\"metadata-too-long\", `metadata.${field} is over ${MAX_METADATA_LENGTH} characters`);\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","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","/**\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 { 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 { 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.\n *\n * @public\n */\nexport type AudioSessionEvent =\n | ({ readonly type: \"recording_opened\" | \"recording_inserted\" } & AudioRecordingFacts)\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\";\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 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 /** Receives anonymous usage events. Errors it throws are ignored. */\n readonly onEvent?: (event: AudioSessionEvent) => void;\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 /** 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/** 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: 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 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;ACfD,IAAM,eAAe;AA8CrB,SAAgB,aAAa,QAAqB,SAAA,KAAoC;CACpF,MAAM,SAA2B,CAAC;CAClC,IAAI,UAAU;CACd,IAAI,kBAAkB;CAC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C3vBA,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":["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/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/envelope.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 { 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","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","/**\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,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