From 6eebd43ee60a4c260382fb29a99724b26d95b107 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:20:12 +0000 Subject: [PATCH 1/2] fix: calibrate drain budgets and processor resets - Initialize Punch with the configured gain in Processor::new. - Calibrate reverb tail budgets from the tap layout at -60 dBFS. - Defer the drain reset to the next non-empty zero-frame drain call. - Clear the harmony, resynthesis and correction state on a reset. - Reset the reverb filters, the pitch tracker, formants and the seed. - Update the lifecycle documentation in Rust, Wasm and the README. --- README.md | 15 ++-- docs/images/lifecycle.svg | 6 +- src/effects/reverb.rs | 143 +++++++++++++++++++++++++++++--------- src/events.rs | 5 +- src/formant.rs | 5 +- src/harmony.rs | 56 ++++++++------- src/lib.rs | 18 ++--- src/numeric.rs | 5 +- src/numeric/rng.rs | 3 +- src/pitch/tracker.rs | 21 ++++-- src/processor.rs | 131 +++++++++++++++++----------------- src/resynthesis.rs | 58 +++++++++------- src/scale.rs | 12 ++-- src/wasm.rs | 27 ++++--- 14 files changed, 311 insertions(+), 194 deletions(-) diff --git a/README.md b/README.md index d2993dc..aa0ea85 100644 --- a/README.md +++ b/README.md @@ -273,14 +273,19 @@ block. To get the tail, do these steps: 3. From each drain call, use only the frames that the call returns. The drain fills the unused output with zeros. The drain has a finite budget, -`tail_frames()`, which can include silence. The last drain call resets the -audio histories and the feedback. A successful call that processes audio or -sets the configuration cancels the drain. `reset()` also cancels the drain. +`tail_frames()`, which can include silence. Every call that returns frames +keeps the feedback and the telemetry of that block. After the last tail +frames, the next non-empty drain call returns zero and resets the processor. +Empty buffers do not advance or finish the drain. A successful call that +processes audio or sets the configuration, or `reset()`, 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()` clears all audio histories, filter memories, MIDI state, peak +windows and the frame count. It loads the configured correction notes again +and starts the random stream again from `random_seed` without memory +allocation. It keeps the preparation and the configuration, and gives the +same PCM output as `Processor::new` for equal inputs, settings and seeds. ## Feedback and telemetry diff --git a/docs/images/lifecycle.svg b/docs/images/lifecycle.svg index 05208f4..815d6f0 100644 --- a/docs/images/lifecycle.svg +++ b/docs/images/lifecycle.svg @@ -1,6 +1,6 @@ The processor lifecycle - Construction allocates the storage. Then the processor processes blocks. After the last block, begin_drain starts the tail. Drain calls return frames until the budget is used. Then the processor resets and can process again. + Construction allocates the storage. Then the processor processes blocks. After the last block, begin_drain starts the tail. Drain calls return frames until the budget is zero. Then the next non-empty drain call returns 0, resets the processor and finishes the drain. diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..333d398 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 cursor 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( @@ -125,11 +125,9 @@ pub(crate) struct Reverb { config: ReverbConfig, /// The shared circular storage for all network topologies. delay: DelayLine, - /// The first damping filter. A delay reset or a mode change does not - /// clear its memories. + /// The first damping filter. A mode change does not clear its memories. lpf1: Biquad, - /// The second damping filter. It keeps its memories in the same way as - /// the first filter. + /// The second damping filter. A mode change does not clear its memories. lpf2: Biquad, /// 67 prepared frame offsets into the shared ring. taps: [usize; 67], @@ -204,10 +202,12 @@ impl Reverb { self.lpf1.set_design(design); self.lpf2.set_design(design); } - /// Clears only the delay contents, and keeps the write cursor and the - /// damping memories. + /// Clears the delay buffer, sets the write cursor to zero and resets both + /// damping filters. pub(crate) fn reset(&mut self) { self.delay.reset(); + self.lpf1.reset(); + self.lpf2.reset(); } /// Returns the largest absolute Q14 wet contribution since the last /// clear, as f32. @@ -387,33 +387,113 @@ impl Reverb { } } -/// Estimates a finite tail budget from the largest modeled feedback -/// gain. +/// Estimates a finite tail budget from the tap layout and a -60 dBFS (1e-3) +/// decay threshold. /// -/// Each assumed circulation is 0.8 seconds long. The budget has the -/// circulations necessary to reach an amplitude of 1e-6, plus two seconds. -/// Fixed-point limit cycles can continue longer than this budget. If the -/// stage is disabled or the mix is zero, the function returns zero. +/// The function models outer comb loops and short allpass sections separately +/// for each [`ReverbMode`]. Fixed-point limit cycles below -60 dBFS can +/// continue after this budget. If the stage is disabled or the mix is zero, +/// the function returns zero. pub(crate) fn tail_frames(rate: SampleRate, config: ReverbConfig) -> usize { if !config.enabled || config.mix == 0.0 { return 0; } - let decay = config.decay as f64 / 1.05; - let diffuse = config.diffusion as f64; - let gain = match config.mode { - ReverbMode::Binaural => 0.0, - ReverbMode::Echo => decay, - ReverbMode::Schroeder => 0.9f64.max(decay), - ReverbMode::SmallRoom => 0.7f64.max(decay), - ReverbMode::MediumHall => (0.9 * diffuse).max(decay), - ReverbMode::LargeHall => (0.95 * diffuse).max(decay), + let layout = reverb_layout(rate.hz()); + let t = layout.taps; + let diffuse_q14 = Q14::from_f64((config.diffusion * 100.0) as f64 / 100.0); + let decay_q14 = Q14::from_f64((config.decay * 100.0) as f64 / 105.0); + let diffuse = diffuse_q14.to_bits() as f64 / 16384.0; + let decay = decay_q14.to_bits() as f64 / 16384.0; + let threshold = 1e-3_f64; + let comb_frames = |delay: usize, gain: f64| -> usize { + if delay == 0 || gain < threshold { + 0 + } else { + let turns = (threshold.ln() / gain.ln()).floor() as usize + 1; + turns * delay + } }; - let turns = if gain > 0.0 { - (1e-6f64.ln() / gain.ln()).ceil() - } else { - 1.0 + let allpass_frames = |first: usize, second: usize, gain: f64| -> usize { + let delay = t[second] - t[first]; + let initial = 1.0 - gain * gain; + if delay == 0 || gain <= 0.0 || initial < threshold { + delay + } else { + let turns = 1 + ((threshold / initial).ln() / gain.ln()).floor().max(0.0) as usize + 1; + turns * delay + } }; - (rate.hz() as f64 * (turns * 0.8 + 2.0)).ceil() as usize + let filter_margin = (rate.hz() as f64 * 0.05).ceil() as usize; + match config.mode { + ReverbMode::Binaural => (t[54] - t[40] + t[10] + layout.binaural_offset) + filter_margin, + ReverbMode::Echo => { + let echo: Fixed<0> = Fixed::<0>::from_bits(t[39] as i32).mul(diffuse_q14); + comb_frames(echo.to_bits() as usize, decay) + t[32] + filter_margin + } + ReverbMode::Schroeder => { + let combs = [ + comb_frames(t[12] - t[0], 0.9), + comb_frames(t[22] - t[13], 0.89), + comb_frames(t[28] - t[23], 0.87), + comb_frames(t[34] - t[29], 0.86), + ] + .into_iter() + .max() + .unwrap_or(0); + let allpasses = allpass_frames(40, 43, decay) + allpass_frames(44, 45, decay); + combs + allpasses + filter_margin + } + ReverbMode::SmallRoom => { + let half = (t[35] - t[0]).max(t[66] - t[40]); + let comb = comb_frames(half, decay) + half; + let allpasses = [ + allpass_frames(1, 15, 0.3), + allpass_frames(2, 7, 0.7), + allpass_frames(8, 14, 0.5), + allpass_frames(18, 24, 0.5), + allpass_frames(41, 50, 0.3), + allpass_frames(42, 46, 0.6), + allpass_frames(53, 57, 0.5), + ] + .into_iter() + .max() + .unwrap_or(0); + comb + allpasses + filter_margin + } + ReverbMode::MediumHall => { + let outer = (t[35] - t[0]) + (t[66] - t[40]); + let comb = comb_frames(outer, decay) + outer; + let allpasses = [ + allpass_frames(3, 15, 0.4 * diffuse), + allpass_frames(4, 7, 0.9 * diffuse), + allpass_frames(8, 14, 0.6 * diffuse), + allpass_frames(18, 24, 0.6 * diffuse), + allpass_frames(41, 50, 0.5 * diffuse), + allpass_frames(42, 46, 0.8 * diffuse), + ] + .into_iter() + .max() + .unwrap_or(0); + comb + allpasses + filter_margin + } + ReverbMode::LargeHall => { + let outer = (t[38] - t[1]) + (t[64] - t[40]); + let comb = comb_frames(outer, decay) + outer; + let allpasses = [ + allpass_frames(3, 5, 0.6 * diffuse), + allpass_frames(6, 9, 0.6 * diffuse), + allpass_frames(19, 30, 0.95 * diffuse), + allpass_frames(20, 27, 0.5 * diffuse), + allpass_frames(41, 63, 0.95 * diffuse), + allpass_frames(42, 58, 0.5 * diffuse), + allpass_frames(59, 62, 0.5 * diffuse), + ] + .into_iter() + .max() + .unwrap_or(0); + comb + allpasses + filter_margin + } + } } /// Circular Q14 storage. Its prepared capacity limits the tap offsets. @@ -423,7 +503,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. + /// reset sets it to zero. write: usize, } impl DelayLine { @@ -435,9 +515,10 @@ impl DelayLine { write: 0, } } - /// Clears the samples and does not move the current write position. + /// Clears the samples and sets the current write position to zero. fn reset(&mut self) { self.buffer.fill(Q14::default()); + self.write = 0; } /// Maps a delay to a storage index with a maximum of one wrap. /// diff --git a/src/events.rs b/src/events.rs index e1c975c..47a8843 100644 --- a/src/events.rs +++ b/src/events.rs @@ -51,8 +51,9 @@ pub enum ControlEvent { /// The held notes 0..=126 become pitch classes. Channels and nonzero /// velocities do not change the selected classes. Key 127 is stored, but /// the classes do not include it. Each event replaces the active - /// correction table. If a later change sets new configured notes, or - /// enables or disables correction, the configured mask loads again. + /// correction table. If a later reset occurs, or a change sets new + /// configured notes or enables or disables correction, the configured mask + /// loads again. CorrectionMidi(MidiEvent), /// This event resets immediately before the event frame, with the semantics of /// [`crate::Processor::reset`]. diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..85041cb 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -308,8 +308,8 @@ impl Formant { self.noise_filter .set_design(Design::high_pass(self.rate.hz(), frequency as f32, 0.707)); } - /// Clears the audio, the stamps, the synthesis history and the history of - /// the aspiration filter. + /// Clears the audio, the stamps, the synthesis history, the history of + /// the aspiration filter and the analysis generation count. /// /// The function also selects and clears the initial bank pair, and starts /// the correlation smoothing again. The other banks stay allocated. The @@ -326,6 +326,7 @@ impl Formant { self.design_counter = 0; self.noise_filter.reset(); self.smooth_reset = true; + self.generation = 0; } /// Starts a new model and a new correlation window when pitch acquisition /// locks. diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..8977871 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 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 releases all MIDI 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_all_notes(); } if old.key != config.key || old.scale != config.scale @@ -543,24 +543,30 @@ impl HarmonyState { self.setup_chord(); } } - /// Releases all MIDI notes and starts the MIDI assignment order again. - /// - /// The function clears these items: - /// - /// - The active MIDI periods, which releases the voices. - /// - The pending stolen notes and their assignment orders. - /// - The portamento start state. - /// - The MIDI event counter. - /// - /// It keeps the gain envelopes, the current ratios, the output and target - /// periods, the scale tables and the last note numbers, gains and orders. - /// Thus each released voice decays with the gain release. - /// - /// For [`HarmonySource::ChordViaMidi`], the function also prepares the - /// chord again from the released notes. Thus the chord voices decay - /// with the gain release. The other chord sources keep their chord - /// preparation. + /// Clears the voice envelopes, ratios, periods, MIDI state and scale search + /// state, then prepares the configured chord again. pub(crate) fn reset(&mut self) { + self.midi_note.fill(0); + self.midi_period.fill(Q6::ZERO); + self.midi_gain.fill(Q12::ZERO); + self.midi_order.fill(0); + self.portamento_period.fill(Q6::ZERO); + self.current_ratio.fill(Q14::ONE); + self.smoothed_gain.fill(Q12::ZERO); + self.period_output.fill(Q6::ZERO); + self.target_period.fill(Q6::ZERO); + self.chord_gain.fill(Q12::from_bits(-16_384)); + self.current_idx.fill(39); + self.scale_target.fill(Q6::ZERO); + self.scale_note.fill(0); + self.pending_gain.fill(Q12::ZERO); + self.pending_order.fill(0); + self.event_counter = 0; + self.setup_chord(); + } + /// Releases all MIDI notes and starts the MIDI assignment order again, + /// while each active voice keeps its release envelope. + fn release_all_notes(&mut self) { self.midi_period.fill(Q6::ZERO); self.portamento_period.fill(Q6::ZERO); self.pending_gain.fill(Q12::ZERO); @@ -701,12 +707,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 releases all MIDI 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_all_notes(); return false; } MidiEvent::NoteOn { diff --git a/src/lib.rs b/src/lib.rs index 0e29119..2f0aef9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,14 +68,16 @@ //! output with zeros. The drain uses a finite configured budget and mutes //! aspiration. It is not a silence detector. //! -//! The call that uses all of the budget does the same reset as -//! [`Processor::reset`]. This occurs also if that call returns audio. A -//! 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. +//! Every drain call that returns frames keeps [`Feedback`] and [`Telemetry`] +//! for that block. After the last tail frames, the next non-empty drain call +//! returns zero and does the same reset as [`Processor::reset`]. Empty buffers +//! do not advance or finish the drain. A successful process call, a successful +//! configuration call or a reset cancels the drain. +//! +//! [`Processor::reset`] clears all audio histories, filter memories, MIDI +//! state, peak windows and the frame count, and starts the random stream again +//! from `random_seed`. It keeps the preparation and the configuration, and +//! produces the same output as [`Processor::new`] without memory allocation. //! //! # Execution model //! diff --git a/src/numeric.rs b/src/numeric.rs index 10ba0fb..2770a2a 100644 --- a/src/numeric.rs +++ b/src/numeric.rs @@ -157,10 +157,11 @@ 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. +/// `Processor::reset` builds this context again from the configured seed. #[derive(Debug)] pub(crate) struct NumericContext { - /// The lookup cursor for Punch. An audio reset keeps its position. + /// The lookup cursor for Punch. A processor reset sets its initial index + /// again. 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. diff --git a/src/numeric/rng.rs b/src/numeric/rng.rs index b8600ff..b7eb1c7 100644 --- a/src/numeric/rng.rs +++ b/src/numeric/rng.rs @@ -5,7 +5,8 @@ //! 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 +//! configured 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 5123e0b..2d911ba 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -90,8 +90,7 @@ pub(crate) struct PitchTracker { tracking_counter: i32, /// The latest refined Q6 period. A restart of acquisition sets it to zero. period: Q6, - /// The last refined Q6 period. A restart or an audio reset does not clear - /// it. + /// The last refined Q6 period. A restart of acquisition does not clear it. previous_period: Q6, /// The Q14 threshold of the normalized difference. It applies only to the /// acceptance of acquisition minima. @@ -143,14 +142,24 @@ impl PitchTracker { self.threshold = Q14::from_f64(config.threshold as f64); } - /// Clears the full-rate audio, the current period and the prefilter - /// memories, and requests acquisition. - /// The acquisition tables clear at the next decimated call. The previous - /// usable period stays until another tracking update replaces it. + /// Clears the full-rate audio, the acquisition and tracking correlations, + /// the current and previous periods and the prefilter memories, and + /// requests acquisition. pub(crate) fn reset(&mut self) { self.raw.fill(0); self.write = 0; self.restart(); + self.previous_period = Q6::default(); + self.detection.fill(0); + self.detection_index = 0; + self.detection_count = 0; + self.energy.fill(0); + self.cross.fill(0); + self.tracking_energy.fill(0); + self.tracking_cross.fill(0); + self.base = 0; + self.tracking_counter = 0; + self.best = 0; for pre in &mut self.pre { pre.reset(); } diff --git a/src/processor.rs b/src/processor.rs index cc910f4..75219f8 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -1,7 +1,7 @@ //! The processor: audio blocks, timed controls, host feedback and the tail. use crate::effects::alien::{self, Alien}; -use crate::effects::punch::{Punch, PunchConfig}; +use crate::effects::punch::Punch; use crate::effects::reverb::{self, Reverb}; use crate::effects::warm::Warm; use crate::events::{ValidatedEvent, ValidatedEvents}; @@ -67,7 +67,7 @@ pub struct Processor { /// The number of frames of silent input that are left for the drain. /// /// `None` means that the drain is not active. `Some(0)` means that the - /// drain is complete. + /// next non-empty drain call resets the processor and finishes the drain. drain_remaining: Option, } @@ -90,9 +90,9 @@ impl Processor { /// I/O. Audio histories, pitch reports and meters start clear. The random /// stream starts from the low 32 bits of `random_seed`. /// - /// Punch uses its default cached drive until the first window of 100 - /// frames with Punch enabled. The initial note table of correction has the - /// rate behavior that [`crate::CorrectionConfig`] describes. + /// Punch calculates its initial drive from the configured input gain + /// before frame zero. The initial note table of correction has the rate + /// behavior that [`crate::CorrectionConfig`] describes. /// /// # Errors /// @@ -103,9 +103,7 @@ impl Processor { pub fn new(preparation: PrepareConfig, config: ProcessorConfig) -> Result { config.validate()?; let rate = preparation.sample_rate; - // Drive uses the default gain until the first 100-frame peak window. - let mut punch = Punch::new(rate, PunchConfig::default()); - punch.set_config(config.punch); + let punch = Punch::new(rate, config.punch); Ok(Self { preparation, config, @@ -215,16 +213,16 @@ impl Processor { /// budget and returns that budget. /// /// Call this method one time after the last input block. Another call - /// starts the full budget again, but does not clear histories. A + /// starts the full budget again, and does not clear histories. A /// successful process call, a successful configuration call or a reset /// cancels the drain. /// /// The drain uses silent input and mutes aspiration temporarily. Each - /// drain call returns a frame count and fills the unused output with zeros. - /// The call that uses all of the budget does a [`reset`](Self::reset), - /// also if it returns frames. An empty buffer uses no budget. The budget - /// can include silence. The reset at the end of the budget stops the - /// fixed-point output that is left in the histories that it clears. + /// drain call returns a frame count and fills the unused output with + /// zeros. Every call that returns frames keeps [`Feedback`] and + /// [`Telemetry`] for that block. After the last tail frames, the next + /// non-empty drain call returns zero and calls [`reset`](Self::reset). + /// An empty buffer uses no budget and does not finish the drain. pub fn begin_drain(&mut self) -> usize { let count = self.tail_frames(); self.drain_remaining = Some(count); @@ -233,10 +231,13 @@ impl Processor { /// Renders the next stereo tail frames and returns their count. /// - /// Call [`begin_drain`](Self::begin_drain) first. Before a drain starts or - /// after it finishes, this method returns zero and clears the output. The - /// method always fills unused frames with zeros. An empty buffer does not - /// advance the drain. + /// Call [`begin_drain`](Self::begin_drain) first. Every call that returns + /// positive frames keeps the peaks and the frame count of that block. + /// After the budget is zero, the next non-empty call returns zero and + /// calls [`reset`](Self::reset). Before a drain starts or after that + /// reset, this method returns zero and clears the output. The method + /// always fills unused frames with zeros, and an empty buffer does not + /// advance or finish the drain. /// /// # Errors /// @@ -251,8 +252,9 @@ impl Processor { /// Renders the tail into separate output channels of equal size. /// /// The return values, the zeros in unused samples, empty buffers and - /// completion are the same as for [`drain`](Self::drain). A final call can - /// return frames and also do the reset in that call. + /// completion are the same as for [`drain`](Self::drain). After the last + /// positive block, the next non-empty call returns zero and resets the + /// processor. /// /// # Errors /// @@ -274,9 +276,10 @@ impl Processor { /// /// The downmix is the same as in /// [`process_mono_in_place`](Self::process_mono_in_place). The method - /// fills unused samples with zeros. If the drain is not active or is - /// complete, the method returns zero. An empty output uses no budget. At - /// completion, the method does a reset, as + /// fills unused samples with zeros. Before a drain starts or after it + /// finishes, the method returns zero. An empty output uses no budget and + /// does not finish the drain. After the last positive block, the next + /// non-empty call returns zero and does a reset, as /// [`begin_drain`](Self::begin_drain) describes. /// /// # Errors @@ -458,11 +461,11 @@ impl Processor { /// /// 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. + /// resets the resynthesis audio state, the harmony voices, Alien, the + /// reverb, the peak windows and the reported ratio. It keeps Punch, Warm, + /// the correction keys, the active correction table, the random stream 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 @@ -512,35 +515,25 @@ 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. + /// Clears all audio histories, filter memories, envelopes, MIDI state, + /// pitch reports, peak windows and the frame count. + /// + /// This method cancels an active drain and does not allocate memory. It + /// clears all 128 correction keys and loads the configured correction + /// notes again with the rate rule of [`crate::CorrectionConfig`]. It also + /// starts the random stream and the arctangent lookup cursor again from + /// `random_seed`. + /// + /// The preparation and the active configuration do not change. After this + /// call, the processor produces the same PCM output as [`Self::new`] for + /// equal inputs, events and configuration. pub fn reset(&mut self) { self.punch.reset(); self.warm.reset(); self.resynthesis.reset(); self.alien.reset(); self.reverb.reset(); + self.numeric = NumericContext::new(self.config.resynthesis.random_seed as u32); self.peak = 0; self.clear_telemetry_peaks(); self.frames = 0; @@ -661,17 +654,28 @@ impl Processor { /// Renders only the budget that is left. The caller writes zeros in the /// unused frames. /// - /// The method mutes aspiration temporarily, but does not change the - /// settings that the host sees. It restores the configuration before - /// completion resets the state. `Some(0)` records completion, so later - /// drain calls continue to return zero. + /// An empty request does not change the drain state. The method mutes + /// aspiration temporarily, and restores the configuration after the block. + /// The last positive block sets `drain_remaining` to `Some(0)` without a + /// reset. The next non-empty call sees `Some(0)`, resets the processor and + /// returns zero. fn drain_into( &mut self, frames: usize, mut write: impl FnMut(usize, [i16; 2]), ) -> Result { self.check_block(frames)?; - let count = self.drain_remaining.unwrap_or(0).min(frames); + if frames == 0 { + return Ok(0); + } + let Some(remaining) = self.drain_remaining else { + return Ok(0); + }; + if remaining == 0 { + self.reset(); + return Ok(0); + } + let count = remaining.min(frames); let configured = self.config.resynthesis; if configured.formant.aspiration_mix != 0.0 { let mut silent = configured; @@ -685,13 +689,7 @@ impl Processor { if configured.formant.aspiration_mix != 0.0 { self.resynthesis.apply_config(configured); } - if let Some(remaining) = self.drain_remaining { - let remaining = remaining - count; - if remaining == 0 { - self.reset(); - } - self.drain_remaining = Some(remaining); - } + self.drain_remaining = Some(remaining - count); Ok(count) } } @@ -763,8 +761,8 @@ pub struct Feedback { /// The number of frames processed since construction or the last reset, /// with drain frames included. /// - /// The count saturates at `u64::MAX`. Drain completion resets it in the - /// last drain call. + /// The count saturates at `u64::MAX`. After the tail frames, the next + /// non-empty drain call returns zero and resets this count. pub processed_frames: u64, /// The nominal resynthesis latency, as [`Processor::latency_frames`] gives. #[cfg_attr( @@ -872,7 +870,8 @@ pub struct Telemetry { /// The reverse reader is two times this number of frames behind the /// recording position. The value advances also while Alien is disabled. pub alien_phase_frames: u32, - /// The wrapping count of formant analyses since construction. + /// The wrapping count of formant analyses since construction or the last + /// reset. /// /// The count increases every 441 frames while the formant stage is /// enabled. Compare two values to find if diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..f67baf2 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. A reset clears all 128 correction keys and loads `notes` again +/// with the rate rule below. 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 at 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: +/// - A configured 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,7 @@ 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 `enabled`. pub notes: NoteMask, /// The half-life of the smoothing in milliseconds, 0..=400. The default /// is 0. @@ -248,7 +248,7 @@ 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 + /// bits. A reset 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, } @@ -414,7 +414,7 @@ pub(crate) struct Resynthesis { /// The Q14 random choir drift offsets of the secondary voices. drift: [Q14; 16], /// The Q14 multipliers, each equal to 1.0 plus the drift. An audio reset - /// sets them to 1.0, but it keeps the drift state. + /// clears the drift and sets these multipliers to 1.0. drift_ratio: [Q14; 16], /// The Q14 left and right gains of the choir voices. The code reads them /// only if the stereo pan is enabled. @@ -425,7 +425,7 @@ pub(crate) struct Resynthesis { /// The last Q14 target ratios from the harmony controller. harmony_ratios: [Q14; HARMONY_VOICES], /// The last Q12 gain envelopes from the harmony controller. An audio - /// reset keeps them. + /// reset clears them. harmony_gains: [Q12; HARMONY_VOICES], /// The effective Q14 ratios of the lead and the four harmony readers from /// the last frame. In Choir mode, only the lead slot changes. Only the @@ -456,7 +456,7 @@ pub(crate) struct Resynthesis { /// The plain integer modulation depth. It is the public control times /// two, truncated. modulation: i32, - /// The Q14 phase in the cosine cycle. An audio reset keeps it. + /// The Q14 phase in the cosine cycle. An audio reset clears it. modulation_phase: Q14, /// The Q8 weight of the delayed raw audio. The wet weight is 1.0 minus /// this weight. @@ -669,27 +669,29 @@ impl Resynthesis { } } - /// Releases the correction keys 0..=126 and resets the audio state. + /// Clears all 128 correction keys, loads the configured note mask again + /// and resets the audio state. /// - /// The active correction table, key 127 and the items that - /// `reset_audio` keeps do not change. + /// The chromatic mask uses 44.1 kHz periods, and any other mask uses the + /// prepared rate, as at construction. pub(crate) fn reset(&mut self) { self.scale.reset(); + self.scale.set_sample_rate(SampleRate::Hz44100); + self.scale.set_notes(NoteMask::default()); + self.scale.set_sample_rate(self.rate); + if self.config.correction.notes != NoteMask::default() { + self.scale.set_notes(self.config.correction.notes); + } self.reset_audio(); } - /// Clears the audio and period histories, the tracker, the formant - /// synthesis and the filter history. Then initializes the readers and - /// the correction again. + /// Clears the audio and period histories, the tracker, the formant stage, + /// the harmony voices, the drift, the modulation phase and the filter + /// history. Then initializes the readers, the control counter and the + /// correction state 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. - /// - The harmony release envelopes and the last harmony gains. + /// The correction keyboard, the active note table and the random state + /// that the caller holds do not change here. fn reset_audio(&mut self) { self.pitch.reset(); self.raw.fill(Q14::ZERO); @@ -708,15 +710,21 @@ impl Resynthesis { filter.reset(); } self.create_delays(); + self.drift.fill(Q14::ZERO); self.drift_ratio.fill(Q14::ONE); self.old_position = self.positions[0]; self.fade = Q14::ONE; self.harmony_ratios.fill(Q14::ONE); + self.harmony_gains.fill(Q12::ZERO); self.voice_ratios.fill(Q14::ONE); self.formant_position = 0; self.current_output_period = Q6::ZERO; + self.control_counter = CONTROL_DUE; + self.modulation_phase = Q14::ZERO; self.correction = Q14::ONE; self.scale_initialized = false; + self.scale_index = 0; + self.octave = 0; } /// Applies a MIDI event that the API or the block code checked before. diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..96e5e9a 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -163,7 +163,7 @@ pub(crate) struct CorrectionTable { base_periods: [i32; 12], /// The held MIDI keys. /// - /// A reset keeps key 127, and mask creation excludes it. + /// A reset clears all 128 keys, and mask creation excludes key 127. pub keyboard: [bool; 128], } @@ -219,11 +219,9 @@ impl CorrectionTable { self.midpoints[0] = self.midpoints[self.count] / 2; } } - /// 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. + /// Clears all 128 keys on the correction keyboard. pub(crate) fn reset(&mut self) { - self.keyboard[..127].fill(false); + self.keyboard.fill(false); } /// Applies an event whose MIDI ranges were already checked. pub(crate) fn apply_validated_midi(&mut self, event: MidiEvent) { @@ -232,10 +230,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.keyboard[..127].fill(false), } 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 c9cec08..7915055 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -314,10 +314,11 @@ impl WasmProcessor { /// Renders stereo tail frames into `Int16Array` buffers of equal length. /// /// The method returns the number of rendered frames and fills the unused - /// output with zeros. If the drain is not active or is complete, the method - /// returns zero. Empty arrays do not use the budget. Completion resets the - /// histories and the feedback in the final drain call, also when that call - /// returns audio. + /// output with zeros. Every call that returns positive frames keeps the + /// feedback and the telemetry of that block. After the last tail frames, + /// the next non-empty call returns zero and resets the processor. Before a + /// drain starts or after that reset, the method returns zero. Empty arrays + /// do not use the budget and do not finish the drain. /// /// # Errors /// @@ -338,8 +339,9 @@ impl WasmProcessor { /// Renders a mono tail block and returns its frame count. /// - /// The method fills the unused output with zeros. The downmix, completion - /// and feedback behavior are the same as for `drainMono`. + /// The method fills the unused output with zeros. The downmix, empty + /// buffers, feedback retention and reset on the next non-empty zero call + /// are the same as for `drain`. /// /// # Errors /// @@ -465,11 +467,14 @@ impl WasmProcessor { Ok(valid) } - /// Resets the audio histories and feedback, 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`. + /// Resets all audio histories, filter memories, MIDI state, feedback and + /// telemetry, as the native processor does. + /// + /// The method clears all correction keys, loads the configured correction + /// notes again and starts the random stream again from `randomSeed`. It + /// cancels any active drain and keeps the preparation and the active + /// configuration. After this call, the instance gives the same PCM output + /// as a new `Tunelet` with the same configuration. pub fn reset(&mut self) { self.processor.reset(); } From 0398413da8232c40f989308568adaf7f36e05336 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 17:48:59 +0000 Subject: [PATCH 2/2] docs: wrap the drain reset label in lifecycle.svg - Wrap the drain reset label onto two tspan lines at x=570. --- docs/images/lifecycle.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/images/lifecycle.svg b/docs/images/lifecycle.svg index ffe7168..6be9181 100644 --- a/docs/images/lifecycle.svg +++ b/docs/images/lifecycle.svg @@ -69,6 +69,6 @@ cancels the drain - after the budget, the next non-empty call returns 0 and calls reset() + after the budget, the next non-empty callreturns 0 and calls reset() later drain calls return 0