From 7a9a4b4e34243dc1878958b52a340fb5dd84759e Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:04:10 +0000 Subject: [PATCH 1/3] feat(processor): add Q14 2x and 4x resampler, f32 audio and MIDI calls - Add 88.2, 96, 176.4 and 192 kHz variants to SampleRate - Add a Q14 biquad 2x and 4x resampler around the core audio stages - Include the Q14 filter delay in latency_frames and tail_frames - Scale feedback period_samples and formant envelopes to the host rate - Add f32 process, f32 drain and direct MIDI methods on Processor - Update the crate documentation in src/lib.rs --- src/config.rs | 47 ++++++- src/formant.rs | 5 + src/lib.rs | 48 ++++--- src/processor.rs | 335 ++++++++++++++++++++++++++++++++++++++++++----- src/resample.rs | 190 +++++++++++++++++++++++++++ 5 files changed, 567 insertions(+), 58 deletions(-) create mode 100644 src/resample.rs diff --git a/src/config.rs b/src/config.rs index 75bcd82..216428d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -11,10 +11,12 @@ use std::num::NonZeroUsize; /// The sample rate of the input and the output. /// -/// The default is 44.1 kHz. The prepared delay and filter layouts support only -/// the listed rates. To convert an integer device rate, use -/// [`SampleRate::try_from`]. The rate of a processor is fixed at construction. -/// To change the rate, you must make a new processor. +/// The default is 44.1 kHz. The processor runs its core stages directly at +/// 44.1 kHz and 48 kHz. At 88.2, 96, 176.4 and 192 kHz, fixed-point Q14 biquad +/// filters resample between the host rate and the 44.1 kHz or 48 kHz base +/// rate. To convert an integer device rate, use [`SampleRate::try_from`]. The +/// rate of a processor is fixed at construction. To change the rate, you must +/// make a new processor. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] #[non_exhaustive] pub enum SampleRate { @@ -23,6 +25,14 @@ pub enum SampleRate { Hz44100, /// 48 kHz. Hz48000, + /// 88.2 kHz (2x 44.1 kHz). + Hz88200, + /// 96 kHz (2x 48 kHz). + Hz96000, + /// 176.4 kHz (4x 44.1 kHz). + Hz176400, + /// 192 kHz (4x 48 kHz). + Hz192000, } impl SampleRate { @@ -31,6 +41,10 @@ impl SampleRate { match self { Self::Hz44100 => 44_100, Self::Hz48000 => 48_000, + Self::Hz88200 => 88_200, + Self::Hz96000 => 96_000, + Self::Hz176400 => 176_400, + Self::Hz192000 => 192_000, } } @@ -38,6 +52,23 @@ impl SampleRate { pub fn hz(self) -> f32 { self.as_u32() as f32 } + + /// Returns the 44.1 kHz or 48 kHz base rate of the core stages. + pub(crate) const fn base_rate(self) -> Self { + match self { + Self::Hz44100 | Self::Hz88200 | Self::Hz176400 => Self::Hz44100, + Self::Hz48000 | Self::Hz96000 | Self::Hz192000 => Self::Hz48000, + } + } + + /// Returns the integer ratio between this rate and its base rate. + pub(crate) const fn factor(self) -> usize { + match self { + Self::Hz44100 | Self::Hz48000 => 1, + Self::Hz88200 | Self::Hz96000 => 2, + Self::Hz176400 | Self::Hz192000 => 4, + } + } } impl TryFrom for SampleRate { @@ -48,12 +79,16 @@ impl TryFrom for SampleRate { /// # Errors /// /// Returns [`Error::UnsupportedSampleRate`] with `hz`, unless the value is - /// exactly 44,100 or 48,000. The function does not resample and does not - /// select the nearest rate. + /// 44,100, 48,000, 88,200, 96,000, 176,400 or 192,000. The function does + /// not select the nearest rate. fn try_from(hz: u32) -> Result { match hz { 44_100 => Ok(Self::Hz44100), 48_000 => Ok(Self::Hz48000), + 88_200 => Ok(Self::Hz88200), + 96_000 => Ok(Self::Hz96000), + 176_400 => Ok(Self::Hz176400), + 192_000 => Ok(Self::Hz192000), _ => Err(Error::UnsupportedSampleRate { hz }), } } diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..5becd51 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -769,6 +769,11 @@ impl Formant { }; for (k, (input, output)) in input.iter_mut().zip(output.iter_mut()).enumerate() { let omega = step * k as f64; + if omega > std::f64::consts::PI { + *input = 0.0; + *output = 0.0; + continue; + } let (sine, cosine) = omega.sin_cos(); let emphasis = ((1.0 - glottal * cosine).powi(2) + (glottal * sine).powi(2)) .sqrt() diff --git a/src/lib.rs b/src/lib.rs index 0e29119..e9ccf60 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,13 @@ //! A crate for vocal pitch correction, choir, harmony, formant control and effects. //! -//! [`Processor`] changes mono signed 16-bit PCM into the same number of stereo -//! or mono frames. The sample rate is 44.1 kHz or 48 kHz. The signal chain is -//! Punch → Warm → pitch tracking and resynthesis → Alien → reverb → output -//! gain. The default configuration enables chromatic pitch correction and one -//! choir voice. The optional effects and the formant stage are disabled. +//! [`Processor`] changes mono 16-bit PCM or normalized `f32` audio into the +//! same number of stereo or mono frames. The sample rate is 44.1, 48, 88.2, +//! 96, 176.4 or 192 kHz. At 88.2, 96, 176.4 and 192 kHz, fixed-point Q14 +//! biquad filters resample between the host rate and the 44.1 or 48 kHz base +//! rate. The signal chain is Punch → Warm → pitch tracking and resynthesis → +//! Alien → reverb → output gain. The default configuration enables chromatic +//! pitch correction and one choir voice. The optional effects and the formant +//! stage are disabled. //! //! # Preparing and configuring //! @@ -26,15 +29,19 @@ //! //! # Audio and timed controls //! -//! There are three process methods: +//! There are three 16-bit PCM process methods and three `f32` process methods: //! -//! - [`Processor::process`] writes `[left, right]` frames. -//! - [`Processor::process_planar`] writes separate channels. -//! - [`Processor::process_mono_in_place`] replaces the input with the stereo +//! - [`Processor::process`] and [`Processor::process_f32`] write `[left, right]` +//! frames. +//! - [`Processor::process_planar`] and [`Processor::process_planar_f32`] write +//! separate channels. +//! - [`Processor::process_mono_in_place`] and +//! [`Processor::process_mono_in_place_f32`] replace the input with the stereo //! downmix. //! //! These layouts do not depend on [`ResynthesisConfig::stereo_output`], which -//! controls voice panning. The output is clipped to -32767..=32767. +//! controls voice panning. PCM output is clipped to -32767..=32767, and `f32` +//! output is scaled by 1/32768. //! //! An event applies before its selected frame. Offsets must be in the current //! block and must not decrease. Events with equal offsets execute in slice @@ -42,8 +49,9 @@ //! or its state. Thus, an invalid last event also rejects the full call. An //! empty block accepts no events. //! -//! [`ControlEvent::Midi`] controls harmony. [`ControlEvent::CorrectionMidi`] -//! selects the correction pitch classes independently. The processor does not +//! [`ControlEvent::Midi`] and [`Processor::apply_midi`] control harmony. +//! [`ControlEvent::CorrectionMidi`] and [`Processor::apply_correction_midi`] +//! select the correction pitch classes independently. The processor does not //! keep MIDI controls in a queue after the current call. //! //! # Feedback, latency and lifecycle @@ -52,9 +60,10 @@ //! accumulated stereo peak and the frame count. //! [`Processor::take_feedback`] also clears the peak window. The pitch //! reporting bounds change only the reports. They do not change the detection -//! or the audio signal. [`Processor::latency_frames`] gives a nominal -//! resynthesis delay. Voice delays, pitch changes and effects have their own -//! timing. +//! or the audio signal. [`Processor::latency_frames`] gives the nominal +//! resynthesis delay in host frames, with the Q14 resampler filter delay +//! included at 88.2, 96, 176.4 and 192 kHz. Voice delays, pitch changes and +//! effects have their own timing. //! //! [`Processor::telemetry`] gives data for meters and displays: the ratio and //! the gain of each voice, the input and output peaks, the pitch clarity and @@ -92,9 +101,11 @@ //! //! To export JavaScript bindings and generated TypeScript definitions, enable //! the optional `wasm` feature for `wasm32-unknown-unknown`. The binding owns -//! PCM buffers that it uses again. Configuration conversion, event conversion, -//! feedback objects and errors cause more allocation at the JavaScript -//! boundary. +//! reusable 16-bit PCM and `f32` buffers, and exposes typed-array methods for +//! MIDI controls, feedback and telemetry without heap allocation. Object +//! conversion and errors cause allocation at the JavaScript boundary. The npm +//! package also provides `createTuneletNode`, `TuneletWorkletNode` and the +//! `tunelet/worklet` runtime for Web Audio. //! Refer to the README for how to build the shared package for browsers and //! Node.js. @@ -115,6 +126,7 @@ mod midi; mod numeric; mod pitch; mod processor; +mod resample; mod resynthesis; mod scale; diff --git a/src/processor.rs b/src/processor.rs index cc910f4..1aba732 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -7,8 +7,9 @@ use crate::effects::warm::Warm; use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; +use crate::resample::Resampler; use crate::resynthesis::{self, Resynthesis}; -use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{ControlEvent, Error, MidiEvent, PrepareConfig, ProcessorConfig, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -45,6 +46,8 @@ pub struct Processor { /// /// In bypass, their histories do not change. reverb: Reverb, + /// The fixed-point 2x or 4x rate converter, or `None` at 44.1 and 48 kHz. + resampler: Option>, /// The random sequence of this instance and the cached arctangent position. numeric: NumericContext, /// The largest absolute clipped stereo PCM sample in the feedback window. @@ -102,7 +105,7 @@ impl Processor { /// not zero and that the sample rate is supported. pub fn new(preparation: PrepareConfig, config: ProcessorConfig) -> Result { config.validate()?; - let rate = preparation.sample_rate; + let rate = preparation.sample_rate.base_rate(); // Drive uses the default gain until the first 100-frame peak window. let mut punch = Punch::new(rate, PunchConfig::default()); punch.set_config(config.punch); @@ -114,6 +117,7 @@ impl Processor { resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), alien: Alien::new(config.alien), reverb: Reverb::new(rate, config.reverb), + resampler: Resampler::new(preparation.sample_rate), numeric: NumericContext::new(config.resynthesis.random_seed as u32), peak: 0, input_peak: 0, @@ -211,6 +215,85 @@ impl Processor { Ok(()) } + /// Processes mono `f32` audio into `[left, right]` stereo frames. + /// + /// Input samples in `-1.0..=1.0` map to rounded, clamped 16-bit PCM. The + /// method scales output samples by `1.0 / 32768.0` into + /// `-32767.0 / 32768.0..=32767.0 / 32768.0`. Block limits, event timing and + /// drain cancellation are the same as for [`process`](Self::process). + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] first and + /// [`Error::BlockTooLarge`] second. Then it checks [`Error::InvalidEvent`] + /// before the state or the output changes. + pub fn process_f32( + &mut self, + input: &[f32], + output: &mut [[f32; 2]], + events: &[TimedEvent], + ) -> Result<(), Error> { + Error::check_length(input.len(), output.len())?; + self.process_into_f32(input, events, |index, frame| output[index] = frame) + } + + /// Processes mono `f32` audio into separate left and right output slices. + /// + /// The three slices must have equal frame counts. Input quantization, + /// output scaling, event order and drain cancellation are the same as for + /// [`process_f32`](Self::process_f32). + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] for the left channel, then for + /// the right channel. Next, it checks [`Error::BlockTooLarge`], then + /// [`Error::InvalidEvent`] before the output buffers or the state change. + pub fn process_planar_f32( + &mut self, + input: &[f32], + left: &mut [f32], + right: &mut [f32], + events: &[TimedEvent], + ) -> Result<(), Error> { + Error::check_length(input.len(), left.len())?; + Error::check_length(input.len(), right.len())?; + self.process_into_f32(input, events, |index, frame| { + left[index] = frame[0]; + right[index] = frame[1]; + }) + } + + /// Replaces mono `f32` audio with the stereo downmix. + /// + /// Input conversion, stereo peak measurement, downmix rounding, event + /// order and drain cancellation are the same as for + /// [`process_mono_in_place`](Self::process_mono_in_place) and + /// [`process_f32`](Self::process_f32). + /// + /// # Errors + /// + /// Returns [`Error::BlockTooLarge`] for a slice that is too large. Returns + /// [`Error::InvalidEvent`] for the first invalid event before the audio + /// slice or the processor state changes. + pub fn process_mono_in_place_f32( + &mut self, + audio: &mut [f32], + events: &[TimedEvent], + ) -> Result<(), Error> { + self.check_block(audio.len())?; + let mut events = ValidatedEvents::new(events, audio.len())?; + self.drain_remaining = None; + for (index, sample) in audio.iter_mut().enumerate() { + while let Some(event) = events.next_at(index) { + self.apply(event); + } + let output = self.next(pcm_from_f32(*sample)); + let mono = ((i32::from(output[0]) + i32::from(output[1])) >> 1) as i16; + *sample = pcm_to_f32(mono); + } + Ok(()) + } + /// Starts a tail with the current [`tail_frames`](Self::tail_frames) /// budget and returns that budget. /// @@ -291,20 +374,85 @@ impl Processor { Ok(count) } - /// Returns the finite tail budget for the current configuration. + /// Renders the next stereo tail frames as `f32` and returns their count. + /// + /// Output scaling, zero fill and completion follow [`drain`](Self::drain). + /// + /// # Errors + /// + /// If the output is larger than the prepared block limit, the method + /// returns [`Error::BlockTooLarge`] and does not change state or output. + pub fn drain_f32(&mut self, output: &mut [[f32; 2]]) -> Result { + let count = self.drain_into(output.len(), |index, frame| { + output[index] = frame.map(pcm_to_f32); + })?; + output[count..].fill([0.0; 2]); + Ok(count) + } + + /// Renders the tail into separate `f32` output channels of equal size. + /// + /// Output scaling, zero fill and completion follow + /// [`drain_planar`](Self::drain_planar). + /// + /// # Errors + /// + /// The method checks [`Error::BufferLength`] before + /// [`Error::BlockTooLarge`]. If either error occurs, the two channels and + /// the drain state do not change. + pub fn drain_planar_f32( + &mut self, + left: &mut [f32], + right: &mut [f32], + ) -> Result { + Error::check_length(left.len(), right.len())?; + let count = self.drain_into(left.len(), |index, frame| { + left[index] = pcm_to_f32(frame[0]); + right[index] = pcm_to_f32(frame[1]); + })?; + left[count..].fill(0.0); + right[count..].fill(0.0); + Ok(count) + } + + /// Renders the tail as mono `f32` audio and returns the number of rendered + /// frames. + /// + /// Downmix rounding, zero fill and completion follow + /// [`drain_mono`](Self::drain_mono). + /// + /// # Errors + /// + /// If the output is larger than the prepared block limit, the method + /// returns [`Error::BlockTooLarge`] before it changes output or state. + pub fn drain_mono_f32(&mut self, output: &mut [f32]) -> Result { + let count = self.drain_into(output.len(), |index, frame| { + let mono = ((i32::from(frame[0]) + i32::from(frame[1])) >> 1) as i16; + output[index] = pcm_to_f32(mono); + })?; + output[count..].fill(0.0); + Ok(count) + } + + /// Returns the finite tail budget for the current configuration, in host + /// frames. /// /// This value is a configured limit. It is not the number of drain frames - /// that are left, and it is not a measured decay time. It can include - /// silence. It can also stop filter output that continues for a long - /// time. + /// that are left, and it is not a measured decay time. At 88.2, 96, 176.4 + /// and 192 kHz, the budget scales to host frames and adds the Q14 filter + /// tail. It can include silence, and it can stop filter output that + /// continues for a long time. pub fn tail_frames(&self) -> usize { - self.resynthesis + let rate = self.preparation.sample_rate; + let base_tail = self + .resynthesis .tail_frames() .saturating_add(alien::tail_frames(self.config.alien)) - .saturating_add(reverb::tail_frames( - self.preparation.sample_rate, - self.config.reverb, - )) + .saturating_add(reverb::tail_frames(rate.base_rate(), self.config.reverb)); + let filter_tail = self.resampler.as_deref().map_or(0, Resampler::tail_frames); + base_tail + .saturating_mul(rate.factor()) + .saturating_add(filter_tail) } /// Returns the fixed sample rate and block limit. @@ -322,13 +470,17 @@ impl Processor { self.config } - /// Returns the nominal resynthesis latency: 1,593 frames at both rates. + /// Returns the nominal latency in host frames. /// - /// The dry path has a delay of 1,543 frames. Resampled voices, choir delays - /// and effects have their own timing. Thus, this value does not align all - /// paths. + /// The value is 1,593 frames at 44.1 and 48 kHz. With the Q14 filter delay, + /// the value is 3,190 frames at 88.2 and 96 kHz, and 6,384 frames at 176.4 + /// and 192 kHz. At 44.1 and 48 kHz, the dry path has a delay of 1,543 + /// frames. Resampled voices, choir delays and effects have their own + /// timing. Thus, this value does not align all paths. pub fn latency_frames(&self) -> usize { - resynthesis::LATENCY_FRAMES + let factor = self.preparation.sample_rate.factor(); + let filter_delay = self.resampler.as_deref().map_or(0, Resampler::delay_frames); + resynthesis::LATENCY_FRAMES * factor + filter_delay } /// Returns the pitch, stereo peak and frame count, and does not clear them. @@ -336,9 +488,10 @@ impl Processor { /// To start a new peak window, use [`take_feedback`](Self::take_feedback). pub fn feedback(&self) -> Feedback { let estimate = self.resynthesis.estimate(); + let factor = self.preparation.sample_rate.factor() as f32; Feedback { resample_ratio: self.last_resample_ratio, - period_samples: estimate.period_samples, + period_samples: estimate.period_samples * factor, frequency_hz: estimate.frequency_hz, target_midi_note: self.resynthesis.target_note(), voiced: estimate.voiced, @@ -480,6 +633,41 @@ impl Processor { Ok(()) } + /// Validates and applies one harmony MIDI control immediately. + /// + /// Channel numbers are in `0..=15`, and note and velocity numbers are in + /// `0..=127`. A successful call cancels an active drain and does not + /// allocate memory. + /// + /// # Errors + /// + /// Returns [`Error::InvalidMidi`] before the state or any active drain + /// changes. + pub fn apply_midi(&mut self, event: MidiEvent) -> Result<(), Error> { + event.validate()?; + self.drain_remaining = None; + self.resynthesis.apply_midi(event); + Ok(()) + } + + /// Validates and applies one MIDI control for the correction keyboard + /// immediately. + /// + /// Channel numbers are in `0..=15`, and note and velocity numbers are in + /// `0..=127`. A successful call cancels an active drain and does not + /// allocate memory. + /// + /// # Errors + /// + /// Returns [`Error::InvalidMidi`] before the state or any active drain + /// changes. + pub fn apply_correction_midi(&mut self, event: MidiEvent) -> Result<(), Error> { + event.validate()?; + self.drain_remaining = None; + self.resynthesis.apply_correction_midi(event); + Ok(()) + } + /// Applies a configuration that the public setter or the preflight checked. fn apply_config(&mut self, config: ProcessorConfig) { if self.config.punch != config.punch { @@ -495,6 +683,9 @@ impl Processor { // Resynthesis resets its histories if its stereo setting changes. self.alien.reset(); self.reverb.reset(); + if let Some(resampler) = &mut self.resampler { + resampler.reset_output(); + } self.peak = 0; self.clear_telemetry_peaks(); self.last_resample_ratio = 0.0; @@ -541,6 +732,9 @@ impl Processor { self.resynthesis.reset(); self.alien.reset(); self.reverb.reset(); + if let Some(resampler) = &mut self.resampler { + resampler.reset(); + } self.peak = 0; self.clear_telemetry_peaks(); self.frames = 0; @@ -602,30 +796,71 @@ impl Processor { self.apply_config(config); } + /// Renders one base-rate sample through the core stages. + #[allow(clippy::too_many_arguments)] + fn core_sample( + mut input: i16, + config: &ProcessorConfig, + punch: &mut Punch, + warm: &mut Warm, + resynthesis: &mut Resynthesis, + alien: &mut Alien, + reverb: &mut Reverb, + numeric: &mut NumericContext, + last_resample_ratio: &mut f32, + ) -> [i16; 2] { + if config.punch.enabled { + input = punch.process_sample(input, numeric); + } + if config.warm.enabled { + input = warm.process_sample(input); + } + let voice = resynthesis.process_sample(input, numeric); + *last_resample_ratio = resynthesis.resample_ratio(); + let alien = alien.process_sample(voice); + let reverb = reverb.process_sample(alien); + let gain = (config.output_gain as f64 * 256.0) as i32; + reverb.map(|sample| { + (sample.to_bits().wrapping_mul(gain) >> 8) + .wrapping_shl(1) + .clamp(-32767, 32767) as i16 + }) + } + /// Renders one frame through the full chain and updates stereo feedback. /// /// Resynthesis produces Q14 audio. Output gain is Q8. The multiplication /// wraps before the shift. PCM conversion clips to the symmetric 16-bit /// range. This order and the peak measurement before the downmix are part /// of the output. - fn next(&mut self, mut input: i16) -> [i16; 2] { + fn next(&mut self, input: i16) -> [i16; 2] { self.input_peak = self.input_peak.max((input as i32).abs()); - if self.config.punch.enabled { - input = self.punch.process_sample(input, &mut self.numeric); - } - if self.config.warm.enabled { - input = self.warm.process_sample(input); - } - let voice = self.resynthesis.process_sample(input, &mut self.numeric); - self.last_resample_ratio = self.resynthesis.resample_ratio(); - let alien = self.alien.process_sample(voice); - let reverb = self.reverb.process_sample(alien); - let gain = (self.config.output_gain as f64 * 256.0) as i32; - let result = reverb.map(|sample| { - (sample.to_bits().wrapping_mul(gain) >> 8) - .wrapping_shl(1) - .clamp(-32767, 32767) as i16 - }); + let result = match self.resampler.as_mut() { + None => Self::core_sample( + input, + &self.config, + &mut self.punch, + &mut self.warm, + &mut self.resynthesis, + &mut self.alien, + &mut self.reverb, + &mut self.numeric, + &mut self.last_resample_ratio, + ), + Some(resampler) => resampler.process_sample(input, |decimated| { + Self::core_sample( + decimated, + &self.config, + &mut self.punch, + &mut self.warm, + &mut self.resynthesis, + &mut self.alien, + &mut self.reverb, + &mut self.numeric, + &mut self.last_resample_ratio, + ) + }), + }; self.peak = self .peak .max((result[0] as i32).abs()) @@ -658,6 +893,26 @@ impl Processor { Ok(()) } + /// Checks a `f32` block, applies all controls at each offset and writes + /// each rendered stereo `f32` frame. + fn process_into_f32( + &mut self, + input: &[f32], + events: &[TimedEvent], + mut write: impl FnMut(usize, [f32; 2]), + ) -> Result<(), Error> { + self.check_block(input.len())?; + let mut events = ValidatedEvents::new(events, input.len())?; + self.drain_remaining = None; + for (index, sample) in input.iter().enumerate() { + while let Some(event) = events.next_at(index) { + self.apply(event); + } + write(index, self.next(pcm_from_f32(*sample)).map(pcm_to_f32)); + } + Ok(()) + } + /// Renders only the budget that is left. The caller writes zeros in the /// unused frames. /// @@ -696,6 +951,18 @@ impl Processor { } } +/// Converts a normalized `f32` sample to rounded, clamped 16-bit PCM. +#[inline] +fn pcm_from_f32(sample: f32) -> i16 { + (sample * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16 +} + +/// Scales a 16-bit PCM sample into normalized `f32` audio. +#[inline] +fn pcm_to_f32(sample: i16) -> f32 { + f32::from(sample) / 32_768.0 +} + /// A snapshot of the pitch analysis and the output level that you can copy. /// /// Get it with [`Processor::feedback`] or [`Processor::take_feedback`]. The diff --git a/src/resample.rs b/src/resample.rs new file mode 100644 index 0000000..9c651c5 --- /dev/null +++ b/src/resample.rs @@ -0,0 +1,190 @@ +//! Fixed-point 2x and 4x resampling with Q14 biquad low-pass sections. +//! +//! A 2x stage filters the input with two second-order Butterworth sections, +//! runs the core path on every second frame and filters the zero-stuffed +//! stereo output with two second-order Butterworth sections on each channel. +//! A 4x resampler puts an outer 2x stage around an inner 2x stage. + +use crate::filter::{Biquad, Design}; +use crate::numeric::fixed::Q14; +use crate::SampleRate; + +/// The quality factors of a fourth-order Butterworth low-pass cascade. +const BUTTERWORTH_Q: [f32; 2] = [0.541_196_1, 1.306_563]; + +/// The cutoff of each 2x low-pass cascade, as a fraction of the lower rate. +const CUTOFF_RATIO: f32 = 0.42; + +/// The nominal delay of one 2x stage, in frames at the upper rate of that +/// stage. +const STAGE_DELAY_FRAMES: usize = 4; + +/// The drain allowance of one 2x stage, in frames at the upper rate of that +/// stage. +const STAGE_TAIL_FRAMES: usize = 64; + +/// One 2:1 decimation and 1:2 interpolation stage in Q14 format. +#[derive(Debug)] +struct Stage2x { + /// Two anti-alias low-pass sections for the mono input. + decimate: [Biquad; 2], + /// Two anti-image low-pass sections for each stereo output channel. + interpolate: [[Biquad; 2]; 2], + /// If `false`, the next frame runs the lower-rate path. + odd: bool, +} + +impl Stage2x { + /// Designs the input and output cascades for a 2x stage above `low_rate`. + fn new(low_rate: f32) -> Self { + let high_rate = low_rate * 2.0; + let cutoff = low_rate * CUTOFF_RATIO; + let make_cascade = || { + std::array::from_fn(|section| { + let mut filter = Biquad::new(); + filter.set_design(Design::low_pass(high_rate, cutoff, BUTTERWORTH_Q[section])); + filter + }) + }; + Self { + decimate: make_cascade(), + interpolate: [make_cascade(), make_cascade()], + odd: false, + } + } + + /// Clears the phase and all filter histories, and keeps the coefficients. + fn reset(&mut self) { + self.odd = false; + for filter in &mut self.decimate { + filter.reset(); + } + self.reset_output(); + } + + /// Clears only the output filter histories. + fn reset_output(&mut self) { + for channel in &mut self.interpolate { + for filter in channel { + filter.reset(); + } + } + } + + /// Processes one upper-rate Q14 frame and calls `core` on even frames. + #[inline] + fn process(&mut self, mut input: Q14, core: impl FnOnce(Q14) -> [Q14; 2]) -> [Q14; 2] { + for filter in &mut self.decimate { + input = filter.process_sample(input); + } + let excited = if !self.odd { + let step = core(input); + [step[0] << 1, step[1] << 1] + } else { + [Q14::ZERO; 2] + }; + self.odd = !self.odd; + let mut output = [Q14::ZERO; 2]; + for (slot, (mut sample, filters)) in output + .iter_mut() + .zip(excited.into_iter().zip(&mut self.interpolate)) + { + for filter in filters { + sample = filter.process_sample(sample); + } + *slot = sample; + } + output + } +} + +/// The 2x or 4x rate converter around the 44.1 kHz or 48 kHz core path. +#[derive(Debug)] +pub(crate) struct Resampler { + /// The host-rate 2x stage (between 2x and 1x, or between 4x and 2x). + outer: Stage2x, + /// The optional inner 2x stage between 2x and 1x for 4x rates. + inner: Option, +} + +impl Resampler { + /// Returns a boxed resampler for 2x or 4x rates, or `None` for 1x rates. + pub(crate) fn new(rate: SampleRate) -> Option> { + let base_hz = rate.base_rate().hz(); + match rate.factor() { + 1 => None, + 2 => Some(Box::new(Self { + outer: Stage2x::new(base_hz), + inner: None, + })), + 4 => Some(Box::new(Self { + outer: Stage2x::new(base_hz * 2.0), + inner: Some(Stage2x::new(base_hz)), + })), + _ => None, + } + } + + /// Returns the nominal filter and commutation delay in host frames. + pub(crate) const fn delay_frames(&self) -> usize { + if self.inner.is_some() { + STAGE_DELAY_FRAMES + 2 * STAGE_DELAY_FRAMES + } else { + STAGE_DELAY_FRAMES + } + } + + /// Returns the finite tail allowance of the filter cascades in host frames. + pub(crate) const fn tail_frames(&self) -> usize { + if self.inner.is_some() { + STAGE_TAIL_FRAMES + 2 * STAGE_TAIL_FRAMES + } else { + STAGE_TAIL_FRAMES + } + } + + /// Clears the phase and all filter histories. + pub(crate) fn reset(&mut self) { + self.outer.reset(); + if let Some(inner) = &mut self.inner { + inner.reset(); + } + } + + /// Clears the output filter histories after a stereo pan mode change. + pub(crate) fn reset_output(&mut self) { + self.outer.reset_output(); + if let Some(inner) = &mut self.inner { + inner.reset_output(); + } + } + + /// Processes one host-rate PCM sample around the base-rate core callback. + pub(crate) fn process_sample( + &mut self, + input: i16, + mut core: impl FnMut(i16) -> [i16; 2], + ) -> [i16; 2] { + let sample = pcm_to_q14(input); + let mut run_core = |decimated: Q14| core(q14_to_pcm(decimated)).map(pcm_to_q14); + let output = match &mut self.inner { + None => self.outer.process(sample, &mut run_core), + Some(inner) => self + .outer + .process(sample, |mid| inner.process(mid, &mut run_core)), + }; + output.map(q14_to_pcm) + } +} + +/// Converts a 16-bit PCM sample to Q14 audio, where 1.0 is full scale. +#[inline] +fn pcm_to_q14(sample: i16) -> Q14 { + Q14::from_bits(i32::from(sample) >> 1) +} + +/// Converts a Q14 audio sample to symmetric 16-bit PCM. +#[inline] +fn q14_to_pcm(sample: Q14) -> i16 { + sample.to_bits().wrapping_shl(1).clamp(-32767, 32767) as i16 +} From 4a5172d64422823ee898c449b07e5f597337299f Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:04:10 +0000 Subject: [PATCH 2/3] feat(wasm): add Float32 audio, typed-array MIDI and meter methods - Accept 88.2, 96, 176.4 and 192 kHz sample rates in Tunelet - Add processFloat32 and processMonoFloat32 for Float32Array audio - Add drainFloat32 and drainMonoFloat32 for Float32Array tails - Decode Uint32Array block MIDI events into a reusable buffer - Add applyMidi and applyCorrectionMidi for 3-byte Uint8Array messages - Add typed-array feedbackInto and telemetryInto meter methods --- src/wasm.rs | 532 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 475 insertions(+), 57 deletions(-) diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..d2cc2fa 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -7,12 +7,13 @@ //! 2. Run wasm-bindgen on the result. //! //! wasm-pack can do the two steps in one command. The npm entry point uses -//! `loadTunelet()` to initialize these bindings in browsers and in Node.js. +//! `loadTunelet()` to initialize these bindings in browsers and in Node.js, +//! and `createTuneletNode()` to connect an `AudioWorkletNode`. //! -//! The exported `Tunelet` class owns a native [`Processor`] and three reusable -//! PCM buffers. JavaScript gives the `Int16Array` input and output buffers. The -//! PCM API does not give buffer pointers or long-lived memory views to -//! JavaScript. The class copies the input before it writes the output. +//! The exported `Tunelet` class owns a native [`Processor`], reusable 16-bit +//! PCM buffers, reusable `f32` buffers and a reusable timed MIDI buffer. +//! JavaScript gives `Int16Array` or `Float32Array` audio buffers. The class +//! copies the input before it writes the output. //! //! Configuration objects obey these rules: //! @@ -24,41 +25,74 @@ //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use //! `{ type, channel, note, velocity }`, with the fields that apply to the -//! selected variant. The TypeScript declarations come from the same Rust types -//! that validation uses. +//! selected variant. You can also supply timed MIDI controls in a +//! `Uint32Array` of 4-word tuples `[offset, status, data1, data2]`, or immediate +//! 3-byte MIDI messages in a `Uint8Array`. The TypeScript declarations come +//! from the same Rust types that validation uses. //! -//! The class allocates the PCM storage at construction and uses it again for -//! each block. These operations can allocate: +//! The class allocates the PCM, `f32` and MIDI buffers at construction and +//! uses them again for each block. The typed-array methods for MIDI controls +//! (`Uint32Array` block events, `applyMidi`, `applyCorrectionMidi`), feedback +//! (`feedbackInto`, `takeFeedbackInto`) and telemetry (`telemetryInto`, +//! `takeTelemetryInto`) do not allocate Wasm memory or JavaScript objects. +//! These operations can allocate: //! -//! - The decode of events. +//! - The decode of `TimedEvent[]` object arrays. //! - The conversion of configurations. -//! - Feedback and telemetry objects. -//! - The buffers of the formant envelopes. +//! - `feedback`, `takeFeedback`, `telemetry` and `takeTelemetry` objects. +//! - The buffers of the formant envelopes on the first or larger call. //! - Errors. //! -//! The JavaScript glue can also make temporary views when it copies data. This -//! generic binding does not guarantee an AudioWorklet callback that is free of -//! allocation. If you do not need a processor any more, call the generated -//! `free()` method. +//! If you do not need a processor any more, call the generated `free()` +//! method. +use crate::error::EventProblem; use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + ControlEvent, Error, Feedback, MidiEvent, PrepareConfig, Processor, ProcessorConfig, + SampleRate, Telemetry, TimedEvent, }; -use js_sys::{Float32Array, Int16Array}; +use js_sys::{Float32Array, Float64Array, Int16Array, Uint32Array, Uint8Array}; use serde::{Deserialize, Serialize}; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; -/// The events for one call that processes audio (`TimedEvent[]` in TypeScript). +/// The number of `f64` elements in a typed-array [`Feedback`] snapshot. +const FEEDBACK_LEN: usize = 8; + +/// The number of `f64` elements in a typed-array [`Telemetry`] snapshot. +const TELEMETRY_LEN: usize = 45; + +/// The number of `u32` words for each timed MIDI event in a `Uint32Array`. +const MIDI_EVENT_WORDS: usize = 4; + +/// The status flag that routes a `Uint32Array` MIDI event to the correction +/// keyboard instead of harmony. +const CORRECTION_MIDI_FLAG: u32 = 0x100; + +/// The minimum preallocated capacity for timed `Uint32Array` MIDI events. +const MIN_MIDI_CAPACITY: usize = 64; + +/// The maximum initial preallocated capacity for timed `Uint32Array` MIDI +/// events. +const MAX_MIDI_CAPACITY: usize = 4096; + +/// The events for one call that processes audio (`TimedEvent[] | Uint32Array` +/// in TypeScript). /// /// Each offset is a zero-based frame index in the current block. Each offset /// must be in the block and must not be less than the offset before it. Events /// with equal offsets execute in array order. An empty block accepts no -/// events. If there are no events, omit the optional argument. Then the -/// binding does not decode an array. +/// events. +/// +/// For zero-allocation MIDI controls, supply a `Uint32Array` whose length is a +/// multiple of 4. Each group of four words is `[offset, status, data1, data2]`, +/// where `status` is in `0x80..=0xff` for harmony MIDI or `0x180..=0x1ff` +/// (`status | 0x100`) for correction MIDI, and `data1` and `data2` are in +/// `0..=127`. If there are no events, omit the optional argument. #[derive(Default, Serialize, Deserialize, Tsify)] #[serde(transparent)] -pub struct BlockEvents(Vec); +pub struct BlockEvents(#[tsify(type = "TimedEvent[] | Uint32Array")] Vec); /// Returns a complete, independent default configuration for JavaScript. /// @@ -76,12 +110,12 @@ pub fn default_config() -> Result, JsError> { Ok(ProcessorConfig::default().into_ts()?) } -/// A stateful PCM processor that JavaScript uses as the `Tunelet` class. +/// A stateful audio processor that JavaScript uses as the `Tunelet` class. /// -/// The input is signed 16-bit mono PCM. The output is planar stereo or an -/// in-place mono downmix. The quantization, latency and configuration behavior -/// are the same as in the native processor. Buffer lengths count frames, not -/// bytes. +/// The input is mono signed 16-bit PCM (`Int16Array`) or normalized mono audio +/// (`Float32Array`). The output is planar stereo or an in-place mono downmix. +/// The quantization, latency and configuration behavior are the same as in the +/// native processor. Buffer lengths count frames, not bytes. /// /// These rules apply to the buffers: /// @@ -93,9 +127,7 @@ pub fn default_config() -> Result, JsError> { /// If a call that processes audio fails, it throws a JavaScript `Error` before /// the audio state or the output changes. The class rejects malformed /// configuration objects and malformed event objects. It also rejects values -/// that are out of range. The class decodes objects inside the methods that -/// can fail. Thus, if a conversion fails, Rust releases the temporary values -/// as usual. +/// that are out of range. #[wasm_bindgen(js_name = Tunelet)] pub struct WasmProcessor { /// The DSP state, with its preparation limits, which do not change. @@ -109,6 +141,14 @@ pub struct WasmProcessor { /// The reusable PCM buffer for the right channel, which the class copies to /// the caller only after a successful call. right: Vec, + /// The reusable `f32` buffer for input or in-place mono audio. + float_input: Vec, + /// The reusable `f32` buffer for the left channel. + float_left: Vec, + /// The reusable `f32` buffer for the right channel. + float_right: Vec, + /// The preallocated event storage for `Uint32Array` MIDI blocks. + midi_events: Vec, /// The reusable buffers for the two formant envelopes. They become longer /// when a call needs more points, and they do not become shorter. envelope_input: Vec, @@ -117,24 +157,25 @@ pub struct WasmProcessor { #[wasm_bindgen(js_class = Tunelet)] impl WasmProcessor { - /// Prepares a processor and its reusable PCM buffers. + /// Prepares a processor and its reusable audio and MIDI buffers. /// - /// `sample_rate` must be 44100 or 48000. `max_block_frames` 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 - /// the settings before it allocates the processor or the PCM buffers. In - /// TypeScript, use `new Tunelet(sampleRate, maxBlockFrames, config)`. + /// `sample_rate` must be 44100, 48000, 88200, 96000, 176400 or 192000. + /// `max_block_frames` 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 the settings before it allocates the processor or + /// the buffers. In TypeScript, use + /// `new Tunelet(sampleRate, maxBlockFrames, config)`. /// /// # Errors /// /// The constructor throws if one of these conditions occurs: /// - /// - The rate is not 44100 or 48000. + /// - The rate is not 44100, 48000, 88200, 96000, 176400 or 192000. /// - The block limit is not an integer or is out of range. /// - The configuration object is malformed or a field is missing. /// - The configuration is not valid. - /// - The reservation of a PCM buffer fails. + /// - The reservation of a buffer fails. /// /// The available Wasm memory must also have sufficient space for the DSP /// histories. @@ -149,7 +190,15 @@ impl WasmProcessor { let rate = match sample_rate { 44100.0 => SampleRate::Hz44100, 48000.0 => SampleRate::Hz48000, - _ => return Err(JsError::new("sampleRate must be 44100 or 48000")), + 88200.0 => SampleRate::Hz88200, + 96000.0 => SampleRate::Hz96000, + 176400.0 => SampleRate::Hz176400, + 192000.0 => SampleRate::Hz192000, + _ => { + return Err(JsError::new( + "sampleRate must be 44100, 48000, 88200, 96000, 176400 or 192000", + )) + } }; if !(1.0..=f64::from(u32::MAX)).contains(&max_block_frames) || max_block_frames.fract() != 0.0 @@ -165,11 +214,18 @@ impl WasmProcessor { None => ProcessorConfig::default(), }; let processor = Processor::new(preparation, config)?; + let midi_capacity = max_block_frames.clamp(MIN_MIDI_CAPACITY, MAX_MIDI_CAPACITY); + let mut midi_events = Vec::new(); + midi_events.try_reserve_exact(midi_capacity)?; Ok(Self { processor, input: pcm_buffer(max_block_frames)?, left: pcm_buffer(max_block_frames)?, right: pcm_buffer(max_block_frames)?, + float_input: float_buffer(max_block_frames)?, + float_left: float_buffer(max_block_frames)?, + float_right: float_buffer(max_block_frames)?, + midi_events, envelope_input: Vec::new(), envelope_output: Vec::new(), }) @@ -191,10 +247,10 @@ impl WasmProcessor { self.input.len() } - /// The nominal resynthesis delay in frames. + /// The nominal delay in host frames, with the Q14 resampler filter delay + /// included at 88.2, 96, 176.4 and 192 kHz. /// - /// Other signal paths have different timing. See the `latencyFrames` - /// property for the timing of the dry path and the voices. + /// Other signal paths have different timing. #[wasm_bindgen(getter, js_name = latencyFrames)] pub fn latency_frames(&self) -> usize { self.processor.latency_frames() @@ -228,14 +284,55 @@ impl WasmProcessor { Ok(()) } + /// Decodes a 3-byte MIDI message from a `Uint8Array` and applies it to + /// harmony immediately. + /// + /// `bytes` must have length 3 (`[status, data1, data2]`, with `status` in + /// `0x80..=0xff` and `data1` and `data2` in `0..=127`). Returns `true` if + /// the message is Note On, Note Off or controller 123 (All Notes Off). + /// Returns `false` for other valid 3-byte MIDI messages. This method does + /// not allocate Wasm memory or JavaScript objects. + /// + /// # Errors + /// + /// Throws if `bytes.length` is not 3 or if the MIDI bytes are out of range, + /// before the processor state changes. + #[wasm_bindgen(js_name = applyMidi)] + pub fn apply_midi(&mut self, bytes: &Uint8Array) -> Result { + let Some(event) = decode_midi_bytes(bytes)? else { + return Ok(false); + }; + self.processor.apply_midi(event)?; + Ok(true) + } + + /// Decodes a 3-byte MIDI message from a `Uint8Array` and applies it to the + /// correction keyboard immediately. + /// + /// Byte rules, return values and zero-allocation behavior are the same as + /// for `applyMidi`. + /// + /// # Errors + /// + /// Throws if `bytes.length` is not 3 or if the MIDI bytes are out of range, + /// before the processor state changes. + #[wasm_bindgen(js_name = applyCorrectionMidi)] + pub fn apply_correction_midi(&mut self, bytes: &Uint8Array) -> Result { + let Some(event) = decode_midi_bytes(bytes)? else { + return Ok(false); + }; + self.processor.apply_correction_midi(event)?; + Ok(true) + } + /// Processes mono input into left and right `Int16Array` buffers of equal /// length. /// /// If the call is successful, it writes every output sample. Optional /// events apply before their frame, and their offsets obey the rules of - /// `TimedEvent[]`. An empty block must have no events. A successful call - /// cancels a drain, also for an empty block. The call uses the existing - /// JavaScript and Rust PCM buffers again. + /// `BlockEvents` (`TimedEvent[]` or `Uint32Array`). An empty block must + /// have no events. A successful call cancels a drain, also for an empty + /// block. The call uses the existing JavaScript and Rust PCM buffers again. /// /// # Errors /// @@ -255,13 +352,13 @@ impl WasmProcessor { Error::check_length(frames, left.length() as usize)?; Error::check_length(frames, right.length() as usize)?; self.check_frames(frames)?; - let events = decode_events(events)?; + let events = decode_events(&mut self.midi_events, frames, events)?; input.copy_to(&mut self.input[..frames]); self.processor.process_planar( &self.input[..frames], &mut self.left[..frames], &mut self.right[..frames], - &events.0, + events.as_slice(), )?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); @@ -286,14 +383,77 @@ impl WasmProcessor { ) -> Result<(), JsError> { let frames = audio.length() as usize; self.check_frames(frames)?; - let events = decode_events(events)?; + let events = decode_events(&mut self.midi_events, frames, events)?; audio.copy_to(&mut self.input[..frames]); self.processor - .process_mono_in_place(&mut self.input[..frames], &events.0)?; + .process_mono_in_place(&mut self.input[..frames], events.as_slice())?; audio.copy_from(&self.input[..frames]); Ok(()) } + /// Processes mono `Float32Array` input in `-1.0..=1.0` into left and right + /// `Float32Array` buffers of equal length. + /// + /// Optional events accept `TimedEvent[]` or a packed `Uint32Array` of + /// `[offset, status, data1, data2]` MIDI tuples. Channel length checks, + /// block limits, event timing and drain cancellation are the same as for + /// `process`. + /// + /// # Errors + /// + /// Throws if the channel lengths are not equal, if the block is larger + /// than `maxBlockFrames` or if an event is not valid. On error, the output + /// arrays and the DSP state do not change. + #[wasm_bindgen(js_name = processFloat32)] + pub fn process_f32( + &mut self, + input: &Float32Array, + left: &Float32Array, + right: &Float32Array, + 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.check_frames(frames)?; + let events = decode_events(&mut self.midi_events, frames, events)?; + input.copy_to(&mut self.float_input[..frames]); + self.processor.process_planar_f32( + &self.float_input[..frames], + &mut self.float_left[..frames], + &mut self.float_right[..frames], + events.as_slice(), + )?; + left.copy_from(&self.float_left[..frames]); + right.copy_from(&self.float_right[..frames]); + Ok(()) + } + + /// Replaces the audio in a mono `Float32Array` with the stereo downmix. + /// + /// Input quantization, output scaling, stereo peak measurement, events and + /// drain cancellation follow `processFloat32` and `processMono`. + /// + /// # Errors + /// + /// Throws if the block is larger than `maxBlockFrames` or an event is not + /// valid, before the array or the DSP state changes. + #[wasm_bindgen(js_name = processMonoFloat32)] + pub fn process_mono_f32( + &mut self, + audio: &Float32Array, + events: Option>, + ) -> Result<(), JsError> { + let frames = audio.length() as usize; + self.check_frames(frames)?; + let events = decode_events(&mut self.midi_events, frames, events)?; + audio.copy_to(&mut self.float_input[..frames]); + self.processor + .process_mono_in_place_f32(&mut self.float_input[..frames], events.as_slice())?; + audio.copy_from(&self.float_input[..frames]); + Ok(()) + } + /// Starts a finite tail budget and returns its frame count as a number. /// /// Call this method one time after the final input block. Another call @@ -354,6 +514,52 @@ impl WasmProcessor { Ok(count) } + /// Renders stereo tail frames into `Float32Array` buffers of equal length. + /// + /// Output scaling, zero fill and completion are the same as for `drain`. + /// + /// # Errors + /// + /// Throws if the channel lengths are not equal or if the block is larger + /// than `maxBlockFrames`, before the arrays or the drain state change. + #[wasm_bindgen(js_name = drainFloat32)] + pub fn drain_f32( + &mut self, + left: &Float32Array, + right: &Float32Array, + ) -> Result { + let frames = left.length() as usize; + Error::check_length(frames, right.length() as usize)?; + self.check_frames(frames)?; + let count = self.processor.drain_planar_f32( + &mut self.float_left[..frames], + &mut self.float_right[..frames], + )?; + left.copy_from(&self.float_left[..frames]); + right.copy_from(&self.float_right[..frames]); + Ok(count) + } + + /// Renders a mono tail block into a `Float32Array` and returns its frame + /// count. + /// + /// Output scaling, zero fill and completion follow `drainMono`. + /// + /// # Errors + /// + /// Throws if the block is larger than `maxBlockFrames` before the output + /// or the state changes. + #[wasm_bindgen(js_name = drainMonoFloat32)] + pub fn drain_mono_f32(&mut self, audio: &Float32Array) -> Result { + let frames = audio.length() as usize; + self.check_frames(frames)?; + let count = self + .processor + .drain_mono_f32(&mut self.float_input[..frames])?; + audio.copy_from(&self.float_input[..frames]); + Ok(count) + } + /// Returns a new feedback object and does not clear the peak window. /// /// `processedFrames` is a `bigint`, so its 64-bit count stays exact. @@ -390,6 +596,38 @@ impl WasmProcessor { Ok(feedback) } + /// Writes the feedback snapshot into a `Float64Array` of length 8 without + /// allocation, and does not clear the peak window. + /// + /// The indices are `0`: `resampleRatio`, `1`: `periodSamples`, + /// `2`: `frequencyHz`, `3`: `targetMidiNote` (`NaN` if `voiced` is `0`), + /// `4`: `voiced` (`1` or `0`), `5`: `peakLevel`, `6`: `processedFrames` + /// and `7`: `latencyFrames`. + /// + /// # Errors + /// + /// Throws if `output.length` is not 8, before `output` changes. + #[wasm_bindgen(js_name = feedbackInto)] + pub fn feedback_into(&self, output: &Float64Array) -> Result<(), JsError> { + Error::check_length(FEEDBACK_LEN, output.length() as usize)?; + write_feedback(&self.processor.feedback(), output); + Ok(()) + } + + /// Writes the feedback snapshot into a `Float64Array` of length 8 without + /// allocation, and clears only the stereo peak window. + /// + /// # Errors + /// + /// Throws if `output.length` is not 8, before `output` or the peak window + /// changes. + #[wasm_bindgen(js_name = takeFeedbackInto)] + pub fn take_feedback_into(&mut self, output: &Float64Array) -> Result<(), JsError> { + Error::check_length(FEEDBACK_LEN, output.length() as usize)?; + write_feedback(&self.processor.take_feedback(), output); + Ok(()) + } + /// Returns a new telemetry object and does not clear its peak windows. /// /// The telemetry is for meters and displays. It gives the ratio and the @@ -420,6 +658,40 @@ impl WasmProcessor { Ok(telemetry) } + /// Writes the telemetry snapshot into a `Float64Array` of length 45 without + /// allocation, and does not clear its peak windows. + /// + /// The indices are `0`: `processedFrames`, `1`: `inputPeak`, + /// `2..=3`: `outputPeak`, `4`: `reverbWetPeak`, `5`: `clarity`, + /// `6`: `tracking` (`1` or `0`), `7`: `voiceCount`, + /// `8..=23`: `voiceRatios`, `24..=39`: `voiceGains`, `40`: `punchGain`, + /// `41`: `warmGain`, `42`: `alienLoopFrames`, `43`: `alienPhaseFrames` and + /// `44`: `formantGeneration`. + /// + /// # Errors + /// + /// Throws if `output.length` is not 45, before `output` changes. + #[wasm_bindgen(js_name = telemetryInto)] + pub fn telemetry_into(&self, output: &Float64Array) -> Result<(), JsError> { + Error::check_length(TELEMETRY_LEN, output.length() as usize)?; + write_telemetry(&self.processor.telemetry(), output); + Ok(()) + } + + /// Writes the telemetry snapshot into a `Float64Array` of length 45 without + /// allocation, and clears only its three peak windows. + /// + /// # Errors + /// + /// Throws if `output.length` is not 45, before `output` or the peak windows + /// change. + #[wasm_bindgen(js_name = takeTelemetryInto)] + pub fn take_telemetry_into(&mut self, output: &Float64Array) -> Result<(), JsError> { + Error::check_length(TELEMETRY_LEN, output.length() as usize)?; + write_telemetry(&self.processor.take_telemetry(), output); + Ok(()) + } + /// Writes the formant envelopes of the current model into two /// `Float32Array` buffers of equal length. /// @@ -487,15 +759,150 @@ impl WasmProcessor { } } +/// A borrowed slice of MIDI controls or an owned vector of block events. +enum DecodedEvents<'a> { + /// An empty slice or events decoded into the preallocated MIDI buffer. + Borrowed(&'a [TimedEvent]), + /// Events decoded from a JavaScript `TimedEvent[]` array. + Owned(Vec), +} + +impl DecodedEvents<'_> { + /// Returns the validated or decoded slice for the native processor. + fn as_slice(&self) -> &[TimedEvent] { + match self { + Self::Borrowed(slice) => slice, + Self::Owned(events) => events.as_slice(), + } + } +} + /// Decodes the optional block controls before the audio state changes. /// -/// If there is no value, the result is an empty `Vec`, and no allocation -/// occurs. If the caller gives an array, the decode can allocate storage. -fn decode_events(events: Option>) -> Result { - Ok(match events { - Some(value) => value.to_rust()?, - None => BlockEvents::default(), - }) +/// If there is no value, no allocation occurs. If the caller supplies a +/// `Uint32Array`, the function decodes the 4-word MIDI tuples into `scratch` +/// without allocation. If the caller supplies `TimedEvent[]`, serde decodes +/// the array. +fn decode_events<'a>( + scratch: &'a mut Vec, + frames: usize, + events: Option>, +) -> Result, JsError> { + let Some(value) = events else { + return Ok(DecodedEvents::Borrowed(&[])); + }; + let js = value.js_value(); + if let Some(words) = js.dyn_ref::() { + decode_midi_words(scratch, frames, words)?; + return Ok(DecodedEvents::Borrowed(scratch.as_slice())); + } + Ok(DecodedEvents::Owned(value.to_rust()?.0)) +} + +/// Decodes and validates packed `[offset, status, data1, data2]` MIDI tuples. +fn decode_midi_words( + scratch: &mut Vec, + frames: usize, + words: &Uint32Array, +) -> Result<(), JsError> { + scratch.clear(); + let length = words.length() as usize; + if !length.is_multiple_of(MIDI_EVENT_WORDS) { + return Err(Error::InvalidMidi.into()); + } + let count = length / MIDI_EVENT_WORDS; + if scratch.capacity() < count { + scratch.try_reserve_exact(count - scratch.capacity())?; + } + let mut previous = 0usize; + for index in 0..count { + let base = (index * MIDI_EVENT_WORDS) as u32; + let offset = words.get_index(base) as usize; + if offset >= frames { + return Err(Error::InvalidEvent { + index, + problem: EventProblem::OffsetOutsideBlock, + } + .into()); + } + if offset < previous { + return Err(Error::InvalidEvent { + index, + problem: EventProblem::OffsetDecreasing, + } + .into()); + } + let raw_status = words.get_index(base + 1); + let data1 = words.get_index(base + 2); + let data2 = words.get_index(base + 3); + let correction = (raw_status & CORRECTION_MIDI_FLAG) != 0; + let status = raw_status & !CORRECTION_MIDI_FLAG; + if !(0x80..=0xff).contains(&status) || data1 > 127 || data2 > 127 { + return Err(Error::InvalidEvent { + index, + problem: EventProblem::Midi, + } + .into()); + } + let parsed = + MidiEvent::from_bytes([status as u8, data1 as u8, data2 as u8]).map_err(|_| { + Error::InvalidEvent { + index, + problem: EventProblem::Midi, + } + })?; + if let Some(midi) = parsed { + let event = if correction { + ControlEvent::CorrectionMidi(midi) + } else { + ControlEvent::Midi(midi) + }; + scratch.push(TimedEvent { offset, event }); + } + previous = offset; + } + Ok(()) +} + +/// Decodes one 3-byte MIDI message from a `Uint8Array` without allocation. +fn decode_midi_bytes(bytes: &Uint8Array) -> Result, Error> { + Error::check_length(3, bytes.length() as usize)?; + MidiEvent::from_bytes([bytes.get_index(0), bytes.get_index(1), bytes.get_index(2)]) +} + +/// Writes all 8 [`Feedback`] fields into a validated `Float64Array`. +fn write_feedback(feedback: &Feedback, output: &Float64Array) { + output.set_index(0, f64::from(feedback.resample_ratio)); + output.set_index(1, f64::from(feedback.period_samples)); + output.set_index(2, f64::from(feedback.frequency_hz)); + output.set_index(3, feedback.target_midi_note.map_or(f64::NAN, f64::from)); + output.set_index(4, if feedback.voiced { 1.0 } else { 0.0 }); + output.set_index(5, f64::from(feedback.peak_level)); + output.set_index(6, feedback.processed_frames as f64); + output.set_index(7, feedback.latency_frames as f64); +} + +/// Writes all 45 [`Telemetry`] fields into a validated `Float64Array`. +fn write_telemetry(telemetry: &Telemetry, output: &Float64Array) { + output.set_index(0, telemetry.processed_frames as f64); + output.set_index(1, f64::from(telemetry.input_peak)); + output.set_index(2, f64::from(telemetry.output_peak[0])); + output.set_index(3, f64::from(telemetry.output_peak[1])); + output.set_index(4, f64::from(telemetry.reverb_wet_peak)); + output.set_index(5, f64::from(telemetry.clarity)); + output.set_index(6, if telemetry.tracking { 1.0 } else { 0.0 }); + output.set_index(7, f64::from(telemetry.voice_count)); + for (index, &ratio) in telemetry.voice_ratios.iter().enumerate() { + output.set_index(8 + index as u32, f64::from(ratio)); + } + for (index, &gain) in telemetry.voice_gains.iter().enumerate() { + output.set_index(24 + index as u32, f64::from(gain)); + } + output.set_index(40, f64::from(telemetry.punch_gain)); + output.set_index(41, f64::from(telemetry.warm_gain)); + output.set_index(42, f64::from(telemetry.alien_loop_frames)); + output.set_index(43, f64::from(telemetry.alien_phase_frames)); + output.set_index(44, f64::from(telemetry.formant_generation)); } /// Returns the first `points` entries of a reusable envelope buffer. If the @@ -522,6 +929,17 @@ fn pcm_buffer(frames: usize) -> Result, JsError> { Ok(buffer) } +/// Allocates `f32` audio storage that contains zeros. +/// +/// If the capacity overflows or the allocation fails, this function returns a +/// JavaScript error. It does not panic. +fn float_buffer(frames: usize) -> Result, JsError> { + let mut buffer = Vec::new(); + buffer.try_reserve_exact(frames)?; + buffer.resize(frames, 0.0); + Ok(buffer) +} + /// Serializes the bounded Wasm frame count as a JavaScript number. /// /// The serializer of the feedback structure keeps its other counter, a `u64`, From f35e747f8b2419fad47a157573944013013d4e68 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:04:10 +0000 Subject: [PATCH 3/3] feat(npm): add the tunelet/worklet runtime and createTuneletNode - Add an internal UTF-8 TextDecoder and TextEncoder shim for worklets - Add the tunelet/worklet processor with preallocated worklet views - Export tunelet/worklet and mark worklet side effects in package.json - Export createTuneletNode, TuneletWorkletNode and meter indices - Document Web Audio setup, Float32Array calls and resampled latency --- README.md | 126 +++++++----- package.json | 9 +- src/index.ts | 502 ++++++++++++++++++++++++++++++++++++++++++++++- src/utf8-shim.ts | 256 ++++++++++++++++++++++++ src/worklet.ts | 436 ++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 2 +- 6 files changed, 1274 insertions(+), 57 deletions(-) create mode 100644 src/utf8-shim.ts create mode 100644 src/worklet.ts diff --git a/README.md b/README.md index d2993dc..317c392 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,9 @@ browsers and Node.js. - **No dependencies**: The default Rust build has no dependencies and uses only safe Rust. -The input is mono signed 16-bit PCM at 44.1 kHz or 48 kHz. The output is -stereo or mono 16-bit PCM. +The input is mono signed 16-bit PCM or normalized `f32` audio at 44.1, 48, +88.2, 96, 176.4 or 192 kHz. The output is stereo or mono 16-bit PCM or `f32` +audio. ## Installation @@ -133,7 +134,16 @@ fn main() -> Result<(), tunelet::Error> { } ``` -### TypeScript +### Web Audio + +```ts +import { createTuneletNode } from "tunelet"; + +const node = await createTuneletNode(audioContext); +microphone.connect(node).connect(audioContext.destination); +``` + +### TypeScript (`Tunelet`) ```ts import { loadTunelet, Tunelet, defaultConfig } from "tunelet"; @@ -141,13 +151,13 @@ import { loadTunelet, Tunelet, defaultConfig } from "tunelet"; await loadTunelet(); const config = defaultConfig(); config.resynthesis.pitchRatio = 1.25; -const processor = new Tunelet(48000, 1024, config); +const processor = new Tunelet(48000, 128, config); -const input = new Int16Array(1024); -const left = new Int16Array(1024); -const right = new Int16Array(1024); -// Fill input with mono PCM before each call; reuse all three arrays. -processor.process(input, left, right); +const input = new Float32Array(128); +const left = new Float32Array(128); +const right = new Float32Array(128); +// Fill input with mono audio before each call; reuse all three arrays. +processor.processFloat32(input, left, right); // After all processing and optional drain calls: processor.free(); @@ -209,11 +219,14 @@ processor. Select the process function for your output layout: -| Output layout | Function for input | Function for the tail | -| ------------------------------ | ----------------------- | --------------------- | -| `[[i16; 2]]` stereo frames | `process` | `drain` | -| Separate left and right slices | `process_planar` | `drain_planar` | -| Mono slice | `process_mono_in_place` | `drain_mono` | +| Output layout | Function for input | Function for the tail | +| ------------------------------------ | --------------------------- | --------------------- | +| `[[i16; 2]]` stereo frames | `process` | `drain` | +| `[[f32; 2]]` stereo frames | `process_f32` | `drain_f32` | +| Separate `i16` left and right slices | `process_planar` | `drain_planar` | +| Separate `f32` left and right slices | `process_planar_f32` | `drain_planar_f32` | +| Mono `i16` slice | `process_mono_in_place` | `drain_mono` | +| Mono `f32` slice | `process_mono_in_place_f32` | `drain_mono_f32` | These rules apply to each call: @@ -292,7 +305,7 @@ These calls read the state of the processor. They do not change the audio. | `take_feedback()` | The same data as `feedback()`, and clears the peak window | | `telemetry()` | Data for meters and displays (refer to the list below) | | `take_telemetry()` | The same data as `telemetry()`, and clears its three peak windows | -| `latency_frames()` | 1,593 frames of nominal resynthesis latency at both sample rates | +| `latency_frames()` | Nominal latency in host frames (1,593 at 1x, 3,190 at 2x, 6,384 at 4x) | | `formant_envelope()` | The LPC envelopes before and after the formant controls | The telemetry includes these items: @@ -357,7 +370,8 @@ these items: - One Wasm binary. - The generated bindings. -- A shared `loadTunelet` entry point. +- A shared `loadTunelet` entry point and `createTuneletNode` helper. +- A built-in `tunelet/worklet` runtime with an internal UTF-8 shim. ### Load the module @@ -406,33 +420,39 @@ page that opens the JavaScript. ### TypeScript API -| Operation | TypeScript API | -| --------------------------------- | -------------------------------------------------------- | -| Shared initialization | `loadTunelet(source?)` | -| Mono PCM to planar stereo | `process(input, left, right, events?)` | -| In-place mono downmix | `processMono(audio, events?)` | -| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | -| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | -| Feedback | `feedback()`, `takeFeedback()` | -| Telemetry | `telemetry()`, `takeTelemetry()` | -| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | -| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | -| Configured tail budget | `tailFrames()` | -| Reset or release memory | `reset()`, `free()` | - -### Audio buffers - -All audio buffers are `Int16Array` buffers, and they must fit in the prepared -frame limit. These rules apply: +| Operation | TypeScript API | +| --------------------------------- | -------------------------------------------------------------------- | +| Web Audio worklet node | `createTuneletNode(context, options?)`, `TuneletWorkletNode` | +| Shared initialization | `loadTunelet(source?)` | +| Mono PCM to planar stereo | `process(input, left, right, events?)` | +| Mono Float32 to planar stereo | `processFloat32(input, left, right, events?)` | +| In-place mono downmix | `processMono(audio, events?)`, `processMonoFloat32(audio, events?)` | +| Immediate 3-byte MIDI | `applyMidi(bytes)`, `applyCorrectionMidi(bytes)` | +| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | +| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | +| Feedback | `feedback()`, `takeFeedback()`, `feedbackInto(out)`, `takeFeedbackInto(out)` | +| Telemetry | `telemetry()`, `takeTelemetry()`, `telemetryInto(out)`, `takeTelemetryInto(out)` | +| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | +| Finite tail | `beginDrain()`, `drain(left, right)`, `drainFloat32(left, right)`, `drainMono(audio)`, `drainMonoFloat32(audio)` | +| Configured tail budget | `tailFrames()` | +| Reset or release memory | `reset()`, `free()` | + +### Audio buffers and Web Audio + +Audio buffers use `Float32Array` (`-1.0..=1.0`) or `Int16Array`, and they must +fit in the prepared frame limit. Supported sample rates are 44.1, 48, 88.2, +96, 176.4 and 192 kHz. These rules apply: - Stereo output arrays must not overlap. - The input can overlap an output, because the binding copies the input first. - Buffers must stay attached during each call. -Web Audio uses Float32 samples, which you must convert to and from 16-bit -PCM. This package does not install an AudioWorklet or an integration with an -audio device. +In browsers, call `await createTuneletNode(audioContext)` to compile Wasm, +register `tunelet/worklet` and construct a stereo `TuneletWorkletNode`. The +worklet module installs an internal UTF-8 shim before the generated bindings +evaluate, so `AudioWorkletGlobalScope` needs no `TextDecoder`, `TextEncoder` or +`fetch` polyfill. ### Configuration objects @@ -469,13 +489,20 @@ A harmony Note On event has this form: { offset: 0, event: { type: "midi", value: { type: "noteOn", channel: 0, note: 60, velocity: 100 } } } ``` -Use `correctionMidi` for the separate correction keyboard. The native rules -for event order and for the validation of the whole block also apply to these -bindings. +Use `correctionMidi` for the separate correction keyboard. For zero-allocation +block MIDI, give a `Uint32Array` of `[offset, status, data1, data2]` tuples as +`events`. For immediate 3-byte MIDI, call `applyMidi(bytes)` or +`applyCorrectionMidi(bytes)` with a `Uint8Array`. In `Uint32Array` events, +combine `status` with `CORRECTION_MIDI_FLAG` (`0x100`) to select the correction +keyboard. The native rules for event order and for the validation of the whole +block also apply to these bindings. ### Feedback, telemetry and formant envelopes -`telemetry()` and `takeTelemetry()` return a `Telemetry` object. +`telemetry()` and `takeTelemetry()` return a `Telemetry` object. For +zero-allocation meter updates, `feedbackInto(out)` and `takeFeedbackInto(out)` +write 8 values into a `Float64Array`, and `telemetryInto(out)` and +`takeTelemetryInto(out)` write 45 values into a `Float64Array`. In feedback, `targetMidiNote` is `undefined` in these cases, which are also the cases where `voiced` is `false`: @@ -495,16 +522,17 @@ call with more points than before reserve memory. ### Memory allocation -The constructor allocates reusable PCM buffers. A successful call that -processes audio without events does not allocate new Rust PCM storage. -However, the call copies the audio across the boundary between JavaScript and -Wasm. These items can allocate: +The constructor allocates reusable 16-bit PCM, `f32` and MIDI buffers. Calls +to `processFloat32`, `process`, `applyMidi`, `feedbackInto` and +`telemetryInto` with typed arrays do not allocate Wasm memory. `applyMidi`, +`feedbackInto` and `telemetryInto` also allocate no JavaScript objects. +These items can allocate: -- Object conversion. -- Supplied events. +- Configuration conversion. +- `TimedEvent[]` object arrays. - Errors. -- Feedback and telemetry. -- The formant envelopes. +- `feedback`, `takeFeedback`, `telemetry` and `takeTelemetry` objects. +- The formant envelopes on the first or larger call. The generated glue can also make temporary views. This binding is for general use, and it does not guarantee hard real-time behavior for allocation or diff --git a/package.json b/package.json index 511ddfa..d1eede8 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,10 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./worklet": { + "types": "./dist/worklet.d.ts", + "import": "./dist/worklet.js" + }, "./wasm": { "types": "./pkg/tunelet.d.ts", "import": "./pkg/tunelet.js" @@ -26,7 +30,10 @@ "pkg/tunelet.d.ts", "pkg/tunelet_bg.wasm" ], - "sideEffects": false, + "sideEffects": [ + "./dist/worklet.js", + "./dist/utf8-shim.js" + ], "scripts": { "build": "npm run build:wasm && npm run build:ts", "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-opt --features wasm --locked", diff --git a/src/index.ts b/src/index.ts index da35a57..4e756d6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,20 +1,510 @@ /** * 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 re-exports all named exports of the module - * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, event and feedback types. + * In browsers, call `createTuneletNode(audioContext)` to compile Wasm, register + * the `AudioWorklet` processor and construct a stereo `TuneletWorkletNode`. + * Call `loadTunelet()` for direct `Tunelet` instances in Node.js or on the main + * thread. This module re-exports all named exports of the generated module, + * which include `Tunelet`, `defaultConfig`, `initSync` and the configuration, + * event and feedback types. */ import init, { initSync } from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import type { + Feedback, + InitInput, + InitOutput, + ProcessorConfig, + Telemetry, +} from "../pkg/tunelet.js"; +import { + CORRECTION_MIDI_FLAG, + FEEDBACK_LEN, + MIDI_EVENT_WORDS, + TELEMETRY_LEN, + TUNELET_PROCESSOR_NAME, +} from "./worklet.js"; +import type { TuneletProcessorOptions } from "./worklet.js"; export * from "../pkg/tunelet.js"; +export { + CORRECTION_MIDI_FLAG, + FEEDBACK_LEN, + MIDI_EVENT_WORDS, + TELEMETRY_LEN, + TUNELET_PROCESSOR_NAME, +}; + +/** The named indices for the 8-element `Float64Array` of `feedbackInto`. */ +export const FEEDBACK_INDEX = { + resampleRatio: 0, + periodSamples: 1, + frequencyHz: 2, + targetMidiNote: 3, + voiced: 4, + peakLevel: 5, + processedFrames: 6, + latencyFrames: 7, +} as const; + +/** The named indices for the 45-element `Float64Array` of `telemetryInto`. */ +export const TELEMETRY_INDEX = { + processedFrames: 0, + inputPeak: 1, + outputPeakLeft: 2, + outputPeakRight: 3, + reverbWetPeak: 4, + clarity: 5, + tracking: 6, + voiceCount: 7, + voiceRatiosOffset: 8, + voiceGainsOffset: 24, + punchGain: 40, + warmGain: 41, + alienLoopFrames: 42, + alienPhaseFrames: 43, + formantGeneration: 44, +} as const; + +/** The options for `createTuneletNode` and `TuneletWorkletNode`. */ +export interface TuneletNodeOptions { + /** The optional initial processor configuration. */ + config?: ProcessorConfig; + /** The maximum frames in one render quantum. The default is 128. */ + maxBlockFrames?: number; + /** The blocks between meter updates. The default is 4. */ + meterIntervalBlocks?: number; + /** A custom Wasm source for `createTuneletNode`. */ + wasmSource?: InitInput | Promise; + /** A custom URL for the `tunelet/worklet` module script. */ + workletUrl?: string | URL; + /** If you construct `TuneletWorkletNode` directly, give the compiled Wasm module here. */ + module?: WebAssembly.Module; +} + +/** A listener callback for meter updates on `TuneletWorkletNode`. */ +export type TuneletMeterListener = ( + feedback: Float64Array, + telemetry: Float64Array, +) => void; /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; +/** The cached default compiled `WebAssembly.Module`, which a failure clears. */ +let defaultWasmModule: Promise | undefined; + +/** Tracks worklet module registration for each `BaseAudioContext`. */ +const registeredContexts = new WeakMap>(); + +/** The MIDI ring capacity in 4-word events when `SharedArrayBuffer` exists. */ +const SHARED_MIDI_CAPACITY = 256; + +/** Returns the nominal latency in host frames for a supported sample rate. */ +function nominalLatencyForRate(sampleRate: number): number { + switch (sampleRate) { + case 44100: + case 48000: + return 1593; + case 88200: + case 96000: + return 3190; + case 176400: + case 192000: + return 6384; + default: + throw new Error( + "sampleRate must be 44100, 48000, 88200, 96000, 176400 or 192000", + ); + } +} + +const BaseAudioWorkletNode: typeof AudioWorkletNode = + typeof AudioWorkletNode === "function" + ? AudioWorkletNode + : (class {} as unknown as typeof AudioWorkletNode); + +/** + * A stereo `AudioWorkletNode` that runs `tunelet` on the Web Audio render + * thread. + * + * Construct it with `await createTuneletNode(audioContext, options)`. The node + * accepts mono or multi-channel input, outputs stereo audio, applies + * sample-accurate MIDI controls and exposes typed-array feedback and telemetry + * buffers. + */ +export class TuneletWorkletNode extends BaseAudioWorkletNode { + /** The live 8-element `Float64Array` view of the latest `Feedback` snapshot. */ + readonly feedbackData: Float64Array; + /** The live 45-element `Float64Array` view of the latest `Telemetry` snapshot. */ + readonly telemetryData: Float64Array; + /** The nominal processor latency in host frames, with resampler delay included. */ + readonly latencyFrames: number; + + private readonly midiRingHeader: Int32Array | null; + private readonly midiRingData: Uint32Array | null; + private readonly sharedMeters: boolean; + private readonly listeners = new Set(); + + constructor( + context: BaseAudioContext, + options: TuneletNodeOptions & { module: WebAssembly.Module }, + ) { + if (typeof AudioWorkletNode !== "function") { + throw new Error("AudioWorkletNode is not available in this environment."); + } + const latencyFrames = nominalLatencyForRate(context.sampleRate); + const canShare = + typeof SharedArrayBuffer === "function" && typeof Atomics === "object"; + + const midiRingBuffer = canShare + ? new SharedArrayBuffer(8 + SHARED_MIDI_CAPACITY * MIDI_EVENT_WORDS * 4) + : undefined; + const meterBuffer = canShare + ? new SharedArrayBuffer( + (FEEDBACK_LEN + TELEMETRY_LEN) * Float64Array.BYTES_PER_ELEMENT, + ) + : undefined; + + const processorOptions: TuneletProcessorOptions = { + module: options.module, + config: options.config, + maxBlockFrames: options.maxBlockFrames ?? 128, + sampleRate: context.sampleRate, + meterIntervalBlocks: options.meterIntervalBlocks ?? 4, + midiRingBuffer, + meterBuffer, + postMeters: !canShare, + }; + + super(context, TUNELET_PROCESSOR_NAME, { + numberOfInputs: 1, + numberOfOutputs: 1, + outputChannelCount: [2], + channelCount: 1, + channelCountMode: "explicit", + channelInterpretation: "speakers", + processorOptions, + }); + + this.latencyFrames = latencyFrames; + this.sharedMeters = canShare; + + if (midiRingBuffer && meterBuffer) { + this.midiRingHeader = new Int32Array(midiRingBuffer, 0, 2); + this.midiRingData = new Uint32Array( + midiRingBuffer, + 8, + SHARED_MIDI_CAPACITY * MIDI_EVENT_WORDS, + ); + this.feedbackData = new Float64Array(meterBuffer, 0, FEEDBACK_LEN); + this.telemetryData = new Float64Array( + meterBuffer, + FEEDBACK_LEN * Float64Array.BYTES_PER_ELEMENT, + TELEMETRY_LEN, + ); + } else { + this.midiRingHeader = null; + this.midiRingData = null; + this.feedbackData = new Float64Array(FEEDBACK_LEN); + this.feedbackData[FEEDBACK_INDEX.latencyFrames] = latencyFrames; + this.telemetryData = new Float64Array(TELEMETRY_LEN); + } + + this.port.onmessage = ( + event: MessageEvent<{ + type?: string; + feedback?: Float64Array; + telemetry?: Float64Array; + }>, + ) => { + const data = event.data; + if (data && data.type === "meters" && data.feedback && data.telemetry) { + if (!this.sharedMeters) { + this.feedbackData.set(data.feedback); + this.telemetryData.set(data.telemetry); + } + for (const listener of this.listeners) { + listener(this.feedbackData, this.telemetryData); + } + } + }; + } + + /** Replaces the active processor configuration on the audio thread. */ + setConfig(config: ProcessorConfig): void { + this.port.postMessage({ type: "config", config }); + } + + /** Sends a 3-byte harmony MIDI message at an optional frame offset. */ + sendMidi(bytes: ArrayLike, offset = 0): void { + if (bytes.length !== 3) { + throw new RangeError("MIDI message must contain 3 bytes."); + } + this.enqueueMidi(offset, bytes[0] & 0xff, bytes[1] & 0x7f, bytes[2] & 0x7f); + } + + /** Sends a 3-byte correction keyboard MIDI message at an optional offset. */ + sendCorrectionMidi(bytes: ArrayLike, offset = 0): void { + if (bytes.length !== 3) { + throw new RangeError("MIDI message must contain 3 bytes."); + } + this.enqueueMidi( + offset, + (bytes[0] & 0xff) | CORRECTION_MIDI_FLAG, + bytes[1] & 0x7f, + bytes[2] & 0x7f, + ); + } + + /** Sends packed `[offset, status, data1, data2]` MIDI words. */ + sendMidiWords(words: Uint32Array): void { + if (words.length % MIDI_EVENT_WORDS !== 0) { + throw new RangeError("MIDI word length must be a multiple of 4."); + } + for (let i = 0; i < words.length; i += MIDI_EVENT_WORDS) { + this.enqueueMidi(words[i], words[i + 1], words[i + 2], words[i + 3]); + } + } + + /** Sends a harmony MIDI Note On event (`channel` 0..15, `note` 0..127). */ + noteOn(channel: number, note: number, velocity: number, offset = 0): void { + this.enqueueMidi( + offset, + 0x90 | (channel & 0x0f), + note & 0x7f, + velocity & 0x7f, + ); + } + + /** Sends a harmony MIDI Note Off event (`channel` 0..15, `note` 0..127). */ + noteOff(channel: number, note: number, offset = 0): void { + this.enqueueMidi(offset, 0x80 | (channel & 0x0f), note & 0x7f, 0); + } + + /** Releases all active harmony MIDI notes (controller 123). */ + allNotesOff(offset = 0): void { + this.enqueueMidi(offset, 0xb0, 123, 0); + } + + /** Starts the finite tail drain on the audio thread. */ + beginDrain(): void { + this.port.postMessage({ type: "drain" }); + } + + /** Resets the processor audio histories and feedback on the audio thread. */ + reset(): void { + this.port.postMessage({ type: "reset" }); + } + + /** Requests an immediate meter snapshot from the audio thread. */ + requestMeters(): void { + this.port.postMessage({ type: "requestMeters" }); + } + + /** Subscribes to meter updates and returns an unsubscribe function. */ + onMeters(listener: TuneletMeterListener): () => void { + this.listeners.add(listener); + if (this.sharedMeters) { + this.port.postMessage({ type: "postMeters", enabled: true }); + } + return () => { + this.listeners.delete(listener); + if (this.sharedMeters && this.listeners.size === 0) { + this.port.postMessage({ type: "postMeters", enabled: false }); + } + }; + } + + /** Converts the current `feedbackData` buffer into a `Feedback` object. */ + feedback(): Feedback { + const data = this.feedbackData; + const voiced = data[FEEDBACK_INDEX.voiced] !== 0; + const note = data[FEEDBACK_INDEX.targetMidiNote]; + return { + resampleRatio: data[FEEDBACK_INDEX.resampleRatio], + periodSamples: data[FEEDBACK_INDEX.periodSamples], + frequencyHz: data[FEEDBACK_INDEX.frequencyHz], + targetMidiNote: voiced && !Number.isNaN(note) ? note : undefined, + voiced, + peakLevel: data[FEEDBACK_INDEX.peakLevel], + processedFrames: BigInt(Math.trunc(data[FEEDBACK_INDEX.processedFrames])), + latencyFrames: data[FEEDBACK_INDEX.latencyFrames], + }; + } + + /** Converts the current `telemetryData` buffer into a `Telemetry` object. */ + telemetry(): Telemetry { + const d = this.telemetryData; + const ratios = Array.from( + d.subarray( + TELEMETRY_INDEX.voiceRatiosOffset, + TELEMETRY_INDEX.voiceRatiosOffset + 16, + ), + ) as Telemetry["voiceRatios"]; + const gains = Array.from( + d.subarray( + TELEMETRY_INDEX.voiceGainsOffset, + TELEMETRY_INDEX.voiceGainsOffset + 16, + ), + ) as Telemetry["voiceGains"]; + return { + processedFrames: BigInt(Math.trunc(d[TELEMETRY_INDEX.processedFrames])), + inputPeak: d[TELEMETRY_INDEX.inputPeak], + outputPeak: [ + d[TELEMETRY_INDEX.outputPeakLeft], + d[TELEMETRY_INDEX.outputPeakRight], + ], + reverbWetPeak: d[TELEMETRY_INDEX.reverbWetPeak], + clarity: d[TELEMETRY_INDEX.clarity], + tracking: d[TELEMETRY_INDEX.tracking] !== 0, + voiceCount: d[TELEMETRY_INDEX.voiceCount], + voiceRatios: ratios, + voiceGains: gains, + punchGain: d[TELEMETRY_INDEX.punchGain], + warmGain: d[TELEMETRY_INDEX.warmGain], + alienLoopFrames: d[TELEMETRY_INDEX.alienLoopFrames], + alienPhaseFrames: d[TELEMETRY_INDEX.alienPhaseFrames], + formantGeneration: d[TELEMETRY_INDEX.formantGeneration], + }; + } + + /** Releases the Wasm processor on the audio thread and disconnects the node. */ + free(): void { + this.port.postMessage({ type: "free" }); + this.disconnect(); + } + + [Symbol.dispose](): void { + this.free(); + } + + private enqueueMidi( + offset: number, + status: number, + data1: number, + data2: number, + ): void { + if (this.midiRingHeader && this.midiRingData) { + const write = Atomics.load(this.midiRingHeader, 0) >>> 0; + const read = Atomics.load(this.midiRingHeader, 1) >>> 0; + if (((write - read) >>> 0) < SHARED_MIDI_CAPACITY) { + const slot = (write % SHARED_MIDI_CAPACITY) * MIDI_EVENT_WORDS; + this.midiRingData[slot] = offset > 0 ? offset >>> 0 : 0; + this.midiRingData[slot + 1] = status >>> 0; + this.midiRingData[slot + 2] = data1 & 0x7f; + this.midiRingData[slot + 3] = data2 & 0x7f; + Atomics.store(this.midiRingHeader, 0, (write + 1) >>> 0); + return; + } + } + this.port.postMessage({ + type: "midi", + offset: offset > 0 ? offset >>> 0 : 0, + status: status >>> 0, + data1: data1 & 0x7f, + data2: data2 & 0x7f, + }); + } +} + +/** + * Compiles the Wasm binary, registers `tunelet/worklet` on `context` and + * returns a stereo `TuneletWorkletNode`. + * + * Supported context sample rates are 44100, 48000, 88200, 96000, 176400 and + * 192000 Hz. + */ +export async function createTuneletNode( + context: BaseAudioContext, + options?: TuneletNodeOptions, +): Promise { + if (!context || !context.audioWorklet) { + throw new Error("context.audioWorklet is not available."); + } + nominalLatencyForRate(context.sampleRate); + + const modulePromise = + options?.module !== undefined + ? Promise.resolve(options.module) + : options?.wasmSource !== undefined + ? compileWasmModule(options.wasmSource) + : (defaultWasmModule ??= compileWasmModule( + new URL("../pkg/tunelet_bg.wasm", import.meta.url), + ).catch((error: unknown) => { + defaultWasmModule = undefined; + throw error; + })); + + const workletUrl = + options?.workletUrl ?? new URL("./worklet.js", import.meta.url); + let registration = registeredContexts.get(context); + if (!registration) { + registration = context.audioWorklet + .addModule(workletUrl) + .catch((error: unknown) => { + registeredContexts.delete(context); + throw error; + }); + registeredContexts.set(context, registration); + } + + const [module] = await Promise.all([modulePromise, registration]); + await (initialization ??= init({ module_or_path: module }).catch( + (error: unknown) => { + initialization = undefined; + throw error; + }, + )); + return new TuneletWorkletNode(context, { ...options, module }); +} + +/** Compiles a `WebAssembly.Module` from a URL, `Response`, buffer or module. */ +async function compileWasmModule( + source: InitInput | Promise, +): Promise { + const input = await source; + if (input instanceof WebAssembly.Module) { + return input; + } + if (input instanceof URL && input.protocol === "file:") { + const moduleName = "node:fs/promises"; + const fs: typeof import("node:fs/promises") = await import( + /* webpackIgnore: true */ /* @vite-ignore */ moduleName + ); + return WebAssembly.compile(await fs.readFile(input)); + } + if ( + typeof input === "string" || + input instanceof URL || + (typeof Request === "function" && input instanceof Request) + ) { + return compileResponse(await fetch(input)); + } + if (typeof Response === "function" && input instanceof Response) { + return compileResponse(input); + } + return WebAssembly.compile(input as BufferSource); +} + +/** Compiles a `WebAssembly.Module` from an HTTP `Response`. */ +async function compileResponse( + response: Response, +): Promise { + if (!response.ok) { + throw new Error( + `Failed to fetch Wasm: ${response.status} ${response.statusText}`, + ); + } + if (typeof WebAssembly.compileStreaming === "function") { + try { + return await WebAssembly.compileStreaming(response.clone()); + } catch { + // If the server omits application/wasm, compile from the byte buffer. + } + } + return WebAssembly.compile(await response.arrayBuffer()); +} + /** * Initializes the Wasm module one time for this imported package instance. * diff --git a/src/utf8-shim.ts b/src/utf8-shim.ts new file mode 100644 index 0000000..ef342af --- /dev/null +++ b/src/utf8-shim.ts @@ -0,0 +1,256 @@ +/** + * Internal UTF-8 `TextDecoder` and `TextEncoder` shim for `AudioWorkletGlobalScope`. + * + * Standard `AudioWorkletGlobalScope` environments do not expose `TextDecoder` + * or `TextEncoder`. The generated wasm-bindgen module constructs both at + * evaluation time. If `globalThis` does not define them, this module installs + * minimal UTF-8 classes. + */ + +/** The options for the UTF-8 decoder constructor. */ +export interface Utf8DecoderOptions { + readonly fatal?: boolean; + readonly ignoreBOM?: boolean; +} + +/** The counts from a bounded UTF-8 encode into a target `Uint8Array`. */ +export interface Utf8EncodeIntoResult { + read: number; + written: number; +} + +const CHUNK_UNITS = 4096; + +/** A UTF-8 `TextDecoder` for worklet scopes that lack a native decoder. */ +class Utf8TextDecoder { + readonly encoding = "utf-8"; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + + constructor(label = "utf-8", options?: Utf8DecoderOptions) { + const normalized = String(label).trim().toLowerCase(); + if (normalized !== "utf-8" && normalized !== "utf8") { + throw new RangeError(`The encoding label "${label}" is not supported.`); + } + this.fatal = Boolean(options?.fatal); + this.ignoreBOM = Boolean(options?.ignoreBOM); + } + + decode(input?: AllowSharedBufferSource): string { + if (input === undefined) { + return ""; + } + const bytes = ArrayBuffer.isView(input) + ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) + : new Uint8Array(input); + + let index = 0; + const length = bytes.length; + if ( + !this.ignoreBOM && + length >= 3 && + bytes[0] === 0xef && + bytes[1] === 0xbb && + bytes[2] === 0xbf + ) { + index = 3; + } + + const units: number[] = []; + let result = ""; + + const fail = (): void => { + if (this.fatal) { + throw new TypeError("The byte sequence is not valid UTF-8."); + } + units.push(0xfffd); + }; + + while (index < length) { + const b0 = bytes[index]; + if (b0 < 0x80) { + units.push(b0); + index += 1; + } else if (b0 >= 0xc2 && b0 <= 0xdf) { + if (index + 1 >= length) { + fail(); + break; + } + const b1 = bytes[index + 1]; + if ((b1 & 0xc0) !== 0x80) { + fail(); + index += 1; + } else { + units.push(((b0 & 0x1f) << 6) | (b1 & 0x3f)); + index += 2; + } + } else if (b0 >= 0xe0 && b0 <= 0xef) { + if (index + 2 >= length) { + fail(); + break; + } + const b1 = bytes[index + 1]; + const b2 = bytes[index + 2]; + const validSecond = + (b0 === 0xe0 ? b1 >= 0xa0 && b1 <= 0xbf : true) && + (b0 === 0xed ? b1 >= 0x80 && b1 <= 0x9f : true) && + (b1 & 0xc0) === 0x80; + if (!validSecond || (b2 & 0xc0) !== 0x80) { + fail(); + index += 1; + } else { + units.push(((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f)); + index += 3; + } + } else if (b0 >= 0xf0 && b0 <= 0xf4) { + if (index + 3 >= length) { + fail(); + break; + } + const b1 = bytes[index + 1]; + const b2 = bytes[index + 2]; + const b3 = bytes[index + 3]; + const validSecond = + (b0 === 0xf0 ? b1 >= 0x90 && b1 <= 0xbf : true) && + (b0 === 0xf4 ? b1 >= 0x80 && b1 <= 0x8f : true) && + (b1 & 0xc0) === 0x80; + if ( + !validSecond || + (b2 & 0xc0) !== 0x80 || + (b3 & 0xc0) !== 0x80 + ) { + fail(); + index += 1; + } else { + const codePoint = + (((b0 & 0x07) << 18) | + ((b1 & 0x3f) << 12) | + ((b2 & 0x3f) << 6) | + (b3 & 0x3f)) - + 0x10000; + units.push(0xd800 | (codePoint >> 10), 0xdc00 | (codePoint & 0x3ff)); + index += 4; + } + } else { + fail(); + index += 1; + } + + if (units.length >= CHUNK_UNITS) { + result += String.fromCharCode(...units); + units.length = 0; + } + } + + if (units.length > 0) { + result += String.fromCharCode(...units); + } + return result; + } +} + +/** A UTF-8 `TextEncoder` for worklet scopes that lack a native encoder. */ +class Utf8TextEncoder { + readonly encoding = "utf-8"; + + encode(input = ""): Uint8Array { + const text = String(input); + const bytes: number[] = []; + for (let index = 0; index < text.length; index += 1) { + let code = text.charCodeAt(index); + if (code < 0x80) { + bytes.push(code); + } else if (code < 0x800) { + bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)); + } else if (code >= 0xd800 && code <= 0xdbff) { + const next = index + 1 < text.length ? text.charCodeAt(index + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + code = 0x10000 + (((code & 0x3ff) << 10) | (next & 0x3ff)); + bytes.push( + 0xf0 | (code >> 18), + 0x80 | ((code >> 12) & 0x3f), + 0x80 | ((code >> 6) & 0x3f), + 0x80 | (code & 0x3f), + ); + index += 1; + } else { + bytes.push(0xef, 0xbf, 0xbd); + } + } else if (code >= 0xdc00 && code <= 0xdfff) { + bytes.push(0xef, 0xbf, 0xbd); + } else { + bytes.push( + 0xe0 | (code >> 12), + 0x80 | ((code >> 6) & 0x3f), + 0x80 | (code & 0x3f), + ); + } + } + return new Uint8Array(bytes); + } + + encodeInto(source: string, destination: Uint8Array): Utf8EncodeIntoResult { + const text = String(source); + const limit = destination.length; + let read = 0; + let written = 0; + + while (read < text.length) { + const code = text.charCodeAt(read); + if (code < 0x80) { + if (written + 1 > limit) break; + destination[written] = code; + written += 1; + read += 1; + } else if (code < 0x800) { + if (written + 2 > limit) break; + destination[written] = 0xc0 | (code >> 6); + destination[written + 1] = 0x80 | (code & 0x3f); + written += 2; + read += 1; + } else if (code >= 0xd800 && code <= 0xdbff) { + const next = read + 1 < text.length ? text.charCodeAt(read + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + if (written + 4 > limit) break; + const point = 0x10000 + (((code & 0x3ff) << 10) | (next & 0x3ff)); + destination[written] = 0xf0 | (point >> 18); + destination[written + 1] = 0x80 | ((point >> 12) & 0x3f); + destination[written + 2] = 0x80 | ((point >> 6) & 0x3f); + destination[written + 3] = 0x80 | (point & 0x3f); + written += 4; + read += 2; + } else { + if (written + 3 > limit) break; + destination[written] = 0xef; + destination[written + 1] = 0xbf; + destination[written + 2] = 0xbd; + written += 3; + read += 1; + } + } else { + if (written + 3 > limit) break; + const unit = code >= 0xdc00 && code <= 0xdfff ? 0xfffd : code; + destination[written] = 0xe0 | (unit >> 12); + destination[written + 1] = 0x80 | ((unit >> 6) & 0x3f); + destination[written + 2] = 0x80 | (unit & 0x3f); + written += 3; + read += 1; + } + } + + return { read, written }; + } +} + +/** If `globalThis` lacks `TextDecoder` or `TextEncoder`, installs the UTF-8 shim. */ +export function installUtf8Shim(): void { + const scope = globalThis as Record; + if (typeof scope.TextDecoder === "undefined") { + scope.TextDecoder = Utf8TextDecoder; + } + if (typeof scope.TextEncoder === "undefined") { + scope.TextEncoder = Utf8TextEncoder; + } +} + +installUtf8Shim(); diff --git a/src/worklet.ts b/src/worklet.ts new file mode 100644 index 0000000..e29fe8f --- /dev/null +++ b/src/worklet.ts @@ -0,0 +1,436 @@ +/** + * The `AudioWorklet` runtime module (`tunelet/worklet`). + * + * This module installs the internal UTF-8 shim before the generated Wasm + * bindings evaluate. Inside an `AudioWorkletGlobalScope`, it registers + * `"tunelet-processor"` and runs 128-frame `Float32Array` blocks, MIDI + * controls and meter snapshots with preallocated buffers. + */ +import "./utf8-shim.js"; +import { initSync, Tunelet } from "../pkg/tunelet.js"; +import type { ProcessorConfig, SyncInitInput } from "../pkg/tunelet.js"; + +/** The registered `AudioWorkletProcessor` name. */ +export const TUNELET_PROCESSOR_NAME = "tunelet-processor"; + +/** The number of `f64` elements in a typed-array `Feedback` snapshot. */ +export const FEEDBACK_LEN = 8; + +/** The number of `f64` elements in a typed-array `Telemetry` snapshot. */ +export const TELEMETRY_LEN = 45; + +/** The number of `u32` words for each timed MIDI event in a `Uint32Array`. */ +export const MIDI_EVENT_WORDS = 4; + +/** The status flag that selects the correction MIDI keyboard in a `Uint32Array`. */ +export const CORRECTION_MIDI_FLAG = 0x100; + +/** The maximum number of MIDI events in one worklet block buffer. */ +const MAX_BLOCK_MIDI = 128; + +/** The options in `AudioWorkletNodeOptions.processorOptions`. */ +export interface TuneletProcessorOptions { + /** The compiled Wasm module or raw bytes for synchronous setup. */ + module: SyncInitInput; + /** The optional initial processor configuration. */ + config?: ProcessorConfig; + /** The maximum frames in one render call. The default is 128. */ + maxBlockFrames?: number; + /** An explicit sample rate. The default is the global worklet rate. */ + sampleRate?: number; + /** The blocks between meter updates. Zero disables automatic meter updates. */ + meterIntervalBlocks?: number; + /** An optional `SharedArrayBuffer` for the MIDI ring words. */ + midiRingBuffer?: SharedArrayBuffer; + /** An optional `SharedArrayBuffer` for the feedback and telemetry `f64` values. */ + meterBuffer?: SharedArrayBuffer; + /** If `true` and no shared buffer exists, posts meter updates on the `MessagePort`. */ + postMeters?: boolean; +} + +/** The control messages from `TuneletWorkletNode` to the worklet port. */ +export type TuneletWorkletInboundMessage = + | { type: "config"; config: ProcessorConfig } + | { + type: "midi"; + offset: number; + status: number; + data1: number; + data2: number; + } + | { type: "midiWords"; words: Uint32Array } + | { type: "drain" } + | { type: "reset" } + | { type: "free" } + | { type: "postMeters"; enabled: boolean } + | { type: "requestMeters" }; + +/** The minimal shape of `AudioWorkletProcessor` in a worklet scope. */ +export interface AudioWorkletProcessorInstance { + readonly port: MessagePort; + process( + inputs: Float32Array[][], + outputs: Float32Array[][], + parameters: Record, + ): boolean; +} + +interface AudioWorkletProcessorConstructor { + new (options?: { + processorOptions?: TuneletProcessorOptions; + }): AudioWorkletProcessorInstance; +} + +interface WorkletScope { + readonly sampleRate?: number; + readonly AudioWorkletProcessor?: AudioWorkletProcessorConstructor; + readonly registerProcessor?: ( + name: string, + processorCtor: unknown, + ) => void; + __tuneletRegistered?: boolean; +} + +const workletScope = globalThis as unknown as WorkletScope; + +const BaseProcessor: AudioWorkletProcessorConstructor = + typeof workletScope.AudioWorkletProcessor === "function" + ? workletScope.AudioWorkletProcessor + : (class { + readonly port: MessagePort; + constructor() { + const channel = + typeof MessageChannel === "function" ? new MessageChannel() : null; + this.port = (channel ? channel.port1 : {}) as MessagePort; + } + process(): boolean { + return true; + } + } as unknown as AudioWorkletProcessorConstructor); + +/** + * The `AudioWorkletProcessor` implementation for `tunelet`. + * + * Construction initializes Wasm synchronously and preallocates all audio, + * MIDI and meter views. Steady-state `process` calls execute without scalar + * sample conversion loops or heap allocations. + */ +export class TuneletWorkletProcessor extends BaseProcessor { + private processor: Tunelet | null; + private readonly maxBlockFrames: number; + private readonly silentViews: Float32Array[]; + private readonly monoViews: Float32Array[]; + private readonly rightViews: Float32Array[]; + private readonly midiWords: Uint32Array; + private readonly midiViews: Uint32Array[]; + private queuedMidiCount = 0; + private readonly midiRingHeader: Int32Array | null; + private readonly midiRingData: Uint32Array | null; + private readonly midiRingCapacity: number; + private readonly feedbackView: Float64Array; + private readonly telemetryView: Float64Array; + private readonly sharedMeters: boolean; + private postMeters: boolean; + private readonly meterIntervalBlocks: number; + private meterBlockCounter = 0; + private readonly meterMessage: { + readonly type: "meters"; + readonly feedback: Float64Array; + readonly telemetry: Float64Array; + }; + private draining = false; + private disposed = false; + + constructor(options?: { processorOptions?: TuneletProcessorOptions }) { + super(options); + const procOptions = options?.processorOptions; + if (!procOptions || !procOptions.module) { + throw new Error("processorOptions.module must provide a Wasm module."); + } + initSync({ module: procOptions.module }); + + const rate = procOptions.sampleRate ?? workletScope.sampleRate ?? 48000; + const maxBlockFrames = procOptions.maxBlockFrames ?? 128; + this.maxBlockFrames = maxBlockFrames; + this.processor = new Tunelet(rate, maxBlockFrames, procOptions.config); + + const silentBacking = new Float32Array(maxBlockFrames); + const monoBacking = new Float32Array(maxBlockFrames); + const rightBacking = new Float32Array(maxBlockFrames); + this.silentViews = new Array(maxBlockFrames + 1); + this.monoViews = new Array(maxBlockFrames + 1); + this.rightViews = new Array(maxBlockFrames + 1); + for (let length = 0; length <= maxBlockFrames; length += 1) { + this.silentViews[length] = silentBacking.subarray(0, length); + this.monoViews[length] = monoBacking.subarray(0, length); + this.rightViews[length] = rightBacking.subarray(0, length); + } + + this.midiWords = new Uint32Array(MAX_BLOCK_MIDI * MIDI_EVENT_WORDS); + this.midiViews = new Array(MAX_BLOCK_MIDI + 1); + for (let count = 0; count <= MAX_BLOCK_MIDI; count += 1) { + this.midiViews[count] = this.midiWords.subarray( + 0, + count * MIDI_EVENT_WORDS, + ); + } + + if ( + procOptions.midiRingBuffer && + typeof Atomics === "object" && + procOptions.midiRingBuffer.byteLength >= 24 + ) { + this.midiRingHeader = new Int32Array(procOptions.midiRingBuffer, 0, 2); + const wordLength = (procOptions.midiRingBuffer.byteLength - 8) >>> 2; + this.midiRingCapacity = (wordLength / MIDI_EVENT_WORDS) | 0; + this.midiRingData = new Uint32Array( + procOptions.midiRingBuffer, + 8, + this.midiRingCapacity * MIDI_EVENT_WORDS, + ); + } else { + this.midiRingHeader = null; + this.midiRingData = null; + this.midiRingCapacity = 0; + } + + if ( + procOptions.meterBuffer && + procOptions.meterBuffer.byteLength >= + (FEEDBACK_LEN + TELEMETRY_LEN) * Float64Array.BYTES_PER_ELEMENT + ) { + this.feedbackView = new Float64Array( + procOptions.meterBuffer, + 0, + FEEDBACK_LEN, + ); + this.telemetryView = new Float64Array( + procOptions.meterBuffer, + FEEDBACK_LEN * Float64Array.BYTES_PER_ELEMENT, + TELEMETRY_LEN, + ); + this.sharedMeters = true; + } else { + this.feedbackView = new Float64Array(FEEDBACK_LEN); + this.telemetryView = new Float64Array(TELEMETRY_LEN); + this.sharedMeters = false; + } + + this.meterIntervalBlocks = procOptions.meterIntervalBlocks ?? 4; + this.postMeters = Boolean(procOptions.postMeters); + this.meterMessage = { + type: "meters", + feedback: this.feedbackView, + telemetry: this.telemetryView, + }; + + this.processor.feedbackInto(this.feedbackView); + this.processor.telemetryInto(this.telemetryView); + + if (this.port && typeof this.port.onmessage !== "undefined") { + this.port.onmessage = (event: MessageEvent) => { + this.handleMessage(event.data); + }; + } + } + + private insertMidi( + offset: number, + status: number, + data1: number, + data2: number, + ): void { + if (this.queuedMidiCount >= MAX_BLOCK_MIDI) { + return; + } + const clampedOffset = offset > 0 ? offset >>> 0 : 0; + let slot = this.queuedMidiCount; + while ( + slot > 0 && + this.midiWords[(slot - 1) * MIDI_EVENT_WORDS] > clampedOffset + ) { + const src = (slot - 1) * MIDI_EVENT_WORDS; + const dst = slot * MIDI_EVENT_WORDS; + this.midiWords[dst] = this.midiWords[src]; + this.midiWords[dst + 1] = this.midiWords[src + 1]; + this.midiWords[dst + 2] = this.midiWords[src + 2]; + this.midiWords[dst + 3] = this.midiWords[src + 3]; + slot -= 1; + } + const base = slot * MIDI_EVENT_WORDS; + this.midiWords[base] = clampedOffset; + this.midiWords[base + 1] = status >>> 0; + this.midiWords[base + 2] = data1 & 0x7f; + this.midiWords[base + 3] = data2 & 0x7f; + this.queuedMidiCount += 1; + } + + private pullSharedMidi(): void { + if (!this.midiRingHeader || !this.midiRingData) { + return; + } + const write = Atomics.load(this.midiRingHeader, 0); + let read = Atomics.load(this.midiRingHeader, 1); + while (read !== write && this.queuedMidiCount < MAX_BLOCK_MIDI) { + const slot = (read % this.midiRingCapacity) * MIDI_EVENT_WORDS; + this.insertMidi( + this.midiRingData[slot], + this.midiRingData[slot + 1], + this.midiRingData[slot + 2], + this.midiRingData[slot + 3], + ); + read = (read + 1) >>> 0; + } + Atomics.store(this.midiRingHeader, 1, read); + } + + private handleMessage(message: TuneletWorkletInboundMessage): void { + if (!this.processor || !message) { + return; + } + switch (message.type) { + case "config": + this.processor.setConfig(message.config); + this.draining = false; + break; + case "midi": + this.insertMidi( + message.offset, + message.status, + message.data1, + message.data2, + ); + this.draining = false; + break; + case "midiWords": { + const words = message.words; + for (let i = 0; i + 3 < words.length; i += MIDI_EVENT_WORDS) { + this.insertMidi(words[i], words[i + 1], words[i + 2], words[i + 3]); + } + this.draining = false; + break; + } + case "drain": + this.processor.beginDrain(); + this.draining = true; + break; + case "reset": + this.processor.reset(); + this.queuedMidiCount = 0; + this.draining = false; + break; + case "postMeters": + this.postMeters = message.enabled; + break; + case "requestMeters": + this.processor.takeFeedbackInto(this.feedbackView); + this.processor.takeTelemetryInto(this.telemetryView); + if (!this.sharedMeters) { + this.port.postMessage(this.meterMessage); + } + break; + case "free": + this.processor.free(); + this.processor = null; + this.disposed = true; + break; + } + } + + override process( + inputs: Float32Array[][], + outputs: Float32Array[][], + ): boolean { + if (this.disposed || !this.processor) { + return false; + } + const outputBus = outputs[0]; + if (!outputBus || outputBus.length === 0) { + return true; + } + const outLeft = outputBus[0]; + const frames = outLeft.length; + if (frames === 0 || frames > this.maxBlockFrames) { + return true; + } + const hasRight = outputBus.length > 1 && outputBus[1].length === frames; + const outRight = hasRight ? outputBus[1] : this.rightViews[frames]; + + this.pullSharedMidi(); + + if (this.draining && this.queuedMidiCount === 0) { + const rendered = this.processor.drainFloat32(outLeft, outRight); + if (rendered === 0) { + this.draining = false; + } + } else { + this.draining = false; + const inputBus = inputs[0]; + let monoInput: Float32Array; + if (!inputBus || inputBus.length === 0 || inputBus[0].length !== frames) { + monoInput = this.silentViews[frames]; + } else if (inputBus.length === 1) { + monoInput = inputBus[0]; + } else { + const downmix = this.monoViews[frames]; + const ch0 = inputBus[0]; + const ch1 = inputBus[1]; + for (let i = 0; i < frames; i += 1) { + downmix[i] = (ch0[i] + ch1[i]) * 0.5; + } + monoInput = downmix; + } + + const midiCount = this.queuedMidiCount; + if (midiCount > 0) { + const maxOffset = frames - 1; + for (let i = 0; i < midiCount; i += 1) { + const idx = i * MIDI_EVENT_WORDS; + if (this.midiWords[idx] > maxOffset) { + this.midiWords[idx] = maxOffset; + } + } + this.queuedMidiCount = 0; + this.processor.processFloat32( + monoInput, + outLeft, + outRight, + this.midiViews[midiCount], + ); + } else { + this.processor.processFloat32(monoInput, outLeft, outRight); + } + } + + if (!hasRight) { + for (let i = 0; i < frames; i += 1) { + outLeft[i] = (outLeft[i] + outRight[i]) * 0.5; + } + } + + if (this.meterIntervalBlocks > 0) { + this.meterBlockCounter += 1; + if (this.meterBlockCounter >= this.meterIntervalBlocks) { + this.meterBlockCounter = 0; + this.processor.takeFeedbackInto(this.feedbackView); + this.processor.takeTelemetryInto(this.telemetryView); + if (!this.sharedMeters && this.postMeters) { + this.port.postMessage(this.meterMessage); + } + } + } + + return true; + } +} + +if ( + typeof workletScope.registerProcessor === "function" && + !workletScope.__tuneletRegistered +) { + workletScope.__tuneletRegistered = true; + workletScope.registerProcessor( + TUNELET_PROCESSOR_NAME, + TuneletWorkletProcessor, + ); +} diff --git a/tsconfig.json b/tsconfig.json index 27aa560..7f1d57b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,5 +11,5 @@ "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": ["src/index.ts", "src/worklet.ts", "src/utf8-shim.ts"] }