From 51c76d4c869eaf0e47cc25aee70e1184dcf99fb0 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 01:50:06 +0000 Subject: [PATCH 1/6] fix(resynthesis): load chromatic periods for the prepared rate - Prepare the correction table for the internal rate at construction. - Make CorrectionTable::set_sample_rate private to scale. - Update the CorrectionConfig documentation for the initial table. --- src/resynthesis.rs | 21 ++++----------------- src/scale.rs | 2 +- 2 files changed, 5 insertions(+), 18 deletions(-) diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..19977a0 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -73,12 +73,9 @@ pub enum MultiVoiceMode { /// mask again. Reset releases the correction keys 0..=126. It keeps key 127 /// and the active note table. Key 127 has no effect on the note table. /// -/// At construction, the chromatic table uses 44.1 kHz periods, also for a -/// 48 kHz processor. Each of these events loads the periods for the prepared -/// rate: -/// - An initial mask that is not chromatic. -/// - A later change to the mask or to `enabled`. -/// - A correction MIDI event. +/// Construction loads the configured note mask for the internal rate. A later +/// change to `notes` or to `enabled`, or a correction MIDI event, builds the +/// active table again for that rate. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -503,17 +500,7 @@ impl Resynthesis { }, formant: Formant::new(rate, config.formant), harmony: HarmonyState::new(rate, config.harmony), - scale: { - // The initial chromatic table uses 44.1 kHz periods at the two - // rates. If the notes load again, the periods for the - // configured rate become active. - let mut scale = CorrectionTable::new(SampleRate::Hz44100, NoteMask::default()); - scale.set_sample_rate(rate); - if config.correction.notes != NoteMask::default() { - scale.set_notes(config.correction.notes); - } - scale - }, + scale: CorrectionTable::new(rate, config.correction.notes), filtered: prepare_history(Q14::ZERO), lead: prepare_history(Q14::ZERO), periods: prepare_history(Q6::ZERO), diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..4ce8320 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -187,7 +187,7 @@ impl CorrectionTable { /// active scale. /// /// The new periods apply from the next `set_notes` call. - pub(crate) fn set_sample_rate(&mut self, rate: SampleRate) { + fn set_sample_rate(&mut self, rate: SampleRate) { let frequency = ((-9.0 * std::f64::consts::LN_2 / 12.0).exp() * 440.0) as f32; let mut base = rate.hz() / frequency; while base < 10820.625 { From 58d73becc4b83af800186bf7b7f7e8d99bc12f1e 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 01:50:06 +0000 Subject: [PATCH 2/6] feat(processor): support 8 kHz to 192 kHz with a polyphase resampler - Extend SampleRate and Tunelet to accept 8000..=192000 Hz integers. - Add a fixed-point Q14 polyphase sinc resampler with 32-bit phases. - Bypass rate conversion at 44.1 kHz and 48 kHz. - Select the 44.1 kHz core for 44.1 kHz multiples and divisors. - Map timed events to core frames and report delays in host frames. - Document the sample rate range and the host latency in the README. --- README.md | 12 +- src/config.rs | 51 ++++-- src/error.rs | 2 +- src/events.rs | 6 + src/lib.rs | 11 +- src/processor.rs | 223 ++++++++++++++++++++----- src/resample.rs | 411 +++++++++++++++++++++++++++++++++++++++++++++++ src/wasm.rs | 23 +-- 8 files changed, 670 insertions(+), 69 deletions(-) create mode 100644 src/resample.rs diff --git a/README.md b/README.md index d2993dc..64cbbab 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ 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 at an integer rate in 8000..=192000 Hz. The +output is stereo or mono 16-bit PCM. ## Installation @@ -292,7 +292,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()` | The nominal delay in host frames (1,593 frames at 44.1 kHz and 48 kHz) | | `formant_envelope()` | The LPC envelopes before and after the formant controls | The telemetry includes these items: @@ -304,8 +304,10 @@ The telemetry includes these items: - The current gains of Punch and Warm, and the position in the Alien loop. The peak windows of the telemetry are independent of the peak window of the -feedback. The latency is nominal. Dry mixes, resampled voices and effects -have different timing. +feedback. The latency is nominal. At 44.1 kHz and 48 kHz, the processor +bypasses rate conversion. Other rates scale the core delay to host frames and +add the polyphase filter delay. Dry mixes, resampled voices and effects have +different timing. `formant_envelope()` writes two LPC envelopes into slices of equal length: diff --git a/src/config.rs b/src/config.rs index 75bcd82..f4e883d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -9,12 +9,19 @@ use crate::Error; use crate::ResynthesisConfig; use std::num::NonZeroUsize; -/// The sample rate of the input and the output. +/// The lowest supported sample rate in hertz. +pub(crate) const MIN_SAMPLE_RATE_HZ: u32 = 8_000; +/// The highest supported sample rate in hertz. +pub(crate) const MAX_SAMPLE_RATE_HZ: u32 = 192_000; + +/// The sample rate of the input and the output, 8000..=192000 Hz. /// -/// 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. To convert an integer device rate in +/// 8000..=192000 Hz, use [`SampleRate::try_from`]. At 44.1 kHz and 48 kHz, the +/// processor runs directly at that rate. At other rates, a fixed-point +/// polyphase resampler converts to and from the 44.1 kHz or 48 kHz core. 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,14 +30,21 @@ pub enum SampleRate { Hz44100, /// 48 kHz. Hz48000, + /// Another integer rate in 8000..=192000 Hz, from [`Self::try_from`]. + #[non_exhaustive] + Custom { + /// The rate in hertz, 8000..=192000, except 44,100 and 48,000. + hz: u32, + }, } impl SampleRate { - /// Returns the rate in hertz. + /// Returns the rate in hertz, 8000..=192000. pub const fn as_u32(self) -> u32 { match self { Self::Hz44100 => 44_100, Self::Hz48000 => 48_000, + Self::Custom { hz } => hz, } } @@ -38,22 +52,39 @@ impl SampleRate { pub fn hz(self) -> f32 { self.as_u32() as f32 } + + /// Selects the 44.1 kHz or 48 kHz internal core rate for this host rate. + /// + /// Multiples and divisors of 44,100 Hz use the 44.1 kHz core. All other + /// rates use the 48 kHz core. + pub(crate) const fn core_rate(self) -> Self { + let hz = self.as_u32(); + if hz == 44_100 || hz == 48_000 { + self + } else if hz.is_multiple_of(44_100) || 44_100_u32.is_multiple_of(hz) { + Self::Hz44100 + } else { + Self::Hz48000 + } + } } impl TryFrom for SampleRate { type Error = Error; - /// Converts a device sample rate in hertz. + /// Converts a device sample rate in hertz, 8000..=192000. + /// + /// Returns [`Self::Hz44100`] for 44,100 and [`Self::Hz48000`] for 48,000. /// /// # 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. + /// Returns [`Error::UnsupportedSampleRate`] with `hz` if `hz` is outside + /// 8000..=192000. fn try_from(hz: u32) -> Result { match hz { 44_100 => Ok(Self::Hz44100), 48_000 => Ok(Self::Hz48000), + MIN_SAMPLE_RATE_HZ..=MAX_SAMPLE_RATE_HZ => Ok(Self::Custom { hz }), _ => Err(Error::UnsupportedSampleRate { hz }), } } diff --git a/src/error.rs b/src/error.rs index b971968..850f921 100644 --- a/src/error.rs +++ b/src/error.rs @@ -9,7 +9,7 @@ use std::fmt; #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub enum Error { - /// The numeric rate has no [`crate::SampleRate`] variant that matches it. + /// The sample rate is outside 8000..=192000 Hz. UnsupportedSampleRate { /// The unsupported rate, in hertz. hz: u32, diff --git a/src/events.rs b/src/events.rs index e1c975c..c03a661 100644 --- a/src/events.rs +++ b/src/events.rs @@ -178,4 +178,10 @@ impl<'a> ValidatedEvents<'a> { self.remaining = remaining; Some(ValidatedEvent(event.event)) } + + /// Returns the offset of the next event without consumption, or `None` if + /// no events remain. + pub(crate) fn peek_offset(&self) -> Option { + self.remaining.first().map(|event| event.offset) + } } diff --git a/src/lib.rs b/src/lib.rs index 0e29119..a1e97c1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,9 @@ //! 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 +//! or mono frames. The sample rate is an integer in 8000..=192000 Hz. At rates +//! other than 44.1 kHz and 48 kHz, a fixed-point polyphase resampler converts +//! to and from the 44.1 kHz or 48 kHz core. 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. @@ -52,9 +54,9 @@ //! 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 +//! delay in host frames. 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 @@ -115,6 +117,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..4eef7f6 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, PrepareConfig, ProcessorConfig, SampleRate, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -27,6 +28,11 @@ use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; pub struct Processor { /// The fixed rate and the block limit for each call. preparation: PrepareConfig, + /// The internal 44.1 kHz or 48 kHz rate for the DSP stages. + core_rate: SampleRate, + /// The optional polyphase rate converter for host rates other than 44.1 + /// kHz and 48 kHz. + resampler: Option, /// The settings that the host sees. /// /// The temporary aspiration mute of a drain is not stored here. @@ -91,8 +97,7 @@ impl Processor { /// stream starts from the low 32 bits of `random_seed`. /// /// Punch uses its default cached drive until the first window of 100 - /// frames with Punch enabled. The initial note table of correction has the - /// rate behavior that [`crate::CorrectionConfig`] describes. + /// frames with Punch enabled. /// /// # Errors /// @@ -102,18 +107,22 @@ 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 host_rate = preparation.sample_rate; + let core_rate = host_rate.core_rate(); + let resampler = Resampler::new(host_rate, core_rate, preparation.max_block_frames.get())?; // Drive uses the default gain until the first 100-frame peak window. - let mut punch = Punch::new(rate, PunchConfig::default()); + let mut punch = Punch::new(core_rate, PunchConfig::default()); punch.set_config(config.punch); Ok(Self { preparation, + core_rate, + resampler, config, punch, - warm: Warm::new(rate, config.warm), - resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), + warm: Warm::new(core_rate, config.warm), + resynthesis: Box::new(Resynthesis::new(core_rate, config.resynthesis)), alien: Alien::new(config.alien), - reverb: Reverb::new(rate, config.reverb), + reverb: Reverb::new(core_rate, config.reverb), numeric: NumericContext::new(config.resynthesis.random_seed as u32), peak: 0, input_peak: 0, @@ -201,12 +210,28 @@ impl Processor { ) -> Result<(), Error> { let mut events = self.validate(audio, events)?; self.drain_remaining = None; - for (index, sample) in audio.iter_mut().enumerate() { - while let Some(event) = events.next_at(index) { + if self.resampler.is_none() { + for (index, sample) in audio.iter_mut().enumerate() { + while let Some(event) = events.next_at(index) { + self.apply(event); + } + let output = self.next(*sample); + *sample = ((output[0] as i32 + output[1] as i32) >> 1) as i16; + } + return Ok(()); + } + let mut cursor = 0; + while cursor < audio.len() { + while let Some(event) = events.next_at(cursor) { self.apply(event); } - let output = self.next(*sample); - *sample = ((output[0] as i32 + output[1] as i32) >> 1) as i16; + let end = events.peek_offset().unwrap_or(audio.len()); + let core_count = self.run_resampled_core(&audio[cursor..end]); + let slice = &mut audio[cursor..end]; + self.finish_resampled_output(core_count, slice.len(), |index, frame| { + slice[index] = ((i32::from(frame[0]) + i32::from(frame[1])) >> 1) as i16; + }); + cursor = end; } Ok(()) } @@ -291,20 +316,23 @@ impl Processor { Ok(count) } - /// Returns the finite tail budget for the current configuration. + /// Returns the finite tail budget in host frames for the current + /// configuration. /// /// 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. pub fn tail_frames(&self) -> usize { - self.resynthesis + let core_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(self.core_rate, self.config.reverb)); + match &self.resampler { + Some(resampler) => resampler.tail_frames(core_tail), + None => core_tail, + } } /// Returns the fixed sample rate and block limit. @@ -322,13 +350,18 @@ 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. + /// At 44.1 kHz and 48 kHz, the value is 1,593 frames and the dry path has + /// a delay of 1,543 frames. At other rates, the value scales the core + /// delay to host frames and adds the polyphase filter delay. 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 + match &self.resampler { + Some(resampler) => resampler.latency_frames(resynthesis::LATENCY_FRAMES), + None => resynthesis::LATENCY_FRAMES, + } } /// Returns the pitch, stereo peak and frame count, and does not clear them. @@ -336,9 +369,15 @@ 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 period_samples = if self.resampler.is_some() { + (f64::from(estimate.period_samples) * f64::from(self.preparation.sample_rate.as_u32()) + / f64::from(self.core_rate.as_u32())) as f32 + } else { + estimate.period_samples + }; Feedback { resample_ratio: self.last_resample_ratio, - period_samples: estimate.period_samples, + period_samples, frequency_hz: estimate.frequency_hz, target_midi_note: self.resynthesis.target_note(), voiced: estimate.voiced, @@ -536,6 +575,9 @@ impl Processor { /// When the method clears the held keys, it does not load the configured /// scale again. For a fully new state, make a new processor. pub fn reset(&mut self) { + if let Some(resampler) = &mut self.resampler { + resampler.reset(); + } self.punch.reset(); self.warm.reset(); self.resynthesis.reset(); @@ -602,14 +644,8 @@ impl Processor { self.apply_config(config); } - /// 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] { - self.input_peak = self.input_peak.max((input as i32).abs()); + /// Renders one core frame through the stages without host meter updates. + fn next_core(&mut self, mut input: i16) -> [i16; 2] { if self.config.punch.enabled { input = self.punch.process_sample(input, &mut self.numeric); } @@ -621,11 +657,17 @@ impl Processor { 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| { + reverb.map(|sample| { (sample.to_bits().wrapping_mul(gain) >> 8) .wrapping_shl(1) .clamp(-32767, 32767) as i16 - }); + }) + } + + /// Updates the stereo peaks and the host frame counter for one output + /// frame. + #[inline] + fn record_output(&mut self, result: [i16; 2]) { self.peak = self .peak .max((result[0] as i32).abs()) @@ -634,9 +676,76 @@ impl Processor { *peak = (*peak).max((sample as i32).abs()); } self.frames = self.frames.saturating_add(1); + } + + /// 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, input: i16) -> [i16; 2] { + self.input_peak = self.input_peak.max((input as i32).abs()); + let result = self.next_core(input); + self.record_output(result); result } + /// Resamples a host input segment and runs the internal core stages on the + /// generated core frames. + fn run_resampled_core(&mut self, input: &[i16]) -> usize { + for &sample in input { + self.input_peak = self.input_peak.max(i32::from(sample).abs()); + } + let core_count = self + .resampler + .as_mut() + .expect("resampler active") + .resample_input(input); + for index in 0..core_count { + let sample = self + .resampler + .as_ref() + .expect("resampler active") + .core_input[index]; + let frame = self.next_core(sample); + self.resampler + .as_mut() + .expect("resampler active") + .core_output[index] = frame; + } + core_count + } + + /// Resamples the current `core_output` prefix to `host_frames` stereo + /// frames and updates output meters. + fn finish_resampled_output( + &mut self, + core_count: usize, + host_frames: usize, + mut write: impl FnMut(usize, [i16; 2]), + ) { + let mut peak = self.peak; + let mut output_peaks = self.output_peaks; + let mut frames = self.frames; + self.resampler + .as_mut() + .expect("resampler active") + .resample_output(core_count, host_frames, |index, frame| { + peak = peak + .max(i32::from(frame[0]).abs()) + .max(i32::from(frame[1]).abs()); + for (channel_peak, sample) in output_peaks.iter_mut().zip(frame) { + *channel_peak = (*channel_peak).max(i32::from(sample).abs()); + } + frames = frames.saturating_add(1); + write(index, frame); + }); + self.peak = peak; + self.output_peaks = output_peaks; + self.frames = frames; + } + /// Checks the block, applies all controls at each offset and writes each /// rendered frame. /// @@ -649,11 +758,26 @@ impl Processor { ) -> Result<(), Error> { let mut events = self.validate(input, events)?; self.drain_remaining = None; - for (index, sample) in input.iter().enumerate() { - while let Some(event) = events.next_at(index) { + if self.resampler.is_none() { + for (index, sample) in input.iter().enumerate() { + while let Some(event) = events.next_at(index) { + self.apply(event); + } + write(index, self.next(*sample)); + } + return Ok(()); + } + let mut cursor = 0; + while cursor < input.len() { + while let Some(event) = events.next_at(cursor) { self.apply(event); } - write(index, self.next(*sample)); + let end = events.peek_offset().unwrap_or(input.len()); + let core_count = self.run_resampled_core(&input[cursor..end]); + self.finish_resampled_output(core_count, end - cursor, |index, frame| { + write(cursor + index, frame); + }); + cursor = end; } Ok(()) } @@ -679,8 +803,29 @@ impl Processor { // Zero aspiration is valid in all validated configurations. self.resynthesis.apply_config(silent); } - for index in 0..count { - write(index, self.next(0)); + if self.resampler.is_none() { + for index in 0..count { + write(index, self.next(0)); + } + } else if count > 0 { + let core_count = self + .resampler + .as_mut() + .expect("resampler active") + .resample_silence(count); + for index in 0..core_count { + let sample = self + .resampler + .as_ref() + .expect("resampler active") + .core_input[index]; + let frame = self.next_core(sample); + self.resampler + .as_mut() + .expect("resampler active") + .core_output[index] = frame; + } + self.finish_resampled_output(core_count, count, write); } if configured.formant.aspiration_mix != 0.0 { self.resynthesis.apply_config(configured); diff --git a/src/resample.rs b/src/resample.rs new file mode 100644 index 0000000..f4f1efa --- /dev/null +++ b/src/resample.rs @@ -0,0 +1,411 @@ +//! The fixed-point polyphase sinc rate converter around the internal DSP core. +//! +//! At host rates other than 44,100 Hz and 48,000 Hz, this module converts +//! mono PCM input to the core rate and converts stereo PCM output back to the +//! host rate. Construction precomputes Q14 polyphase FIR tables and allocates +//! the conversion buffers. Audio calls use 32-bit integer phase accumulators +//! and Q14 dot products without heap allocation or floating-point operations. + +use crate::error::ConfigProblem; +use crate::numeric::fixed::Q14; +use crate::numeric::round_q14; +use crate::{Error, SampleRate}; +use std::f64::consts::PI; + +/// The number of fractional phase intervals in each polyphase table. +/// +/// Each table stores `PHASES + 1` branches so rounded phase lookups stay in +/// bounds at both endpoints of the unit interval. +const PHASES: usize = 512; + +/// The half-length in taps of the prototype sinc filter before expansion for +/// lower output rates. +const BASE_HALF_TAPS: usize = 12; + +/// The normalized low-pass cutoff relative to the lower Nyquist frequency. +const CUTOFF_RATIO: f64 = 0.90; + +/// The preallocated mono-input and stereo-output polyphase rate converters. +#[derive(Debug)] +pub(crate) struct Resampler { + /// The host sample rate in hertz. + host_hz: u32, + /// The internal core sample rate in hertz (44,100 or 48,000). + core_hz: u32, + /// The reduced host step (`host_hz / gcd`). + host_step: u32, + /// The reduced core step (`core_hz / gcd`). + core_step: u32, + /// The mono polyphase filter from the host rate to the core rate. + input_filter: MonoPolyphase, + /// The stereo polyphase filter from the core rate to the host rate. + output_filter: StereoPolyphase, + /// The preallocated mono core samples for one host block. + pub(crate) core_input: Vec, + /// The preallocated stereo core frames for one host block. + pub(crate) core_output: Vec<[i16; 2]>, +} + +/// A mono polyphase FIR filter with a double-length contiguous history ring. +#[derive(Debug)] +struct MonoPolyphase { + /// The flattened `(PHASES + 1) * taps` Q14 coefficients. + table: Vec, + /// A double-length ring of size `2 * taps` for contiguous slice reads. + history: Vec, + /// The number of taps in each polyphase branch. + taps: usize, + /// Half of `taps`, equal to the nominal delay in input frames. + half: usize, + /// The write cursor in `0..taps`. + write: usize, + /// The 32-bit modular phase accumulator. + phase: u32, +} + +/// A stereo polyphase FIR filter with a double-length contiguous history ring. +#[derive(Debug)] +struct StereoPolyphase { + /// The flattened `(PHASES + 1) * taps` Q14 coefficients. + table: Vec, + /// A double-length stereo ring of size `2 * taps`. + history: Vec<[i16; 2]>, + /// The number of taps in each polyphase branch. + taps: usize, + /// Half of `taps`, equal to the nominal delay in core frames. + half: usize, + /// The write cursor in `0..taps`. + write: usize, + /// The 32-bit modular phase accumulator, locked to `MonoPolyphase::phase`. + phase: u32, +} + +impl Resampler { + /// Precomputes Q14 polyphase tables and allocates conversion buffers for + /// `max_block_frames`. + /// + /// Returns `Ok(None)` at 44,100 Hz and 48,000 Hz so the processor bypasses + /// rate conversion. + pub(crate) fn new( + host_rate: SampleRate, + core_rate: SampleRate, + max_block_frames: usize, + ) -> Result, Error> { + let host_hz = host_rate.as_u32(); + let core_hz = core_rate.as_u32(); + if host_hz == core_hz { + return Ok(None); + } + let divisor = gcd(host_hz, core_hz); + let host_step = host_hz / divisor; + let core_step = core_hz / divisor; + + let max_core_u128 = + (max_block_frames as u128 * core_step as u128).div_ceil(host_step as u128); + let max_limit = (isize::MAX as usize) / std::mem::size_of::<[i16; 2]>(); + if max_core_u128 > max_limit as u128 { + return Err(Error::config( + "prepare.max_block_frames", + ConfigProblem::OutOfRange { + min: 1.0, + max: ((max_limit as u128 * host_step as u128) / core_step as u128) as f64, + }, + )); + } + let max_core_frames = max_core_u128 as usize; + + let mut core_input = Vec::new(); + core_input.try_reserve_exact(max_core_frames).map_err(|_| { + Error::config( + "prepare.max_block_frames", + ConfigProblem::OutOfRange { + min: 1.0, + max: max_limit as f64, + }, + ) + })?; + core_input.resize(max_core_frames, 0); + + let mut core_output = Vec::new(); + core_output + .try_reserve_exact(max_core_frames) + .map_err(|_| { + Error::config( + "prepare.max_block_frames", + ConfigProblem::OutOfRange { + min: 1.0, + max: max_limit as f64, + }, + ) + })?; + core_output.resize(max_core_frames, [0; 2]); + + Ok(Some(Self { + host_hz, + core_hz, + host_step, + core_step, + input_filter: MonoPolyphase::new(host_hz, core_hz), + output_filter: StereoPolyphase::new(core_hz, host_hz), + core_input, + core_output, + })) + } + + /// Clears both filter histories and resets both phase accumulators to zero. + pub(crate) fn reset(&mut self) { + self.input_filter.reset(); + self.output_filter.reset(); + } + + /// Converts `input` from the host rate into `self.core_input` and returns + /// the number of generated core frames. + pub(crate) fn resample_input(&mut self, input: &[i16]) -> usize { + let mut core_count = 0; + let host_step = self.host_step; + let core_step = self.core_step; + let half_core = core_step >> 1; + for &sample in input { + self.input_filter.push(sample); + while self.input_filter.phase < core_step { + let phase_index = + ((self.input_filter.phase * PHASES as u32 + half_core) / core_step) as usize; + self.core_input[core_count] = self.input_filter.evaluate(phase_index); + core_count += 1; + self.input_filter.phase += host_step; + } + self.input_filter.phase -= core_step; + } + core_count + } + + /// Converts `host_frames` of silent host input into `self.core_input` and + /// returns the number of generated core frames. + pub(crate) fn resample_silence(&mut self, host_frames: usize) -> usize { + let mut core_count = 0; + let host_step = self.host_step; + let core_step = self.core_step; + let half_core = core_step >> 1; + for _ in 0..host_frames { + self.input_filter.push(0); + while self.input_filter.phase < core_step { + let phase_index = + ((self.input_filter.phase * PHASES as u32 + half_core) / core_step) as usize; + self.core_input[core_count] = self.input_filter.evaluate(phase_index); + core_count += 1; + self.input_filter.phase += host_step; + } + self.input_filter.phase -= core_step; + } + core_count + } + + /// Converts `core_count` frames from `self.core_output` into `host_frames` + /// stereo frames at the host rate. + pub(crate) fn resample_output( + &mut self, + core_count: usize, + host_frames: usize, + mut write: impl FnMut(usize, [i16; 2]), + ) { + let mut core_index = 0; + let host_step = self.host_step; + let core_step = self.core_step; + let half_host = host_step >> 1; + for host_index in 0..host_frames { + while self.output_filter.phase < core_step { + self.output_filter.push(self.core_output[core_index]); + core_index += 1; + self.output_filter.phase += host_step; + } + self.output_filter.phase -= core_step; + let lag_index = + ((self.output_filter.phase * PHASES as u32 + half_host) / host_step) as usize; + let frame = self.output_filter.evaluate(PHASES - lag_index); + write(host_index, frame); + } + debug_assert_eq!(core_index, core_count); + } + + /// Returns the total nominal latency in host frames from `core_latency`. + pub(crate) fn latency_frames(&self, core_latency: usize) -> usize { + let core_total = (core_latency + self.output_filter.half) as u64; + let scaled = (core_total * u64::from(self.host_hz) + u64::from(self.core_hz / 2)) + / u64::from(self.core_hz); + self.input_filter.half.saturating_add(scaled as usize) + } + + /// Converts a core tail budget into a host frame budget that also flushes + /// both polyphase filters. + pub(crate) fn tail_frames(&self, core_tail: usize) -> usize { + let core_total = core_tail.saturating_add(self.output_filter.taps) as u128; + let host_tail = (core_total * self.host_hz as u128).div_ceil(self.core_hz as u128); + self.input_filter.taps.saturating_add(host_tail as usize) + } +} + +impl MonoPolyphase { + /// Builds a mono polyphase sinc filter for `in_hz` to `out_hz`. + fn new(in_hz: u32, out_hz: u32) -> Self { + let (table, taps, half) = build_polyphase_table(in_hz, out_hz); + Self { + table, + history: vec![0; 2 * taps], + taps, + half, + write: 0, + phase: 0, + } + } + + /// Clears the sample history and sets the phase accumulator to zero. + fn reset(&mut self) { + self.history.fill(0); + self.write = 0; + self.phase = 0; + } + + /// Stores one input sample into both halves of the contiguous ring. + #[inline] + fn push(&mut self, sample: i16) { + self.history[self.write] = sample; + self.history[self.write + self.taps] = sample; + self.write += 1; + if self.write == self.taps { + self.write = 0; + } + } + + /// Evaluates one polyphase FIR branch in Q14 fixed-point arithmetic. + #[inline] + fn evaluate(&self, phase_index: usize) -> i16 { + let samples = &self.history[self.write..self.write + self.taps]; + let offset = phase_index * self.taps; + let coeffs = &self.table[offset..offset + self.taps]; + let mut sum: i32 = 0; + for (&sample, &coeff) in samples.iter().zip(coeffs) { + sum = sum.wrapping_add(i32::from(sample).wrapping_mul(coeff.to_bits())); + } + round_q14(sum).clamp(-32768, 32767) as i16 + } +} + +impl StereoPolyphase { + /// Builds a stereo polyphase sinc filter for `in_hz` to `out_hz`. + fn new(in_hz: u32, out_hz: u32) -> Self { + let (table, taps, half) = build_polyphase_table(in_hz, out_hz); + Self { + table, + history: vec![[0; 2]; 2 * taps], + taps, + half, + write: 0, + phase: 0, + } + } + + /// Clears the stereo sample history and sets the phase accumulator to zero. + fn reset(&mut self) { + self.history.fill([0; 2]); + self.write = 0; + self.phase = 0; + } + + /// Stores one stereo frame into both halves of the contiguous ring. + #[inline] + fn push(&mut self, frame: [i16; 2]) { + self.history[self.write] = frame; + self.history[self.write + self.taps] = frame; + self.write += 1; + if self.write == self.taps { + self.write = 0; + } + } + + /// Evaluates one polyphase FIR branch on both channels and clips to + /// `-32767..=32767`. + #[inline] + fn evaluate(&self, phase_index: usize) -> [i16; 2] { + let frames = &self.history[self.write..self.write + self.taps]; + let offset = phase_index * self.taps; + let coeffs = &self.table[offset..offset + self.taps]; + let mut left: i32 = 0; + let mut right: i32 = 0; + for (&frame, &coeff) in frames.iter().zip(coeffs) { + let weight = coeff.to_bits(); + left = left.wrapping_add(i32::from(frame[0]).wrapping_mul(weight)); + right = right.wrapping_add(i32::from(frame[1]).wrapping_mul(weight)); + } + [ + round_q14(left).clamp(-32767, 32767) as i16, + round_q14(right).clamp(-32767, 32767) as i16, + ] + } +} + +/// Computes the `(PHASES + 1) * taps` table of Q14 windowed-sinc coefficients. +/// +/// Each polyphase branch is normalized so its Q14 integer sum equals `16384`. +fn build_polyphase_table(in_hz: u32, out_hz: u32) -> (Vec, usize, usize) { + let ratio = f64::from(out_hz) / f64::from(in_hz); + let (half, cutoff) = if out_hz < in_hz { + ( + (BASE_HALF_TAPS as f64 / ratio).ceil() as usize, + CUTOFF_RATIO * ratio, + ) + } else { + (BASE_HALF_TAPS, CUTOFF_RATIO) + }; + let taps = 2 * half; + let mut table = Vec::with_capacity((PHASES + 1) * taps); + let mut weights = vec![0.0_f64; taps]; + + for phase in 0..=PHASES { + let fraction = phase as f64 / PHASES as f64; + let center = (half - 1) as f64 + fraction; + let mut weight_sum = 0.0_f64; + for (tap, slot) in weights.iter_mut().enumerate() { + let delta = center - tap as f64; + let window_pos = delta / half as f64; + if window_pos.abs() >= 1.0 { + *slot = 0.0; + } else { + let window = 0.4243801 + + 0.4973406 * (PI * window_pos).cos() + + 0.0782793 * (2.0 * PI * window_pos).cos(); + let arg = delta * cutoff; + let sinc = if arg.abs() < 1e-12 { + 1.0 + } else { + (PI * arg).sin() / (PI * arg) + }; + let value = window * sinc * cutoff; + *slot = value; + weight_sum += value; + } + } + + let start = table.len(); + let mut quantized_sum: i32 = 0; + for &weight in &weights { + let q = ((weight / weight_sum) * 16384.0).round() as i32; + quantized_sum += q; + table.push(Q14::from_bits(q)); + } + let center_tap = if fraction < 0.5 { half - 1 } else { half }; + let adjusted = table[start + center_tap].to_bits() + (16_384 - quantized_sum); + table[start + center_tap] = Q14::from_bits(adjusted); + } + + (table, taps, half) +} + +/// Returns the greatest common divisor of two positive sample rates. +const fn gcd(mut a: u32, mut b: u32) -> u32 { + while b != 0 { + let remainder = a % b; + a = b; + b = remainder; + } + a +} diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..73f1093 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -119,10 +119,10 @@ pub struct WasmProcessor { impl WasmProcessor { /// Prepares a processor and its reusable PCM buffers. /// - /// `sample_rate` must be 44100 or 48000. `max_block_frames` must be an - /// 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 + /// `sample_rate` must be an integer in 8000..=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 PCM buffers. In /// TypeScript, use `new Tunelet(sampleRate, maxBlockFrames, config)`. /// @@ -130,7 +130,7 @@ impl WasmProcessor { /// /// The constructor throws if one of these conditions occurs: /// - /// - The rate is not 44100 or 48000. + /// - The rate is not an integer or is outside 8000..=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. @@ -146,11 +146,14 @@ impl WasmProcessor { ) -> Result { // Accept JavaScript numbers without the u32 coercion of wasm-bindgen. // That coercion silently truncates fractions and wraps large values. - let rate = match sample_rate { - 44100.0 => SampleRate::Hz44100, - 48000.0 => SampleRate::Hz48000, - _ => return Err(JsError::new("sampleRate must be 44100 or 48000")), - }; + let min_rate = f64::from(crate::config::MIN_SAMPLE_RATE_HZ); + let max_rate = f64::from(crate::config::MAX_SAMPLE_RATE_HZ); + if !(min_rate..=max_rate).contains(&sample_rate) || sample_rate.fract() != 0.0 { + return Err(JsError::new( + "sampleRate must be an integer in 8000..=192000", + )); + } + let rate = SampleRate::try_from(sample_rate as u32)?; if !(1.0..=f64::from(u32::MAX)).contains(&max_block_frames) || max_block_frames.fract() != 0.0 { From e7590de46801a15ea80fe0e941e4297d3bff1ce6 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:26:27 +0000 Subject: [PATCH 3/6] fix(formant): zero-fill envelopes above the core Nyquist limit - Write zero for formant envelope points above half of the core rate. - Document the core rate selection on SampleRate. - Document the formant envelope limit in Rust, Wasm and the README. - Align the Feedback latency field documentation with Processor. --- README.md | 10 +++++++--- src/config.rs | 12 +++++++----- src/formant.rs | 11 ++++++++++- src/processor.rs | 7 +++++-- src/wasm.rs | 3 ++- 5 files changed, 31 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index f765d29..ace68ed 100644 --- a/README.md +++ b/README.md @@ -325,7 +325,9 @@ voices, choir delays and effects use different delays. The values are linear and have no absolute level. The formant stage must be enabled. The envelopes are those of the model that the audio used for the -last frame. The method returns `Result`: +last frame. If the sample rate is above the internal core rate, the method +writes zero for frequencies above half of the core rate. The method returns +`Result`: | Result | Description | | ----------- | ---------------------------------------------------------------- | @@ -501,8 +503,10 @@ buffers of equal length and returns `false` if no envelope is available. In that case, it fills both buffers with zeros. If the lengths are not equal or the frequency is not valid, it throws and does not change the buffers. The frequency must be finite, more than zero and not more than half of the sample -rate. The class keeps a buffer for the points, so only the first call and a -call with more points than before reserve memory. +rate. If the sample rate is above the internal core rate, the method writes +zero for frequencies above half of the core rate. The class keeps a buffer for +the points, so only the first call and a call with more points than before +reserve memory. ### Memory allocation diff --git a/src/config.rs b/src/config.rs index f4e883d..0249e0f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -17,11 +17,13 @@ pub(crate) const MAX_SAMPLE_RATE_HZ: u32 = 192_000; /// The sample rate of the input and the output, 8000..=192000 Hz. /// /// The default is 44.1 kHz. To convert an integer device rate in -/// 8000..=192000 Hz, use [`SampleRate::try_from`]. At 44.1 kHz and 48 kHz, the -/// processor runs directly at that rate. At other rates, a fixed-point -/// polyphase resampler converts to and from the 44.1 kHz or 48 kHz core. The -/// rate of a processor is fixed at construction. To change the rate, you must -/// make a new processor. +/// 8000..=192000 Hz, use [`SampleRate::try_from`]. The rate of a processor is +/// fixed at construction. To change the rate, you must make a new processor. +/// +/// At 44.1 kHz and 48 kHz, the processor runs directly at that rate. At other +/// rates, a fixed-point polyphase resampler converts to and from an internal +/// core rate. Multiples and divisors of 44,100 Hz use the 44.1 kHz core. All +/// other rates use the 48 kHz core. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] #[non_exhaustive] pub enum SampleRate { diff --git a/src/formant.rs b/src/formant.rs index 7c59008..947a1a6 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -770,7 +770,8 @@ impl Formant { /// `input` gets the vocal-tract envelope from the analysis. `output` gets /// the envelope of the synthesis model, which includes the width gain. /// The two responses include the glottal de-emphasis. Point `k` of `n` is - /// at the frequency `max_frequency_hz * k / (n - 1)`. The values are + /// at the frequency `max_frequency_hz * k / (n - 1)`. Points at + /// frequencies above half of the stage rate are zero. The values are /// linear and have no absolute level, because the analysis normalizes the /// signal energy. /// @@ -806,6 +807,9 @@ impl Formant { } else { 0.0 }; + let core_nyquist = f64::from(self.rate.as_u32()) * 0.5; + let max_hz = f64::from(max_frequency_hz); + let nyquist_scaled = core_nyquist * points.saturating_sub(1) as f64; let glottal = self.glottal as f64 / 16384.0; let width = self.width as f64 / 16384.0; // |1 - sum(c[i] * z^-(i+1))| at z = e^(j * omega). @@ -821,6 +825,11 @@ impl Formant { (real * real + imaginary * imaginary).sqrt().max(1e-6) }; for (k, (input, output)) in input.iter_mut().zip(output.iter_mut()).enumerate() { + if points > 1 && max_hz > core_nyquist && max_hz * k as f64 > nyquist_scaled { + *input = 0.0; + *output = 0.0; + continue; + } let omega = step * k as f64; let (sine, cosine) = omega.sin_cos(); let emphasis = ((1.0 - glottal * cosine).powi(2) + (glottal * sine).powi(2)) diff --git a/src/processor.rs b/src/processor.rs index 02e79d7..e84e7eb 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -441,7 +441,9 @@ impl Processor { /// analysis normalizes the signal energy. Scale them for a display. /// /// `max_frequency_hz` must be finite, more than zero and not more than - /// half of the sample rate. The two slices must have the same length. + /// half of the sample rate. If the sample rate is above the internal core + /// rate, the method writes zero for frequencies above half of the core + /// rate. The two slices must have the same length. /// /// Returns `Ok(true)` if the envelopes are valid. Returns `Ok(false)` and /// fills the two slices with zeros in these cases: @@ -977,7 +979,8 @@ pub struct Feedback { /// The count saturates at `u64::MAX`. Drain completion resets it in the /// last drain call. pub processed_frames: u64, - /// The nominal resynthesis latency, as [`Processor::latency_frames`] gives. + /// The nominal latency in host frames, as [`Processor::latency_frames`] + /// gives. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), serde(serialize_with = "crate::wasm::serialize_frame_count"), diff --git a/src/wasm.rs b/src/wasm.rs index 6be8143..921d8f9 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -451,7 +451,8 @@ impl WasmProcessor { /// display. /// /// `maxFrequencyHz` must be finite, more than zero and not more than half - /// of the sample rate. + /// of the sample rate. If the sample rate is above the internal core rate, + /// the method writes zero for frequencies above half of the core rate. /// /// The method returns `true` if the envelopes are valid. It returns /// `false` and fills the two arrays with zeros if the formant stage is From ce0ac1910c65fa949fa99df5ae795064fae387d0 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:27:54 +0000 Subject: [PATCH 4/6] fix(resample): subtract one host frame in latency_frames - Subtract one host frame from input_filter.half in latency_frames. --- src/resample.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/resample.rs b/src/resample.rs index 908347a..ea10bab 100644 --- a/src/resample.rs +++ b/src/resample.rs @@ -221,7 +221,10 @@ impl Resampler { let core_total = (core_latency + self.output_filter.half) as u64; let scaled = (core_total * u64::from(self.host_hz) + u64::from(self.core_hz / 2)) / u64::from(self.core_hz); - self.input_filter.half.saturating_add(scaled as usize) + self.input_filter + .half + .saturating_sub(1) + .saturating_add(scaled as usize) } /// Converts a core tail budget into a host frame budget that also flushes From 935b6976975980a9861f8085fc53a88e24421e85 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:27:55 +0000 Subject: [PATCH 5/6] docs(processor): document max_block_frames error in Processor::new - Note InvalidConfig for prepare.max_block_frames at resampled rates. --- src/processor.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/processor.rs b/src/processor.rs index ef9bd45..607e4f1 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -131,8 +131,11 @@ impl Processor { /// /// Returns [`Error::InvalidConfig`] if a stage field or the output gain is /// not valid. This check occurs before the allocation of the histories. - /// The types of `preparation` already make sure that the block limit is - /// not zero and that the sample rate is supported. + /// At resampled rates, if the scaled core buffers for + /// `prepare.max_block_frames` exceed the size limit or fail to allocate, + /// the method also returns [`Error::InvalidConfig`]. The types of + /// `preparation` already make sure that the block limit is not zero and + /// that the sample rate is supported. pub fn new(preparation: PrepareConfig, config: ProcessorConfig) -> Result { config.validate()?; let host_rate = preparation.sample_rate; From b823186efb6accae0c48d0f2a53ef9f741fbfca1 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:27:56 +0000 Subject: [PATCH 6/6] test(npm): add resampled sample rate checks in verify-pack - Check invalid sample rates in verifyRuntimeImport. - Check 8 kHz and 96 kHz audio, feedback, telemetry and drain. --- scripts/verify-pack.mjs | 62 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..b03f309 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -561,6 +561,68 @@ function verifyRuntimeImport(consumerDir, packageName) { 'assert.equal(typeof disposableProcessor[Symbol.dispose], "function");', "disposableProcessor[Symbol.dispose]();", "", + "assert.throws(() => new rootModule.Tunelet(7999, 128));", + "assert.throws(() => new rootModule.Tunelet(192001, 128));", + "assert.throws(() => new rootModule.Tunelet(44100.5, 128));", + "", + "const resampled8k = new rootModule.Tunelet(8000, 128, config);", + "try {", + " assert.equal(resampled8k.sampleRate, 8000);", + " assert.equal(resampled8k.latencyFrames, 289);", + " const in8k = new Int16Array(128);", + " const left8k = new Int16Array(128);", + " const right8k = new Int16Array(128);", + " for (let block = 0; block < 24; block++) {", + " for (let i = 0; i < 128; i++) {", + " in8k[i] = Math.round(0.6 * Math.sin(((block * 128 + i) * 2 * Math.PI * 220) / 8000) * 32767);", + " }", + " resampled8k.process(in8k, left8k, right8k);", + " }", + " const fb8k = resampled8k.feedback();", + " const tel8k = resampled8k.telemetry();", + " assert.equal(fb8k.processedFrames, 3072n);", + " assert.equal(fb8k.latencyFrames, 289);", + " assert.equal(fb8k.voiced, true);", + " assert.equal(fb8k.targetMidiNote, 57);", + " assert.ok(Math.abs(fb8k.periodSamples - 8000 / 220) < 0.5);", + " assert.equal(tel8k.periodSamples, fb8k.periodSamples);", + " assert.ok(resampled8k.beginDrain() > 0);", + " assert.equal(resampled8k.drain(left8k, right8k), 128);", + "} finally {", + " resampled8k.free();", + "}", + "", + "const resampled96k = new rootModule.Tunelet(96000, 256, config);", + "try {", + " assert.equal(resampled96k.sampleRate, 96000);", + " assert.equal(resampled96k.latencyFrames, 3233);", + " const in96k = new Float32Array(256);", + " const left96k = new Float32Array(256);", + " const right96k = new Float32Array(256);", + " for (let block = 0; block < 40; block++) {", + " for (let i = 0; i < 256; i++) {", + " in96k[i] = Math.fround(0.6 * Math.sin(((block * 256 + i) * 2 * Math.PI * 440) / 96000));", + " }", + " resampled96k.processF32(in96k, left96k, right96k);", + " }", + " const fb96k = resampled96k.feedback();", + " const tel96k = resampled96k.telemetry();", + " assert.equal(fb96k.processedFrames, 10240n);", + " assert.equal(fb96k.latencyFrames, 3233);", + " assert.equal(fb96k.voiced, true);", + " assert.equal(fb96k.targetMidiNote, 69);", + " assert.ok(Math.abs(fb96k.periodSamples - 96000 / 440) < 1.0);", + " assert.equal(tel96k.periodSamples, fb96k.periodSamples);", + " const envIn96k = new Float32Array(65);", + " const envOut96k = new Float32Array(65);", + " assert.equal(resampled96k.formantEnvelope(48000, envIn96k, envOut96k), true);", + " assert.ok(envIn96k[8] > 0);", + " assert.equal(envIn96k[64], 0);", + " assert.equal(envOut96k[64], 0);", + "} finally {", + " resampled96k.free();", + "}", + "", ].join("\n"), );