From c32141492a048c320c8c1e2f12395a8d78f7cc6e 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:38:08 +0000 Subject: [PATCH] fix: restore the initial state on reset without memory allocation - Reload the configured correction scale in CorrectionTable::reset - Clear the harmony envelopes and caches in HarmonyState::reset - Clear the resynthesis controllers in Resynthesis::reset - Clear PitchTracker::previous_period and best on a full reset - Restore NumericContext in Processor::reset - Clear the reverb filters and write cursor in Reverb::reset - Restore the initial base drive in Punch::reset - Update the reset documentation in README.md and rustdoc --- README.md | 7 +++-- src/effects/punch.rs | 9 +++---- src/effects/reverb.rs | 27 +++++++++++++++---- src/harmony.rs | 40 +++++++++++++++++++++------- src/lib.rs | 7 ++--- src/numeric.rs | 10 +++++-- src/numeric/rng.rs | 2 +- src/pitch/tracker.rs | 10 ++++++- src/processor.rs | 59 ++++++++++++++++++++-------------------- src/resynthesis.rs | 62 +++++++++++++++++++++++++------------------ src/scale.rs | 22 ++++++++++++--- src/wasm.rs | 10 ++++--- 12 files changed, 174 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index 83a8f47..fb19c02 100644 --- a/README.md +++ b/README.md @@ -286,8 +286,11 @@ sets the configuration cancels the drain. `reset()` also cancels the drain. ### Reset -`reset()` keeps the configuration, the random stream and some controller and -filter state. If you need a fully new state, construct a new processor. +`reset()` restores the initial state for the current configuration without +memory allocation. It clears the audio histories, the controllers, the held +MIDI notes, the feedback and the frame count. It loads the configured +correction notes again. It also starts the random stream from `random_seed`. +The configuration and `formant_generation` in the telemetry do not change. ## Feedback and telemetry diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..ac36a45 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -21,8 +21,7 @@ const TWO_OVER_PI: Q14 = Q14::from_bits(10430); /// its envelope and window state do not change. /// /// A gain change updates the cached drive at the next boundary of the peak -/// window. A reset calculates that drive again immediately from the -/// configured gain. +/// window. A reset restores the default base drive until that boundary. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -160,14 +159,14 @@ impl Punch { 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)); } - /// Clears both envelopes and the current window, then calculates the drive - /// again from the base drive and the input gain. + /// Clears both envelopes and the current window, and restores the base + /// drive. pub(crate) fn reset(&mut self) { self.slow = Q14::default(); self.fast = Q14::default(); self.counter = 0; self.peak = Q14::default(); - self.drive = BASE_DRIVE.mul(self.gain); + self.drive = BASE_DRIVE; } /// Moves `current` toward `target` with a one-pole filter. diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index 3a7dfce..78544d7 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -39,9 +39,9 @@ pub enum ReverbMode { /// The reverb is disabled by default. In bypass, the stage returns the input /// and does not advance the delay network or the damping filters. If the /// stage is enabled and the mix is zero, the network still operates. A reset -/// clears the delay buffer but keeps the memories of the damping filters. The -/// mix, diffusion and decay controls are quantized to Q14. The function of -/// each control changes with the network. +/// clears the delay buffer, the write position and the memories of the +/// damping filters. The mix, diffusion and decay controls are quantized to +/// Q14. The function of each control changes with the network. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -209,11 +209,23 @@ impl Reverb { } /// Clears only the delay contents, and keeps the write cursor and the /// damping memories. + pub(crate) fn reset_delay(&mut self) { + if self.dirty { + self.delay.clear(); + self.dirty = false; + } + } + /// Clears the delay contents, resets the write cursor to zero and clears + /// both damping filters. pub(crate) fn reset(&mut self) { if self.dirty { self.delay.reset(); self.dirty = false; + } else { + self.delay.write = 0; } + self.lpf1.reset(); + self.lpf2.reset(); } /// Returns the largest absolute Q14 wet contribution since the last /// clear, as f32. @@ -431,7 +443,7 @@ struct DelayLine { /// the Q14 audio scale. buffer: Vec, /// The current frame position, always less than the buffer length. A - /// reset does not change it. + /// delay clear keeps it, and a full reset sets it to zero. write: usize, } impl DelayLine { @@ -444,9 +456,14 @@ impl DelayLine { } } /// Clears the samples and does not move the current write position. - fn reset(&mut self) { + fn clear(&mut self) { self.buffer.fill(Q14::default()); } + /// Clears the samples and sets the write position to zero. + fn reset(&mut self) { + self.clear(); + self.write = 0; + } /// Maps a delay to a storage index with a maximum of one wrap. /// /// Each offset from the caller must not be more than the buffer length. diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..f89ceab 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -423,8 +423,8 @@ pub(crate) struct HarmonyState { /// The last usable Q14 ratio of the input period to the smoothed target /// period for each voice. current_ratio: [Q14; HARMONY_VOICES], - /// The Q12 attack and release envelope. A MIDI release or a reset does - /// not clear it. + /// The Q12 attack and release envelope. A MIDI release does not clear it, + /// and a full reset sets it to zero. smoothed_gain: [Q12; HARMONY_VOICES], /// The last active Q6 target. It is kept while the gain of a released /// voice decreases to zero. @@ -509,8 +509,8 @@ impl HarmonyState { /// Applies a configuration that validation already accepted. /// /// If the source changes to an interval source or to a named or degree - /// chord source, the function calls `reset`. It prepares the tables - /// again only for the fields that changed. + /// chord source, the function calls `release_notes`. It prepares the + /// tables again only for the fields that changed. pub(crate) fn apply_config(&mut self, config: HarmonyConfig) { let old = self.config; self.config = config; @@ -523,7 +523,7 @@ impl HarmonyState { | HarmonySource::ChordByName ) { - self.reset(); + self.release_notes(); } if old.key != config.key || old.scale != config.scale @@ -560,7 +560,7 @@ impl HarmonyState { /// chord again from the released notes. Thus the chord voices decay /// with the gain release. The other chord sources keep their chord /// preparation. - pub(crate) fn reset(&mut self) { + pub(crate) fn release_notes(&mut self) { self.midi_period.fill(Q6::ZERO); self.portamento_period.fill(Q6::ZERO); self.pending_gain.fill(Q12::ZERO); @@ -570,6 +570,28 @@ impl HarmonyState { self.setup_chord(); } } + /// Restores the envelopes, targets, MIDI slots and scale caches to their + /// initial values for the current configuration. + pub(crate) fn reset(&mut self) { + self.midi_note = [0; HARMONY_VOICES]; + self.midi_period = [Q6::ZERO; HARMONY_VOICES]; + self.midi_gain = [Q12::ZERO; HARMONY_VOICES]; + self.midi_order = [0; HARMONY_VOICES]; + self.portamento_period = [Q6::ZERO; HARMONY_VOICES]; + self.current_ratio = [Q14::ONE; HARMONY_VOICES]; + self.smoothed_gain = [Q12::ZERO; HARMONY_VOICES]; + self.period_output = [Q6::ZERO; HARMONY_VOICES]; + self.target_period = [Q6::ZERO; HARMONY_VOICES]; + self.chord_period = [Q6::ZERO; HARMONY_VOICES]; + self.chord_gain = [Q12::from_bits(-16_384); HARMONY_VOICES]; + self.current_idx = [39; HARMONY_VOICES]; + self.scale_target = [Q6::ZERO; HARMONY_VOICES]; + self.scale_note = [0; HARMONY_VOICES]; + self.pending_gain.fill(Q12::ZERO); + self.pending_order.fill(0); + self.event_counter = 0; + self.setup_chord(); + } /// Converts cents above C4 to a Q6 sample period. C4 is 900 cents below /// A4 at 440 Hz. /// The intermediate period is rounded to f32 before the fixed-point @@ -701,12 +723,12 @@ impl HarmonyState { /// the omni sources. The omni sources steal the oldest voice and resume /// the newest pending note. If two orders are equal, strict comparisons /// keep the lowest voice index or pitch. Each Note Off clears the pending - /// entry of its pitch. All Notes Off calls `reset` and returns `false`. - /// The gain releases occur at the next control steps. + /// entry of its pitch. All Notes Off calls `release_notes` and returns + /// `false`. The gain releases occur at the next control steps. pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) -> bool { let (channel, note, velocity) = match event { MidiEvent::AllNotesOff => { - self.reset(); + self.release_notes(); return false; } MidiEvent::NoteOn { diff --git a/src/lib.rs b/src/lib.rs index f17bc85..e189b23 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -73,9 +73,10 @@ //! successful process call, a successful configuration call or a reset //! cancels the drain. //! -//! [`Processor::reset`] keeps the configuration and some controller state, for -//! example the random stream. Its documentation lists the state that it keeps. -//! If you need a fully new instance, make a new processor. +//! [`Processor::reset`] restores the initial state for the current +//! configuration without memory allocation. It clears the audio histories, the +//! controllers, the held MIDI notes, the feedback and the frame count. The +//! configuration and [`Telemetry::formant_generation`] do not change. //! //! # Execution model //! diff --git a/src/numeric.rs b/src/numeric.rs index e67db8f..8bf6c9e 100644 --- a/src/numeric.rs +++ b/src/numeric.rs @@ -162,10 +162,10 @@ pub(crate) fn envelope_decay(milliseconds: f64, rate: f64, window: usize) -> f64 /// The lookup cache and the pseudo-random state for all stages of one /// processor chain. /// -/// An audio reset keeps this state. +/// A stereo change keeps this state, and a processor reset restores it. #[derive(Debug)] pub(crate) struct NumericContext { - /// The lookup cursor for Punch. An audio reset keeps its position. + /// The lookup cursor for Punch. pub atan_q14: AtanQ14, /// The random stream for choir and aspiration. The order in which stages /// read values sets the random values that later stages get. @@ -180,6 +180,12 @@ impl NumericContext { random: RandomStream::new(seed), } } + /// Restores the initial arctangent lookup cursor and starts the random + /// stream again from `seed`. + pub(crate) fn reset(&mut self, seed: u32) { + self.atan_q14 = AtanQ14::default(); + self.random = RandomStream::new(seed); + } } /// The capacity in frames of the history for pitch and resynthesis. The /// value is the same at the two supported rates. diff --git a/src/numeric/rng.rs b/src/numeric/rng.rs index b8600ff..e09fec8 100644 --- a/src/numeric/rng.rs +++ b/src/numeric/rng.rs @@ -5,7 +5,7 @@ //! stream. The order in which stages read values is part of the repeatable //! result. If you enable a stage that reads the stream, later stages get //! different values. This generator is for audio. It is not a cryptographic -//! random source. An audio reset does not set a new seed. +//! random source. A processor reset starts the stream again from the seed. /// The 48-bit linear congruential state, made from a 32-bit seed. #[derive(Debug)] diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index c46ed9b..0c3d8c5 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -150,7 +150,7 @@ impl PitchTracker { /// memories, and requests acquisition. /// The acquisition tables clear at the next decimated call. The previous /// usable period stays until another tracking update replaces it. - pub(crate) fn reset(&mut self) { + pub(crate) fn reset_audio(&mut self) { let written = usize::from(self.written); if written == HISTORY { self.raw.fill(0); @@ -165,6 +165,14 @@ impl PitchTracker { } } + /// Clears the audio state, the previous usable period and the last minimum + /// slot. + pub(crate) fn reset(&mut self) { + self.reset_audio(); + self.previous_period = Q6::default(); + self.best = 0; + } + /// Invalidates the current period and keeps the previous usable period. /// The acquisition tables clear later, at the next acquisition sample. fn restart(&mut self) { diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..8c68e1c 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -490,7 +490,7 @@ impl Processor { } if self.config.resynthesis.stereo_output != config.resynthesis.stereo_output { // Resynthesis resets its histories if its stereo setting changes. - self.reset_post_resynthesis(); + self.reset_post_resynthesis(false); } if self.config.resynthesis.random_seed != config.resynthesis.random_seed { self.numeric.random = RandomStream::new(config.resynthesis.random_seed as u32); @@ -505,45 +505,46 @@ impl Processor { self.drain_remaining = None; } - /// 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: - /// - /// - the configuration - /// - the random stream and the arctangent lookup position of Punch - /// - the reverb low-pass memories and the reverb write position - /// - correction key 127 and the active correction note table - /// - the last usable period of the pitch tracker, which fills unvoiced - /// gaps - /// - the harmony gain envelopes and the last voice ratios of the harmony - /// controller - /// - the prepared chord targets of the named and degree chord sources - /// - the choir drift - /// - the control-step counter of Choir and Harmony - /// - the phase of the harmonic modulation. - /// - /// When the method clears the held keys, it does not load the configured - /// scale again. For a fully new state, make a new processor. + /// Restores the initial state for the current configuration without memory + /// allocation. + /// + /// This method cancels an active drain. It clears all audio and filter + /// histories, the pitch tracker and the formant synthesis state. It also + /// clears the choir drift, the modulation phase and the harmony envelopes + /// and voices. The peak windows, the reported correction ratio and the + /// frame count reset to zero. + /// + /// The method releases all harmony MIDI notes and all 128 correction keys. + /// Then it loads the configured correction scale again, with the initial + /// sample-rate rule of [`crate::CorrectionConfig`]. It restores the + /// initial Punch drive and arctangent cursor. It also starts the random + /// stream again from the low 32 bits of `random_seed`. + /// + /// The preparation, the active configuration and + /// [`Telemetry::formant_generation`] do not change. pub fn reset(&mut self) { self.punch.reset(); self.warm.reset(); self.resynthesis.reset(); - self.reset_post_resynthesis(); + self.reset_post_resynthesis(true); + self.numeric + .reset(self.config.resynthesis.random_seed as u32); self.frames = 0; self.drain_remaining = None; } /// 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. - fn reset_post_resynthesis(&mut self) { + /// A full reset clears the reverb filters and write cursor. A change of + /// stereo output clears only the reverb delay buffer. The frame count does + /// not change here. + fn reset_post_resynthesis(&mut self, full: bool) { self.alien.reset(); - self.reverb.reset(); + if full { + self.reverb.reset(); + } else { + self.reverb.reset_delay(); + } self.peak = 0; self.clear_telemetry_peaks(); self.last_resample_ratio = 0.0; diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..abaf2ae 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -70,13 +70,13 @@ pub enum MultiVoiceMode { /// /// Correction MIDI replaces the active note table. It does not change this /// configuration. A change to `notes` or to `enabled` loads the configured -/// mask again. Reset releases the correction keys 0..=126. It keeps key 127 -/// and the active note table. Key 127 has no effect on the note table. +/// mask again. Reset clears all 128 correction keys and loads the configured +/// mask again. Key 127 has no effect on the note table. /// -/// At construction, the chromatic table uses 44.1 kHz periods, also for a -/// 48 kHz processor. Each of these events loads the periods for the prepared -/// rate: -/// - An initial mask that is not chromatic. +/// At construction and after a reset, the chromatic table uses 44.1 kHz +/// periods, also for a 48 kHz processor. Each of these events loads the +/// periods for the prepared rate: +/// - An initial or reset mask that is not chromatic. /// - A later change to the mask or to `enabled`. /// - A correction MIDI event. #[derive(Clone, Copy, Debug, PartialEq)] @@ -97,7 +97,8 @@ pub struct CorrectionConfig { /// [`NoteMask::CHROMATIC`]. /// /// All boolean masks are valid. MIDI can replace the active table. This - /// replacement stays until this mask or `enabled` changes. + /// replacement stays until a reset or a change to this mask or to + /// `enabled`. pub notes: NoteMask, /// The half-life of the smoothing in milliseconds, 0..=400. The default /// is 0. @@ -248,8 +249,8 @@ pub struct ResynthesisConfig { /// Only the low 32 bits select the sequence. If a configuration change /// gives a different 64-bit value, the processor starts the stream again /// from the low 32 bits. This is also true for a change to only the high - /// bits. Reset keeps the current position in the stream. The enabled - /// stages set the number of random values that the code reads. + /// bits. Reset also starts the stream again from the low 32 bits. The + /// enabled stages set the number of random values that the code reads. pub random_seed: u64, } @@ -673,35 +674,40 @@ impl Resynthesis { if old.stereo_output != config.stereo_output { // A stereo change resets the audio state. The correction keyboard // keeps its held keys. - self.reset_audio(); + self.reset_audio(false); } } - /// Releases the correction keys 0..=126 and resets the audio state. - /// - /// The active correction table, key 127 and the items that - /// `reset_audio` keeps do not change. + /// Restores the correction table, the audio histories and the voice + /// controllers to their initial state for the current configuration. pub(crate) fn reset(&mut self) { - self.scale.reset(); - self.reset_audio(); + self.scale.reset(self.rate, self.config.correction.notes); + self.reset_audio(true); + self.drift.fill(Q14::ZERO); + self.harmony_gains.fill(Q12::ZERO); + self.modulation_phase = Q14::ZERO; + self.scale_index = 0; + self.octave = 0; + self.control_counter = CONTROL_DUE; } /// Clears the audio and period histories, the tracker, the formant /// synthesis and the filter history. Then initializes the readers and /// the correction again. /// - /// These items do not change: - /// - The correction keyboard. - /// - The active note table. - /// - The random state that the caller holds. - /// - The choir drift. - /// - The modulation phase. - /// - The control counter. + /// If `full` is `false`, a stereo change keeps these items: + /// - The correction keyboard and the active note table. + /// - The previous usable period of the pitch tracker. + /// - The choir drift, the modulation phase and the control counter. /// - The harmony release envelopes and the last harmony gains. - fn reset_audio(&mut self) { + fn reset_audio(&mut self, full: bool) { let written = usize::from(self.written); self.written = 0; - self.pitch.reset(); + if full { + self.pitch.reset(); + } else { + self.pitch.reset_audio(); + } if written == HISTORY { self.raw.fill(Q14::ZERO); self.filtered.fill(Q14::ZERO); @@ -729,7 +735,11 @@ impl Resynthesis { } self.write = 0; self.formant.reset(); - self.harmony.reset(); + if full { + self.harmony.reset(); + } else { + self.harmony.release_notes(); + } if written >= OVERLAP_FRAMES { self.overlap.fill(Q14::ZERO); } else if written > 0 { diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..fee1bfa 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -163,7 +163,8 @@ pub(crate) struct CorrectionTable { base_periods: [i32; 12], /// The held MIDI keys. /// - /// A reset keeps key 127, and mask creation excludes it. + /// All Notes Off keeps key 127, a full reset clears all keys, and mask + /// creation excludes key 127. pub keyboard: [bool; 128], } @@ -222,9 +223,22 @@ impl CorrectionTable { /// Releases keys 0..=126, and keeps key 127 and the active target table. /// /// A later MIDI event builds the table again from the new keyboard state. - pub(crate) fn reset(&mut self) { + pub(crate) fn release_keys(&mut self) { self.keyboard[..127].fill(false); } + /// Clears all 128 keys and loads `mask` with the initial sample-rate rule. + /// + /// Chromatic loads the 44.1 kHz periods first and updates `base_periods` + /// to `rate`. Other masks load the periods for `rate`. + pub(crate) fn reset(&mut self, rate: SampleRate, mask: NoteMask) { + self.keyboard.fill(false); + self.set_sample_rate(SampleRate::Hz44100); + self.set_notes(NoteMask::default()); + self.set_sample_rate(rate); + if mask != NoteMask::default() { + self.set_notes(mask); + } + } /// Applies an event whose MIDI ranges were already checked. pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) { match event { @@ -232,10 +246,10 @@ impl CorrectionTable { self.keyboard[note as usize] = velocity != 0 } MidiEvent::NoteOff { note, .. } => self.keyboard[note as usize] = false, - MidiEvent::AllNotesOff => self.reset(), + MidiEvent::AllNotesOff => self.release_keys(), } let mut mask = [false; 12]; - // Correction excludes key 127, and a reset keeps that key. + // Correction excludes key 127, and All Notes Off keeps that key. for i in 0..127 { mask[i % 12] |= self.keyboard[i]; } diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..841d793 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -467,11 +467,13 @@ impl WasmProcessor { Ok(valid) } - /// Resets the audio histories and feedback, as the native processor does. + /// Restores the initial state for the current configuration, as the native + /// processor does. /// - /// The configuration, the random stream and some controller and filter - /// state do not change. This method cancels any active drain. For a fully - /// new instance, construct a new `Tunelet`. + /// This method cancels any active drain. It clears the audio histories, + /// the controllers, the held MIDI notes, the feedback and the frame count. + /// The configuration and `formantGeneration` in the telemetry do not + /// change. pub fn reset(&mut self) { self.processor.reset(); }