From 94a7b13b39b3655a9dd44226a7df0b0cb6e2add4 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 03:33:27 +0000 Subject: [PATCH] feat: align dry tap and add global mix, bypass and Alien mix - Read the resynthesis dry tap at the 1,593-frame latency - Blend direct and reversed stereo frames with AlienConfig::mix in Q14 - Add global mix and bypass controls to ProcessorConfig - Delay the input before Punch by 1,593 frames for mix and bypass - Clear the processor dry buffer in Processor::reset - Make the new configuration fields optional in WebAssembly - Document the 1,593-frame dry delay and the new controls --- README.md | 25 ++++++++------ docs/images/signal-chain.svg | 2 +- src/config.rs | 65 ++++++++++++++++++++++++++-------- src/effects/alien.rs | 62 +++++++++++++++++++++++++-------- src/lib.rs | 5 +-- src/processor.rs | 67 ++++++++++++++++++++++++++---------- src/resynthesis.rs | 22 ++++++------ src/wasm.rs | 8 +++-- 8 files changed, 181 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index 83a8f47..c436317 100644 --- a/README.md +++ b/README.md @@ -167,16 +167,20 @@ voice. It disables the effects and the formant stage. | Correction | Moves the pitch to the nearest permitted note | Chromatic | `resynthesis.correction` | | Voices | Renders a choir (1 to 16 voices) or harmony (lead and 0–4) | Choir, 1 voice | `resynthesis.mode` | | Formant | Changes the vocal tract with an LPC model and aspiration | Disabled | `resynthesis.formant` | -| Alien | Plays recent audio in reverse loops | Disabled | `alien` | +| Alien | Plays recent audio in reverse loops, with wet mix | Disabled | `alien` | | Reverb | Echo, Schroeder, SmallRoom, Binaural, MediumHall, LargeHall | Disabled | `reverb` | -| Output gain | Linear gain, 0..=64, before `-32767..=32767` clipping | 1 | `output_gain` | +| Output gain | Linear gain, 0..=64, before global mix | 1 | `output_gain` | +| Mix | Global wet fraction, 0..=1, before `-32767..=32767` clip | 1 | `mix` | +| Bypass | Outputs the 1,593-frame delayed input before Punch | Disabled | `bypass` | 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.dry_mix` sets the dry fraction at the resynthesis stage. That +dry path starts after Warm and has a delay of 1,593 frames. `mix` blends +the wet output with the 1,593-frame delayed input before Punch. If Alien is +enabled, `alien.mix` sets the wet fraction of the reversed loop. ### Harmony sources @@ -311,8 +315,8 @@ 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. The dry paths and bypass have a delay of +1,593 frames. Resampled voices and effects have their own delays. `formant_envelope()` writes two LPC envelopes into slices of equal length: @@ -451,10 +455,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`. If an optional field is absent, +`resynthesis.harmony.voices` defaults to 4, `mix` and `alien.mix` default to +1, and `bypass` defaults to `false`. 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/docs/images/signal-chain.svg b/docs/images/signal-chain.svg index 5310bc8..fe441f1 100644 --- a/docs/images/signal-chain.svg +++ b/docs/images/signal-chain.svg @@ -92,7 +92,7 @@ - dry_mix: the dry path, 1,543 frames of delay (default 0) + dry_mix: the dry path, 1,593 frames of delay (default 0) diff --git a/src/config.rs b/src/config.rs index 75bcd82..fe287a7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -121,14 +121,15 @@ impl PrepareConfig { /// The settings for the complete signal chain, in the order of the stages. /// -/// The default enables chromatic pitch correction, one choir voice and unity -/// output gain. Punch, Warm, formants, Alien and reverb are disabled. This -/// configuration does active pitch processing. It is not a bypass with zero -/// latency. +/// The default enables chromatic pitch correction, one choir voice, unity +/// output gain and unity global mix. Punch, Warm, formants, Alien, reverb and +/// bypass are disabled. This configuration does active pitch correction. It is +/// not a bypass with zero latency. /// /// Change a copy, then apply it with [`crate::Processor::set_config`] or /// [`crate::ControlEvent::Configure`]. The validation examines all fields -/// before a change has an effect. This includes the fields of disabled stages. +/// before a change has an effect. This includes the fields of disabled stages +/// and `mix` while `bypass` is `true`. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -161,16 +162,48 @@ pub struct ProcessorConfig { pub reverb: ReverbConfig, /// The linear gain after all effects, 0..=64. /// - /// The default is 1 (unity). Zero mutes the output, but the internal - /// processing continues. The gain is quantized in steps of 1/256 before - /// the fixed-point multiplication and the final PCM clipping. Thus, a - /// positive value below 1/256 also mutes the output. + /// The default is 1 (unity). If `mix` is 1, zero mutes the output, and + /// the internal stages continue to advance. The code quantizes the gain in + /// steps of 1/256 before the fixed-point multiplication and the global + /// mix. Thus, a positive value below 1/256 also mutes the wet path. pub output_gain: f32, + /// The global wet fraction after the output gain, 0..=1. + /// + /// The default is 1. The code quantizes this value to Q14. The dry path + /// delays the input before Punch by 1,593 frames. The wet weight is `mix` + /// and the dry weight is `1 - mix`, before the `-32767..=32767` clip. In + /// JavaScript, this field is optional. If it is absent, the default is 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_mix"), + tsify(optional) + )] + pub mix: f32, + /// Selects the latency-aligned dry input instead of the processed chain. + /// + /// The default is `false`. If `bypass` is `true`, the processor outputs + /// the 1,593-frame delayed input before Punch, clipped to + /// `-32767..=32767`. The internal stages continue to advance. In + /// JavaScript, this field is optional. If it is absent, the default is + /// `false`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub bypass: bool, +} + +/// The default global wet fraction: the full processed signal. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_mix() -> f32 { + 1.0 } impl Default for ProcessorConfig { /// Returns chromatic correction with zero retune time, one choir voice, - /// disabled effects, disabled formants and unity gain. + /// disabled effects, disabled formants, unity gain, unity mix and + /// disabled bypass. fn default() -> Self { Self { punch: PunchConfig::default(), @@ -179,16 +212,19 @@ impl Default for ProcessorConfig { alien: AlienConfig::default(), reverb: ReverbConfig::default(), output_gain: 1.0, + mix: 1.0, + bypass: false, } } } impl ProcessorConfig { - /// Checks all stages and the final gain, and does not change state. + /// Checks all stages, the output gain and the global mix, and does not + /// change state. /// /// The validation uses the signal order: Punch, Warm, resynthesis, Alien, - /// reverb, then output gain. It includes disabled stages and the controls - /// of voice modes that are not active. + /// reverb, output gain, then global mix. It includes disabled stages, + /// inactive voice modes and `mix` while `bypass` is `true`. /// /// # Errors /// @@ -201,7 +237,8 @@ impl ProcessorConfig { self.resynthesis.validate()?; self.alien.validate()?; self.reverb.validate()?; - validate_output_gain(self.output_gain) + validate_output_gain(self.output_gain)?; + check_range("mix", self.mix, 0.0, 1.0) } } diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 271cae5..5ff73d9 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -1,6 +1,7 @@ //! Reverse-loop playback with a continuous input history and boundary fades. -use crate::error::check_count; +use crate::error::{check_count, check_range}; +use crate::numeric::clamp_i32; use crate::numeric::fixed::{Fixed, Q14}; use crate::Error; @@ -24,36 +25,58 @@ const FADE_FRAMES: usize = 200; serde(rename_all = "camelCase") )] pub struct AlienConfig { - /// Selects reversed playback instead of the direct input. The default is - /// `false`. The recording and the phase continue to advance in both - /// states. + /// Enables the reversed loop. The default is `false`. + /// + /// The history and the phase continue to advance in both states. pub enabled: bool, /// The loop length in frames, 1..=96000. The default is 95,999. /// This value is a frame count at the two rates. Thus, its duration in /// seconds changes with the sample rate. A short loop can be fully inside /// the fades. pub loop_frames: u32, + /// The wet fraction of the reversed loop, 0..=1. + /// + /// The default is 1. The code quantizes this value to Q14. The dry weight + /// of the direct stereo input is `1 - mix`. If `enabled` is `false`, the + /// stage returns the direct input. In JavaScript, this field is optional. + /// If it is absent, the default is 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "default_mix"), + tsify(optional) + )] + pub mix: f32, } + +/// The default wet fraction of Alien: full reversed playback. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn default_mix() -> f32 { + 1.0 +} + impl Default for AlienConfig { fn default() -> Self { Self { enabled: false, loop_frames: 95_999, + mix: 1.0, } } } impl AlienConfig { /// Validates all fields, also when Alien is disabled. /// - /// `loop_frames` must be in its documented inclusive range. Validation - /// does not clamp values. It does not change the processor state. + /// `loop_frames` must be in its documented inclusive range. `mix` must be + /// finite and in 0..=1. Validation does not clamp values. It does not + /// change the processor state. /// /// # Errors /// /// Returns the first [`Error::InvalidConfig`] with its dotted field path /// and the problem. pub fn validate(self) -> Result<(), Error> { - check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 96_000) + check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 96_000)?; + check_range("alien.mix", self.mix, 0.0, 1.0) } } @@ -76,6 +99,8 @@ pub(crate) struct Alien { loop_len: usize, /// The number of frames in `buffer` since construction or the last reset. written: usize, + /// The Q14 wet weight of the reversed loop. + mix: Q14, } impl Alien { /// Allocates a silent stereo ring from validated loop settings. @@ -87,6 +112,7 @@ impl Alien { phase: 0, loop_len: config.loop_frames as usize, written: 0, + mix: Q14::from_f64(f64::from(config.mix)), } } /// Applies a validated configuration, keeps the recorded audio and clamps @@ -95,6 +121,7 @@ impl Alien { self.config = config; self.loop_len = config.loop_frames as usize; self.phase = self.phase.min(self.loop_len - 1); + self.mix = Q14::from_f64(f64::from(config.mix)); } /// Returns the loop length and the current frame in the loop. /// @@ -111,11 +138,11 @@ impl Alien { self.read = 0; self.phase = 0; } - /// Records a frame, selects the direct or reverse output, then advances + /// Records a frame, blends the direct and reverse output, then advances /// both cursors. - /// The recording cursor moves forward by one and the reverse offset - /// increases by two. Thus, the playback moves backward by one frame. The - /// validated loop limit keeps that subtraction in a single ring wrap. + /// The cursor moves forward by one and the reverse offset increases by + /// two. Thus, the playback moves backward by one frame. The validated + /// loop limit keeps that subtraction in a single ring wrap. pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] { self.buffer[self.read] = input; if self.written < HISTORY_FRAMES { @@ -129,13 +156,20 @@ impl Alien { read }; let distance = self.phase.min(self.loop_len - self.phase); - let mut result = self.buffer[read]; + let mut reverse = self.buffer[read]; if distance < FADE_FRAMES { let gain: Q14 = Fixed::<0>::from_bits(distance as i32) .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); - result = result.map(|sample| sample.mul::<14, 14>(gain)); + reverse = reverse.map(|sample| sample.mul::<14, 14>(gain)); } - result + let wet = i64::from(self.mix.to_bits()); + let dry = i64::from((Q14::ONE - self.mix).to_bits()); + [0, 1].map(|channel| { + let blended = (i64::from(input[channel].to_bits()) * dry + + i64::from(reverse[channel].to_bits()) * wet) + >> 14; + Q14::from_bits(clamp_i32(blended)) + }) } else { input }; diff --git a/src/lib.rs b/src/lib.rs index f17bc85..ed71234 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,8 +3,9 @@ //! [`Processor`] changes mono signed 16-bit PCM into the same number of stereo //! or mono frames. The sample rate is 44.1 kHz or 48 kHz. The signal chain is //! Punch → Warm → pitch tracking and resynthesis → Alien → reverb → output -//! gain. The default configuration enables chromatic pitch correction and one -//! choir voice. The optional effects and the formant stage are disabled. +//! gain → mix, with a latency-aligned bypass. The default configuration +//! enables chromatic pitch correction and one choir voice. The optional +//! effects, the formant stage and bypass are disabled. //! //! # Preparing and configuring //! diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..e6c5ebe 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -5,6 +5,7 @@ use crate::effects::punch::{Punch, PunchConfig}; use crate::effects::reverb::{self, Reverb}; use crate::effects::warm::Warm; use crate::events::{ValidatedEvent, ValidatedEvents}; +use crate::numeric::fixed::Q14; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; @@ -31,6 +32,13 @@ pub struct Processor { /// /// The temporary aspiration mute of a drain is not stored here. config: ProcessorConfig, + /// The 1,593-frame input delay line before Punch, for global mix and + /// bypass. + dry: Box<[i16; resynthesis::LATENCY_FRAMES]>, + /// The current cursor in `dry`, always less than `LATENCY_FRAMES`. + dry_index: usize, + /// The Q14 global wet weight. + mix: Q14, /// The input dynamics stage, which advances only while it is enabled. punch: Punch, /// The input saturation stage, which advances only while it is enabled. @@ -96,10 +104,10 @@ impl Processor { /// /// # Errors /// - /// 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. + /// Returns [`Error::InvalidConfig`] if a stage field, the output gain or + /// the global mix 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. pub fn new(preparation: PrepareConfig, config: ProcessorConfig) -> Result { config.validate()?; let rate = preparation.sample_rate; @@ -109,6 +117,9 @@ impl Processor { Ok(Self { preparation, config, + dry: Box::new([0; resynthesis::LATENCY_FRAMES]), + dry_index: 0, + mix: Q14::from_f64(f64::from(config.mix)), punch, warm: Warm::new(rate, config.warm), resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), @@ -321,9 +332,9 @@ impl Processor { /// Returns the nominal resynthesis latency: 1,593 frames 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 paths and bypass have a delay of 1,593 frames. Resampled + /// voices, choir delays and effects have their own timing. Thus, this + /// value does not align all paths. pub fn latency_frames(&self) -> usize { resynthesis::LATENCY_FRAMES } @@ -501,6 +512,7 @@ impl Processor { if self.config.reverb != config.reverb { self.reverb.set_config(config.reverb); } + self.mix = Q14::from_f64(f64::from(config.mix)); self.config = config; self.drain_remaining = None; } @@ -508,10 +520,10 @@ impl Processor { /// Clears the audio histories, held notes, pitch feedback, peak and frame /// count. /// - /// This method cancels an active drain. It also clears the correction - /// ratio, the Punch envelopes, the Warm filters, the Alien recording and - /// the reverb delays. It releases the harmony MIDI notes and, in - /// MIDI-chord mode, the chord voices. It keeps these items: + /// This method cancels an active drain. It also clears the dry delay + /// buffer, the correction ratio, the Punch envelopes, the Warm filters, + /// the Alien history and the reverb delays. It releases the harmony MIDI + /// notes and, in MIDI-chord mode, the chord voices. It keeps these items: /// /// - the configuration /// - the random stream and the arctangent lookup position of Punch @@ -529,6 +541,8 @@ 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) { + self.dry.fill(0); + self.dry_index = 0; self.punch.reset(); self.warm.reset(); self.resynthesis.reset(); @@ -605,12 +619,18 @@ impl Processor { /// Renders one frame through the full chain and updates stereo feedback. /// - /// Resynthesis produces Q14 audio. Output gain is Q8. The gain product - /// uses `i64` arithmetic before the symmetric `-32767..=32767` PCM clamp. - /// This order and the peak measurement before the downmix are part of the - /// output. + /// Resynthesis produces Q14 audio. Output gain is Q8, and global mix is + /// Q14. The products use `i64` arithmetic before the symmetric + /// `-32767..=32767` PCM clamp. 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()); + let delayed = self.dry[self.dry_index]; + self.dry[self.dry_index] = input; + self.dry_index += 1; + if self.dry_index == resynthesis::LATENCY_FRAMES { + self.dry_index = 0; + } if self.config.punch.enabled { input = self.punch.process_sample(input, &mut self.numeric); } @@ -621,10 +641,19 @@ impl Processor { self.last_resample_ratio = self.resynthesis.resample_ratio(); let alien = self.alien.process_sample(voice); let reverb = self.reverb.process_sample(alien); - let gain = (self.config.output_gain as f64 * 256.0) as i64; - let result = reverb.map(|sample| { - (((i64::from(sample.to_bits()) * gain) >> 8) << 1).clamp(-32767, 32767) as i16 - }); + let result = if self.config.bypass { + [delayed.max(-32767); 2] + } else { + let gain = (self.config.output_gain as f64 * 256.0) as i64; + let wet_mix = i64::from(self.mix.to_bits()); + let dry_mix = i64::from((Q14::ONE - self.mix).to_bits()); + let dry = i64::from(delayed); + reverb.map(|sample| { + let wet = ((i64::from(sample.to_bits()) * gain) >> 8) << 1; + let blended = (dry * dry_mix + wet * wet_mix) >> 14; + blended.clamp(-32767, 32767) as i16 + }) + }; self.peak = self .peak .max((result[0] as i32).abs()) diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..7c3edab 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -153,10 +153,10 @@ impl CorrectionConfig { /// 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. +/// The dry path takes the audio after Punch and Warm and delays it by 1,593 +/// frames. The wet voice readers start at the same delay and move with the +/// pitch and the choir delay. After this stage, the two paths go through +/// Alien, reverb, the output gain and the global mix. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -239,8 +239,8 @@ pub struct ResynthesisConfig { /// /// 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. + /// delay of 1,593 frames. Alien, reverb, the output gain and the global + /// mix 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`. @@ -321,18 +321,16 @@ const SEEDS: [i32; 16] = [ 0x0dda, 0x01da, 0x167f, 0x0896, ]; -/// The length of the analysis overlap buffer. The dry path has the same -/// delay. +/// The length of the analysis overlap buffer. const OVERLAP_FRAMES: usize = 1543; /// The offset from the history position of a reader to its position for /// formant synthesis. 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 and the delay of the dry paths. /// -/// The dry path uses only `OVERLAP_FRAMES`. +/// Each reader starts at this lag and moves with the pitch and the delay. pub(crate) const LATENCY_FRAMES: usize = OVERLAP_FRAMES + READER_LAG_FRAMES as usize; /// The counter value at which a control step runs. Usually, a step runs /// every 101 eligible frames. @@ -1183,7 +1181,7 @@ impl Resynthesis { } self.filtered[write] = filtered; let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); - let dry = self.raw[delayed]; + let dry = self.raw[ring(write as i32 - LATENCY_FRAMES as i32)]; let mut mix = [Q14::ZERO; 2]; let mut final_ratio = Q14::ONE; if self.config.mode == MultiVoiceMode::Choir { diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..ec0cb97 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -20,6 +20,8 @@ //! - Enum values are strings. //! - Each object must contain all required fields. //! - The optional harmony `voices` field defaults to 4. +//! - The optional `mix` and `alien.mix` fields default to 1. +//! - The optional `bypass` field defaults to `false`. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use @@ -193,9 +195,9 @@ impl WasmProcessor { /// The nominal resynthesis latency: 1,593 frames 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 - /// paths. + /// The dry paths and bypass have a delay of 1,593 frames. 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 { self.processor.latency_frames()