diff --git a/README.md b/README.md index a06715f..42f3a1b 100644 --- a/README.md +++ b/README.md @@ -340,14 +340,20 @@ 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. The preparation, the configuration and `formant_generation` in +the telemetry do not change. After `reset()`, the processor 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 661f1ba..6be9181 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 335a9fa..a014508 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( @@ -145,11 +145,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], @@ -168,7 +166,7 @@ pub(crate) struct Reverb { /// The largest absolute Q14 wet contribution in the telemetry window. No /// audio calculation reads it. wet_peak: i32, - /// If `true`, the delay buffer changed since construction or the last reset. + /// If `true`, the stage changed state since construction or the last reset. dirty: bool, } @@ -304,11 +302,13 @@ impl Reverb { self.configure_brightness_hz(); } } - /// 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) { if self.dirty { self.delay.reset(); + self.lpf1.reset(); + self.lpf2.reset(); self.dirty = false; } } @@ -491,33 +491,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 + } + } } /// The length in frames of the shared delay ring at both sample rates. @@ -528,8 +608,8 @@ const CAPACITY: usize = 17_000; struct DelayLine { /// Fixed-length storage on the heap. The values use the Q14 audio scale. buffer: Box<[Q14; CAPACITY]>, - /// The current frame position, always less than `CAPACITY`. A reset does - /// not change it. + /// The current frame position, always less than `CAPACITY`. A reset sets + /// it to zero. write: usize, } impl DelayLine { @@ -541,9 +621,10 @@ impl DelayLine { .unwrap_or_else(|_| unreachable!("prepared reverb delay length")); Self { buffer, 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/harmony.rs b/src/harmony.rs index f2adfe3..70c9634 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -478,8 +478,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. @@ -563,13 +563,13 @@ impl HarmonyState { /// Applies a configuration that validation already accepted. /// - /// If the source changes, the function calls `reset`. It prepares the - /// tables again only for the fields that changed. + /// If the source changes, 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; if old.source != config.source { - self.reset(); + self.release_all_notes(); } if old.key != config.key || old.scale != config.scale @@ -628,24 +628,30 @@ impl HarmonyState { pub(crate) fn set_voices(&mut self, voices: u8) { self.config.voices = voices; } - /// 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); @@ -782,12 +788,13 @@ impl HarmonyState { /// channel that the MIDI source uses. 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. + /// clears the pending 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 80f8d33..4edea58 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -81,14 +81,17 @@ //! 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`. The preparation, the configuration and +//! [`Telemetry::formant_generation`] do not change. Without memory allocation, +//! the processor then produces the same PCM output as [`Processor::new`]. //! //! # Execution model //! diff --git a/src/numeric.rs b/src/numeric.rs index ea4c555..ce82238 100644 --- a/src/numeric.rs +++ b/src/numeric.rs @@ -195,10 +195,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 71bbbc0..d36080b 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -93,8 +93,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. @@ -149,15 +148,25 @@ impl PitchTracker { self.threshold = Q14::from_f64(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) { clear_dirty_ring(self.raw.as_mut_slice(), usize::from(self.written), 0); self.written = 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 9f8ae9b..6140bc6 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -94,7 +94,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, } @@ -324,16 +324,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); @@ -342,10 +342,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 /// @@ -362,8 +365,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 /// @@ -385,9 +389,10 @@ impl Processor { /// /// The downmix and the peak measurements are 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 @@ -684,11 +689,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 @@ -734,33 +739,24 @@ 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 releases correction keys 0..=127 - /// and loads the configured correction notes again. 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 - /// - 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. - /// - /// 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 + /// releases correction keys 0..=127 and loads the configured correction + /// notes again. It also starts the random stream and the arctangent lookup + /// cursor again from `random_seed`. + /// + /// The preparation, the active configuration and + /// [`Telemetry::formant_generation`] 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.reset_post_resynthesis(); + self.numeric = NumericContext::new(self.config.resynthesis.random_seed as u32); self.frames = 0; self.drain_remaining = None; } @@ -1030,10 +1026,11 @@ 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 clears the mute 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 does not change the settings that the host + /// sees. 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, @@ -1041,19 +1038,23 @@ impl Processor { 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); self.resynthesis.set_aspiration_muted(true); for index in 0..count { write(index, self.next(0, layout)); } self.resynthesis.set_aspiration_muted(false); - 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) } } @@ -1143,8 +1144,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( diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..875b0e7 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -74,9 +74,9 @@ pub enum MultiVoiceMode { /// A change to `notes` or to `enabled` also loads the configured mask again. /// Reset releases the correction keys 0..=127. /// -/// Construction loads the configured `notes` mask with the periods for the -/// prepared sample rate. Later changes to `notes`, to `enabled` or from -/// correction MIDI also use the periods for the prepared sample rate. +/// Construction and reset load the configured `notes` mask with the periods +/// for the prepared sample rate. Later changes to `notes`, to `enabled` or +/// from correction MIDI also use the periods for the prepared sample rate. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -95,8 +95,8 @@ pub struct CorrectionConfig { /// [`NoteMask::CHROMATIC`]. /// /// All boolean masks are valid. Held keys from correction MIDI replace the - /// active table. When all keys release, or if this mask or `enabled` - /// changes, this mask loads again. + /// active table. When all keys release, on reset or if this mask or + /// `enabled` changes, this mask loads again. pub notes: NoteMask, /// The half-life of the smoothing in milliseconds, 0..=400. The default /// is 0. @@ -302,7 +302,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, } @@ -510,7 +510,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. @@ -523,7 +523,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 @@ -575,7 +575,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. @@ -1081,26 +1081,18 @@ impl Resynthesis { /// Releases the correction keys 0..=127, loads the configured correction /// notes again and resets the audio state. - /// - /// The items that `reset_audio` keeps do not change, except the correction - /// keyboard and the active note table. pub(crate) fn reset(&mut self) { self.scale.reset(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) { let written = usize::from(self.written); self.written = 0; @@ -1132,16 +1124,22 @@ 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.dwell = Q14::ZERO; self.scale_initialized = false; + self.scale_index = 0; + self.octave = 0; self.previous_scale_index = 0; self.previous_octave = 0; } diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..221ab04 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -517,10 +517,12 @@ impl WasmProcessor { /// Starts a finite tail budget and returns its frame count as a number. /// - /// Call this method one time after the final input block. Then call `drain` - /// or `drainMono` until the call returns zero. Completion resets the audio - /// histories and the feedback in the final drain call. Another call starts - /// the full budget again, and it does not clear the histories. + /// Call this method one time after the final input block. Then call a drain + /// method until the call returns zero. Every call that returns positive + /// frames keeps the feedback and the telemetry of that block. Completion + /// resets the processor on the next non-empty call that returns zero. + /// Another call starts the full budget again, and it does not clear the + /// histories. #[wasm_bindgen(js_name = beginDrain)] pub fn begin_drain(&mut self) -> usize { self.processor.begin_drain() @@ -536,10 +538,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 /// @@ -562,10 +565,11 @@ impl WasmProcessor { /// /// The method mixes each stereo tail frame to mono and fills the unused /// output with zeros. Peak feedback and telemetry measure the mono signal - /// after the mono downmix. 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. + /// after the mono downmix. Every call that returns positive frames keeps + /// the feedback and the telemetry of that block. Empty arrays do not use + /// the budget and do not finish the drain. Completion resets the processor + /// on the next non-empty call that returns zero. Before a drain starts or + /// after that reset, the method returns zero. /// /// # Errors /// @@ -807,11 +811,15 @@ 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, peak windows + /// and the frame count, 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. The preparation, the active configuration and + /// `formantGeneration` in the telemetry do not change. 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(); }