From efba4ed0f09fdd54f27ab5832e6a3a6f921b5393 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:02:29 +0000 Subject: [PATCH 1/2] feat(resynthesis): add causal low-latency formant mode - Export LatencyMode with Standard and LowLatency variants - Add the optional latency_mode field to ResynthesisConfig - Add causal 128-frame LPC analysis with zero inverse delay - Store resampled choir lead periods in preallocated lead_periods - Bypass the overlap buffer in LowLatency resynthesis - Align Choir and Harmony formant stamps with zero offset in LowLatency - Clear lead_periods on reset and on latency_mode changes - Return 50 or 1,593 nominal frames from latency_frames - Document LatencyMode in the crate docs, Wasm docs and README.md --- README.md | 18 +++-- src/formant.rs | 67 ++++++++++++---- src/lib.rs | 9 ++- src/processor.rs | 57 +++++++------ src/resynthesis.rs | 195 +++++++++++++++++++++++++++++++++------------ src/wasm.rs | 9 ++- 6 files changed, 250 insertions(+), 105 deletions(-) diff --git a/README.md b/README.md index 83a8f47..8a538c1 100644 --- a/README.md +++ b/README.md @@ -175,8 +175,11 @@ The internal Q14 stages use `i64` products and saturate at the `i32` limits. Decrease `output_gain` to prevent `-32767..=32767` clipping on multi-voice mixes. -`resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The -dry path starts after Warm and has a delay of 1,543 frames. +`resynthesis.latency_mode` selects `Standard` (1,593 nominal frames, default) +or `LowLatency` (50 nominal frames, causal formant analysis). +`resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The dry +path starts after Warm and has a delay of 1,543 frames in `Standard` mode and +zero frames in `LowLatency` mode. ### Harmony sources @@ -299,7 +302,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()` | 1,593 (`Standard`) or 50 (`LowLatency`) frames of nominal latency | | `formant_envelope()` | The LPC envelopes before and after the formant controls | The telemetry includes these items: @@ -451,10 +454,11 @@ and show enums as string literals. To change the configuration, do these steps: 3. Call `setConfig()`. If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust -types. +JavaScript `Error`. The optional `resynthesis.latencyMode` field defaults to +`"standard"` if it is absent. The optional `resynthesis.harmony.voices` field +defaults to 4 if it is absent. The conversion ignores extra object +properties. The generated declarations contain the parameter documentation +from the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use diff --git a/src/formant.rs b/src/formant.rs index bf9ee5a..4596023 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -11,11 +11,13 @@ //! //! Thirty model banks keep the history of the coefficients. Each audio frame //! stores a pair of banks and a blend. Thus, a fractional voice reader can -//! find the model that applies to the audio that it reads again. The inverse -//! filter has a delay of 441 frames. Resynthesis uses this delay to align -//! each source sample with the stamp of the frame that filtered it. Audio -//! and coefficients use Q14 words. All areas use one common scale that the -//! code sets at runtime. The order of the arithmetic and of the rescale +//! find the model that applies to the audio that it reads again. In standard +//! latency mode, the inverse filter has a delay of 441 frames. In low-latency +//! mode, the stage updates the model every 128 frames and filters the current +//! frame without delay. +//! +//! Audio and coefficients use Q14 words. All areas use one common scale that +//! the code sets at runtime. The order of the arithmetic and of the rescale //! operations changes the output samples. use crate::error::check_range; @@ -107,9 +109,11 @@ impl FormantConfig { /// The number of frames of input history for analysis and synthesis. The /// value is equal to the resynthesis history length. pub(crate) const HISTORY_FRAMES: usize = 11568; -/// The number of frames in each analysis step. The analysis output has a -/// delay of this number of frames. +/// The number of frames in each standard analysis step. The standard analysis +/// output has a delay of this number of frames. pub(crate) const ANALYSIS_FRAMES: usize = 441; +/// The number of frames in each causal low-latency analysis step. +const CAUSAL_ANALYSIS_FRAMES: usize = 128; /// The order of the input LPC predictor and of the synthesis model without /// changes. const ORDER: usize = 50; @@ -395,9 +399,29 @@ impl Formant { self.dirty = true; self.input[write] = self.remove_glottal(sample, previous); - self.design(periods, write, output_period_q6); + self.design(periods, write, output_period_q6, ANALYSIS_FRAMES); self.inverse(write) } + /// Stores the pre-emphasized input, tries a model design each 128 frames, + /// and filters the current frame without delay. + /// + /// `write` and the period history must refer to the same full-size ring of + /// audio frames. `output_period_q6` is the kept period that sets the + /// analysis segments. + pub(crate) fn process_causal_analysis( + &mut self, + sample: i32, + previous: i32, + periods: &[Q6], + write: usize, + output_period_q6: i32, + ) -> i32 { + self.dirty = true; + self.input[write] = self.remove_glottal(sample, previous); + + self.design(periods, write, output_period_q6, CAUSAL_ANALYSIS_FRAMES); + self.inverse_at(write) + } /// Moves to the next bank and keeps the old bank for the blend. /// /// The function clears the inverse coefficients, the forward coefficients @@ -448,8 +472,8 @@ impl Formant { } self.smooth_index = (self.smooth_index + 1) % 2; } - /// Tries a model that uses the pitch each ANALYSIS_FRAMES, and stamps - /// each frame. + /// Tries a model that uses the pitch each `step_frames`, and stamps each + /// frame. /// /// If a pitch is available, the segment folds adjacent cycles and clamps /// the period to `rate / 40`. If not, the segment is a window of @@ -467,14 +491,20 @@ impl Formant { /// /// If the Durbin analysis fails, smoothing starts again. The selected /// bank keeps the inverse coefficients that the analysis wrote. - fn design(&mut self, periods: &[Q6], position: usize, output_period_q6: i32) { + fn design( + &mut self, + periods: &[Q6], + position: usize, + output_period_q6: i32, + step_frames: usize, + ) { let max_period = (self.rate.as_u32() as usize / 40).max(1); let period = (output_period_q6.wrapping_shr(6).max(0) as usize).min(max_period); let design_now = self.design_counter == 0; self.design_counter += 1; let one = 16384; if design_now { - self.design_counter -= ANALYSIS_FRAMES as i32; + self.design_counter -= step_frames as i32; let count; if period == 0 { count = (self.rate.as_u32() as usize + 50) / 100; @@ -664,16 +694,21 @@ impl Formant { /// Applies the blended 50th-order prediction-error filter to the delayed /// input. - /// - /// The full sum of Q28 products accumulates in `i64` before one signed - /// shift and an `i32` clamp. The function blends the coefficients for the - /// current transition. Then it multiplies them with the previous samples. fn inverse(&self, position: usize) -> i32 { let read = if position < ANALYSIS_FRAMES { position + HISTORY_FRAMES - ANALYSIS_FRAMES } else { position - ANALYSIS_FRAMES }; + self.inverse_at(read) + } + + /// Applies the blended 50th-order prediction-error filter to `input[read]`. + /// + /// The full sum of Q28 products accumulates in `i64` before one signed + /// shift and an `i32` clamp. The function blends the coefficients for the + /// current transition. Then it multiplies them with the previous samples. + fn inverse_at(&self, read: usize) -> i32 { let mut blended; let coefficients = if self.blend < 16384 { blended = [0_i32; ORDER]; diff --git a/src/lib.rs b/src/lib.rs index f17bc85..7d5df49 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -52,9 +52,10 @@ //! accumulated stereo peak and the frame count. //! [`Processor::take_feedback`] also clears the peak window. The pitch //! reporting bounds change only the reports. They do not change the detection -//! or the audio signal. [`Processor::latency_frames`] gives a nominal -//! resynthesis delay. Voice delays, pitch changes and effects have their own -//! timing. +//! or the audio signal. [`Processor::latency_frames`] gives the nominal +//! resynthesis delay: 1,593 frames in [`LatencyMode::Standard`] and 50 frames +//! in [`LatencyMode::LowLatency`]. 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 @@ -135,5 +136,5 @@ pub use harmony::{ pub use midi::MidiEvent; pub use pitch::PitchConfig; pub use processor::{Feedback, Processor, Telemetry}; -pub use resynthesis::{CorrectionConfig, MultiVoiceMode, ResynthesisConfig}; +pub use resynthesis::{CorrectionConfig, LatencyMode, MultiVoiceMode, ResynthesisConfig}; pub use scale::{CorrectionScale, NoteMask, PitchClass}; diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..a61ab08 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -319,13 +319,15 @@ impl Processor { self.config } - /// Returns the nominal resynthesis latency: 1,593 frames at both rates. + /// Returns the nominal resynthesis latency: 1,593 frames in + /// [`crate::LatencyMode::Standard`] or 50 frames in + /// [`crate::LatencyMode::LowLatency`] at both rates. /// - /// The dry path has a delay of 1,543 frames. Resampled voices, choir delays - /// and effects have their own timing. Thus, this value does not align all - /// paths. + /// The dry path has a delay of 1,543 frames in standard mode and zero + /// frames in low-latency mode. 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 + resynthesis::latency_frames(self.config.resynthesis.latency_mode) } /// Returns the pitch, stereo peak and frame count, and does not clear them. @@ -454,12 +456,12 @@ impl Processor { /// Validates all configuration fields and applies them. /// /// The validation also examines the fields of disabled stages. A stage - /// that does not change keeps its state. A change of `stereo_output` - /// resets the resynthesis audio state, Alien, the reverb delays, the peak - /// and the reported ratio. It also releases the harmony MIDI notes. It - /// keeps Punch, Warm, the correction keys, the random stream, the reverb - /// low-pass memories and the frame count. A change of `random_seed` starts - /// the random stream again. + /// that does not change keeps its state. A change of `stereo_output` or + /// `latency_mode` resets the resynthesis audio state, Alien, the reverb + /// delays, the peak and the reported ratio. It also releases the harmony + /// MIDI notes. It keeps Punch, Warm, the correction keys, the random + /// stream, the reverb low-pass memories and the frame count. A change of + /// `random_seed` starts the random stream again. /// /// Each successful call cancels a drain, also for an identical /// configuration. A change of reverb mode keeps the delay contents. If you @@ -488,8 +490,11 @@ impl Processor { if self.config.resynthesis != config.resynthesis { self.resynthesis.apply_config(config.resynthesis); } - if self.config.resynthesis.stereo_output != config.resynthesis.stereo_output { - // Resynthesis resets its histories if its stereo setting changes. + if self.config.resynthesis.stereo_output != config.resynthesis.stereo_output + || self.config.resynthesis.latency_mode != config.resynthesis.latency_mode + { + // Resynthesis resets its histories if its stereo or latency mode + // changes. self.reset_post_resynthesis(); } if self.config.resynthesis.random_seed != config.resynthesis.random_seed { @@ -539,8 +544,8 @@ impl Processor { /// Clears the stages, the peak windows and the ratio after resynthesis. /// - /// Both a full reset and a change of stereo output clear this state. The - /// frame count does not change here. + /// A full reset, a stereo change or a latency-mode change clears this + /// state. The frame count does not change here. fn reset_post_resynthesis(&mut self) { self.alien.reset(); self.reverb.reset(); @@ -721,7 +726,7 @@ pub struct Feedback { /// /// It does not include the configured pitch shift or the ratios of /// individual voices. It is zero before processing, after a reset or after - /// a change of stereo output. + /// a change of stereo output or latency mode. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// @@ -761,9 +766,10 @@ pub struct Feedback { /// The largest absolute clipped stereo sample, divided by 32768. /// /// The peak window starts at construction, at a reset, at a change of - /// stereo output or at a call to [`Processor::take_feedback`]. The value - /// is in 0..=32767/32768. The mono downmix occurs after this measurement. - /// [`Processor::feedback`] does not clear the value. + /// stereo output or latency mode, or at a call to + /// [`Processor::take_feedback`]. The value is in 0..=32767/32768. The mono + /// downmix occurs after this measurement. [`Processor::feedback`] does not + /// clear the value. pub peak_level: f32, /// The number of frames processed since construction or the last reset, /// with drain frames included. @@ -788,9 +794,9 @@ pub struct Feedback { /// `Default` gives a snapshot with all zeros. /// /// The three peak fields measure a window. The window starts at -/// construction, at a reset, at a change of stereo output or at a call to -/// [`Processor::take_telemetry`]. This window is independent of the peak -/// window of [`Feedback`]. +/// construction, at a reset, at a change of stereo output or latency mode, or +/// at a call to [`Processor::take_telemetry`]. This window is independent of +/// the peak window of [`Feedback`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -879,8 +885,9 @@ pub struct Telemetry { pub alien_phase_frames: u32, /// The wrapping count of formant analyses since construction. /// - /// The count increases every 441 frames while the formant stage is - /// enabled. Compare two values to find if - /// [`Processor::formant_envelope`] can give a new result. + /// While the formant stage is enabled, the count increases every 441 + /// frames in standard mode and every 128 frames in low-latency mode. + /// Compare two values to find if [`Processor::formant_envelope`] can give + /// a new result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..f4734e5 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -4,11 +4,11 @@ //! the correction and control steps that are due. The raw input, the tracked //! periods and the correction ratios use the same history cursor. //! -//! The source comes from a fixed overlap buffer. If formants are enabled, -//! this buffer holds the output of the formant inverse analysis. If not, -//! it holds the raw input. Voice readers read this source at fractional -//! positions. If the shift is upward, prepared low-pass filters also -//! change the source. +//! In standard latency mode, the source comes from a fixed overlap buffer. In +//! low-latency mode, the source uses the current frame directly. If formants +//! are enabled, the source holds the output of the formant inverse analysis. +//! If not, it holds the raw input. Voice readers read this source at +//! fractional positions, after the prepared upward-shift filters. //! //! Choir renders the lead voice first. Then it makes delayed secondary voices //! with drift from the lead history. Harmony renders the lead voice and four @@ -58,6 +58,26 @@ pub enum MultiVoiceMode { Harmony, } +/// The latency and lookahead mode of resynthesis and formant analysis. +/// +/// A change to this mode resets the resynthesis audio histories and the stages +/// after resynthesis, in the same way as [`ResynthesisConfig::stereo_output`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum LatencyMode { + /// A nominal resynthesis delay of 1,593 frames, with a 1,543-frame source + /// and dry delay. This is the default. + #[default] + Standard, + /// A causal nominal resynthesis delay of 50 frames, with zero source and + /// dry delay. + LowLatency, +} + /// The controls for pitch-class correction, with target selection in the /// period domain. /// @@ -149,14 +169,16 @@ impl CorrectionConfig { /// - No harmonic modulation. /// - No dry mix. /// - No stereo pan. +/// - Standard latency mode. /// /// Validation applies to all controls, also when their stage or voice mode /// is not active. /// -/// The dry path takes the audio after Punch and Warm and delays it by 1,543 -/// frames. The wet voice readers have more delay, which changes with the -/// pitch. After this stage, the two paths go through Alien, reverb and the -/// final output gain. +/// In [`LatencyMode::Standard`], the dry path takes the audio after Punch and +/// Warm and delays it by 1,543 frames. In [`LatencyMode::LowLatency`], the dry +/// path has zero delay. The wet voice readers add at least 50 frames of delay, +/// which changes with the pitch. After this stage, the two paths go through +/// Alien, reverb and the final output gain. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -238,9 +260,10 @@ pub struct ResynthesisConfig { /// The dry fraction at the resynthesis stage, 0..=1. The default is 0. /// /// The code truncates this value to Q8. The wet weight is 1.0 minus the - /// Q8 dry weight. The dry path starts after Punch and Warm and has a - /// delay of 1,543 frames. Alien, reverb and the output gain still occur - /// after this stage. + /// Q8 dry weight. The dry path starts after Punch and Warm. Its delay is + /// 1,543 frames in [`LatencyMode::Standard`] and zero frames in + /// [`LatencyMode::LowLatency`]. Alien, reverb and the output gain still + /// occur after this stage. pub dry_mix: f32, /// The seed for choir drift and aspiration, which use the same stream. /// The default is `0x1234_abcd`. @@ -251,6 +274,19 @@ pub struct ResynthesisConfig { /// bits. Reset keeps the current position in the stream. The enabled /// stages set the number of random values that the code reads. pub random_seed: u64, + /// The latency and formant analysis mode. The default is + /// [`LatencyMode::Standard`]. + /// + /// [`LatencyMode::LowLatency`] bypasses the 1,543-frame overlap buffer and + /// uses causal formant analysis. A change to this field resets the same + /// audio histories and feedback state as `stereo_output`. In JavaScript, + /// the field is optional and an absent value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub latency_mode: LatencyMode, } impl Default for ResynthesisConfig { @@ -271,6 +307,7 @@ impl Default for ResynthesisConfig { harmonic_modulation: 0.0, dry_mix: 0.0, random_seed: 0x1234_abcd, + latency_mode: LatencyMode::Standard, } } } @@ -329,11 +366,20 @@ const OVERLAP_FRAMES: usize = 1543; const FORMANT_OFFSET_FRAMES: i32 = (OVERLAP_FRAMES - ANALYSIS_FRAMES) as i32; /// The number of frames that a new reader stays behind the write position. const READER_LAG_FRAMES: i32 = 50; -/// The nominal latency of resynthesis. Each reader moves with the pitch and -/// the delay. +/// The nominal latency of resynthesis in [`LatencyMode::Standard`]. /// /// The dry path uses only `OVERLAP_FRAMES`. pub(crate) const LATENCY_FRAMES: usize = OVERLAP_FRAMES + READER_LAG_FRAMES as usize; +/// The nominal latency of resynthesis in [`LatencyMode::LowLatency`]. +pub(crate) const LOW_LATENCY_FRAMES: usize = READER_LAG_FRAMES as usize; + +/// Returns the nominal resynthesis latency in frames for `mode`. +pub(crate) const fn latency_frames(mode: LatencyMode) -> usize { + match mode { + LatencyMode::Standard => LATENCY_FRAMES, + LatencyMode::LowLatency => LOW_LATENCY_FRAMES, + } +} /// The counter value at which a control step runs. Usually, a step runs /// every 101 eligible frames. /// @@ -390,10 +436,12 @@ pub(crate) struct Resynthesis { /// The history of the rendered choir lead. All secondary choir voices /// read this history. lead: Box<[Q14; HISTORY]>, - /// The Q6 tracked periods, aligned to the audio. The lead voice can - /// replace a delayed entry with its resampled output period. This aligns - /// the secondary voices. + /// The Q6 tracked input periods, aligned to the audio. Formant analysis + /// and pitch feedback read these unmodified values. periods: Box<[Q6; HISTORY]>, + /// The Q6 periods of the rendered choir lead. The lead voice stores its + /// resampled output period here to align the secondary voices. + lead_periods: Box<[Q6; HISTORY]>, /// The last usable Q6 tracker periods. The code keeps them through /// unvoiced gaps. previous_periods: Box<[Q6; HISTORY]>, @@ -521,6 +569,7 @@ impl Resynthesis { filtered: prepare_history(Q14::ZERO), lead: prepare_history(Q14::ZERO), periods: prepare_history(Q6::ZERO), + lead_periods: prepare_history(Q6::ZERO), previous_periods: prepare_history(Q6::ZERO), ratios: prepare_history(Q14::ONE), overlap: [Q14::ZERO; OVERLAP_FRAMES], @@ -670,9 +719,9 @@ impl Resynthesis { } } self.configure_coefficients(); - if old.stereo_output != config.stereo_output { - // A stereo change resets the audio state. The correction keyboard - // keeps its held keys. + if old.stereo_output != config.stereo_output || old.latency_mode != config.latency_mode { + // A stereo or latency-mode change resets the audio state. The + // correction keyboard keeps its held keys. self.reset_audio(); } } @@ -707,6 +756,7 @@ impl Resynthesis { self.filtered.fill(Q14::ZERO); self.lead.fill(Q14::ZERO); self.periods.fill(Q6::ZERO); + self.lead_periods.fill(Q6::ZERO); self.previous_periods.fill(Q6::ZERO); self.ratios.fill(Q14::ONE); } else if written > 0 { @@ -715,14 +765,15 @@ impl Resynthesis { self.raw[1..end].fill(Q14::ZERO); self.filtered[1..end].fill(Q14::ZERO); self.lead[1..end].fill(Q14::ZERO); + self.periods[1..end].fill(Q6::ZERO); if written < OVERLAP_FRAMES { - self.periods[1..end].fill(Q6::ZERO); - self.periods[lead_start..lead_start + written].fill(Q6::ZERO); + self.lead_periods[1..end].fill(Q6::ZERO); + self.lead_periods[lead_start..lead_start + written].fill(Q6::ZERO); } else if written < HISTORY - OVERLAP_FRAMES { - self.periods[..end].fill(Q6::ZERO); - self.periods[lead_start..].fill(Q6::ZERO); + self.lead_periods[..end].fill(Q6::ZERO); + self.lead_periods[lead_start..].fill(Q6::ZERO); } else { - self.periods.fill(Q6::ZERO); + self.lead_periods.fill(Q6::ZERO); } self.previous_periods[1..end].fill(Q6::ZERO); self.ratios[1..end].fill(Q14::ONE); @@ -966,6 +1017,30 @@ impl Resynthesis { } } + /// Selects the period for a secondary choir voice from the lead history. + /// + /// If the delayed lead frame is voiced, the function uses its resampled + /// period. If not, it uses the current lead period, or the last usable + /// delayed input period. The indices must be less than HISTORY. + fn lead_period_for(&self, delayed: usize, current: usize) -> Q6 { + if self.lead_periods[delayed] != Q6::ZERO { + self.lead_periods[delayed] + } else if self.lead_periods[current] != Q6::ZERO { + self.lead_periods[current] + } else { + self.previous_periods[delayed] + } + } + + /// Returns the frame offset from a reader position to its formant stamp. + #[inline] + fn formant_offset_frames(&self) -> i32 { + match self.config.latency_mode { + LatencyMode::Standard => FORMANT_OFFSET_FRAMES, + LatencyMode::LowLatency => 0, + } + } + /// Returns the upper limit, the lower limit and the Q14 period jump for a /// reader. /// @@ -1056,7 +1131,7 @@ impl Resynthesis { ratio = Q14::ONE; } if ratio != Q14::ZERO { - self.periods[delay] = period.div(ratio); + self.lead_periods[delay] = period.div(ratio); } self.old_position = self.old_position + ratio; let position = self.move_reader(0, ratio, period, self.delays[0], true); @@ -1067,7 +1142,7 @@ impl Resynthesis { self.fade = (self.fade + FADE_STEP).min(Q14::ONE); } if self.config.formant.enabled { - self.formant_position = center - FORMANT_OFFSET_FRAMES; + self.formant_position = center - self.formant_offset_frames(); value = Q14::from_bits(self.formant.forward( value.to_bits(), self.formant_position, @@ -1155,34 +1230,53 @@ impl Resynthesis { } } self.periods[write] = step.period; + self.lead_periods[write] = step.period; self.previous_periods[write] = step.previous_period; self.ratios[write] = self.correction; - self.overlap_index += 1; - if self.overlap_index == OVERLAP_FRAMES { - self.overlap_index = 0; - } - self.overlap[self.overlap_index] = if self.config.formant.enabled { - let previous = self.raw[ring(write as i32 - 1)]; - Q14::from_bits(self.formant.process_analysis( - sample.to_bits(), - previous.to_bits(), - self.periods.as_slice(), - write, - step.previous_period.to_bits(), - )) + let (mut filtered, delayed) = if self.config.latency_mode == LatencyMode::LowLatency { + let source = if self.config.formant.enabled { + let previous = self.raw[ring(write as i32 - 1)]; + Q14::from_bits(self.formant.process_causal_analysis( + sample.to_bits(), + previous.to_bits(), + self.periods.as_slice(), + write, + step.previous_period.to_bits(), + )) + } else { + sample + }; + (source, write) } else { - self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] + self.overlap_index += 1; + if self.overlap_index == OVERLAP_FRAMES { + self.overlap_index = 0; + } + self.overlap[self.overlap_index] = if self.config.formant.enabled { + let previous = self.raw[ring(write as i32 - 1)]; + Q14::from_bits(self.formant.process_analysis( + sample.to_bits(), + previous.to_bits(), + self.periods.as_slice(), + write, + step.previous_period.to_bits(), + )) + } else { + self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] + }; + // The inverse analysis adds a delay of ANALYSIS_FRAMES. Read ahead by + // the same number of frames in the overlap ring. Then the total delay + // of the source is OVERLAP_FRAMES in the two formant modes. + let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; + ( + self.overlap[overlap_read], + ring(write as i32 - OVERLAP_FRAMES as i32), + ) }; - // The inverse analysis adds a delay of ANALYSIS_FRAMES. Read ahead by - // the same number of frames in the overlap ring. Then the total delay - // of the source is OVERLAP_FRAMES in the two formant modes. - let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; - let mut filtered = self.overlap[overlap_read]; for filter in &mut self.post { filtered = filter.process_sample(filtered); } self.filtered[write] = filtered; - let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); let dry = self.raw[delayed]; let mut mix = [Q14::ZERO; 2]; let mut final_ratio = Q14::ONE; @@ -1211,7 +1305,7 @@ impl Resynthesis { for (lane, position) in positions.iter_mut().enumerate() { let current_voice = voice + lane; let delay = ring(delayed as i32 - self.delays[current_voice]); - let (period, _) = self.period_for(delay, write); + let period = self.lead_period_for(delay, write); self.current_output_period = period; let ratio = self.drift_ratio[current_voice]; final_ratio = ratio; @@ -1243,7 +1337,7 @@ impl Resynthesis { // scalar code. for voice in voice..voice_count { let delay = ring(delayed as i32 - self.delays[voice]); - let (period, _) = self.period_for(delay, write); + let period = self.lead_period_for(delay, write); self.current_output_period = period; let ratio = self.drift_ratio[voice]; final_ratio = ratio; @@ -1320,7 +1414,8 @@ impl Resynthesis { } } if self.config.formant.enabled { - self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; + self.formant_position = + (self.positions[0].to_bits() >> 14) - self.formant_offset_frames(); mix = self .formant .forward_stereo(mix.map(Q14::to_bits), self.formant_position, numeric) diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..41c5e6e 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,6 +19,7 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. +//! - The optional `latencyMode` field of resynthesis defaults to `"standard"`. //! - The optional harmony `voices` field defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use @@ -191,10 +192,12 @@ impl WasmProcessor { self.input.len() } - /// The nominal resynthesis latency: 1,593 frames at both sample rates. + /// The nominal resynthesis latency: 1,593 frames in `"standard"` mode or + /// 50 frames in `"lowLatency"` mode at both sample rates. /// - /// 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 + /// The dry path has a delay of 1,543 frames in `"standard"` mode and zero + /// frames in `"lowLatency"` mode. Resampled voices, choir delays and + /// effects have their own timing. Thus, this value does not align all /// paths. #[wasm_bindgen(getter, js_name = latencyFrames)] pub fn latency_frames(&self) -> usize { From 293655147ef5a220bd7602208249228635a387e9 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 16:05:10 +0000 Subject: [PATCH 2/2] chore: sync pull request head with main (v0.3.4)