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
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ browsers and Node.js.
- **No dependencies**: The default Rust build has no dependencies and uses
only safe Rust.

The input is mono signed 16-bit PCM at 44.1 kHz or 48 kHz. The output is
stereo or mono 16-bit PCM.
The input is mono signed 16-bit PCM at 8, 16, 22.05, 24, 32, 44.1, 48,
88.2, 96 or 192 kHz. The output is stereo or mono 16-bit PCM.

## Installation

Expand Down Expand Up @@ -176,7 +176,8 @@ limits. Decrease `output_gain` to prevent `-32767..=32767` clipping on
multi-voice mixes.

`resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The
dry path starts after Warm and has a delay of 1,543 frames.
dry path starts after Warm and adds the overlap delay (approximately 35 ms;
1,543 frames at 44.1 kHz).

### Harmony sources

Expand Down Expand Up @@ -299,7 +300,7 @@ These calls read the state of the processor. They do not change the audio.
| `take_feedback()` | The same data as `feedback()`, and clears the peak window |
| `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 |
| `latency_frames()` | Nominal resynthesis latency in frames for the prepared sample rate |
| `formant_envelope()` | The LPC envelopes before and after the formant controls |

The telemetry includes these items:
Expand Down
46 changes: 40 additions & 6 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,51 @@ use std::num::NonZeroUsize;

/// The sample rate of the input and the output.
///
/// The default is 44.1 kHz. The prepared delay and filter layouts support only
/// the listed rates. To convert an integer device rate, use
/// [`SampleRate::try_from`]. The rate of a processor is fixed at construction.
/// To change the rate, you must make a new processor.
/// The default is 44.1 kHz. The prepared delay and filter layouts support ten
/// standard voice, WebRTC and studio rates from 8 kHz to 192 kHz. To convert
/// an integer device rate, use [`SampleRate::try_from`]. The rate of a
/// processor is fixed at construction. To change the rate, you must make a new
/// processor.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum SampleRate {
/// 8 kHz.
Hz8000,
/// 16 kHz.
Hz16000,
/// 22.05 kHz.
Hz22050,
/// 24 kHz.
Hz24000,
/// 32 kHz.
Hz32000,
/// 44.1 kHz.
#[default]
Hz44100,
/// 48 kHz.
Hz48000,
/// 88.2 kHz.
Hz88200,
/// 96 kHz.
Hz96000,
/// 192 kHz.
Hz192000,
}

