diff --git a/README.md b/README.md index a06715f..cbd823a 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ browsers and Node.js. only safe Rust. The input is mono signed 16-bit PCM or normalized 32-bit floating-point audio -at 44.1 kHz or 48 kHz. The output is stereo or mono in 16-bit PCM or 32-bit -floating-point form. +at an integer rate in 8000..=192000 Hz. The output is stereo or mono in 16-bit +PCM or 32-bit floating-point form. ## Installation @@ -360,7 +360,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 | `Processor::control_activity()` and `ProcessorConfig::control_activity()` @@ -380,8 +380,10 @@ The telemetry includes these items: `active_voice_ratios()` and `active_voice_gains()` return slices for the active voices. The peak windows of the telemetry are independent of the peak window of the feedback. In mono calls, the output and reverb wet peaks measure the audio -after the downmix. The dry path has the 1,593-frame delay. Resampled voices, -choir delays and effects use different delays. +after the downmix. At 44.1 kHz and 48 kHz, the processor bypasses rate +conversion and the dry path has the 1,593-frame delay. Other rates scale the +core delay to host frames and add the polyphase filter delay. Resampled +voices, choir delays and effects use different delays. `formant_envelope()` writes two LPC envelopes into slices of equal length: @@ -390,7 +392,9 @@ 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 | | ----------- | ---------------------------------------------------------------- | @@ -635,8 +639,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/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"), ); diff --git a/src/config.rs b/src/config.rs index 741d08c..abb4712 100644 --- a/src/config.rs +++ b/src/config.rs @@ -11,12 +11,21 @@ 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. To convert an integer device rate in +/// 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. /// -/// 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. +/// 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 { @@ -25,14 +34,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, } } @@ -40,22 +56,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 ef07dee..667d19d 100644 --- a/src/events.rs +++ b/src/events.rs @@ -379,6 +379,12 @@ 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) + } } /// Validates one event and advances the stack configuration copy. diff --git a/src/formant.rs b/src/formant.rs index b4ea383..00e79e6 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -905,7 +905,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. /// @@ -946,6 +947,27 @@ 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 active = if points > 1 && max_hz > core_nyquist { + let nyquist_scaled = core_nyquist * (points - 1) as f64; + let mut count = ((nyquist_scaled / max_hz) as usize) + .saturating_add(1) + .min(points); + while count > 1 && max_hz * (count - 1) as f64 > nyquist_scaled { + count -= 1; + } + while count < points && max_hz * count as f64 <= nyquist_scaled { + count += 1; + } + count + } else { + points + }; + input[active..].fill(0.0); + output[active..].fill(0.0); + let input = &mut input[..active]; + let output = &mut output[..active]; const SCALE: f64 = 1.0 / 16384.0; let glottal = self.glottal as f64 * SCALE; let width = self.width as f64 * SCALE; diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..56cdb94 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. @@ -62,8 +64,8 @@ //! accumulated output 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, which the dry path also uses. Voice delays, pitch +//! or the audio signal. [`Processor::latency_frames`] gives the nominal +//! delay in host frames, which the dry path also uses. Voice delays, pitch //! changes and effects have their own timing. //! //! [`Processor::control_activity`] and [`ProcessorConfig::control_activity`] @@ -128,6 +130,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 9f8ae9b..607e4f1 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -7,10 +7,11 @@ 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::{ ControlActivity, ControlEvent, Error, ParameterControl, PrepareConfig, ProcessorConfig, - TimedEvent, + SampleRate, TimedEvent, }; /// Selects the output channel layout for the downmix and the peak meters. @@ -54,6 +55,11 @@ pub(crate) struct EnvelopeKey { 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. @@ -125,19 +131,26 @@ 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 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())?; Ok(Self { preparation, + core_rate, + resampler, config, - punch: Punch::new(rate, config.punch), - warm: Warm::new(rate, config.warm), - resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), + punch: Punch::new(core_rate, config.punch), + 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, @@ -174,9 +187,7 @@ impl Processor { events: &[TimedEvent], ) -> Result<(), Error> { Error::check_length(input.len(), output.len())?; - self.process_into(input.len(), events, |processor, index| { - output[index] = processor.next(input[index], OutputLayout::Stereo); - }) + self.process_into(input.len(), events, (input, output)) } /// Processes mono PCM into separate left and right output slices. @@ -201,11 +212,7 @@ impl Processor { ) -> Result<(), Error> { Error::check_length(input.len(), left.len())?; Error::check_length(input.len(), right.len())?; - self.process_into(input.len(), events, |processor, index| { - let frame = processor.next(input[index], OutputLayout::Stereo); - left[index] = frame[0]; - right[index] = frame[1]; - }) + self.process_into(input.len(), events, (input, left, right)) } /// Replaces mono PCM with the stereo result after the downmix. @@ -227,10 +234,7 @@ impl Processor { audio: &mut [i16], events: &[TimedEvent], ) -> Result<(), Error> { - self.process_into(audio.len(), events, |processor, index| { - let output = processor.next(audio[index], OutputLayout::Mono); - audio[index] = output[0]; - }) + self.process_into(audio.len(), events, audio) } /// Processes mono `f32` audio into `[left, right]` stereo frames. @@ -257,11 +261,7 @@ impl Processor { events: &[TimedEvent], ) -> Result<(), Error> { Error::check_length(input.len(), output.len())?; - self.process_into(input.len(), events, |processor, index| { - output[index] = processor - .next(pcm_from_f32(input[index]), OutputLayout::Stereo) - .map(pcm_to_f32); - }) + self.process_into(input.len(), events, (input, output)) } /// Processes mono `f32` audio into separate left and right `f32` slices. @@ -287,11 +287,7 @@ impl Processor { ) -> Result<(), Error> { Error::check_length(input.len(), left.len())?; Error::check_length(input.len(), right.len())?; - self.process_into(input.len(), events, |processor, index| { - let frame = processor.next(pcm_from_f32(input[index]), OutputLayout::Stereo); - left[index] = pcm_to_f32(frame[0]); - right[index] = pcm_to_f32(frame[1]); - }) + self.process_into(input.len(), events, (input, left, right)) } /// Replaces mono `f32` audio with the stereo result after the downmix. @@ -314,10 +310,7 @@ impl Processor { audio: &mut [f32], events: &[TimedEvent], ) -> Result<(), Error> { - self.process_into(audio.len(), events, |processor, index| { - let output = processor.next(pcm_from_f32(audio[index]), OutputLayout::Mono); - audio[index] = pcm_to_f32(output[0]); - }) + self.process_into(audio.len(), events, audio) } /// Starts a tail with the current [`tail_frames`](Self::tail_frames) @@ -469,20 +462,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. @@ -510,13 +506,28 @@ impl Processor { self.config.control_activity() } - /// Returns the nominal resynthesis latency: 1,593 frames at both rates. + /// Returns the nominal latency in host frames. /// - /// The dry path also has a delay of 1,593 frames. Resampled voices, choir + /// At 44.1 kHz and 48 kHz, the value is 1,593 frames and the dry path has + /// the same delay. 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, + } + } + + /// Scales a core pitch period to host samples at resampled rates. + fn scale_period_samples(&self, period_samples: f32) -> f32 { + if self.resampler.is_some() { + (f64::from(period_samples) * f64::from(self.preparation.sample_rate.as_u32()) + / f64::from(self.core_rate.as_u32())) as f32 + } else { + period_samples + } } /// Returns the pitch, output peak and frame count, and does not clear them. @@ -526,7 +537,7 @@ impl Processor { let estimate = self.resynthesis.estimate(); Feedback { resample_ratio: self.last_resample_ratio, - period_samples: estimate.period_samples, + period_samples: self.scale_period_samples(estimate.period_samples), frequency_hz: estimate.frequency_hz, target_midi_note: self.resynthesis.target_note(), voiced: estimate.voiced, @@ -562,7 +573,7 @@ impl Processor { output_peak: self.output_peaks.map(|peak| peak as f32 / 32_768.0), reverb_wet_peak: self.reverb.wet_peak(), resample_ratio: self.last_resample_ratio, - period_samples: estimate.period_samples, + period_samples: self.scale_period_samples(estimate.period_samples), frequency_hz: estimate.frequency_hz, target_midi_note: self.resynthesis.target_note(), voiced: estimate.voiced, @@ -614,7 +625,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: @@ -757,6 +770,9 @@ impl Processor { /// /// 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(); @@ -969,13 +985,8 @@ impl Processor { self.drain_remaining = None; } - /// Renders one frame through the full chain and updates the peak meters. - /// - /// Resynthesis produces Q14 audio. Output gain is Q8. The gain product - /// uses `i64` arithmetic before the symmetric `-32767..=32767` PCM clamp. - /// In the mono layout, the downmix occurs before the peak measurement. - fn next(&mut self, mut input: i16, layout: OutputLayout) -> [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, layout: OutputLayout) -> [i16; 2] { if self.config.punch.enabled { input = self.punch.process_sample(input, &mut self.numeric); } @@ -987,9 +998,15 @@ impl Processor { let alien = self.alien.process_sample(voice); let reverb = self.reverb.process_sample(alien, layout); let gain = (self.config.output_gain as f64 * 256.0) as i64; - let mut result = reverb.map(|sample| { + reverb.map(|sample| { (((i64::from(sample.to_bits()) * gain) >> 8) << 1).clamp(-32767, 32767) as i16 - }); + }) + } + + /// Applies an optional mono downmix and updates the output peaks and frame + /// count. + #[inline] + fn record_output(&mut self, mut result: [i16; 2], layout: OutputLayout) -> [i16; 2] { if matches!(layout, OutputLayout::Mono) { let mono = downmix(result); result = [mono, mono]; @@ -1005,24 +1022,119 @@ impl Processor { result } + /// Renders one frame through the full chain and updates the peak meters. + /// + /// Resynthesis produces Q14 audio. Output gain is Q8. The gain product + /// uses `i64` arithmetic before the symmetric `-32767..=32767` PCM clamp. + /// In the mono layout, the downmix occurs before the peak measurement. + fn next(&mut self, input: i16, layout: OutputLayout) -> [i16; 2] { + self.input_peak = self.input_peak.max((input as i32).abs()); + let result = self.next_core(input, layout); + self.record_output(result, layout) + } + + /// Runs the core stages across `core_count` resampled input frames. + fn render_core_frames(&mut self, core_count: usize, layout: OutputLayout) { + for index in 0..core_count { + let sample = self + .resampler + .as_ref() + .expect("resampler active") + .core_input[index]; + let frame = self.next_core(sample, layout); + self.resampler + .as_mut() + .expect("resampler active") + .core_output[index] = frame; + } + } + + /// Resamples `start..end` from `block` and runs the core stages on those + /// frames. + fn run_resampled_core(&mut self, block: &B, start: usize, end: usize) -> usize { + let mut input_peak = self.input_peak; + let core_count = self + .resampler + .as_mut() + .expect("resampler active") + .resample_input(end - start, |offset| { + let sample = block.sample(start + offset); + input_peak = input_peak.max(i32::from(sample).abs()); + sample + }); + self.input_peak = input_peak; + self.render_core_frames(core_count, B::LAYOUT); + core_count + } + + /// Resamples the current `core_output` prefix to `host_frames` frames and + /// updates the output peaks and the frame count. + fn finish_resampled_output( + &mut self, + core_count: usize, + host_frames: usize, + layout: OutputLayout, + 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, mut frame| { + if matches!(layout, OutputLayout::Mono) { + let mono = downmix(frame); + frame = [mono, mono]; + } + 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 renders each /// frame. /// - /// A callback reads the input sample and writes the output for its buffer + /// `block` reads the mono input and writes the output for its buffer /// layout. - fn process_into( + fn process_into( &mut self, frames: usize, events: &[TimedEvent], - mut render: impl FnMut(&mut Self, usize), + mut block: B, ) -> Result<(), Error> { let mut events = self.validate(frames, events)?; self.drain_remaining = None; - for index in 0..frames { - while let Some(event) = events.next_at(index) { + if self.resampler.is_none() { + for index in 0..frames { + while let Some(event) = events.next_at(index) { + self.apply(event); + } + let frame = self.next(block.sample(index), B::LAYOUT); + block.write(index, frame); + } + return Ok(()); + } + let mut cursor = 0; + while cursor < frames { + while let Some(event) = events.next_at(cursor) { self.apply(event); } - render(self, index); + let end = events.peek_offset().unwrap_or(frames); + let core_count = self.run_resampled_core(&block, cursor, end); + self.finish_resampled_output(core_count, end - cursor, B::LAYOUT, |index, frame| { + block.write(cursor + index, frame); + }); + cursor = end; } Ok(()) } @@ -1043,8 +1155,18 @@ impl Processor { self.check_block(frames)?; let count = self.drain_remaining.unwrap_or(0).min(frames); self.resynthesis.set_aspiration_muted(true); - for index in 0..count { - write(index, self.next(0, layout)); + if self.resampler.is_none() { + for index in 0..count { + write(index, self.next(0, layout)); + } + } else if count > 0 { + let core_count = self + .resampler + .as_mut() + .expect("resampler active") + .resample_silence(count); + self.render_core_frames(core_count, layout); + self.finish_resampled_output(core_count, count, layout, write); } self.resynthesis.set_aspiration_muted(false); if let Some(remaining) = self.drain_remaining { @@ -1076,6 +1198,104 @@ fn pcm_to_f32(sample: i16) -> f32 { f32::from(sample) / 32_768.0 } +/// Reads the mono input and writes the output frames for one buffer layout. +trait BlockBuffer { + /// The stereo or mono output layout for the downmix and the peak meters. + const LAYOUT: OutputLayout; + + /// Returns the quantized mono input sample at `index`. + fn sample(&self, index: usize) -> i16; + + /// Writes one output frame at `index`. + fn write(&mut self, index: usize, frame: [i16; 2]); +} + +impl BlockBuffer for (&[i16], &mut [[i16; 2]]) { + const LAYOUT: OutputLayout = OutputLayout::Stereo; + + #[inline] + fn sample(&self, index: usize) -> i16 { + self.0[index] + } + + #[inline] + fn write(&mut self, index: usize, frame: [i16; 2]) { + self.1[index] = frame; + } +} + +impl BlockBuffer for (&[i16], &mut [i16], &mut [i16]) { + const LAYOUT: OutputLayout = OutputLayout::Stereo; + + #[inline] + fn sample(&self, index: usize) -> i16 { + self.0[index] + } + + #[inline] + fn write(&mut self, index: usize, frame: [i16; 2]) { + self.1[index] = frame[0]; + self.2[index] = frame[1]; + } +} + +impl BlockBuffer for &mut [i16] { + const LAYOUT: OutputLayout = OutputLayout::Mono; + + #[inline] + fn sample(&self, index: usize) -> i16 { + self[index] + } + + #[inline] + fn write(&mut self, index: usize, frame: [i16; 2]) { + self[index] = frame[0]; + } +} + +impl BlockBuffer for (&[f32], &mut [[f32; 2]]) { + const LAYOUT: OutputLayout = OutputLayout::Stereo; + + #[inline] + fn sample(&self, index: usize) -> i16 { + pcm_from_f32(self.0[index]) + } + + #[inline] + fn write(&mut self, index: usize, frame: [i16; 2]) { + self.1[index] = frame.map(pcm_to_f32); + } +} + +impl BlockBuffer for (&[f32], &mut [f32], &mut [f32]) { + const LAYOUT: OutputLayout = OutputLayout::Stereo; + + #[inline] + fn sample(&self, index: usize) -> i16 { + pcm_from_f32(self.0[index]) + } + + #[inline] + fn write(&mut self, index: usize, frame: [i16; 2]) { + self.1[index] = pcm_to_f32(frame[0]); + self.2[index] = pcm_to_f32(frame[1]); + } +} + +impl BlockBuffer for &mut [f32] { + const LAYOUT: OutputLayout = OutputLayout::Mono; + + #[inline] + fn sample(&self, index: usize) -> i16 { + pcm_from_f32(self[index]) + } + + #[inline] + fn write(&mut self, index: usize, frame: [i16; 2]) { + self[index] = pcm_to_f32(frame[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 @@ -1146,7 +1366,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/resample.rs b/src/resample.rs new file mode 100644 index 0000000..ea10bab --- /dev/null +++ b/src/resample.rs @@ -0,0 +1,403 @@ +//! 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 `host_frames` input samples from `read` into `self.core_input` + /// and returns the number of generated core frames. + pub(crate) fn resample_input( + &mut self, + host_frames: usize, + mut read: impl FnMut(usize) -> 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 index in 0..host_frames { + self.input_filter.push(read(index)); + 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 { + self.resample_input(host_frames, |_| 0) + } + + /// 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_sub(1) + .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 = 0_i64; + for (&sample, &coeff) in samples.iter().zip(coeffs) { + sum = sum.saturating_add(i64::from(sample) * i64::from(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 = 0_i64; + let mut right = 0_i64; + for (&frame, &coeff) in frames.iter().zip(coeffs) { + let weight = i64::from(coeff.to_bits()); + left = left.saturating_add(i64::from(frame[0]) * weight); + right = right.saturating_add(i64::from(frame[1]) * 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 e868d16..f1e60f9 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -153,10 +153,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)`. /// @@ -164,7 +164,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. @@ -180,11 +180,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 { @@ -258,9 +261,11 @@ impl WasmProcessor { self.input.len() } - /// The nominal resynthesis latency: 1,593 frames at both sample rates. + /// The nominal latency in host frames. /// - /// The dry path also has a delay of 1,593 frames. Resampled voices, choir + /// At 44.1 kHz and 48 kHz, the value is 1,593 frames and the dry path has + /// the same delay. 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. #[wasm_bindgen(getter, js_name = latencyFrames)] @@ -761,7 +766,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