Skip to content
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions docs/images/lifecycle.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
147 changes: 114 additions & 33 deletions src/effects/reverb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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],
Expand All @@ -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,
}

Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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.
Expand All @@ -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 {
Expand All @@ -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.
///
Expand Down
57 changes: 32 additions & 25 deletions src/harmony.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand Down
19 changes: 11 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
//!
Expand Down
5 changes: 3 additions & 2 deletions src/numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion src/numeric/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
Loading
Loading