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
25 changes: 15 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,16 +167,20 @@ voice. It disables the effects and the formant stage.
| Correction | Moves the pitch to the nearest permitted note | Chromatic | `resynthesis.correction` |
| Voices | Renders a choir (1 to 16 voices) or harmony (lead and 0–4) | Choir, 1 voice | `resynthesis.mode` |
| Formant | Changes the vocal tract with an LPC model and aspiration | Disabled | `resynthesis.formant` |
| Alien | Plays recent audio in reverse loops | Disabled | `alien` |
| Alien | Plays recent audio in reverse loops, with wet mix | Disabled | `alien` |
| Reverb | Echo, Schroeder, SmallRoom, Binaural, MediumHall, LargeHall | Disabled | `reverb` |
| Output gain | Linear gain, 0..=64, before `-32767..=32767` clipping | 1 | `output_gain` |
| Output gain | Linear gain, 0..=64, before global mix | 1 | `output_gain` |
| Mix | Global wet fraction, 0..=1, before `-32767..=32767` clip | 1 | `mix` |
| Bypass | Outputs the 1,593-frame delayed input before Punch | Disabled | `bypass` |

The internal Q14 stages use `i64` products and saturate at the `i32`
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.
`resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. That
dry path starts after Warm and has a delay of 1,593 frames. `mix` blends
the wet output with the 1,593-frame delayed input before Punch. If Alien is
enabled, `alien.mix` sets the wet fraction of the reversed loop.

### Harmony sources

Expand Down Expand Up @@ -311,8 +315,8 @@ The telemetry includes these items:
- The current gains of Punch and Warm, and the position in the Alien loop.

The peak windows of the telemetry are independent of the peak window of the
feedback. The latency is nominal. Dry mixes, resampled voices and effects
have different timing.
feedback. The latency is nominal. The dry paths and bypass have a delay of
1,593 frames. Resampled voices and effects have their own delays.

`formant_envelope()` writes two LPC envelopes into slices of equal length:

Expand Down Expand Up @@ -451,10 +455,11 @@ and show enums as string literals. To change the configuration, do these steps:
3. Call `setConfig()`.

If a required field is absent or a value is not valid, the call throws a
JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults
to 4 if it is absent. The conversion ignores extra object properties. The
generated declarations contain the parameter documentation from the Rust
types.
JavaScript `Error`. If an optional field is absent,
`resynthesis.harmony.voices` defaults to 4, `mix` and `alien.mix` default to
1, and `bypass` defaults to `false`. The conversion ignores extra object
properties. The generated declarations contain the parameter documentation
from the Rust types.

`resynthesis.randomSeed` and the `processedFrames` field of feedback and
telemetry use `bigint`. Frame offsets, block lengths and latency use
Expand Down
2 changes: 1 addition & 1 deletion docs/images/signal-chain.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
65 changes: 51 additions & 14 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,15 @@ impl PrepareConfig {

/// The settings for the complete signal chain, in the order of the stages.
///
/// The default enables chromatic pitch correction, one choir voice and unity
/// output gain. Punch, Warm, formants, Alien and reverb are disabled. This
/// configuration does active pitch processing. It is not a bypass with zero
/// latency.
/// The default enables chromatic pitch correction, one choir voice, unity
/// output gain and unity global mix. Punch, Warm, formants, Alien, reverb and
/// bypass are disabled. This configuration does active pitch correction. It is
/// not a bypass with zero latency.
///
/// Change a copy, then apply it with [`crate::Processor::set_config`] or
/// [`crate::ControlEvent::Configure`]. The validation examines all fields
/// before a change has an effect. This includes the fields of disabled stages.
/// before a change has an effect. This includes the fields of disabled stages
/// and `mix` while `bypass` is `true`.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
#[cfg_attr(
Expand Down Expand Up @@ -161,16 +162,48 @@ pub struct ProcessorConfig {
pub reverb: ReverbConfig,
/// The linear gain after all effects, 0..=64.
///
/// The default is 1 (unity). Zero mutes the output, but the internal
/// processing continues. The gain is quantized in steps of 1/256 before
/// the fixed-point multiplication and the final PCM clipping. Thus, a
/// positive value below 1/256 also mutes the output.
/// The default is 1 (unity). If `mix` is 1, zero mutes the output, and
/// the internal stages continue to advance. The code quantizes the gain in
/// steps of 1/256 before the fixed-point multiplication and the global
/// mix. Thus, a positive value below 1/256 also mutes the wet path.
pub output_gain: f32,
/// The global wet fraction after the output gain, 0..=1.
///
/// The default is 1. The code quantizes this value to Q14. The dry path
/// delays the input before Punch by 1,593 frames. The wet weight is `mix`
/// and the dry weight is `1 - mix`, before the `-32767..=32767` clip. In
/// JavaScript, this field is optional. If it is absent, the default is 1.
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
serde(default = "default_mix"),
tsify(optional)
)]
pub mix: f32,
/// Selects the latency-aligned dry input instead of the processed chain.
///
/// The default is `false`. If `bypass` is `true`, the processor outputs
/// the 1,593-frame delayed input before Punch, clipped to
/// `-32767..=32767`. The internal stages continue to advance. In
/// JavaScript, this field is optional. If it is absent, the default is
/// `false`.
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
serde(default),
tsify(optional)
)]
pub bypass: bool,
}

/// The default global wet fraction: the full processed signal.
#[cfg(all(feature = "wasm", target_arch = "wasm32"))]
fn default_mix() -> f32 {
1.0
}

impl Default for ProcessorConfig {
/// Returns chromatic correction with zero retune time, one choir voice,
/// disabled effects, disabled formants and unity gain.
/// disabled effects, disabled formants, unity gain, unity mix and
/// disabled bypass.
fn default() -> Self {
Self {
punch: PunchConfig::default(),
Expand All @@ -179,16 +212,19 @@ impl Default for ProcessorConfig {
alien: AlienConfig::default(),
reverb: ReverbConfig::default(),
output_gain: 1.0,
mix: 1.0,
bypass: false,
}
}
}

impl ProcessorConfig {
/// Checks all stages and the final gain, and does not change state.
/// Checks all stages, the output gain and the global mix, and does not
/// change state.
///
/// The validation uses the signal order: Punch, Warm, resynthesis, Alien,
/// reverb, then output gain. It includes disabled stages and the controls
/// of voice modes that are not active.
/// reverb, output gain, then global mix. It includes disabled stages,
/// inactive voice modes and `mix` while `bypass` is `true`.
///
/// # Errors
///
Expand All @@ -201,7 +237,8 @@ impl ProcessorConfig {
self.resynthesis.validate()?;
self.alien.validate()?;
self.reverb.validate()?;
validate_output_gain(self.output_gain)
validate_output_gain(self.output_gain)?;
check_range("mix", self.mix, 0.0, 1.0)
}
}

Expand Down
62 changes: 48 additions & 14 deletions src/effects/alien.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Reverse-loop playback with a continuous input history and boundary fades.

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

Expand All @@ -24,36 +25,58 @@ const FADE_FRAMES: usize = 200;
serde(rename_all = "camelCase")
)]
pub struct AlienConfig {
/// Selects reversed playback instead of the direct input. The default is
/// `false`. The recording and the phase continue to advance in both
/// states.
/// Enables the reversed loop. The default is `false`.
///
/// The history 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.
pub loop_frames: u32,
/// The wet fraction of the reversed loop, 0..=1.
///
/// The default is 1. The code quantizes this value to Q14. The dry weight
/// of the direct stereo input is `1 - mix`. If `enabled` is `false`, the
/// stage returns the direct input. In JavaScript, this field is optional.
/// If it is absent, the default is 1.
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
serde(default = "default_mix"),
tsify(optional)
)]
pub mix: f32,
}

/// The default wet fraction of Alien: full reversed playback.
#[cfg(all(feature = "wasm", target_arch = "wasm32"))]
fn default_mix() -> f32 {
1.0
}

impl Default for AlienConfig {
fn default() -> Self {
Self {
enabled: false,
loop_frames: 95_999,
mix: 1.0,
}
}
}
impl AlienConfig {
/// Validates all fields, also when Alien is disabled.
///
/// `loop_frames` must be in its documented inclusive range. Validation
/// does not clamp values. It does not change the processor state.
/// `loop_frames` must be in its documented inclusive range. `mix` must be
/// finite and in 0..=1. Validation does not clamp values. It does not
/// change the processor state.
///
/// # Errors
///
/// 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, 96_000)?;
check_range("alien.mix", self.mix, 0.0, 1.0)
}
}

Expand All @@ -76,6 +99,8 @@ pub(crate) struct Alien {
loop_len: usize,
/// The number of frames in `buffer` since construction or the last reset.
written: usize,
/// The Q14 wet weight of the reversed loop.
mix: Q14,
}
impl Alien {
/// Allocates a silent stereo ring from validated loop settings.
Expand All @@ -87,6 +112,7 @@ impl Alien {
phase: 0,
loop_len: config.loop_frames as usize,
written: 0,
mix: Q14::from_f64(f64::from(config.mix)),
}
}
/// Applies a validated configuration, keeps the recorded audio and clamps
Expand All @@ -95,6 +121,7 @@ impl Alien {
self.config = config;
self.loop_len = config.loop_frames as usize;
self.phase = self.phase.min(self.loop_len - 1);
self.mix = Q14::from_f64(f64::from(config.mix));
}
/// Returns the loop length and the current frame in the loop.
///
Expand All @@ -111,11 +138,11 @@ impl Alien {
self.read = 0;
self.phase = 0;
}
/// Records a frame, selects the direct or reverse output, then advances
/// Records a frame, blends the direct and reverse output, then advances
/// 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.
/// The 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.
pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] {
self.buffer[self.read] = input;
if self.written < HISTORY_FRAMES {
Expand All @@ -129,13 +156,20 @@ impl Alien {
read
};
let distance = self.phase.min(self.loop_len - self.phase);
let mut result = self.buffer[read];
let mut reverse = self.buffer[read];
if distance < FADE_FRAMES {
let gain: Q14 = Fixed::<0>::from_bits(distance as i32)
.div(Fixed::<0>::from_bits(FADE_FRAMES as i32));
result = result.map(|sample| sample.mul::<14, 14>(gain));
reverse = reverse.map(|sample| sample.mul::<14, 14>(gain));
}
result
let wet = i64::from(self.mix.to_bits());
let dry = i64::from((Q14::ONE - self.mix).to_bits());
[0, 1].map(|channel| {
let blended = (i64::from(input[channel].to_bits()) * dry
+ i64::from(reverse[channel].to_bits()) * wet)
>> 14;
Q14::from_bits(clamp_i32(blended))
})
} else {
input
};
Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
//! [`Processor`] changes mono signed 16-bit PCM into the same number of stereo
//! or mono frames. The sample rate is 44.1 kHz or 48 kHz. The signal chain is
//! Punch → Warm → pitch tracking and resynthesis → Alien → reverb → output
//! gain. The default configuration enables chromatic pitch correction and one
//! choir voice. The optional effects and the formant stage are disabled.
//! gain → mix, with a latency-aligned bypass. The default configuration
//! enables chromatic pitch correction and one choir voice. The optional
//! effects, the formant stage and bypass are disabled.
//!
//! # Preparing and configuring
//!
Expand Down
Loading