impl SampleRate {
/// Returns the rate in hertz.
pub const fn as_u32(self) -> u32 {
match self {
Self::Hz8000 => 8_000,
Self::Hz16000 => 16_000,
Self::Hz22050 => 22_050,
Self::Hz24000 => 24_000,
Self::Hz32000 => 32_000,
Self::Hz44100 => 44_100,
Self::Hz48000 => 48_000,
Self::Hz88200 => 88_200,
Self::Hz96000 => 96_000,
Self::Hz192000 => 192_000,
}
}

Expand All @@ -48,12 +73,21 @@ impl TryFrom<u32> for SampleRate {
/// # Errors
///
/// Returns [`Error::UnsupportedSampleRate`] with `hz`, unless the value is
/// exactly 44,100 or 48,000. The function does not resample and does not
/// select the nearest rate.
/// 8,000, 16,000, 22,050, 24,000, 32,000, 44,100, 48,000, 88,200, 96,000
/// or 192,000. The function does not resample and does not select the
/// nearest rate.
fn try_from(hz: u32) -> Result<Self, Self::Error> {
match hz {
8_000 => Ok(Self::Hz8000),
16_000 => Ok(Self::Hz16000),
22_050 => Ok(Self::Hz22050),
24_000 => Ok(Self::Hz24000),
32_000 => Ok(Self::Hz32000),
44_100 => Ok(Self::Hz44100),
48_000 => Ok(Self::Hz48000),
88_200 => Ok(Self::Hz88200),
96_000 => Ok(Self::Hz96000),
192_000 => Ok(Self::Hz192000),
_ => Err(Error::UnsupportedSampleRate { hz }),
}
}
Expand Down
85 changes: 57 additions & 28 deletions src/effects/alien.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,41 @@

use crate::error::check_count;
use crate::numeric::fixed::{Fixed, Q14};
use crate::Error;
use crate::{Error, SampleRate};

/// The number of history frames that the loop reads from.
const HISTORY_FRAMES: usize = 192_000;
/// The number of frames for the boundary fade at each loop boundary.
const FADE_FRAMES: usize = 200;
/// Returns the stereo history capacity in frames for `rate` (approximately
/// four seconds; 192,000 frames at 44.1 and 48 kHz).
const fn history_frames(rate: SampleRate) -> usize {
match rate {
SampleRate::Hz8000 => 32_000,
SampleRate::Hz16000 => 64_000,
SampleRate::Hz22050 | SampleRate::Hz24000 => 96_000,
SampleRate::Hz32000 => 128_000,
SampleRate::Hz44100 | SampleRate::Hz48000 => 192_000,
SampleRate::Hz88200 | SampleRate::Hz96000 => 384_000,
SampleRate::Hz192000 => 768_000,
}
}

/// Returns the boundary fade length in frames (~4.54 ms; 200 frames at
/// 44.1 kHz).
const fn fade_frames(rate: SampleRate) -> usize {
let frames = (200 * rate.as_u32() as usize + 22_050) / 44_100;
if frames < 1 {
1
} else {
frames
}
}

/// Reverse playback of recent stereo audio in repeated loops with fades.
///
/// Alien comes after resynthesis. Its input history and loop phase advance
/// also when Alien is disabled. Thus, when you enable Alien, it can play
/// audio that it recorded during bypass. A change of the loop length keeps
/// the history and clamps the current phase into the new loop. The boundary
/// fades are 200 frames long at all sample rates.
/// fades scale with the sample rate (approximately 4.54 ms; 200 frames at
/// 44.1 kHz).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
#[cfg_attr(
Expand All @@ -28,10 +49,12 @@ pub struct AlienConfig {
/// `false`. The recording and the phase continue to advance in both
/// states.
pub enabled: bool,
/// The loop length in frames, 1..=96000. The default is 95,999.
/// This value is a frame count at the two rates. Thus, its duration in
/// seconds changes with the sample rate. A short loop can be fully inside
/// the fades.
/// The loop length in frames, 1..=384000. The default is 95,999.
///
/// This value is a frame count, so its duration in seconds changes with
/// the sample rate. The active loop clamps to half of the prepared
/// history capacity (approximately two seconds; 96,000 frames at 44.1 and
/// 48 kHz). A short loop can be fully inside the fades.
pub loop_frames: u32,
}
impl Default for AlienConfig {
Expand All @@ -53,7 +76,7 @@ impl AlienConfig {
/// Returns the first [`Error::InvalidConfig`] with its dotted field path
/// and the problem.
pub fn validate(self) -> Result<(), Error> {
check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 96_000)
check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 384_000)
}
}

Expand All @@ -63,34 +86,38 @@ impl AlienConfig {
pub(crate) struct Alien {
/// The validated controls, which include the selection of the wet output.
config: AlienConfig,
/// 192,000 stereo Q14 frames, which are allocated one time at
/// construction.
/// The boundary fade length in frames for the prepared rate.
fade_frames: usize,
/// The stereo Q14 history frames, allocated one time at construction.
buffer: Vec<[Q14; 2]>,
/// The current recording position. The position of the reverse reader
/// comes from this cursor.
read: usize,
/// The current frame in the loop. It is always less than `loop_len`.
phase: usize,
/// The validated loop length. It is not more than half of the history
/// The active loop length. It is not more than half of the history
/// capacity.
loop_len: usize,
}
impl Alien {
/// Allocates a silent stereo ring from validated loop settings.
pub(crate) fn new(config: AlienConfig) -> Self {
pub(crate) fn new(rate: SampleRate, config: AlienConfig) -> Self {
let history = history_frames(rate);
let loop_len = (config.loop_frames as usize).min(history / 2);
Self {
config,
buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES],
fade_frames: fade_frames(rate),
buffer: vec![[Q14::default(); 2]; history],
read: 0,
phase: 0,
loop_len: config.loop_frames as usize,
loop_len,
}
}
/// Applies a validated configuration, keeps the recorded audio and clamps
/// the phase into the new loop, which is not empty.
pub(crate) fn set_config(&mut self, config: AlienConfig) {
self.config = config;
self.loop_len = config.loop_frames as usize;
self.loop_len = (config.loop_frames as usize).min(self.buffer.len() / 2);
self.phase = self.phase.min(self.loop_len - 1);
}
/// Returns the loop length and the current frame in the loop.
Expand All @@ -111,29 +138,30 @@ impl Alien {
/// both cursors.
/// The recording cursor moves forward by one and the reverse offset
/// increases by two. Thus, the playback moves backward by one frame. The
/// validated loop limit keeps that subtraction in a single ring wrap.
/// active loop limit keeps that subtraction in a single ring wrap.
pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] {
let history = self.buffer.len();
self.buffer[self.read] = input;
let result = if self.config.enabled {
let read = self.read + HISTORY_FRAMES - self.phase * 2;
let read = if read >= HISTORY_FRAMES {
read - HISTORY_FRAMES
let read = self.read + history - self.phase * 2;
let read = if read >= history {
read - history
} else {
read
};
let distance = self.phase.min(self.loop_len - self.phase);
let mut result = self.buffer[read];
if distance < FADE_FRAMES {
if distance < self.fade_frames {
let gain: Q14 = Fixed::<0>::from_bits(distance as i32)
.div(Fixed::<0>::from_bits(FADE_FRAMES as i32));
.div(Fixed::<0>::from_bits(self.fade_frames as i32));
result = result.map(|sample| sample.mul::<14, 14>(gain));
}
result
} else {
input
};
self.read += 1;
if self.read == HISTORY_FRAMES {
if self.read == history {
self.read = 0;
}
self.phase += 1;
Expand All @@ -144,14 +172,15 @@ impl Alien {
}
}

/// Returns the finite tail budget: two loop lengths plus the boundary
/// Returns the finite tail budget: two active loop lengths plus the boundary
/// fade.
///
/// The value is zero when Alien is disabled. It is a configured budget,
/// not a measured tail.
pub(crate) fn tail_frames(config: AlienConfig) -> usize {
pub(crate) fn tail_frames(rate: SampleRate, config: AlienConfig) -> usize {
if config.enabled {
2 * config.loop_frames as usize + FADE_FRAMES
let loop_len = (config.loop_frames as usize).min(history_frames(rate) / 2);
2 * loop_len + fade_frames(rate)
} else {
0
}
Expand Down
35 changes: 24 additions & 11 deletions src/effects/punch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,17 @@ use crate::numeric::fixed::{Q14, Q8};
use crate::numeric::{coefficient_to_exp_value, db_to_gain, envelope_decay, NumericContext};
use crate::{Error, SampleRate};

/// The update interval of the peak follower, in frames.
const WINDOW_FRAMES: usize = 100;
/// Returns the peak-follower update interval in frames (~2.27 ms; 100 frames
/// at 44.1 kHz).
const fn window_frames(rate: SampleRate) -> usize {
let frames = (100 * rate.as_u32() as usize + 22_050) / 44_100;
if frames < 1 {
1
} else {
frames
}
}

/// The base arctangent drive, approximately π/2 in Q8.
const BASE_DRIVE: Q8 = Q8::from_bits(401);
/// The 2/π factor in Q14 that normalizes the arctangent output.
Expand All @@ -16,9 +25,10 @@ const TWO_OVER_PI: Q14 = Q14::from_bits(10430);
/// The input gain and the transient enhancement with arctangent saturation.
///
/// Punch comes before Warm and before pitch detection. It finds the peak of
/// each window of 100 processed frames. Two envelope followers set the drive
/// from these peaks. When Punch is disabled, it does not process audio, and
/// its envelope and window state do not change.
/// each window of processed frames (approximately 2.27 ms; 100 frames at
/// 44.1 kHz). Two envelope followers set the drive from these peaks. When
/// Punch is disabled, it does not process audio, and its envelope and window
/// state do not change.
///
/// A gain change updates the cached drive at the next boundary of the peak
/// window. A reset calculates that drive again immediately from the
Expand All @@ -36,7 +46,7 @@ pub struct PunchConfig {
/// The input gain in decibels, -96..=12.
///
/// The default is 0 dB. The saturation drive from this gain changes at the
/// next 100-frame peak boundary.
/// next boundary of the peak window.
pub gain_db: f32,
/// The transient emphasis without a unit, 0..=1.
///
Expand All @@ -52,7 +62,7 @@ pub struct PunchConfig {
/// The attack half-life of the peak follower in milliseconds, 0.01..=5000.
///
/// The default is 10 ms. The coefficients include the effect of the
/// 100-frame update interval.
/// peak-window update interval.
pub attack_ms: f32,
}
impl Default for PunchConfig {
Expand Down Expand Up @@ -91,12 +101,14 @@ impl PunchConfig {
pub(crate) struct Punch {
/// The prepared rate, which converts the envelope times to sample windows.
rate: SampleRate,
/// The peak-window length in frames for `rate`.
window_frames: usize,
/// The adaptive Q14 peak envelope. The impact control sets its release.
slow: Q14,
/// The second Q14 peak envelope, with a fixed release half-life of 5
/// seconds.
fast: Q14,
/// The number of samples in the current 100-frame peak window.
/// The number of samples in the current peak window.
counter: usize,
/// The largest absolute Q14 input in the current window.
peak: Q14,
Expand All @@ -119,6 +131,7 @@ impl Punch {
pub(crate) fn new(rate: SampleRate, config: PunchConfig) -> Self {
let mut result = Self {
rate,
window_frames: window_frames(rate),
slow: Q14::default(),
fast: Q14::default(),
counter: 0,
Expand Down Expand Up @@ -151,7 +164,7 @@ impl Punch {
Q14::from_f64(envelope_decay(
milliseconds,
self.rate.hz() as f64,
WINDOW_FRAMES,
self.window_frames,
))
};
self.slow_decay = decay(impact as f64);
Expand Down Expand Up @@ -179,7 +192,7 @@ impl Punch {
target + decay.mul(current - target)
}

/// Tracks the current peak, updates the drive every 100 calls and
/// Tracks the current peak, updates the drive at each window boundary and
/// saturates one PCM sample.
/// The envelope ratio is approximately limited to 16 before it is
/// multiplied by the input gain. While the adaptive envelope is zero, the
Expand All @@ -189,7 +202,7 @@ impl Punch {
let sample = Q14::from_bits(i32::from(input) >> 1);
self.peak = self.peak.max(sample.abs());
self.counter += 1;
if self.counter == WINDOW_FRAMES {
if self.counter == self.window_frames {
self.counter = 0;
self.slow = Self::follow(self.slow, self.peak, self.attack_decay, self.slow_decay);
self.fast = Self::follow(self.fast, self.peak, self.attack_decay, self.fast_decay);
Expand Down
Loading