From d77e8101a260a6a4278dd80d9923d37d6fab7923 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 01:56:53 +0000 Subject: [PATCH] feat: add adaptive silence drain and flush lifecycle - Initialize Punch with the configured gain at construction. - Calibrate reverb tail budgets from the loop delays of each mode. - Stop active drains after 17,000 silent frames past the initial delays. - Defer the post-drain reset to the next non-empty drain call. - Expose drain_remaining and flush in Rust, WebAssembly and TypeScript. - Reset all DSP, keyboard and random state without memory allocation. --- README.md | 42 +++++-- docs/images/lifecycle.svg | 8 +- src/effects/reverb.rs | 99 +++++++++++---- src/events.rs | 14 ++- src/formant.rs | 21 +++- src/harmony.rs | 37 ++++-- src/index.ts | 5 +- src/lib.rs | 39 +++--- src/numeric.rs | 4 +- src/numeric/rng.rs | 2 +- src/pitch/tracker.rs | 21 +++- src/processor.rs | 248 +++++++++++++++++++++++++------------- src/resynthesis.rs | 91 +++++++++----- src/scale.rs | 8 +- src/wasm.rs | 67 +++++++--- 15 files changed, 489 insertions(+), 217 deletions(-) diff --git a/README.md b/README.md index d2993dc..0557098 100644 --- a/README.md +++ b/README.md @@ -269,18 +269,33 @@ The drain gives the tail of the reverb and the voices after the last input block. To get the tail, do these steps: 1. Call `begin_drain()` one time. -2. Call `drain`, `drain_planar` or `drain_mono` until the call returns zero. +2. Call `drain`, `drain_planar` or `drain_mono` with a non-empty buffer until + the call returns zero. 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. +The drain fills the unused output with zeros. `tail_frames()` gives the upper +bound for the active configuration, and `drain_remaining()` gives the active +upper-bound count (`None` when no drain is active). After the resynthesis and +Alien delays pass, the drain stops early after 17,000 consecutive frames within +±24 PCM on both channels. -### Reset +The final positive drain block sets `drain_remaining()` to `Some(0)` and keeps +`feedback()` and `telemetry()` intact. The next non-empty drain call returns +zero, runs `reset()` and sets `drain_remaining()` to `None`. Empty drain +buffers neither advance the silence window nor run that reset. A successful +call that processes audio or sets the configuration cancels the drain. +`reset()` and `flush()` also cancel the drain. -`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 and flush + +`reset()` and `ControlEvent::Reset` restore the initial state of the active +configuration without allocation. After `reset()`, the output matches +`Processor::new` with the same configuration sample for sample from frame zero. + +`flush()` and `ControlEvent::Flush` clear the audio delay lines, held notes +0..=126 and the meters for live transport jumps. They keep the active +configuration, the random stream, reverb damping filter memories, harmony +release envelopes and formant generation. ## Feedback and telemetry @@ -293,6 +308,7 @@ These calls read the state of the processor. They do not change the audio. | `telemetry()` | Data for meters and displays (refer to the list below) | | `take_telemetry()` | The same data as `telemetry()`, and clears its three peak windows | | `latency_frames()` | 1,593 frames of nominal resynthesis latency at both sample rates | +| `drain_remaining()` | The active upper-bound drain count, or `None` outside a drain | | `formant_envelope()` | The LPC envelopes before and after the formant controls | The telemetry includes these items: @@ -333,6 +349,7 @@ allocate memory, acquire locks or do I/O: - Feedback - Telemetry - Reset +- Flush - Drain All operations that can fail do their validation before they change the @@ -417,8 +434,8 @@ page that opens the JavaScript. | Telemetry | `telemetry()`, `takeTelemetry()` | | Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | | Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | -| Configured tail budget | `tailFrames()` | -| Reset or release memory | `reset()`, `free()` | +| Tail budget and drain status | `tailFrames()`, `drainRemaining` | +| Reset, flush or release memory | `reset()`, `flush()`, `free()` | ### Audio buffers @@ -456,8 +473,9 @@ telemetry use `bigint`. Frame offsets, block lengths and latency use ### Events The optional event argument is a `TimedEvent[]`. Controls use a `type` -discriminant and a `value` payload. The reset control has no payload. For -example, this event changes the final gain before the first frame: +discriminant and a `value` payload. The `reset` and `flush` controls have no +payload. For example, this event changes the final gain before the first +frame: ```ts { offset: 0, event: { type: "outputGain", value: 0.5 } } diff --git a/docs/images/lifecycle.svg b/docs/images/lifecycle.svg index 05208f4..7938f06 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 silence or the budget limit. Then the next non-empty drain call returns zero and resets the processor. diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..e83b271 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -38,10 +38,10 @@ 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. +/// stage is enabled and the mix is zero, the network still operates. A flush +/// clears the delay buffer and keeps the memories of the damping filters. A +/// reset clears both. 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,8 +125,8 @@ 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 flush or 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. @@ -150,6 +150,9 @@ pub(crate) struct Reverb { wet_peak: i32, } +/// The capacity of the shared circular delay ring, in frames. +pub(crate) const DELAY_CAPACITY: usize = 17_000; + /// The divisor for a division by two that truncates toward zero, also for /// negative values. const TWO: Fixed<0> = Fixed::from_bits(2); @@ -206,8 +209,16 @@ impl Reverb { } /// Clears only the delay contents, and keeps the write cursor and the /// damping memories. + pub(crate) fn flush(&mut self) { + self.delay.flush(); + } + /// Clears the delay contents, the write cursor, the damping memories and + /// the wet peak. pub(crate) fn reset(&mut self) { self.delay.reset(); + self.lpf1.reset(); + self.lpf2.reset(); + self.wet_peak = 0; } /// Returns the largest absolute Q14 wet contribution since the last /// clear, as f32. @@ -387,33 +398,64 @@ impl Reverb { } } -/// Estimates a finite tail budget from the largest modeled feedback -/// gain. +/// Estimates a finite tail budget from the loop delays of the selected +/// network. /// -/// 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. +/// Each feedback path uses the circulations necessary to reach an amplitude +/// of 1e-6, plus one ring pass. This budget sets a finite upper bound against +/// Q14 limit cycles. 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 layout = reverb_layout(rate.hz()); + let t = layout.taps; 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 turns = |gain: f64| { + if gain > 0.0 { + (1e-6f64.ln() / gain.ln()).ceil() as usize + } else { + 0 + } }; - let turns = if gain > 0.0 { - (1e-6f64.ln() / gain.ln()).ceil() - } else { - 1.0 + let loop_frames = match config.mode { + ReverbMode::Binaural => (t[54] - t[40]) + t[10] + layout.binaural_offset, + ReverbMode::Echo => { + let diffuse_q14 = Q14::from_f64((config.diffusion * 100.0) as f64 / 100.0); + let echo = Fixed::<0>::from_bits(t[39] as i32) + .mul::<14, 0>(diffuse_q14) + .to_bits() as usize; + turns(decay).saturating_mul(echo).saturating_add(t[32]) + } + ReverbMode::Schroeder => { + let combs = [(0, 12, 0.9), (13, 22, 0.89), (23, 28, 0.87), (29, 34, 0.86)] + .into_iter() + .map(|(a, b, g)| turns(g).saturating_mul(t[b] - t[a])) + .max() + .unwrap_or(0); + let allpasses = turns(decay).saturating_mul((t[43] - t[40]) + (t[45] - t[44])); + combs.saturating_add(allpasses) + } + ReverbMode::SmallRoom => { + let half = (t[35] - t[0]).max(t[66] - t[40]); + let outer = turns(decay).saturating_mul(half); + let inner = turns(0.7).saturating_mul(t[15] - t[1]); + outer.saturating_add(inner) + } + ReverbMode::MediumHall => { + let outer = turns(decay).saturating_mul((t[35] - t[0]) + (t[66] - t[40])); + let inner = turns(0.9 * diffuse).saturating_mul(t[15] - t[3]); + outer.saturating_add(inner) + } + ReverbMode::LargeHall => { + let outer = turns(decay).saturating_mul((t[38] - t[1]) + (t[64] - t[40])); + let inner = turns(0.95 * diffuse).saturating_mul((t[30] - t[19]) + (t[63] - t[41])); + outer.saturating_add(inner) + } }; - (rate.hz() as f64 * (turns * 0.8 + 2.0)).ceil() as usize + loop_frames.saturating_add(layout.capacity) } /// Circular Q14 storage. Its prepared capacity limits the tap offsets. @@ -423,7 +465,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. + /// flush does not change it. write: usize, } impl DelayLine { @@ -436,8 +478,13 @@ impl DelayLine { } } /// Clears the samples and does not move the current write position. + fn flush(&mut self) { + self.buffer.fill(Q14::default()); + } + /// Clears the samples and sets the 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. /// @@ -605,7 +652,7 @@ fn reverb_layout(rate: f32) -> ReverbLayout { taps[59] = taps[58] + 1; ReverbLayout { taps, - capacity: 17000, + capacity: DELAY_CAPACITY, binaural_offset: (rate as f64 * 0.8 * 0.001) as usize, } } diff --git a/src/events.rs b/src/events.rs index e1c975c..47a7d75 100644 --- a/src/events.rs +++ b/src/events.rs @@ -60,6 +60,12 @@ pub enum ControlEvent { /// Later events in the same block still run. The processor continues to /// render from this frame. Reset, + /// This event flushes immediately before the event frame, with the + /// semantics of [`crate::Processor::flush`]. + /// + /// Later events in the same block still run. The processor continues to + /// render from this frame. + Flush, } impl ControlEvent { @@ -69,9 +75,9 @@ impl ControlEvent { /// # Errors /// /// Returns [`Error::InvalidConfig`] for an invalid configuration or gain. - /// Returns [`Error::InvalidMidi`] for invalid MIDI fields. Reset is always - /// valid. The process call that contains the event checks the offset and - /// the order. + /// Returns [`Error::InvalidMidi`] for invalid MIDI fields. Reset and Flush + /// are always valid. The process call that contains the event checks the + /// offset and the order. pub fn validate(self) -> Result<(), Error> { match self { Self::Configure(config) => config.validate(), @@ -82,7 +88,7 @@ impl ControlEvent { Self::Reverb(config) => config.validate(), Self::OutputGain(gain) => validate_output_gain(gain), Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(), - Self::Reset => Ok(()), + Self::Reset | Self::Flush => Ok(()), } } } diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..1c11dea 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -312,9 +312,8 @@ impl Formant { /// the aspiration filter. /// /// The function also selects and clears the initial bank pair, and starts - /// the correlation smoothing again. The other banks stay allocated. The - /// stage clears each bank when it uses that bank again. - pub(crate) fn reset(&mut self) { + /// the correlation smoothing again. The generation counter stays as it is. + pub(crate) fn flush(&mut self) { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); @@ -327,6 +326,22 @@ impl Formant { self.noise_filter.reset(); self.smooth_reset = true; } + /// Restores the initial state of [`Self::new`] without allocation. + pub(crate) fn reset(&mut self) { + self.temporary.fill(0_i32); + self.inverse.fill([0; MAX_ORDER]); + self.models.fill([0; MAX_ORDER]); + self.orders = [0; BANKS]; + self.correlation_history = [[0; 111]; 2]; + self.correlation_sum = [0; 111]; + self.smooth_index = 0; + self.smooth_filled = 0; + self.stretch_map[self.stretch_count..].fill(0); + self.areas = [0; MAX_ORDER]; + self.stretched_areas = [0; MAX_ORDER]; + self.generation = 0; + self.flush(); + } /// 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..a1082c3 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -423,7 +423,7 @@ 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 + /// The Q12 attack and release envelope. A MIDI release or a flush does /// not clear it. smoothed_gain: [Q12; HARMONY_VOICES], /// The last active Q6 target. It is kept while the gain of a released @@ -464,8 +464,8 @@ pub(crate) struct HarmonyState { /// The signed assignment order of each pending note. The largest positive /// value resumes first. pending_order: [i32; 128], - /// The wrapping i32 counter of Note On and Note Off events. A reset sets - /// it to zero. The note assignment compares its signed values. + /// The wrapping i32 counter of Note On and Note Off events. A flush or a + /// reset sets it to zero. The note assignment compares its signed values. event_counter: i32, /// The precomputed Q12 velocity gains for all 128 MIDI velocity values. gains: [Q12; 128], @@ -509,7 +509,7 @@ 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 + /// chord source, the function calls `flush`. It prepares the tables /// again only for the fields that changed. pub(crate) fn apply_config(&mut self, config: HarmonyConfig) { let old = self.config; @@ -523,7 +523,7 @@ impl HarmonyState { | HarmonySource::ChordByName ) { - self.reset(); + self.flush(); } 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 flush(&mut self) { self.midi_period.fill(Q6::ZERO); self.portamento_period.fill(Q6::ZERO); self.pending_gain.fill(Q12::ZERO); @@ -570,6 +570,27 @@ impl HarmonyState { self.setup_chord(); } } + /// Restores the initial state of [`Self::new`] without allocation. + 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 = [Q12::ZERO; 128]; + self.pending_order = [0; 128]; + 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 +722,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`. + /// entry of its pitch. All Notes Off calls `flush` 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.flush(); return false; } MidiEvent::NoteOn { diff --git a/src/index.ts b/src/index.ts index da35a57..3de5e60 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,8 +4,9 @@ * Call `loadTunelet()` before you construct processors or read the default * configuration. Both environments use the same generated bindings and the * same Wasm binary. This module re-exports all named exports of the module - * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, event and feedback types. + * that wasm-bindgen generates. Those exports include `Tunelet` (with `reset`, + * `flush` and `drainRemaining`), `defaultConfig`, `initSync` and the + * configuration, event, feedback and telemetry types. */ import init, { initSync } from "../pkg/tunelet.js"; import type { InitInput, InitOutput } from "../pkg/tunelet.js"; diff --git a/src/lib.rs b/src/lib.rs index 0e29119..3a9cd82 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,27 +64,32 @@ //! change the audio. //! //! After the last input block, call [`Processor::begin_drain`] one time. Then -//! render drain blocks until a call returns zero. Each call fills the unused -//! 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. +//! render drain blocks until a non-empty call returns zero. Each call fills +//! the unused output with zeros and mutes aspiration. +//! [`Processor::tail_frames`] gives the configured upper bound, and +//! [`Processor::drain_remaining`] gives the active upper-bound count. +//! +//! After the resynthesis and Alien delays pass, the drain stops early after +//! 17,000 consecutive frames within ±24 PCM on both channels. The final +//! positive block sets [`Processor::drain_remaining`] to `Some(0)` and keeps +//! [`Feedback`] and [`Telemetry`]. The next non-empty drain call returns zero +//! and runs [`Processor::reset`]. A successful process call, configuration +//! call, [`Processor::reset`] or [`Processor::flush`] cancels the drain. +//! +//! [`Processor::reset`] and [`ControlEvent::Reset`] restore the initial state +//! of the active configuration without allocation, and match [`Processor::new`] +//! from frame zero. [`Processor::flush`] and [`ControlEvent::Flush`] clear +//! delay lines, held notes 0..=126 and meters while they keep the random +//! stream and live controller continuity. //! //! # Execution model //! //! Construction allocates the audio storage. After construction, the calls for -//! audio, controls, feedback, reset and drain do not allocate memory. They do -//! not acquire locks and do no I/O. Each processor owns its histories and its -//! random stream. Fixed-point arithmetic uses explicit wrapping and -//! quantization. If you change the order of the arithmetic, the samples can -//! change. +//! audio, controls, feedback, telemetry, reset, flush and drain do not +//! allocate memory. They do not acquire locks and do no I/O. Each processor +//! owns its histories and its random stream. Fixed-point arithmetic uses +//! explicit wrapping and quantization. If you change the order of the +//! arithmetic, the samples can change. //! //! The default build uses only safe Rust and has no dependencies. //! diff --git a/src/numeric.rs b/src/numeric.rs index 10ba0fb..a64d244 100644 --- a/src/numeric.rs +++ b/src/numeric.rs @@ -157,10 +157,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 flush keeps this state. A reset starts it again. #[derive(Debug)] pub(crate) struct NumericContext { - /// The lookup cursor for Punch. An audio reset keeps its position. + /// The lookup cursor for Punch. A flush keeps its position. 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..ec72f36 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 flush does not set a new 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..e37d8db 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 or a flush does not clear it. previous_period: Q6, /// The Q14 threshold of the normalized difference. It applies only to the /// acceptance of acquisition minima. @@ -147,7 +146,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 flush(&mut self) { self.raw.fill(0); self.write = 0; self.restart(); @@ -156,6 +155,22 @@ impl PitchTracker { } } + /// Restores the initial state of [`Self::new`] without allocation. + pub(crate) fn reset(&mut self) { + self.flush(); + 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.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 cc910f4..1501034 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}; @@ -10,6 +10,9 @@ use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +/// The symmetric PCM amplitude bound for the drain silence window. +const DRAIN_SILENCE_PCM: i16 = 24; + /// A prepared vocal processor with state, mono input and stereo synthesis. /// /// Construction fixes the sample rate and the block limit, and @@ -18,12 +21,12 @@ use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; /// [`crate::ResynthesisConfig::stereo_output`] selects the voice panning /// separately. /// -/// The audio, configuration, reset and drain calls need exclusive access to -/// this instance. Each processor owns its histories and numeric state, and -/// there is no global audio state. These prepared operations do not allocate, -/// do not lock and do no I/O. Public operations that can fail validate before -/// they change state or output. Refer to the [crate documentation](crate) for -/// the signal chain and the lifecycle. +/// The audio, configuration, reset, flush and drain calls need exclusive +/// access to this instance. Each processor owns its histories and numeric +/// state, and there is no global audio state. These prepared operations do not +/// allocate, do not lock and do no I/O. Public operations that can fail +/// validate before they change state or output. Refer to the [crate +/// documentation](crate) for the signal chain and the lifecycle. pub struct Processor { /// The fixed rate and the block limit for each call. preparation: PrepareConfig, @@ -64,11 +67,16 @@ pub struct Processor { /// /// The count saturates at the maximum value. frames: u64, - /// The number of frames of silent input that are left for the drain. + /// The upper bound on drain frames that are left. /// /// `None` means that the drain is not active. `Some(0)` means that the - /// drain is complete. + /// drain is complete and waits for the final zero-frame drain call. drain_remaining: Option, + /// The drain frames that must pass before the silence counter starts. + drain_holdoff: usize, + /// The consecutive stereo frames within [`DRAIN_SILENCE_PCM`] after the + /// holdoff. + drain_silent_frames: usize, } impl std::fmt::Debug for Processor { @@ -86,13 +94,13 @@ impl Processor { /// /// Each processor is independent. `preparation` fixes the rate and the /// block limit for each call. After construction, the audio, control, - /// feedback, reset and drain calls do not allocate, do not lock and do no - /// I/O. Audio histories, pitch reports and meters start clear. The random - /// stream starts from the low 32 bits of `random_seed`. + /// feedback, reset, flush and drain calls do not allocate, do not lock and + /// do no 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 `config.punch.gain_db`. The + /// initial note table of correction has the rate behavior that + /// [`crate::CorrectionConfig`] describes. /// /// # Errors /// @@ -103,13 +111,10 @@ 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); Ok(Self { preparation, config, - punch, + punch: Punch::new(rate, config.punch), warm: Warm::new(rate, config.warm), resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), alien: Alien::new(config.alien), @@ -121,6 +126,8 @@ impl Processor { last_resample_ratio: 0.0, frames: 0, drain_remaining: None, + drain_holdoff: 0, + drain_silent_frames: 0, }) } @@ -200,7 +207,7 @@ impl Processor { events: &[TimedEvent], ) -> Result<(), Error> { let mut events = self.validate(audio, events)?; - self.drain_remaining = None; + self.cancel_drain(); for (index, sample) in audio.iter_mut().enumerate() { while let Some(event) = events.next_at(index) { self.apply(event); @@ -212,22 +219,28 @@ impl Processor { } /// Starts a tail with the current [`tail_frames`](Self::tail_frames) - /// budget and returns that budget. + /// upper-bound 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 - /// successful process call, a successful configuration call or a reset - /// cancels the drain. + /// starts the full budget again, and does not clear histories. A + /// successful process call, a successful configuration call, a reset or a + /// flush 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. + /// After the resynthesis and Alien budgets pass, the drain stops early if + /// stereo output stays within 24 PCM for 17,000 frames. Every positive + /// drain call preserves [`Feedback`] and [`Telemetry`]. The next non-empty + /// drain call returns zero and does a [`reset`](Self::reset). An empty + /// buffer does not advance the drain or do the reset. pub fn begin_drain(&mut self) -> usize { let count = self.tail_frames(); self.drain_remaining = Some(count); + self.drain_holdoff = self + .resynthesis + .tail_frames() + .saturating_add(alien::tail_frames(self.config.alien)); + self.drain_silent_frames = 0; count } @@ -235,8 +248,9 @@ impl Processor { /// /// 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. + /// method always fills unused frames with zeros. The first non-empty call + /// after completion returns zero and resets the processor. An empty buffer + /// does not advance the drain or do the reset. /// /// # Errors /// @@ -251,8 +265,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). Positive calls + /// keep the peaks and the frame count until the next non-empty call + /// returns zero and resets the processor. /// /// # Errors /// @@ -275,9 +290,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 - /// [`begin_drain`](Self::begin_drain) describes. + /// complete, the method returns zero. An empty output uses no budget and + /// does not do the deferred reset. After completion, the next non-empty + /// call returns zero and does a reset, as [`begin_drain`](Self::begin_drain) + /// describes. /// /// # Errors /// @@ -307,6 +323,17 @@ impl Processor { )) } + /// Returns the upper bound on drain frames that are left, or `None` if no + /// drain is active. + /// + /// Before [`begin_drain`](Self::begin_drain) and after the final + /// zero-frame drain call, this method returns `None`. After the final + /// positive drain block, it returns `Some(0)` until a non-empty drain call + /// returns zero and resets the processor. + pub fn drain_remaining(&self) -> Option { + self.drain_remaining + } + /// Returns the fixed sample rate and block limit. pub fn prepare_config(&self) -> PrepareConfig { self.preparation @@ -492,9 +519,9 @@ impl Processor { self.resynthesis.apply_config(config.resynthesis); } if self.config.resynthesis.stereo_output != config.resynthesis.stereo_output { - // Resynthesis resets its histories if its stereo setting changes. + // Resynthesis flushes its histories if its stereo setting changes. self.alien.reset(); - self.reverb.reset(); + self.reverb.flush(); self.peak = 0; self.clear_telemetry_peaks(); self.last_resample_ratio = 0.0; @@ -509,16 +536,39 @@ impl Processor { self.reverb.set_config(config.reverb); } self.config = config; - self.drain_remaining = None; + self.cancel_drain(); + } + + /// Restores the initial state of [`Self::new`] for the current + /// configuration, with zero allocations. + /// + /// This method clears all audio histories, filter memories, pitch state, + /// formant models, harmony state, held MIDI keys, meters and the frame + /// count. It also starts the random stream again from + /// [`crate::ResynthesisConfig::random_seed`], resets the arctangent lookup + /// cursor and cancels any active drain. The prepared sample rate, the + /// block limit and the active [`ProcessorConfig`] stay the same. + 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; + self.last_resample_ratio = 0.0; + self.cancel_drain(); } - /// Clears the audio histories, held notes, pitch feedback, peak and frame - /// count. + /// Clears the audio histories, held notes, pitch feedback, peaks and frame + /// count, while controller continuity stays intact. /// /// 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: + /// ratio, the Punch envelopes, the Warm filters, the Alien history and the + /// reverb delays. It releases the harmony MIDI notes and, in MIDI-chord + /// mode, the chord voices. It keeps these items: /// /// - the configuration /// - the random stream and the arctangent lookup position of Punch @@ -531,21 +581,30 @@ impl Processor { /// - 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. + /// - the phase of the harmonic modulation + /// - the formant generation counter. /// /// When the method clears the held keys, it does not load the configured - /// scale again. For a fully new state, make a new processor. - pub fn reset(&mut self) { + /// scale again. For a deterministic initial state, call + /// [`reset`](Self::reset). + pub fn flush(&mut self) { self.punch.reset(); self.warm.reset(); - self.resynthesis.reset(); + self.resynthesis.flush(); self.alien.reset(); - self.reverb.reset(); + self.reverb.flush(); self.peak = 0; self.clear_telemetry_peaks(); self.frames = 0; self.last_resample_ratio = 0.0; + self.cancel_drain(); + } + + /// Cancels any active or completed drain and clears the silence counters. + fn cancel_drain(&mut self) { self.drain_remaining = None; + self.drain_holdoff = 0; + self.drain_silent_frames = 0; } /// Checks the block size, then checks all events without a change. @@ -574,8 +633,8 @@ impl Processor { /// Applies a validated control immediately before its frame is rendered. /// /// A partial configuration event replaces one stage in the active - /// configuration. MIDI and reset events act directly. A reset does not - /// discard later events in the block. + /// configuration. MIDI, reset and flush events act directly. A reset or a + /// flush does not discard later events in the block. fn apply(&mut self, event: ValidatedEvent) { let mut config = self.config; match event.into_inner() { @@ -598,6 +657,10 @@ impl Processor { self.reset(); return; } + ControlEvent::Flush => { + self.flush(); + return; + } } self.apply_config(config); } @@ -648,7 +711,7 @@ impl Processor { mut write: impl FnMut(usize, [i16; 2]), ) -> Result<(), Error> { let mut events = self.validate(input, events)?; - self.drain_remaining = None; + self.cancel_drain(); for (index, sample) in input.iter().enumerate() { while let Some(event) = events.next_at(index) { self.apply(event); @@ -661,17 +724,27 @@ 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. + /// The method mutes aspiration temporarily, and does not change the + /// settings that the host sees. `Some(0)` records completion, and the next + /// non-empty drain call 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 remaining = match self.drain_remaining { + None => return Ok(0), + Some(0) => { + self.reset(); + return Ok(0); + } + Some(remaining) => remaining, + }; + let limit = remaining.min(frames); let configured = self.config.resynthesis; if configured.formant.aspiration_mix != 0.0 { let mut silent = configured; @@ -679,18 +752,30 @@ impl Processor { // Zero aspiration is valid in all validated configurations. self.resynthesis.apply_config(silent); } - for index in 0..count { - write(index, self.next(0)); + let mut count = 0; + for index in 0..limit { + let frame = self.next(0); + write(index, frame); + count += 1; + if self.drain_holdoff > 0 { + self.drain_holdoff -= 1; + } else if frame[0].abs() <= DRAIN_SILENCE_PCM && frame[1].abs() <= DRAIN_SILENCE_PCM { + self.drain_silent_frames += 1; + if self.drain_silent_frames >= reverb::DELAY_CAPACITY { + break; + } + } else { + self.drain_silent_frames = 0; + } } 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); + let left = remaining - count; + if left == 0 || self.drain_silent_frames >= reverb::DELAY_CAPACITY { + self.drain_remaining = Some(0); + } else { + self.drain_remaining = Some(left); } Ok(count) } @@ -715,8 +800,8 @@ pub struct Feedback { /// unity. /// /// It does not include the configured pitch shift or the ratios of - /// individual voices. It is zero before processing, after a reset or after - /// a change of stereo output. + /// individual voices. It is zero before the first block, after a reset, + /// after a flush or after a change of stereo output. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// @@ -755,16 +840,16 @@ pub struct Feedback { pub voiced: bool, /// The largest absolute clipped stereo sample, divided by 32768. /// - /// The peak window starts at construction, at a reset, at a change of - /// stereo output or at a call to [`Processor::take_feedback`]. The value - /// is in 0..=32767/32768. The mono downmix occurs after this measurement. - /// [`Processor::feedback`] does not clear the value. + /// The peak window starts at construction, at a reset, at a flush, at a + /// change of stereo output or at a call to [`Processor::take_feedback`]. + /// The value is in 0..=32767/32768. The mono downmix occurs after this + /// measurement. [`Processor::feedback`] does not clear the value. pub peak_level: f32, - /// The number of frames processed since construction or the last reset, - /// with drain frames included. + /// The number of frames processed since construction, the last reset or + /// the last flush, 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 drain completion, 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( @@ -783,9 +868,9 @@ pub struct Feedback { /// `Default` gives a snapshot with all zeros. /// /// The three peak fields measure a window. The window starts at -/// construction, at a reset, at a change of stereo output or at a call to -/// [`Processor::take_telemetry`]. This window is independent of the peak -/// window of [`Feedback`]. +/// construction, at a reset, at a flush, at a change of stereo output or at a +/// call to [`Processor::take_telemetry`]. This window is independent of the +/// peak window of [`Feedback`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -794,8 +879,8 @@ pub struct Feedback { tsify(large_number_types_as_bigints) )] pub struct Telemetry { - /// The number of frames processed since construction or the last reset, - /// as [`Feedback::processed_frames`] gives. + /// The number of frames processed since construction, the last reset or + /// the last flush, as [`Feedback::processed_frames`] gives. pub processed_frames: u64, /// The largest absolute input sample in the window, divided by 32768. /// @@ -872,10 +957,11 @@ 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 + /// enabled. A flush keeps this count. Compare two values to find if /// [`Processor::formant_envelope`] can give a new result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..6cc5a57 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -70,8 +70,9 @@ 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 flush releases the correction keys 0..=126 and keeps key 127 +/// and the active note table. A reset loads the configured mask again and +/// clears all keys. 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 @@ -248,8 +249,9 @@ 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. A flush keeps the current position in the stream. 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, } @@ -413,8 +415,8 @@ pub(crate) struct Resynthesis { positions: [Q14; 16], /// 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. + /// The Q14 multipliers, each equal to 1.0 plus the drift. A flush sets + /// them to 1.0, and keeps the drift state. 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. @@ -424,8 +426,8 @@ pub(crate) struct Resynthesis { harmony_pan: [[Q14; 2]; HARMONY_VOICES], /// 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. + /// The last Q12 gain envelopes from the harmony controller. A flush keeps + /// 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 +458,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. A flush keeps it. modulation_phase: Q14, /// The Q8 weight of the delayed raw audio. The wet weight is 1.0 minus /// this weight. @@ -503,17 +505,7 @@ impl Resynthesis { }, formant: Formant::new(rate, config.formant), harmony: HarmonyState::new(rate, config.harmony), - scale: { - // The initial chromatic table uses 44.1 kHz periods at the two - // rates. If the notes load again, the periods for the - // configured rate become active. - let mut scale = CorrectionTable::new(SampleRate::Hz44100, NoteMask::default()); - scale.set_sample_rate(rate); - if config.correction.notes != NoteMask::default() { - scale.set_notes(config.correction.notes); - } - scale - }, + scale: Self::initial_scale(rate, config.correction.notes), filtered: prepare_history(Q14::ZERO), lead: prepare_history(Q14::ZERO), periods: prepare_history(Q6::ZERO), @@ -551,10 +543,23 @@ impl Resynthesis { }; result.configure_coefficients(); result.configure_shift_filters(); - result.reset(); + result.clear_histories(); result } + /// Builds the initial correction table in the same way as construction. + /// + /// The initial chromatic table uses 44.1 kHz periods at the two rates. If + /// the notes load again, the periods for the configured rate become active. + fn initial_scale(rate: SampleRate, notes: NoteMask) -> CorrectionTable { + let mut scale = CorrectionTable::new(SampleRate::Hz44100, NoteMask::default()); + scale.set_sample_rate(rate); + if notes != NoteMask::default() { + scale.set_notes(notes); + } + scale + } + /// Quantizes the controls and calculates the decay coefficients and the /// voice pan gains again. /// @@ -663,19 +668,37 @@ impl Resynthesis { } self.configure_coefficients(); if old.stereo_output != config.stereo_output { - // A stereo change resets the audio state. The correction keyboard + // A stereo change flushes the audio state. The correction keyboard // keeps its held keys. - self.reset_audio(); + self.flush_audio(); } } - /// Releases the correction keys 0..=126 and resets the audio state. + /// Releases the correction keys 0..=126 and flushes the audio state. /// /// The active correction table, key 127 and the items that - /// `reset_audio` keeps do not change. + /// `flush_audio` keeps do not change. + pub(crate) fn flush(&mut self) { + self.scale.flush(); + self.flush_audio(); + } + + /// Restores the initial state of [`Self::new`] without allocation. pub(crate) fn reset(&mut self) { - self.scale.reset(); - self.reset_audio(); + self.pitch.reset(); + self.formant.reset(); + self.harmony.reset(); + self.scale = Self::initial_scale(self.rate, self.config.correction.notes); + self.drift.fill(Q14::ZERO); + self.pan = [[Q14::ONE; 2]; 16]; + self.harmony_gains.fill(Q12::ZERO); + self.scale_index = 0; + self.octave = 0; + self.modulation_phase = Q14::ZERO; + self.control_counter = CONTROL_DUE; + self.configure_coefficients(); + self.configure_shift_filters(); + self.clear_histories(); } /// Clears the audio and period histories, the tracker, the formant @@ -690,12 +713,18 @@ impl Resynthesis { /// - The modulation phase. /// - The control counter. /// - The harmony release envelopes and the last harmony gains. - fn reset_audio(&mut self) { - self.pitch.reset(); + fn flush_audio(&mut self) { + self.pitch.flush(); + self.formant.flush(); + self.harmony.flush(); + self.clear_histories(); + } + + /// Clears the sample, period and ratio rings and sets the readers and + /// correction state back to their initial positions. + fn clear_histories(&mut self) { self.raw.fill(Q14::ZERO); self.write = 0; - self.formant.reset(); - self.harmony.reset(); self.filtered.fill(Q14::ZERO); self.lead.fill(Q14::ZERO); self.periods.fill(Q6::ZERO); diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..d2b534b 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 flush keeps key 127, and mask creation excludes it. pub keyboard: [bool; 128], } @@ -222,7 +222,7 @@ 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 flush(&mut self) { self.keyboard[..127].fill(false); } /// Applies an event whose MIDI ranges were already checked. @@ -232,10 +232,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.flush(), } let mut mask = [false; 12]; - // Correction excludes key 127, and a reset keeps that key. + // Correction excludes key 127, and a flush 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..be34cab 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -22,10 +22,10 @@ //! - The optional harmony `voices` field defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use -//! `{ type, value }`, and the reset control has no `value`. MIDI messages use -//! `{ type, channel, note, velocity }`, with the fields that apply to the -//! selected variant. The TypeScript declarations come from the same Rust types -//! that validation uses. +//! `{ type, value }`, and the `reset` and `flush` controls have no `value`. +//! MIDI messages use `{ type, channel, note, velocity }`, with the fields that +//! apply to the selected variant. The TypeScript declarations come from the +//! same Rust types that validation uses. //! //! The class allocates the PCM storage at construction and uses it again for //! each block. These operations can allocate: @@ -294,30 +294,47 @@ impl WasmProcessor { Ok(()) } - /// Starts a finite tail budget and returns its frame count as a number. + /// Starts an adaptive drain and returns its upper-bound frame count as a + /// number. /// /// Call this method one time after the final input block. Another call - /// starts the full budget again, but it does not clear the histories. See - /// `beginDrain` for completion. + /// 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() } - /// Returns the tail budget of the current configuration, not the remaining - /// drain count. + /// Returns the upper-bound tail budget of the current configuration. + /// + /// For the active drain budget, read `drainRemaining`. #[wasm_bindgen(js_name = tailFrames)] pub fn tail_frames(&self) -> usize { self.processor.tail_frames() } + /// The upper-bound frame count that is left in the active drain, or + /// `undefined`. + /// + /// The value is `undefined` before `beginDrain` and after the final + /// zero-frame drain call. It decreases on each positive drain block and + /// becomes `0` immediately after the final positive block. + #[wasm_bindgen(getter, js_name = drainRemaining)] + pub fn drain_remaining(&self) -> Option { + self.processor.drain_remaining() + } + /// 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. After the resynthesis and Alien delays pass, the + /// drain stops early after 17,000 consecutive frames within ±24 PCM on + /// both channels. + /// + /// The final positive block sets `drainRemaining` to `0` and keeps the + /// peaks and the frame counts in `feedback` and `telemetry`. The next + /// non-empty drain call returns `0`, resets the processor and sets + /// `drainRemaining` to `undefined`. Empty arrays do not advance the drain + /// or trigger that reset. /// /// # Errors /// @@ -338,8 +355,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, adaptive + /// silence stop, deferred reset and feedback behavior are the same as for + /// `drain`. /// /// # Errors /// @@ -465,14 +483,25 @@ impl WasmProcessor { Ok(valid) } - /// Resets the audio histories and feedback, as the native processor does. + /// Restores the initial state of the active configuration, without memory + /// allocation. /// - /// 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`. + /// The preparation and the active configuration stay the same. All DSP + /// histories, keyboard state, random state, meters and active drain state + /// return to the start of a new `Tunelet`. pub fn reset(&mut self) { self.processor.reset(); } + + /// Clears audio delay lines, held notes 0..=126 and meters for live + /// continuity. + /// + /// The active configuration, the random stream, reverb filter memories, + /// harmony release envelopes and formant generation stay intact. This + /// method cancels any active drain. + pub fn flush(&mut self) { + self.processor.flush(); + } } impl WasmProcessor {