diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..848713e 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -308,6 +308,15 @@ function verifyRuntimeImport(consumerDir, packageName) { 'assert.equal(typeof wasmModule.default, "function");', 'assert.equal(typeof wasmModule.initSync, "function");', "", + "assert.throws(", + " () => rootModule.defaultConfig(),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", + "assert.throws(", + " () => new rootModule.Tunelet(48000, 128),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", + "", "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", "assert.ok(wasmExports.memory instanceof WebAssembly.Memory);", @@ -381,9 +390,92 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.dryMix, 0.25);", " assert.equal(processor.config().resynthesis.correction.humanize, 0.5);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);", + "", + " const invalidConstructorConfig = rootModule.defaultConfig();", + " invalidConstructorConfig.resynthesis.choirDetune = 5;", + " assert.throws(", + " () => new rootModule.Tunelet(48000, 128, invalidConstructorConfig),", + " /invalid config: resynthesis\\.choirDetune must be in 10\\.\\.=100/,", + " );", + "", + " const unorderedPitchConfig = rootModule.defaultConfig();", + " unorderedPitchConfig.resynthesis.pitch.minFrequencyHz = 500;", + " unorderedPitchConfig.resynthesis.pitch.maxFrequencyHz = 400;", + " assert.throws(", + " () => processor.setConfig(unorderedPitchConfig),", + " /invalid config: resynthesis\\.pitch\\.minFrequencyHz must be below resynthesis\\.pitch\\.maxFrequencyHz/,", + " );", + "", + " const invalidFlexTuneConfig = processor.config();", + " invalidFlexTuneConfig.resynthesis.correction.flexTune = 2;", + " assert.throws(", + " () => processor.setConfig(invalidFlexTuneConfig),", + " /invalid config: resynthesis\\.correction\\.flexTune must be in 0\\.\\.=1/,", + " );", + "", + " assert.throws(", + " () => processor.setConfig({}),", + " (err) =>", + ' err instanceof Error &&', + ' err.message.includes("ProcessorConfig") &&', + ' !err.message.includes("tunelet::"),', + " );", + "", + " const framesBeforeEventErrors = processor.feedback().processedFrames;", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "outputGain", value: 100 } },', + " ]),", + " /event 0: outputGain must be in 0\\.\\.=64/,", + " );", + " const badEventResynthesis = processor.config().resynthesis;", + " badEventResynthesis.choirDetune = 5;", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "resynthesis", value: badEventResynthesis } },', + " ]),", + " /event 0: resynthesis\\.choirDetune must be in 10\\.\\.=100/,", + " );", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "parameter", value: { type: "punchGainDb", value: 99 } } },', + " ]),", + " /event 0: punch\\.gainDb must be in -96\\.\\.=12/,", + " );", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "parameter", value: { type: "choirDetune", value: 5 } } },', + " ]),", + " /event 0: resynthesis\\.choirDetune must be in 10\\.\\.=100/,", + " );", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "punch", value: {} } },', + " ]),", + ' (err) => err instanceof Error && !err.message.includes("tunelet::"),', + " );", + " assert.equal(processor.feedback().processedFrames, framesBeforeEventErrors);", "} finally {", " processor.free();", "}", + "processor.free();", + "assert.throws(", + " () => processor.sampleRate,", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + ");", + "assert.throws(", + " () => processor.config(),", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + ");", + "assert.throws(", + " () => processor.reset(),", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + ");", "", "const config = rootModule.defaultConfig();", "config.resynthesis.formant.enabled = true;", @@ -485,6 +577,23 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.throws(() =>", " f32Processor.processF32InPlace(64, [{ offset: 64, event: { type: \"reset\" } }]),", " );", + " assert.throws(", + " () =>", + " f32Processor.processF32InPlace(64, [", + ' { offset: 0, event: { type: "parameter", value: { type: "reverbBrightnessHz", value: 10 } } },', + " ]),", + " /event 0: reverb\\.brightnessHz must be in 80\\.\\.=20000/,", + " );", + " assert.throws(", + " () =>", + " copiedF32Processor.processF32(", + " inputF32.subarray(0, 64),", + " leftF32.subarray(0, 64),", + " rightF32.subarray(0, 64),", + ' [{ offset: 0, event: { type: "parameter", value: { type: "flexTune", value: -1 } } }],', + " ),", + " /event 0: resynthesis\\.correction\\.flexTune must be in 0\\.\\.=1/,", + " );", " assert.equal(f32Processor.feedback().processedFrames, framesBeforeError);", " assert.equal(views.left[0], savedLeft0);", "", @@ -560,6 +669,51 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.equal(disposableViews.disposed, true);", 'assert.equal(typeof disposableProcessor[Symbol.dispose], "function");', "disposableProcessor[Symbol.dispose]();", + "disposableProcessor[Symbol.dispose]();", + "disposableProcessor.free();", + "for (const getter of [", + ' "inputF32Ptr",', + ' "leftF32Ptr",', + ' "rightF32Ptr",', + ' "sampleRate",', + ' "maxBlockFrames",', + ' "latencyFrames",', + "]) {", + " assert.throws(", + " () => disposableProcessor[getter],", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + " );", + "}", + "for (const callDisposed of [", + " () => disposableProcessor.config(),", + " () => disposableProcessor.setConfig(rootModule.defaultConfig()),", + " () => disposableProcessor.process(new Int16Array(0), new Int16Array(0), new Int16Array(0)),", + " () => disposableProcessor.processMono(new Int16Array(0)),", + " () => disposableProcessor.processF32(new Float32Array(0), new Float32Array(0), new Float32Array(0)),", + " () => disposableProcessor.processMonoF32(new Float32Array(0)),", + " () => disposableProcessor.processF32InPlace(0),", + " () => disposableProcessor.processMonoF32InPlace(0),", + " () => disposableProcessor.beginDrain(),", + " () => disposableProcessor.tailFrames(),", + " () => disposableProcessor.drain(new Int16Array(0), new Int16Array(0)),", + " () => disposableProcessor.drainMono(new Int16Array(0)),", + " () => disposableProcessor.drainF32(new Float32Array(0), new Float32Array(0)),", + " () => disposableProcessor.drainMonoF32(new Float32Array(0)),", + " () => disposableProcessor.drainF32InPlace(0),", + " () => disposableProcessor.drainMonoF32InPlace(0),", + " () => disposableProcessor.feedback(),", + " () => disposableProcessor.takeFeedback(),", + " () => disposableProcessor.controlActivity(),", + " () => disposableProcessor.telemetry(),", + " () => disposableProcessor.takeTelemetry(),", + " () => disposableProcessor.formantEnvelope(8000, new Float32Array(16), new Float32Array(16)),", + " () => disposableProcessor.reset(),", + "]) {", + " assert.throws(", + " callDisposed,", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + " );", + "}", "", ].join("\n"), ); @@ -669,7 +823,15 @@ function verifyRuntimeImport(consumerDir, packageName) { "const wasmBytes = fs.readFileSync(", " fileURLToPath(import.meta.resolve(`${packageName}/tunelet_bg.wasm`)),", ");", - "const { initSync, Tunelet } = await import(packageName);", + "const { defaultConfig, initSync, Tunelet } = await import(packageName);", + "assert.throws(", + " () => defaultConfig(),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", + "assert.throws(", + " () => new Tunelet(48000, 128),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", "const exportsFromSync = initSync({ module: wasmBytes });", "assert.ok(exportsFromSync);", "const processor = new Tunelet(48000, 128);", diff --git a/src/index.ts b/src/index.ts index 4f6e6e1..2ba3fc9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,28 @@ /** * The shared ESM entry point for browsers and Node.js. * - * Call `loadTunelet()` before you construct processors or read the default - * configuration. Both environments use the same generated bindings and the - * same Wasm binary. This module exports `TuneletAudioViews` and re-exports all - * named exports of the module that wasm-bindgen generates. Those exports - * include `Tunelet`, `defaultConfig`, `initSync` and the configuration, - * control-activity, event and feedback types. + * Call `loadTunelet()` or `initSync()` before you construct processors or read + * the default configuration. Both environments use the same generated bindings + * and the same Wasm binary. This module exports `TuneletAudioViews`, wraps + * `Tunelet`, `defaultConfig` and `initSync` with lifecycle checks, and + * re-exports the configuration, control-activity, event, feedback and + * telemetry types. */ -import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput, Tunelet } from "../pkg/tunelet.js"; +import init, { + Tunelet as WasmTunelet, + defaultConfig as wasmDefaultConfig, + initSync as wasmInitSync, +} from "../pkg/tunelet.js"; +import type { + BlockEvents, + ControlActivity, + Feedback, + InitInput, + InitOutput, + ProcessorConfig, + SyncInitInput, + Telemetry, +} from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; @@ -132,6 +145,38 @@ if (Symbol.dispose) { /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; +/** True after the Wasm module completes initialization. */ +let initialized = false; + +/** Maps each active wrapper instance to its Wasm processor. */ +const instances = new WeakMap(); + +/** Throws if the Wasm module is not initialized yet. */ +function ensureInitialized(): void { + if (initialized) { + return; + } + try { + wasmInitSync({ module: undefined as never }); + initialized = true; + } catch { + throw new Error( + "Tunelet Wasm is not initialized. Call loadTunelet() or initSync() first.", + ); + } +} + +/** Returns the active Wasm processor, or throws if it was freed. */ +function active(instance: Tunelet): WasmTunelet { + const inner = instances.get(instance); + if (inner === undefined) { + throw new Error( + "Tunelet instance is disposed. Do not use it after free().", + ); + } + return inner; +} + /** * Initializes the Wasm module one time for this imported package instance. * @@ -161,8 +206,8 @@ let initialization: Promise | undefined; * * @param source The optional Wasm source. The default is the binary in this * package. - * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class - * for processors. + * @returns The initialized Wasm exports. Use the exported `Tunelet` class for + * processors. */ export function loadTunelet( source?: InitInput | Promise, @@ -209,6 +254,7 @@ async function initialize( ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) : await source; + let output: InitOutput; const fileUrl = resolveFileUrl(input); if (fileUrl !== undefined) { // Keep the Node.js built-in module out of browser bundles. TypeScript @@ -218,10 +264,273 @@ async function initialize( const fs: typeof import("node:fs/promises") = await import( /* webpackIgnore: true */ /* @vite-ignore */ moduleName ); - return init({ module_or_path: await fs.readFile(fileUrl) }); + output = await init({ module_or_path: await fs.readFile(fileUrl) }); + } else { + output = await init({ module_or_path: input }); + } + + initialized = true; + return output; +} + +/** + * Instantiates the Wasm module synchronously from bytes or a compiled + * `WebAssembly.Module`. + * + * If the module is already initialized, later calls return the active exports + * and do not load Wasm again. + */ +export function initSync( + module: { module: SyncInitInput } | SyncInitInput, +): InitOutput { + const output = wasmInitSync(module); + initialized = true; + initialization ??= Promise.resolve(output); + return output; +} + +/** + * Returns a complete, independent default configuration for JavaScript. + * + * Call `loadTunelet()` or `initSync()` before this function. Change the fields + * of the returned object and give it to `Tunelet` or to `setConfig`. + */ +export function defaultConfig(): ProcessorConfig { + ensureInitialized(); + return wasmDefaultConfig(); +} + +export interface Tunelet { + [Symbol.dispose](): void; +} + +/** + * A stateful vocal processor for mono `Int16Array` PCM and `Float32Array` + * audio. + * + * Call `loadTunelet()` or `initSync()` before you construct an instance. If + * you do not need the instance any more, call `free()`. Duplicate `free()` + * calls do no work. After `free()`, method and property calls throw an + * `Error`. + */ +export class Tunelet { + /** + * Prepares a processor and its reusable PCM buffers. + * + * `sampleRate` must be 44100 or 48000. `maxBlockFrames` must be an integer + * from 1 to 4294967295 (inclusive). If you omit `config`, the processor uses + * the default configuration. + */ + constructor( + sampleRate: number, + maxBlockFrames: number, + config?: ProcessorConfig | null, + ) { + ensureInitialized(); + instances.set(this, new WasmTunelet(sampleRate, maxBlockFrames, config)); + } + + /** Releases the Wasm processor memory. Duplicate calls do no work. */ + free(): void { + const inner = instances.get(this); + if (inner === undefined) { + return; + } + instances.delete(this); + inner.free(); + } + + /** + * The byte offset in Wasm memory of the `maxBlockFrames` `f32` input buffer. + */ + get inputF32Ptr(): number { + return active(this).inputF32Ptr; + } + + /** + * The byte offset in Wasm memory of the `maxBlockFrames` left `f32` output + * buffer. + */ + get leftF32Ptr(): number { + return active(this).leftF32Ptr; + } + + /** + * The byte offset in Wasm memory of the `maxBlockFrames` right `f32` output + * buffer. + */ + get rightF32Ptr(): number { + return active(this).rightF32Ptr; + } + + /** The sample rate of the input and the output in hertz. */ + get sampleRate(): number { + return active(this).sampleRate; + } + + /** The maximum frame count for each call that processes or drains audio. */ + get maxBlockFrames(): number { + return active(this).maxBlockFrames; + } + + /** The nominal resynthesis latency: 1,593 frames at both sample rates. */ + get latencyFrames(): number { + return active(this).latencyFrames; + } + + /** Returns a copy of the active configuration as a new JavaScript object. */ + config(): ProcessorConfig { + return active(this).config(); + } + + /** Validates a configuration and replaces the complete configuration. */ + setConfig(config: ProcessorConfig): void { + active(this).setConfig(config); } - return init({ module_or_path: input }); + /** Processes mono input into left and right `Int16Array` buffers. */ + process( + input: Int16Array, + left: Int16Array, + right: Int16Array, + events?: BlockEvents | null, + ): void { + active(this).process(input, left, right, events); + } + + /** Replaces the audio in a mono `Int16Array` with the stereo downmix. */ + processMono(audio: Int16Array, events?: BlockEvents | null): void { + active(this).processMono(audio, events); + } + + /** + * Processes mono `Float32Array` input into left and right `Float32Array` + * buffers. + */ + processF32( + input: Float32Array, + left: Float32Array, + right: Float32Array, + events?: BlockEvents | null, + ): void { + active(this).processF32(input, left, right, events); + } + + /** Replaces the audio in a mono `Float32Array` with the stereo downmix. */ + processMonoF32(audio: Float32Array, events?: BlockEvents | null): void { + active(this).processMonoF32(audio, events); + } + + /** + * Processes `frames` samples from `inputF32Ptr` into `leftF32Ptr` and + * `rightF32Ptr`. + */ + processF32InPlace(frames: number, events?: BlockEvents | null): void { + active(this).processF32InPlace(frames, events); + } + + /** + * Replaces `frames` samples at `inputF32Ptr` with the mono `f32` downmix. + */ + processMonoF32InPlace(frames: number, events?: BlockEvents | null): void { + active(this).processMonoF32InPlace(frames, events); + } + + /** Starts a finite tail budget and returns its frame count. */ + beginDrain(): number { + return active(this).beginDrain(); + } + + /** Returns the tail budget of the current configuration. */ + tailFrames(): number { + return active(this).tailFrames(); + } + + /** Renders stereo tail frames into `Int16Array` buffers of equal length. */ + drain(left: Int16Array, right: Int16Array): number { + return active(this).drain(left, right); + } + + /** Renders a mono tail block and returns its frame count. */ + drainMono(audio: Int16Array): number { + return active(this).drainMono(audio); + } + + /** + * Renders stereo tail frames into `Float32Array` buffers of equal length. + */ + drainF32(left: Float32Array, right: Float32Array): number { + return active(this).drainF32(left, right); + } + + /** + * Renders a mono `Float32Array` tail block and returns its frame count. + */ + drainMonoF32(audio: Float32Array): number { + return active(this).drainMonoF32(audio); + } + + /** + * Renders up to `frames` stereo tail frames into `leftF32Ptr` and + * `rightF32Ptr`. + */ + drainF32InPlace(frames: number): number { + return active(this).drainF32InPlace(frames); + } + + /** + * Renders up to `frames` mono tail frames into `inputF32Ptr` and returns + * their count. + */ + drainMonoF32InPlace(frames: number): number { + return active(this).drainMonoF32InPlace(frames); + } + + /** Returns a new feedback object and does not clear the peak window. */ + feedback(): Feedback { + return active(this).feedback(); + } + + /** Returns the feedback and clears only the peak window. */ + takeFeedback(): Feedback { + return active(this).takeFeedback(); + } + + /** + * Returns which choir, harmony and reverb controls change the audio in the + * active configuration. + */ + controlActivity(): ControlActivity { + return active(this).controlActivity(); + } + + /** Returns a new telemetry object and does not clear its peak windows. */ + telemetry(): Telemetry { + return active(this).telemetry(); + } + + /** Returns the telemetry and clears only its three peak windows. */ + takeTelemetry(): Telemetry { + return active(this).takeTelemetry(); + } + + /** Writes the formant envelopes into two `Float32Array` buffers. */ + formantEnvelope( + maxFrequencyHz: number, + input: Float32Array, + output: Float32Array, + ): boolean { + return active(this).formantEnvelope(maxFrequencyHz, input, output); + } + + /** Resets the audio histories and feedback. */ + reset(): void { + active(this).reset(); + } +} + +if (typeof Symbol.dispose === "symbol") { + Tunelet.prototype[Symbol.dispose] = Tunelet.prototype.free; } /** The default export is the same function as `loadTunelet`. */ diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..26ba51b 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -52,8 +52,8 @@ use crate::events::ValidatedEvents; use crate::processor::EnvelopeKey; use crate::{ - ControlActivity, ControlEvent, Error, Feedback, MidiEvent, ParameterControl, PrepareConfig, - Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + ConfigProblem, ControlActivity, ControlEvent, Error, EventProblem, Feedback, MidiEvent, + ParameterControl, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; use js_sys::{Array, Float32Array, Int16Array, Object, Reflect}; use serde::{Deserialize, Serialize}; @@ -85,7 +85,7 @@ pub struct BlockEvents(Vec); /// JavaScript `Error`. #[wasm_bindgen(js_name = defaultConfig)] pub fn default_config() -> Result, JsError> { - Ok(ProcessorConfig::default().into_ts()?) + ProcessorConfig::default().into_ts().map_err(ts_error) } /// A stateful vocal processor that JavaScript uses as the `Tunelet` class. @@ -153,7 +153,7 @@ pub struct WasmProcessor { impl WasmProcessor { /// Prepares a processor and its reusable PCM buffers. /// - /// `sample_rate` must be 44100 or 48000. `max_block_frames` must be an + /// `sampleRate` must be 44100 or 48000. `maxBlockFrames` must be an /// integer in 1..=4294967295. It is a limit for each call, and smaller /// blocks and empty blocks are also valid. If you omit `config`, the /// processor uses the default configuration. The constructor validates @@ -174,8 +174,8 @@ impl WasmProcessor { /// histories. #[wasm_bindgen(constructor)] pub fn new( - sample_rate: f64, - max_block_frames: f64, + #[wasm_bindgen(js_name = sampleRate)] sample_rate: f64, + #[wasm_bindgen(js_name = maxBlockFrames)] max_block_frames: f64, config: Option>, ) -> Result { // Accept JavaScript numbers without the u32 coercion of wasm-bindgen. @@ -193,12 +193,12 @@ impl WasmProcessor { )); } let max_block_frames = max_block_frames as usize; - let preparation = PrepareConfig::new(rate, max_block_frames)?; + let preparation = PrepareConfig::new(rate, max_block_frames).map_err(wasm_error)?; let config = match config { - Some(value) => value.to_rust()?, + Some(value) => value.to_rust().map_err(ts_error)?, None => ProcessorConfig::default(), }; - let processor = Processor::new(preparation, config)?; + let processor = Processor::new(preparation, config).map_err(wasm_error)?; Ok(Self { processor, input: pcm_buffer(max_block_frames)?, @@ -277,7 +277,7 @@ impl WasmProcessor { /// /// If the conversion to a JavaScript object fails, this method throws. pub fn config(&self) -> Result, JsError> { - Ok(self.processor.config().into_ts()?) + self.processor.config().into_ts().map_err(ts_error) } /// Decodes and validates a configuration, then replaces the complete @@ -292,7 +292,8 @@ impl WasmProcessor { /// After an error, all processor state and any active drain stay the same. #[wasm_bindgen(js_name = setConfig)] pub fn set_config(&mut self, config: Ts) -> Result<(), JsError> { - self.processor.set_config(config.to_rust()?)?; + let config = config.to_rust().map_err(ts_error)?; + self.processor.set_config(config).map_err(wasm_error)?; Ok(()) } @@ -320,9 +321,9 @@ impl WasmProcessor { events: Option>, ) -> Result<(), JsError> { let frames = input.length() as usize; - Error::check_length(frames, left.length() as usize)?; - Error::check_length(frames, right.length() as usize)?; - self.processor.check_block(frames)?; + Error::check_length(frames, left.length() as usize).map_err(wasm_error)?; + Error::check_length(frames, right.length() as usize).map_err(wasm_error)?; + self.processor.check_block(frames).map_err(wasm_error)?; let events = match events { Some(events) => { decode_events(&mut self.events, events, frames, self.processor.config())? @@ -330,12 +331,14 @@ impl WasmProcessor { None => &[], }; input.copy_to(&mut self.input[..frames]); - self.processor.process_planar( - &self.input[..frames], - &mut self.left[..frames], - &mut self.right[..frames], - events, - )?; + self.processor + .process_planar( + &self.input[..frames], + &mut self.left[..frames], + &mut self.right[..frames], + events, + ) + .map_err(wasm_error)?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); Ok(()) @@ -358,7 +361,7 @@ impl WasmProcessor { events: Option>, ) -> Result<(), JsError> { let frames = audio.length() as usize; - self.processor.check_block(frames)?; + self.processor.check_block(frames).map_err(wasm_error)?; let events = match events { Some(events) => { decode_events(&mut self.events, events, frames, self.processor.config())? @@ -367,7 +370,8 @@ impl WasmProcessor { }; audio.copy_to(&mut self.input[..frames]); self.processor - .process_mono_in_place(&mut self.input[..frames], events)?; + .process_mono_in_place(&mut self.input[..frames], events) + .map_err(wasm_error)?; audio.copy_from(&self.input[..frames]); Ok(()) } @@ -397,9 +401,9 @@ impl WasmProcessor { events: Option>, ) -> Result<(), JsError> { let frames = input.length() as usize; - Error::check_length(frames, left.length() as usize)?; - Error::check_length(frames, right.length() as usize)?; - self.processor.check_block(frames)?; + Error::check_length(frames, left.length() as usize).map_err(wasm_error)?; + Error::check_length(frames, right.length() as usize).map_err(wasm_error)?; + self.processor.check_block(frames).map_err(wasm_error)?; let events = match events { Some(events) => { decode_events(&mut self.events, events, frames, self.processor.config())? @@ -407,12 +411,14 @@ impl WasmProcessor { None => &[], }; input.copy_to(&mut self.input_f32[..frames]); - self.processor.process_planar_f32( - &self.input_f32[..frames], - &mut self.left_f32[..frames], - &mut self.right_f32[..frames], - events, - )?; + self.processor + .process_planar_f32( + &self.input_f32[..frames], + &mut self.left_f32[..frames], + &mut self.right_f32[..frames], + events, + ) + .map_err(wasm_error)?; left.copy_from(&self.left_f32[..frames]); right.copy_from(&self.right_f32[..frames]); Ok(()) @@ -436,7 +442,7 @@ impl WasmProcessor { events: Option>, ) -> Result<(), JsError> { let frames = audio.length() as usize; - self.processor.check_block(frames)?; + self.processor.check_block(frames).map_err(wasm_error)?; let events = match events { Some(events) => { decode_events(&mut self.events, events, frames, self.processor.config())? @@ -445,7 +451,8 @@ impl WasmProcessor { }; audio.copy_to(&mut self.input_f32[..frames]); self.processor - .process_mono_in_place_f32(&mut self.input_f32[..frames], events)?; + .process_mono_in_place_f32(&mut self.input_f32[..frames], events) + .map_err(wasm_error)?; audio.copy_from(&self.input_f32[..frames]); Ok(()) } @@ -476,12 +483,14 @@ impl WasmProcessor { } None => &[], }; - self.processor.process_planar_f32( - &self.input_f32[..frames], - &mut self.left_f32[..frames], - &mut self.right_f32[..frames], - events, - )?; + self.processor + .process_planar_f32( + &self.input_f32[..frames], + &mut self.left_f32[..frames], + &mut self.right_f32[..frames], + events, + ) + .map_err(wasm_error)?; Ok(()) } @@ -511,7 +520,8 @@ impl WasmProcessor { None => &[], }; self.processor - .process_mono_in_place_f32(&mut self.input_f32[..frames], events)?; + .process_mono_in_place_f32(&mut self.input_f32[..frames], events) + .map_err(wasm_error)?; Ok(()) } @@ -548,11 +558,12 @@ impl WasmProcessor { /// drain state do not change. pub fn drain(&mut self, left: &Int16Array, right: &Int16Array) -> Result { let frames = left.length() as usize; - Error::check_length(frames, right.length() as usize)?; - self.processor.check_block(frames)?; + Error::check_length(frames, right.length() as usize).map_err(wasm_error)?; + self.processor.check_block(frames).map_err(wasm_error)?; let count = self .processor - .drain_planar(&mut self.left[..frames], &mut self.right[..frames])?; + .drain_planar(&mut self.left[..frames], &mut self.right[..frames]) + .map_err(wasm_error)?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); Ok(count) @@ -574,8 +585,11 @@ impl WasmProcessor { #[wasm_bindgen(js_name = drainMono)] pub fn drain_mono(&mut self, audio: &Int16Array) -> Result { let frames = audio.length() as usize; - self.processor.check_block(frames)?; - let count = self.processor.drain_mono(&mut self.input[..frames])?; + self.processor.check_block(frames).map_err(wasm_error)?; + let count = self + .processor + .drain_mono(&mut self.input[..frames]) + .map_err(wasm_error)?; audio.copy_from(&self.input[..frames]); Ok(count) } @@ -598,11 +612,12 @@ impl WasmProcessor { right: &Float32Array, ) -> Result { let frames = left.length() as usize; - Error::check_length(frames, right.length() as usize)?; - self.processor.check_block(frames)?; + Error::check_length(frames, right.length() as usize).map_err(wasm_error)?; + self.processor.check_block(frames).map_err(wasm_error)?; let count = self .processor - .drain_planar_f32(&mut self.left_f32[..frames], &mut self.right_f32[..frames])?; + .drain_planar_f32(&mut self.left_f32[..frames], &mut self.right_f32[..frames]) + .map_err(wasm_error)?; left.copy_from(&self.left_f32[..frames]); right.copy_from(&self.right_f32[..frames]); Ok(count) @@ -622,10 +637,11 @@ impl WasmProcessor { #[wasm_bindgen(js_name = drainMonoF32)] pub fn drain_mono_f32(&mut self, audio: &Float32Array) -> Result { let frames = audio.length() as usize; - self.processor.check_block(frames)?; + self.processor.check_block(frames).map_err(wasm_error)?; let count = self .processor - .drain_mono_f32(&mut self.input_f32[..frames])?; + .drain_mono_f32(&mut self.input_f32[..frames]) + .map_err(wasm_error)?; audio.copy_from(&self.input_f32[..frames]); Ok(count) } @@ -644,9 +660,9 @@ impl WasmProcessor { #[wasm_bindgen(js_name = drainF32InPlace)] pub fn drain_f32_in_place(&mut self, frames: f64) -> Result { let frames = self.check_frames(frames)?; - Ok(self - .processor - .drain_planar_f32(&mut self.left_f32[..frames], &mut self.right_f32[..frames])?) + self.processor + .drain_planar_f32(&mut self.left_f32[..frames], &mut self.right_f32[..frames]) + .map_err(wasm_error) } /// Renders up to `frames` mono tail frames into `inputF32Ptr` and returns @@ -663,9 +679,9 @@ impl WasmProcessor { #[wasm_bindgen(js_name = drainMonoF32InPlace)] pub fn drain_mono_f32_in_place(&mut self, frames: f64) -> Result { let frames = self.check_frames(frames)?; - Ok(self - .processor - .drain_mono_f32(&mut self.input_f32[..frames])?) + self.processor + .drain_mono_f32(&mut self.input_f32[..frames]) + .map_err(wasm_error) } /// Returns a new feedback object and does not clear the peak window. @@ -685,7 +701,7 @@ impl WasmProcessor { /// /// If the conversion to a JavaScript object fails, this method throws. pub fn feedback(&self) -> Result, JsError> { - Ok(self.processor.feedback().into_ts()?) + self.processor.feedback().into_ts().map_err(ts_error) } /// Returns the feedback and clears only the peak window. @@ -699,7 +715,7 @@ impl WasmProcessor { /// object. #[wasm_bindgen(js_name = takeFeedback)] pub fn take_feedback(&mut self) -> Result, JsError> { - let feedback = self.processor.feedback().into_ts()?; + let feedback = self.processor.feedback().into_ts().map_err(ts_error)?; self.processor.take_feedback(); Ok(feedback) } @@ -716,7 +732,10 @@ impl WasmProcessor { /// If the conversion to a JavaScript object fails, this method throws. #[wasm_bindgen(js_name = controlActivity)] pub fn control_activity(&self) -> Result, JsError> { - Ok(self.processor.control_activity().into_ts()?) + self.processor + .control_activity() + .into_ts() + .map_err(ts_error) } /// Returns a new telemetry object and does not clear its peak windows. @@ -779,15 +798,16 @@ impl WasmProcessor { #[wasm_bindgen(js_name = formantEnvelope)] pub fn formant_envelope( &mut self, - max_frequency_hz: f32, + #[wasm_bindgen(js_name = maxFrequencyHz)] max_frequency_hz: f32, input: &Float32Array, output: &Float32Array, ) -> Result { let points = input.length() as usize; // Check before the buffers become longer for a call that cannot succeed. - let key = - self.processor - .envelope_key(max_frequency_hz, points, output.length() as usize)?; + let key = self + .processor + .envelope_key(max_frequency_hz, points, output.length() as usize) + .map_err(wasm_error)?; if let Some((cached, valid)) = self.envelope_cache { if cached == key { input.copy_from(&self.envelope_input[..points]); @@ -800,7 +820,8 @@ impl WasmProcessor { self.envelope_cache = None; let valid = self .processor - .formant_envelope(max_frequency_hz, analysis, synthesis)?; + .formant_envelope(max_frequency_hz, analysis, synthesis) + .map_err(wasm_error)?; self.envelope_cache = Some((key, valid)); input.copy_from(&self.envelope_input[..points]); output.copy_from(&self.envelope_output[..points]); @@ -823,7 +844,7 @@ impl WasmProcessor { return Err(JsError::new("frames must be an integer in 0..=4294967295")); } let frames = frames as usize; - self.processor.check_block(frames)?; + self.processor.check_block(frames).map_err(wasm_error)?; Ok(frames) } } @@ -1061,7 +1082,7 @@ fn decode_events( Ok(()) })?; } - ValidatedEvents::new(buffer, frames, config)?; + ValidatedEvents::new(buffer, frames, config).map_err(wasm_error)?; Ok(buffer) } @@ -1102,31 +1123,113 @@ fn decode_control_event(event: &JsValue, keys: &EventKeys) -> Result(value: JsValue) -> Result { + serde_wasm_bindgen::from_value(value).map_err(|error| { + let message = clean_type_names(&error.to_string()); + let message = message.strip_prefix("Error: ").unwrap_or(&message); + JsError::new(message) + }) +} + +/// Converts a dotted `snake_case` field path into a `camelCase` JavaScript +/// property path. +fn format_js_field(field: &str) -> String { + let mut result = String::with_capacity(field.len()); + let mut upper_next = false; + for ch in field.chars() { + if ch == '_' { + upper_next = true; + } else if upper_next { + result.push(ch.to_ascii_uppercase()); + upper_next = false; + } else { + result.push(ch); + } + } + result +} + +/// Formats a `ConfigProblem` with `camelCase` JavaScript property paths. +fn format_js_config_problem(problem: ConfigProblem) -> String { + match problem { + ConfigProblem::Unordered { other } => { + let other = format_js_field(other); + format!("must be below {other}") + } + other => other.to_string(), + } +} + +/// Converts a native `Error` into a `JsError` with `camelCase` JavaScript +/// property paths. +fn wasm_error(error: Error) -> JsError { + let message = match error { + Error::InvalidConfig { field, problem } => { + let path = format_js_field(field); + let detail = format_js_config_problem(problem); + format!("invalid config: {path} {detail}") + } + Error::InvalidEvent { + index, + problem: EventProblem::Config { field, problem }, + } => { + let path = format_js_field(field); + let detail = format_js_config_problem(problem); + format!("event {index}: {path} {detail}") + } + other => other.to_string(), + }; + JsError::new(&message) +} + +/// Replaces internal Rust type paths with public TypeScript names. +fn clean_type_names(text: &str) -> String { + let text = text.replace("tunelet::wasm::BlockEvents", "TimedEvent[]"); + let mut output = String::with_capacity(text.len()); + let mut rest = text.as_str(); + while let Some(start) = rest.find("tunelet::") { + output.push_str(&rest[..start]); + let after_crate = &rest[start + "tunelet::".len()..]; + let end = after_crate + .find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_' && ch != ':') + .unwrap_or(after_crate.len()); + let path = &after_crate[..end]; + let type_name = path.rsplit("::").next().unwrap_or(path); + output.push_str(type_name); + rest = &after_crate[end..]; + } + output.push_str(rest); + output +} + +/// Converts a `tsify` error into a `JsError` with public TypeScript names. +fn ts_error(error: tsify::Error) -> JsError { + let message = clean_type_names(&error.to_string()).replace(": Error: ", ": "); + JsError::new(&message) +} + /// Decodes one `MidiEvent` object from its cached discriminant. fn decode_midi_event(value: &JsValue, keys: &EventKeys) -> Result { let kind = get_property(value, &keys.kind)?;