From c060b89b6844c55d59d8c5501ea03e5ddac6dc09 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:03:37 +0000 Subject: [PATCH 1/2] feat: add parallel mix controls and smoothed bypass - Align the resynthesis dry path to 1,593 frames. - Add Q14 mix controls to Punch, Warm and Alien. - Add global mix and 200-frame bypass to ProcessorConfig. - Add ControlEvent::Mix and ControlEvent::Bypass. - Preallocate the 1,593-frame raw dry buffer in Processor::new. - Clear the global dry buffer in Processor::reset. - Accept absent optional mix and bypass fields in JavaScript. - Update the rustdoc, signal-chain diagram and README.md. --- README.md | 30 ++++++++----- docs/images/signal-chain.svg | 2 +- src/config.rs | 54 +++++++++++++++++++---- src/effects/alien.rs | 44 +++++++++++++++---- src/effects/punch.rs | 25 ++++++++++- src/effects/warm.rs | 50 +++++++++++++++------ src/events.rs | 14 +++++- src/lib.rs | 5 ++- src/processor.rs | 84 ++++++++++++++++++++++++++++++++---- src/resynthesis.rs | 17 ++++---- src/wasm.rs | 25 +++++++---- 11 files changed, 279 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 83a8f47..6bf0fa0 100644 --- a/README.md +++ b/README.md @@ -169,14 +169,20 @@ voice. It disables the effects and the formant stage. | Formant | Changes the vocal tract with an LPC model and aspiration | Disabled | `resynthesis.formant` | | Alien | Plays recent audio in reverse loops | 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 `-32767..=32767` wet clamp | 1 | `output_gain` | +| Global mix | Wet fraction, 0..=1, with 1,593-frame raw dry path | 1 | `mix` | +| Global bypass | 200-frame crossfade to 1,593-frame raw dry path | Disabled | `bypass` | The internal Q14 stages use `i64` products and saturate at the `i32` -limits. Decrease `output_gain` to prevent `-32767..=32767` clipping on +limits. Decrease `output_gain` to prevent `-32767..=32767` saturation 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. +`punch.mix`, `warm.mix`, `alien.mix` and `reverb.mix` set the Q14 wet +fraction of each effect stage, in `0..=1`. In Warm, the 50 Hz high-pass +filter operates only on the wet path. `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` and `bypass` align to the raw input before +Punch with the same 1,593-frame delay. ### Harmony sources @@ -451,10 +457,12 @@ 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`. Optional `mix`, `punch.mix`, `warm.mix` and `alien.mix` +default to 1 if they are absent. Optional `bypass` defaults to `false`, and +optional `resynthesis.harmony.voices` defaults to 4. `defaultConfig()` +returns an object that contains these optional fields with their defaults. +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 @@ -463,8 +471,10 @@ telemetry use `bigint`. Frame offsets, block lengths and latency use ### Events The optional event argument is a `TimedEvent[]`. Controls use a `type` -discriminant and a `value` payload. The reset control has no payload. For -example, this event changes the final gain before the first frame: +discriminant and a `value` payload (`configure`, `resynthesis`, `punch`, +`warm`, `alien`, `reverb`, `outputGain`, `mix`, `bypass`, `midi` and +`correctionMidi`). The `reset` control has no payload. For example, this +event changes the final gain before the first frame: ```ts { offset: 0, event: { type: "outputGain", value: 0.5 } } 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..04540b2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -161,16 +161,41 @@ 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). Zero mutes the wet output, while the internal + /// stages continue to advance. The gain is quantized in steps of 1/256 + /// before the fixed-point multiplication and the `-32767..=32767` wet clamp. + /// Thus, a positive value below 1/256 also mutes the wet output. pub output_gain: f32, + /// The global wet fraction after `output_gain`, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. The dry path + /// reads the raw mono input before Punch, with a delay of 1,593 frames. All + /// internal stages continue to advance at all mix values. In JavaScript, + /// this field is optional and an absent value gives 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "crate::wasm::default_mix"), + tsify(optional) + )] + pub mix: f32, + /// Selects the 1,593-frame delayed raw input instead of the mixed output. + /// + /// The default is `false`. If `bypass` changes after construction, the + /// processor crossfades over 200 frames in Q14 while all internal stages + /// continue to advance. In JavaScript, this field is optional and an + /// absent value gives `false`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub bypass: bool, } 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, full wet mix and + /// disabled bypass. fn default() -> Self { Self { punch: PunchConfig::default(), @@ -179,16 +204,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 and + /// the controls of voice modes that are not active. /// /// # Errors /// @@ -201,7 +229,8 @@ impl ProcessorConfig { self.resynthesis.validate()?; self.alien.validate()?; self.reverb.validate()?; - validate_output_gain(self.output_gain) + validate_output_gain(self.output_gain)?; + validate_mix(self.mix) } } @@ -211,3 +240,10 @@ impl ProcessorConfig { pub(crate) fn validate_output_gain(gain: f32) -> Result<(), Error> { check_range("output_gain", gain, 0.0, 64.0) } + +/// Checks the global wet mix range. +/// +/// `ProcessorConfig` and `ControlEvent::Mix` use the same range. +pub(crate) fn validate_mix(mix: f32) -> Result<(), Error> { + check_range("mix", mix, 0.0, 1.0) +} diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 271cae5..ca8acd9 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,8 +25,9 @@ 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 + /// Enables reversed loop playback. The default is `false`. + /// + /// The history buffer and the loop phase continue to advance in both /// states. pub enabled: bool, /// The loop length in frames, 1..=96000. The default is 95,999. @@ -33,27 +35,42 @@ pub struct AlienConfig { /// seconds changes with the sample rate. A short loop can be fully inside /// the fades. pub loop_frames: u32, + /// The wet fraction, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. While Alien is + /// enabled, a zero mix still advances the history buffer and the loop + /// phase. In JavaScript, this field is optional and an absent value gives + /// 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "crate::wasm::default_mix"), + tsify(optional) + )] + pub mix: f32, } 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 its documented inclusive range. 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) } } @@ -63,11 +80,13 @@ impl AlienConfig { pub(crate) struct Alien { /// The validated controls, which include the selection of the wet output. config: AlienConfig, + /// The Q14 wet weight. The dry weight is `1 - mix`. + mix: Q14, /// 192,000 stereo Q14 frames, which are allocated one time at /// construction. buffer: Vec<[Q14; 2]>, - /// The current recording position. The position of the reverse reader - /// comes from this cursor. + /// The current write position. The position of the reverse reader comes + /// from this cursor. read: usize, /// The current frame in the loop. It is always less than `loop_len`. phase: usize, @@ -82,6 +101,7 @@ impl Alien { pub(crate) fn new(config: AlienConfig) -> Self { Self { config, + mix: Q14::from_f64((config.mix * 100.0) as f64 / 100.0), buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES], read: 0, phase: 0, @@ -93,6 +113,7 @@ impl Alien { /// the phase into the new loop, which is not empty. pub(crate) fn set_config(&mut self, config: AlienConfig) { self.config = config; + self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); self.loop_len = config.loop_frames as usize; self.phase = self.phase.min(self.loop_len - 1); } @@ -135,6 +156,13 @@ impl Alien { .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); result = result.map(|sample| sample.mul::<14, 14>(gain)); } + let wet_w = i64::from(self.mix.to_bits()); + let dry_w = i64::from((Q14::ONE - self.mix).to_bits()); + for (channel, sample) in result.iter_mut().enumerate() { + let dry = i64::from(input[channel].to_bits()); + let wet = i64::from(sample.to_bits()); + *sample = Q14::from_bits(clamp_i32((dry * dry_w + wet * wet_w) >> 14)); + } result } else { input diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..c48d3e8 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -54,6 +54,17 @@ pub struct PunchConfig { /// The default is 10 ms. The coefficients include the effect of the /// 100-frame update interval. pub attack_ms: f32, + /// The wet fraction, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. If Punch is + /// enabled, a zero mix still advances the envelopes and the drive. In + /// JavaScript, this field is optional and an absent value gives 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "crate::wasm::default_mix"), + tsify(optional) + )] + pub mix: f32, } impl Default for PunchConfig { fn default() -> Self { @@ -63,6 +74,7 @@ impl Default for PunchConfig { impact: 0.5, ceiling_db: -3.0, attack_ms: 10.0, + mix: 1.0, } } } @@ -81,7 +93,8 @@ impl PunchConfig { check_range("punch.gain_db", self.gain_db, -96.0, 12.0)?; check_range("punch.impact", self.impact, 0.0, 1.0)?; check_range("punch.ceiling_db", self.ceiling_db, -96.0, 0.0)?; - check_range("punch.attack_ms", self.attack_ms, 0.01, 5000.0) + check_range("punch.attack_ms", self.attack_ms, 0.01, 5000.0)?; + check_range("punch.mix", self.mix, 0.0, 1.0) } } @@ -110,6 +123,8 @@ pub(crate) struct Punch { gain: Q8, /// The linear output ceiling in Q14. It applies to the saturator angle. ceiling_gain: Q14, + /// The Q14 wet weight. The dry weight is `1 - mix`. + mix: Q14, /// The cached Q8 drive: base drive × envelope ratio × input gain. drive: Q8, } @@ -128,6 +143,7 @@ impl Punch { attack_decay: Q14::default(), gain: Q8::ONE, ceiling_gain: Q14::default(), + mix: Q14::ONE, drive: BASE_DRIVE, }; result.set_config(config); @@ -159,6 +175,7 @@ impl Punch { self.attack_decay = decay(config.attack_ms as f64); self.gain = Q8::from_f64(db_to_gain(config.gain_db as f64)); self.ceiling_gain = Q14::from_f64(db_to_gain(config.ceiling_db as f64)); + self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); } /// Clears both envelopes and the current window, then calculates the drive /// again from the base drive and the input gain. @@ -208,6 +225,10 @@ impl Punch { let driven: Q8 = sample.mul(self.drive); let angle = Q14::from_bits(context.atan_q14.process(driven.to_bits(), 14 - 8)); let output: Q14 = TWO_OVER_PI.mul(self.ceiling_gain.mul::<14, 14>(angle)); - output.to_bits().wrapping_shl(1).clamp(-32767, 32767) as i16 + let wet = i64::from(output.to_bits().wrapping_shl(1).clamp(-32767, 32767)); + let dry = i64::from(input); + let wet_w = i64::from(self.mix.to_bits()); + let dry_w = i64::from((Q14::ONE - self.mix).to_bits()); + (((dry * dry_w + wet * wet_w) >> 14).clamp(-32767, 32767)) as i16 } } diff --git a/src/effects/warm.rs b/src/effects/warm.rs index 9721ced..fbbeae0 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -9,10 +9,11 @@ use crate::{Error, SampleRate}; /// The update interval of the peak follower, in frames. const WINDOW_FRAMES: usize = 100; -/// Asymmetric input saturation, followed by a 50 Hz high-pass filter. +/// Asymmetric input saturation, with a 50 Hz high-pass filter on the wet path. /// /// Warm operates after Punch and before pitch detection. Its adaptive -/// normalization updates every 100 enabled frames. When Warm is disabled, +/// normalization updates every 100 enabled frames. The 50 Hz high-pass filter +/// applies only to the wet path, not to the dry path. When Warm is disabled, /// the envelope and filter histories do not change. When Warm is enabled /// again, they continue from their last state, unless the processor was /// reset. @@ -30,28 +31,42 @@ pub struct WarmConfig { /// The output gain changes by -0.35 dB for each dB of drive. At 0 dB, the /// envelope normalization and the output high-pass filter still operate. pub drive_db: f32, + /// The wet fraction, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. The 50 Hz + /// high-pass filter applies only to the wet signal before the blend. If + /// Warm is enabled, a zero mix still advances the envelope and the filter. + /// In JavaScript, this field is optional and an absent value gives 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default = "crate::wasm::default_mix"), + tsify(optional) + )] + pub mix: f32, } impl Default for WarmConfig { fn default() -> Self { Self { enabled: false, drive_db: 3.0, + mix: 1.0, } } } impl WarmConfig { /// Validates all fields, also when Warm is disabled. /// - /// `drive_db` must be finite and in its documented inclusive range. - /// Validation does not clamp values. It does not change the processor - /// state. + /// The floating-point controls must be finite and in their documented + /// inclusive ranges. 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_range("warm.drive_db", self.drive_db, 0.0, 6.0) + check_range("warm.drive_db", self.drive_db, 0.0, 6.0)?; + check_range("warm.mix", self.mix, 0.0, 1.0) } } @@ -77,6 +92,8 @@ pub(crate) struct Warm { drive: Q12, /// The Q14 compensation from the configured drive. output_gain: Q14, + /// The Q14 wet weight. The dry weight is `1 - mix`. + mix: Q14, /// The Q14 threshold of -30 dB. If the peak envelope is not above it, the /// normalization uses a fixed headroom. input_threshold: Q14, @@ -84,8 +101,9 @@ pub(crate) struct Warm { output_headroom: Q8, } impl Warm { - /// Prepares the fixed high-pass filter and the initial normalization - /// state. + /// Prepares the fixed 50 Hz high-pass filter on the wet path and the + /// initial normalization state. The dry path does not go through this + /// filter. pub(crate) fn new(rate: SampleRate, config: WarmConfig) -> Self { let mut filter = Biquad::new(); filter.set_design(Design::high_pass_one_pole(rate.hz(), 50.0)); @@ -98,6 +116,7 @@ impl Warm { smooth: Q14::from_f64(0.5_f64.powf(1.0 / (rate.hz() as f64 * 0.2 / 100.0))), drive: Q12::default(), output_gain: Q14::default(), + mix: Q14::ONE, input_threshold: Q14::from_f64(db_to_gain(-30.0)), output_headroom: Q8::from_f64(db_to_gain(30.0)), }; @@ -114,6 +133,7 @@ impl Warm { pub(crate) fn set_config(&mut self, config: WarmConfig) { self.drive = Q12::from_f64(db_to_gain(config.drive_db as f64)); self.output_gain = Q14::from_f64(db_to_gain(-(config.drive_db as f64) * 0.35)); + self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); } /// Clears the filter memories, the peak windows and the normalization, /// and keeps the coefficients. @@ -166,9 +186,15 @@ impl Warm { } sample = sample.div(self.compression); let output: Q14 = self.output_gain.mul::<14, 14>(sample) << 1; - self.filter - .process_sample(output) - .to_bits() - .clamp(-32767, 32767) as i16 + let wet = i64::from( + self.filter + .process_sample(output) + .to_bits() + .clamp(-32767, 32767), + ); + let dry = i64::from(input); + let wet_w = i64::from(self.mix.to_bits()); + let dry_w = i64::from((Q14::ONE - self.mix).to_bits()); + (((dry * dry_w + wet * wet_w) >> 14).clamp(-32767, 32767)) as i16 } } diff --git a/src/events.rs b/src/events.rs index e1c975c..fc70ec2 100644 --- a/src/events.rs +++ b/src/events.rs @@ -1,6 +1,6 @@ //! Controls for a block, which the processor validates before any change. -use crate::config::validate_output_gain; +use crate::config::{validate_mix, validate_output_gain}; use crate::effects::alien::AlienConfig; use crate::effects::punch::PunchConfig; use crate::effects::reverb::ReverbConfig; @@ -40,6 +40,16 @@ pub enum ControlEvent { /// The quantization and the mute behavior are the same as for /// [`ProcessorConfig::output_gain`]. The value must be finite. OutputGain(f32), + /// This event sets the global wet fraction, 0..=1. + /// + /// The quantization and the dry delay are the same as for + /// [`ProcessorConfig::mix`]. The value must be finite. + Mix(f32), + /// This event sets the global bypass state. + /// + /// If the value changes, the processor crossfades over 200 frames, as + /// [`ProcessorConfig::bypass`] describes. + Bypass(bool), /// This event sends a note control to the harmony source that /// [`crate::HarmonyConfig`] selects. /// @@ -81,6 +91,8 @@ impl ControlEvent { Self::Alien(config) => config.validate(), Self::Reverb(config) => config.validate(), Self::OutputGain(gain) => validate_output_gain(gain), + Self::Mix(mix) => validate_mix(mix), + Self::Bypass(_) => Ok(()), Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(), Self::Reset => Ok(()), } diff --git a/src/lib.rs b/src/lib.rs index f17bc85..85e5aee 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 → global mix → global bypass. The default configuration enables +//! chromatic pitch correction, one choir voice and a full wet mix. The +//! optional effects, the formant stage and the global bypass are disabled. //! //! # Preparing and configuring //! diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..d49210d 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -5,11 +5,23 @@ 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::{Fixed, Q14}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +/// The length in frames of the global bypass crossfade. +const BYPASS_FADE_FRAMES: u8 = 200; + +/// Allocates the 1,593-frame raw PCM delay buffer on the heap one time. +fn prepare_dry() -> Box<[i16; resynthesis::LATENCY_FRAMES]> { + vec![0_i16; resynthesis::LATENCY_FRAMES] + .into_boxed_slice() + .try_into() + .unwrap_or_else(|_| unreachable!("prepared dry buffer length")) +} + /// A prepared vocal processor with state, mono input and stereo synthesis. /// /// Construction fixes the sample rate and the block limit, and @@ -31,6 +43,16 @@ pub struct Processor { /// /// The temporary aspiration mute of a drain is not stored here. config: ProcessorConfig, + /// The 1,593-frame raw PCM ring before Punch, for global `mix` and + /// `bypass`. + dry: Box<[i16; resynthesis::LATENCY_FRAMES]>, + /// The current frame slot in `dry`, always less than 1,593. + dry_index: usize, + /// The quantized Q14 global wet weight. + mix: Q14, + /// The bypass crossfade position in `0..=200`. Zero is active and 200 is + /// bypassed. + bypass_fade: u8, /// The input dynamics stage, which advances only while it is enabled. punch: Punch, /// The input saturation stage, which advances only while it is enabled. @@ -109,6 +131,10 @@ impl Processor { Ok(Self { preparation, config, + dry: prepare_dry(), + dry_index: 0, + mix: Q14::from_f64((config.mix * 100.0) as f64 / 100.0), + bypass_fade: if config.bypass { BYPASS_FADE_FRAMES } else { 0 }, punch, warm: Warm::new(rate, config.warm), resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), @@ -321,9 +347,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 resynthesis dry path and the global `mix` and `bypass` dry path use + /// this 1,593-frame 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 } @@ -501,6 +527,9 @@ impl Processor { if self.config.reverb != config.reverb { self.reverb.set_config(config.reverb); } + if self.config.mix != config.mix { + self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); + } self.config = config; self.drain_remaining = None; } @@ -508,9 +537,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 + /// This method cancels an active drain and settles the bypass crossfade. + /// It clears the global dry 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 @@ -529,6 +559,13 @@ 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.bypass_fade = if self.config.bypass { + BYPASS_FADE_FRAMES + } else { + 0 + }; self.punch.reset(); self.warm.reset(); self.resynthesis.reset(); @@ -587,6 +624,8 @@ impl Processor { ControlEvent::Alien(value) => config.alien = value, ControlEvent::Reverb(value) => config.reverb = value, ControlEvent::OutputGain(value) => config.output_gain = value, + ControlEvent::Mix(value) => config.mix = value, + ControlEvent::Bypass(value) => config.bypass = value, ControlEvent::Midi(event) => { self.resynthesis.apply_midi(event); return; @@ -611,6 +650,12 @@ impl Processor { /// output. fn next(&mut self, mut input: i16) -> [i16; 2] { self.input_peak = self.input_peak.max((input as i32).abs()); + let dry_sample = 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); } @@ -622,9 +667,30 @@ impl Processor { let alien = self.alien.process_sample(voice); let reverb = self.reverb.process_sample(alien); let gain = (self.config.output_gain as f64 * 256.0) as i64; - let result = reverb.map(|sample| { - (((i64::from(sample.to_bits()) * gain) >> 8) << 1).clamp(-32767, 32767) as i16 - }); + let wet = reverb + .map(|sample| (((i64::from(sample.to_bits()) * gain) >> 8) << 1).clamp(-32767, 32767)); + let mix_wet = i64::from(self.mix.to_bits()); + let mix_dry = i64::from((Q14::ONE - self.mix).to_bits()); + let dry = i64::from(dry_sample); + let mixed = wet.map(|channel| (dry * mix_dry + channel * mix_wet) >> 14); + if self.config.bypass { + if self.bypass_fade < BYPASS_FADE_FRAMES { + self.bypass_fade += 1; + } + } else if self.bypass_fade > 0 { + self.bypass_fade -= 1; + } + let result = if self.bypass_fade == 0 { + mixed.map(|channel| channel.clamp(-32767, 32767) as i16) + } else { + let bypass_wet: Q14 = Fixed::<0>::from_bits(i32::from(self.bypass_fade)) + .div(Fixed::<0>::from_bits(i32::from(BYPASS_FADE_FRAMES))); + let dry_w = i64::from(bypass_wet.to_bits()); + let active_w = i64::from((Q14::ONE - bypass_wet).to_bits()); + mixed.map(|channel| { + (((channel * active_w + dry * dry_w) >> 14).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..69def21 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 have a nominal delay of 1,593 frames, which +/// changes with the pitch and the voice delay. After this stage, the two paths +/// go through Alien, reverb and the final output gain. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -239,7 +239,7 @@ 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 + /// delay of 1,593 frames. 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. @@ -321,8 +321,7 @@ 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. @@ -332,7 +331,7 @@ const READER_LAG_FRAMES: i32 = 50; /// The nominal latency of resynthesis. Each reader moves with the pitch and /// the delay. /// -/// The dry path uses only `OVERLAP_FRAMES`. +/// The dry path has this 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 +1182,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..45891de 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,7 +19,9 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. -//! - The optional harmony `voices` field defaults to 4. +//! - Optional `mix`, `punch.mix`, `warm.mix` and `alien.mix` default to 1. +//! - Optional `bypass` defaults to `false`. +//! - Optional `resynthesis.harmony.voices` defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use @@ -62,10 +64,12 @@ pub struct BlockEvents(Vec); /// Returns a complete, independent default configuration for JavaScript. /// -/// Change its fields and give it to `Tunelet` or to `setConfig`. The -/// `randomSeed` field is a JavaScript `bigint`, so it keeps all 64 bits. After -/// the binding decodes them, floating-point controls have the precision of the -/// Rust `f32` type. +/// The returned object includes all optional fields (`mix`, `bypass`, +/// `punch.mix`, `warm.mix`, `alien.mix` and `resynthesis.harmony.voices`) with +/// their default values. Change its fields and give it to `Tunelet` or to +/// `setConfig`. The `randomSeed` field is a JavaScript `bigint`, so it keeps +/// all 64 bits. After the binding decodes them, floating-point controls have +/// the precision of the Rust `f32` type. /// /// # Errors /// @@ -76,6 +80,11 @@ pub fn default_config() -> Result, JsError> { Ok(ProcessorConfig::default().into_ts()?) } +/// Returns the default wet mix of 1.0 for optional JavaScript fields. +pub(crate) fn default_mix() -> f32 { + 1.0 +} + /// A stateful PCM processor that JavaScript uses as the `Tunelet` class. /// /// The input is signed 16-bit mono PCM. The output is planar stereo or an @@ -193,9 +202,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 resynthesis dry path and the global `mix` and `bypass` dry path use + /// this 1,593-frame 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)] pub fn latency_frames(&self) -> usize { self.processor.latency_frames() From 3c2e2822d8311367d8fa327e9d4f312e86eda314 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:40:42 +0000 Subject: [PATCH 2/2] feat(events)!: mark ControlEvent as non-exhaustive - Add #[non_exhaustive] to ControlEvent. - Update the ControlEvent::validate error documentation. BREAKING CHANGE: ControlEvent adds Mix, Bypass and #[non_exhaustive]. --- src/events.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/events.rs b/src/events.rs index fc70ec2..f85a297 100644 --- a/src/events.rs +++ b/src/events.rs @@ -17,6 +17,7 @@ use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig}; /// Configuration changes have the same effects on state as /// [`crate::Processor::set_config`]. #[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), @@ -78,10 +79,10 @@ impl ControlEvent { /// /// # Errors /// - /// Returns [`Error::InvalidConfig`] for an invalid configuration or gain. - /// Returns [`Error::InvalidMidi`] for invalid MIDI fields. Reset is always - /// valid. The process call that contains the event checks the offset and - /// the order. + /// Returns [`Error::InvalidConfig`] for an invalid configuration, gain or + /// mix. Returns [`Error::InvalidMidi`] for invalid MIDI fields. Bypass and + /// reset are always valid. The process call that contains the event checks + /// the offset and the order. pub fn validate(self) -> Result<(), Error> { match self { Self::Configure(config) => config.validate(),