Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 30 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,18 +276,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

Expand All @@ -300,6 +315,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:
Expand Down Expand Up @@ -340,6 +356,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
Expand Down Expand Up @@ -424,8 +441,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

Expand Down Expand Up @@ -463,8 +480,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 } }
Expand Down
8 changes: 4 additions & 4 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.
106 changes: 79 additions & 27 deletions src/effects/reverb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand All @@ -148,10 +148,13 @@ 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 delay buffer changed since construction or the last clear.
dirty: bool,
}

/// 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);
Expand Down Expand Up @@ -209,11 +212,24 @@ impl Reverb {
}
/// Clears only the delay contents, and keeps the write cursor and the
/// damping memories.
pub(crate) fn flush(&mut self) {
if self.dirty {
self.delay.flush();
self.dirty = false;
}
}
/// Clears the delay contents, the write cursor, the damping memories and
/// the wet peak.
pub(crate) fn reset(&mut self) {
if self.dirty {
self.delay.reset();
self.dirty = false;
} else {
self.delay.write = 0;
}
self.lpf1.reset();
self.lpf2.reset();
self.wet_peak = 0;
}
/// Returns the largest absolute Q14 wet contribution since the last
/// clear, as f32.
Expand Down Expand Up @@ -395,33 +411,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.
Expand All @@ -431,7 +478,7 @@ struct DelayLine {
/// the Q14 audio scale.
buffer: Vec<Q14>,
/// 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 {
Expand All @@ -444,8 +491,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.
///
Expand Down Expand Up @@ -613,7 +665,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,
}
}
14 changes: 10 additions & 4 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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(),
Expand All @@ -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(()),
}
}
}
Expand Down
33 changes: 29 additions & 4 deletions src/formant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,12 @@ pub(crate) struct Formant {
/// If `true`, the next call to `smooth` clears the state of the
/// correlation average.
smooth_reset: bool,
/// If `true`, the stage changed state since construction or the last reset.
/// If `true`, the audio or synthesis state changed since construction or
/// the last clear.
dirty: bool,
/// If `true`, the analysis state changed since construction or the last
/// reset.
analysis_dirty: bool,
/// The Q14 first-order coefficient for pre-emphasis and de-emphasis.
glottal: i32,
/// The Q14 width control. The stage also uses it as the output gain of
Expand Down Expand Up @@ -287,6 +291,7 @@ impl Formant {
smooth_filled: 0,
smooth_reset: true,
dirty: false,
analysis_dirty: false,
glottal: (0.5_f64.powf(1.0 / d2) * 16384.0) as i32,
width: 16384,
width_squared: 16384,
Expand Down Expand Up @@ -333,9 +338,9 @@ 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 other banks and the generation
/// counter stay as they are.
pub(crate) fn flush(&mut self) {
if !self.dirty {
return;
}
Expand All @@ -352,6 +357,25 @@ 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) {
if self.analysis_dirty {
self.analysis_dirty = false;
self.temporary.fill(0_i32);
self.inverse.fill([0; 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.areas = [0; MAX_ORDER];
self.stretched_areas = [0; MAX_ORDER];
self.generation = 0;
}
self.stretch_map[self.stretch_count..].fill(0);
self.flush();
}
/// Starts a new model and a new correlation window when pitch acquisition
/// locks.
///
Expand Down Expand Up @@ -393,6 +417,7 @@ impl Formant {
output_period_q6: i32,
) -> i32 {
self.dirty = true;
self.analysis_dirty = true;
self.input[write] = self.remove_glottal(sample, previous);

self.design(periods, write, output_period_q6);
Expand Down
Loading