Skip to content
Open
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
22 changes: 14 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ browsers and Node.js.
only safe Rust.

The input is mono signed 16-bit PCM or normalized 32-bit floating-point audio
at 44.1 kHz or 48 kHz. The output is stereo or mono in 16-bit PCM or 32-bit
floating-point form.
at an integer rate in 8000..=192000 Hz. The output is stereo or mono in 16-bit
PCM or 32-bit floating-point form.

## Installation

Expand Down Expand Up @@ -360,7 +360,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()` | The nominal delay in host frames (1,593 frames at 44.1 kHz and 48 kHz) |
| `formant_envelope()` | The LPC envelopes before and after the formant controls |

`Processor::control_activity()` and `ProcessorConfig::control_activity()`
Expand All @@ -380,8 +380,10 @@ The telemetry includes these items:
`active_voice_ratios()` and `active_voice_gains()` return slices for the active
voices. The peak windows of the telemetry are independent of the peak window of
the feedback. In mono calls, the output and reverb wet peaks measure the audio
after the downmix. The dry path has the 1,593-frame delay. Resampled voices,
choir delays and effects use different delays.
after the downmix. At 44.1 kHz and 48 kHz, the processor bypasses rate
conversion and the dry path has the 1,593-frame delay. Other rates scale the
core delay to host frames and add the polyphase filter delay. Resampled
voices, choir delays and effects use different delays.

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

Expand All @@ -390,7 +392,9 @@ choir delays and effects use different delays.

The values are linear and have no absolute level. The formant stage must be
enabled. The envelopes are those of the model that the audio used for the
last frame. The method returns `Result<bool, Error>`:
last frame. If the sample rate is above the internal core rate, the method
writes zero for frequencies above half of the core rate. The method returns
`Result<bool, Error>`:

| Result | Description |
| ----------- | ---------------------------------------------------------------- |
Expand Down Expand Up @@ -635,8 +639,10 @@ buffers of equal length and returns `false` if no envelope is available.
In that case, it fills both buffers with zeros. If the lengths are not equal
or the frequency is not valid, it throws and does not change the buffers. The
frequency must be finite, more than zero and not more than half of the sample
rate. The class keeps a buffer for the points, so only the first call and a
call with more points than before reserve memory.
rate. If the sample rate is above the internal core rate, the method writes
zero for frequencies above half of the core rate. The class keeps a buffer for
the points, so only the first call and a call with more points than before
reserve memory.

### Memory allocation

Expand Down
62 changes: 62 additions & 0 deletions scripts/verify-pack.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,68 @@ function verifyRuntimeImport(consumerDir, packageName) {
'assert.equal(typeof disposableProcessor[Symbol.dispose], "function");',
"disposableProcessor[Symbol.dispose]();",
"",
"assert.throws(() => new rootModule.Tunelet(7999, 128));",
"assert.throws(() => new rootModule.Tunelet(192001, 128));",
"assert.throws(() => new rootModule.Tunelet(44100.5, 128));",
"",
"const resampled8k = new rootModule.Tunelet(8000, 128, config);",
"try {",
" assert.equal(resampled8k.sampleRate, 8000);",
" assert.equal(resampled8k.latencyFrames, 289);",
" const in8k = new Int16Array(128);",
" const left8k = new Int16Array(128);",
" const right8k = new Int16Array(128);",
" for (let block = 0; block < 24; block++) {",
" for (let i = 0; i < 128; i++) {",
" in8k[i] = Math.round(0.6 * Math.sin(((block * 128 + i) * 2 * Math.PI * 220) / 8000) * 32767);",
" }",
" resampled8k.process(in8k, left8k, right8k);",
" }",
" const fb8k = resampled8k.feedback();",
" const tel8k = resampled8k.telemetry();",
" assert.equal(fb8k.processedFrames, 3072n);",
" assert.equal(fb8k.latencyFrames, 289);",
" assert.equal(fb8k.voiced, true);",
" assert.equal(fb8k.targetMidiNote, 57);",
" assert.ok(Math.abs(fb8k.periodSamples - 8000 / 220) < 0.5);",
" assert.equal(tel8k.periodSamples, fb8k.periodSamples);",
" assert.ok(resampled8k.beginDrain() > 0);",
" assert.equal(resampled8k.drain(left8k, right8k), 128);",
"} finally {",
" resampled8k.free();",
"}",
"",
"const resampled96k = new rootModule.Tunelet(96000, 256, config);",
"try {",
" assert.equal(resampled96k.sampleRate, 96000);",
" assert.equal(resampled96k.latencyFrames, 3233);",
" const in96k = new Float32Array(256);",
" const left96k = new Float32Array(256);",
" const right96k = new Float32Array(256);",
" for (let block = 0; block < 40; block++) {",
" for (let i = 0; i < 256; i++) {",
" in96k[i] = Math.fround(0.6 * Math.sin(((block * 256 + i) * 2 * Math.PI * 440) / 96000));",
" }",
" resampled96k.processF32(in96k, left96k, right96k);",
" }",
" const fb96k = resampled96k.feedback();",
" const tel96k = resampled96k.telemetry();",
" assert.equal(fb96k.processedFrames, 10240n);",
" assert.equal(fb96k.latencyFrames, 3233);",
" assert.equal(fb96k.voiced, true);",
" assert.equal(fb96k.targetMidiNote, 69);",
" assert.ok(Math.abs(fb96k.periodSamples - 96000 / 440) < 1.0);",
" assert.equal(tel96k.periodSamples, fb96k.periodSamples);",
" const envIn96k = new Float32Array(65);",
" const envOut96k = new Float32Array(65);",
" assert.equal(resampled96k.formantEnvelope(48000, envIn96k, envOut96k), true);",
" assert.ok(envIn96k[8] > 0);",
" assert.equal(envIn96k[64], 0);",
" assert.equal(envOut96k[64], 0);",
"} finally {",
" resampled96k.free();",
"}",
"",
].join("\n"),
);

Expand Down
53 changes: 43 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,21 @@ use crate::Error;
use crate::ResynthesisConfig;
use std::num::NonZeroUsize;

/// The sample rate of the input and the output.
/// The lowest supported sample rate in hertz.
pub(crate) const MIN_SAMPLE_RATE_HZ: u32 = 8_000;
/// The highest supported sample rate in hertz.
pub(crate) const MAX_SAMPLE_RATE_HZ: u32 = 192_000;

/// The sample rate of the input and the output, 8000..=192000 Hz.
///
/// The default is 44.1 kHz. To convert an integer device rate in
/// 8000..=192000 Hz, 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 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.
/// At 44.1 kHz and 48 kHz, the processor runs directly at that rate. At other
/// rates, a fixed-point polyphase resampler converts to and from an internal
/// core rate. Multiples and divisors of 44,100 Hz use the 44.1 kHz core. All
/// other rates use the 48 kHz core.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum SampleRate {
Expand All @@ -25,37 +34,61 @@ pub enum SampleRate {
Hz44100,
/// 48 kHz.
Hz48000,
/// Another integer rate in 8000..=192000 Hz, from [`Self::try_from`].
#[non_exhaustive]
Custom {
/// The rate in hertz, 8000..=192000, except 44,100 and 48,000.
hz: u32,
},
}

impl SampleRate {
/// Returns the rate in hertz.
/// Returns the rate in hertz, 8000..=192000.
pub const fn as_u32(self) -> u32 {
match self {
Self::Hz44100 => 44_100,
Self::Hz48000 => 48_000,
Self::Custom { hz } => hz,
}
}

/// Returns the rate in hertz, as `f32`.
pub fn hz(self) -> f32 {
self.as_u32() as f32
}

/// Selects the 44.1 kHz or 48 kHz internal core rate for this host rate.
///
/// Multiples and divisors of 44,100 Hz use the 44.1 kHz core. All other
/// rates use the 48 kHz core.
pub(crate) const fn core_rate(self) -> Self {
let hz = self.as_u32();
if hz == 44_100 || hz == 48_000 {
self
} else if hz.is_multiple_of(44_100) || 44_100_u32.is_multiple_of(hz) {
Self::Hz44100
} else {
Self::Hz48000
}
}
}

impl TryFrom<u32> for SampleRate {
type Error = Error;

/// Converts a device sample rate in hertz.
/// Converts a device sample rate in hertz, 8000..=192000.
///
/// Returns [`Self::Hz44100`] for 44,100 and [`Self::Hz48000`] for 48,000.
///
/// # 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.
/// Returns [`Error::UnsupportedSampleRate`] with `hz` if `hz` is outside
/// 8000..=192000.
fn try_from(hz: u32) -> Result<Self, Self::Error> {
match hz {
44_100 => Ok(Self::Hz44100),
48_000 => Ok(Self::Hz48000),
MIN_SAMPLE_RATE_HZ..=MAX_SAMPLE_RATE_HZ => Ok(Self::Custom { hz }),
_ => Err(Error::UnsupportedSampleRate { hz }),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Error {
/// The numeric rate has no [`crate::SampleRate`] variant that matches it.
/// The sample rate is outside 8000..=192000 Hz.
UnsupportedSampleRate {
/// The unsupported rate, in hertz.
hz: u32,
Expand Down
6 changes: 6 additions & 0 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,12 @@ impl<'a> ValidatedEvents<'a> {
self.remaining = remaining;
Some(ValidatedEvent(event.event))
}

/// Returns the offset of the next event without consumption, or `None` if
/// no events remain.
pub(crate) fn peek_offset(&self) -> Option<usize> {
self.remaining.first().map(|event| event.offset)
}
}

/// Validates one event and advances the stack configuration copy.
Expand Down
24 changes: 23 additions & 1 deletion src/formant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,8 @@ impl Formant {
/// `input` gets the vocal-tract envelope from the analysis. `output` gets
/// the envelope of the synthesis model, which includes the width gain.
/// The two responses include the glottal de-emphasis. Point `k` of `n` is
/// at the frequency `max_frequency_hz * k / (n - 1)`. The values are
/// at the frequency `max_frequency_hz * k / (n - 1)`. Points at
/// frequencies above half of the stage rate are zero. The values are
/// linear and have no absolute level, because the analysis normalizes the
/// signal energy.
///
Expand Down Expand Up @@ -946,6 +947,27 @@ impl Formant {
} else {
0.0
};
let core_nyquist = f64::from(self.rate.as_u32()) * 0.5;
let max_hz = f64::from(max_frequency_hz);
let active = if points > 1 && max_hz > core_nyquist {
let nyquist_scaled = core_nyquist * (points - 1) as f64;
let mut count = ((nyquist_scaled / max_hz) as usize)
.saturating_add(1)
.min(points);
while count > 1 && max_hz * (count - 1) as f64 > nyquist_scaled {
count -= 1;
}
while count < points && max_hz * count as f64 <= nyquist_scaled {
count += 1;
}
count
} else {
points
};
input[active..].fill(0.0);
output[active..].fill(0.0);
let input = &mut input[..active];
let output = &mut output[..active];
const SCALE: f64 = 1.0 / 16384.0;
let glottal = self.glottal as f64 * SCALE;
let width = self.width as f64 * SCALE;
Expand Down
9 changes: 6 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! A crate for vocal pitch correction, choir, harmony, formant control and effects.
//!
//! [`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
//! or mono frames. The sample rate is an integer in 8000..=192000 Hz. At rates
//! other than 44.1 kHz and 48 kHz, a fixed-point polyphase resampler converts
//! to and from the 44.1 kHz or 48 kHz core. 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.
Expand Down Expand Up @@ -62,8 +64,8 @@
//! accumulated output peak and the frame count.
//! [`Processor::take_feedback`] also clears the peak window. The pitch
//! reporting bounds change only the reports. They do not change the detection
//! or the audio signal. [`Processor::latency_frames`] gives a nominal
//! resynthesis delay, which the dry path also uses. Voice delays, pitch
//! or the audio signal. [`Processor::latency_frames`] gives the nominal
//! delay in host frames, which the dry path also uses. Voice delays, pitch
//! changes and effects have their own timing.
//!
//! [`Processor::control_activity`] and [`ProcessorConfig::control_activity`]
Expand Down Expand Up @@ -128,6 +130,7 @@ mod midi;
mod numeric;
mod pitch;
mod processor;
mod resample;
mod resynthesis;
mod scale;

Expand Down
Loading
Loading