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: 12 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,11 @@ multi-voice mixes.
fraction of each half-bin where pull toward the target decreases, in `0..=1`.
The default is 0, which applies full pull across the whole bin.

`resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The
dry path starts after Warm and has a delay of 1,593 frames. All six reverb
modes keep the stereo dry signal.
`resynthesis.latency_mode` selects `Standard` (1,593 nominal frames, default)
or `LowLatency` (50 nominal frames, causal formant analysis).
`resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The dry
path starts after Warm and uses the same 1,593-frame or 50-frame delay. All
six reverb modes keep the stereo dry signal.

### Harmony sources

Expand Down Expand Up @@ -360,7 +362,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()` | 1,593 (`Standard`) or 50 (`LowLatency`) frames of nominal latency |
| `formant_envelope()` | The LPC envelopes before and after the formant controls |

`Processor::control_activity()` and `ProcessorConfig::control_activity()`
Expand All @@ -380,7 +382,7 @@ 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,
after the downmix. The dry path uses the nominal latency. Resampled voices,
choir delays and effects use different delays.

`formant_envelope()` writes two LPC envelopes into slices of equal length:
Expand Down Expand Up @@ -579,11 +581,11 @@ and show enums as string literals. To change the configuration, do these steps:

If a required field is absent or a value is not valid, the call throws a
JavaScript `Error`. If an optional field is absent or `undefined`, it gets its
default. `resynthesis.correction.humanize` and
`resynthesis.correction.flexTune` default to 0, and
`resynthesis.harmony.voices` defaults to 4. The conversion ignores extra object
properties. The generated declarations contain the parameter documentation from
the Rust types.
default. `resynthesis.latencyMode` defaults to `"standard"`,
`resynthesis.correction.humanize` and `resynthesis.correction.flexTune`
default to 0, and `resynthesis.harmony.voices` defaults to 4. 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
10 changes: 10 additions & 0 deletions scripts/normalize-jsdoc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ const EXACT_REPLACEMENTS = [
"`ResynthesisConfig.choirSpreadPercent`",
],
["[`ResynthesisConfig::harmony_gain`]", "`ResynthesisConfig.harmonyGain`"],
[
"[`crate::ResynthesisConfig::stereo_output`]",
"`ResynthesisConfig.stereoOutput`",
],
["[`ResynthesisConfig::stereo_output`]", "`ResynthesisConfig.stereoOutput`"],
["[`crate::HarmonyConfig::source`]", "`HarmonyConfig.source`"],
["[`crate::HarmonyConfig::key`]", "`HarmonyConfig.key`"],
["[`crate::HarmonyConfig::scale`]", "`HarmonyConfig.scale`"],
Expand Down Expand Up @@ -101,12 +106,17 @@ const EXACT_REPLACEMENTS = [
["[`HarmonySource::ChordByName`]", '`"chordByName"`'],
["[`HarmonySource::ChordByDegree`]", '`"chordByDegree"`'],
["[`MultiVoiceMode::Choir`]", '`"choir"`'],
["[`crate::LatencyMode::Standard`]", '`"standard"`'],
["[`LatencyMode::Standard`]", '`"standard"`'],
["[`crate::LatencyMode::LowLatency`]", '`"lowLatency"`'],
["[`LatencyMode::LowLatency`]", '`"lowLatency"`'],
["`None`", "`undefined`"],
["`u64::MAX`", "`2n ** 64n - 1n`"],
["`0x1234_abcd`", "`0x1234abcdn`"],
["`max_frequency_hz`", "`maxFrequencyHz`"],
["`min_frequency_hz`", "`minFrequencyHz`"],
["`stereo_output`", "`stereoOutput`"],
["`latency_mode`", "`latencyMode`"],
["`retune_ms`", "`retuneMs`"],
["`attack_ms`", "`attackMs`"],
["`gain_db`", "`gainDb`"],
Expand Down
17 changes: 16 additions & 1 deletion scripts/verify-pack.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -313,11 +313,14 @@ function verifyRuntimeImport(consumerDir, packageName) {
"assert.ok(wasmExports.memory instanceof WebAssembly.Memory);",
"",
"const initialConfig = rootModule.defaultConfig();",
"initialConfig.resynthesis.latencyMode = undefined;",
"initialConfig.resynthesis.correction.humanize = undefined;",
"initialConfig.resynthesis.correction.flexTune = undefined;",
"initialConfig.resynthesis.harmony.voices = undefined;",
"const processor = new rootModule.Tunelet(48000, 128, initialConfig);",
"try {",
' assert.equal(processor.config().resynthesis.latencyMode, "standard");',
" assert.equal(processor.latencyFrames, 1593);",
" assert.equal(processor.config().resynthesis.correction.humanize, 0);",
" assert.equal(processor.config().resynthesis.correction.flexTune, 0);",
" assert.equal(processor.config().resynthesis.harmony.voices, 4);",
Expand Down Expand Up @@ -345,27 +348,35 @@ function verifyRuntimeImport(consumerDir, packageName) {
" assert.equal(processor.config().resynthesis.harmony.voices, 1);",
"",
" const tunedCorrectionConfig = processor.config();",
' tunedCorrectionConfig.resynthesis.latencyMode = "lowLatency";',
" tunedCorrectionConfig.resynthesis.correction.humanize = 0.5;",
" tunedCorrectionConfig.resynthesis.correction.flexTune = 0.25;",
" processor.setConfig(tunedCorrectionConfig);",
' assert.equal(processor.config().resynthesis.latencyMode, "lowLatency");',
" assert.equal(processor.latencyFrames, 50);",
" assert.equal(processor.config().resynthesis.correction.humanize, 0.5);",
" assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);",
"",
" const omittedCorrectionConfig = processor.config();",
" delete omittedCorrectionConfig.resynthesis.latencyMode;",
" delete omittedCorrectionConfig.resynthesis.correction.humanize;",
" delete omittedCorrectionConfig.resynthesis.correction.flexTune;",
" processor.setConfig(omittedCorrectionConfig);",
' assert.equal(processor.config().resynthesis.latencyMode, "standard");',
" assert.equal(processor.latencyFrames, 1593);",
" assert.equal(processor.config().resynthesis.correction.humanize, 0);",
" assert.equal(processor.config().resynthesis.correction.flexTune, 0);",
"",
" const mono = new Int16Array(128);",
" const eventResynthesis = processor.config().resynthesis;",
" eventResynthesis.latencyMode = undefined;",
" eventResynthesis.correction.humanize = undefined;",
" eventResynthesis.correction.flexTune = undefined;",
" eventResynthesis.harmony.voices = undefined;",
" processor.processMono(mono, [",
' { offset: 0, event: { type: "resynthesis", value: eventResynthesis } },',
" ]);",
' assert.equal(processor.config().resynthesis.latencyMode, "standard");',
" assert.equal(processor.config().resynthesis.correction.humanize, 0);",
" assert.equal(processor.config().resynthesis.correction.flexTune, 0);",
" assert.equal(processor.config().resynthesis.harmony.voices, 4);",
Expand Down Expand Up @@ -738,6 +749,7 @@ function verifyTypeDeclarations(consumerDir, packageName) {
" TuneletAudioViews,",
" type ControlActivity,",
" type ControlEvent,",
" type LatencyMode,",
" type ParameterControl,",
" type ProcessorConfig,",
" type ResynthesisConfig,",
Expand Down Expand Up @@ -770,10 +782,12 @@ function verifyTypeDeclarations(consumerDir, packageName) {
" module: syncSource,",
" });",
" const baseConfig: ProcessorConfig = defaultConfig();",
' const lowLatencyMode: LatencyMode = "lowLatency";',
" const configWithUndefined: ProcessorConfig = {",
" ...baseConfig,",
" resynthesis: {",
" ...baseConfig.resynthesis,",
" latencyMode: undefined,",
" correction: {",
" ...baseConfig.resynthesis.correction,",
" humanize: optionalVoices,",
Expand Down Expand Up @@ -822,6 +836,7 @@ function verifyTypeDeclarations(consumerDir, packageName) {
" views.refresh();",
" const resynthesisUpdate: ResynthesisConfig = {",
" ...configWithUndefined.resynthesis,",
" latencyMode: lowLatencyMode,",
" correction: {",
" enabled: configWithUndefined.resynthesis.correction.enabled,",
" notes: configWithUndefined.resynthesis.correction.notes,",
Expand Down Expand Up @@ -1156,7 +1171,7 @@ function verifyNormalizedJsDoc(consumerDir, packageName) {
);
assert.doesNotMatch(
text,
/`(?:max_frequency_hz|min_frequency_hz|stereo_output|retune_ms|attack_ms|gain_db|ceiling_db)`/,
/`(?:max_frequency_hz|min_frequency_hz|stereo_output|latency_mode|retune_ms|attack_ms|gain_db|ceiling_db)`/,
`Unexpected snake_case config field in ${filePath}`,
);
}
Expand Down
72 changes: 56 additions & 16 deletions src/formant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
//!
//! Thirty model banks keep the history of the coefficients. Each audio frame
//! stores a pair of banks and a blend. Thus, a fractional voice reader can
//! find the model that applies to the audio that it reads again. The inverse
//! filter has a delay of 441 frames. Resynthesis uses this delay to align
//! each source sample with the stamp of the frame that filtered it. Audio
//! and coefficients use Q14 words. All areas use one common scale that the
//! code sets at runtime. The order of the arithmetic and of the rescale
//! find the model that applies to the audio that it reads again. In standard
//! latency mode, the inverse filter has a delay of 441 frames. In low-latency
//! mode, the stage updates the model every 128 frames and filters the current
//! frame without delay.
//!
//! Audio and coefficients use Q14 words. All areas use one common scale that
//! the code sets at runtime. The order of the arithmetic and of the rescale
//! operations changes the output samples.

use crate::error::check_range;
Expand Down Expand Up @@ -134,9 +136,11 @@ pub(crate) fn validate_aspiration_cutoff_hz(aspiration_cutoff_hz: f32) -> Result
)
}

/// The number of frames in each analysis step. The analysis output has a
/// delay of this number of frames.
/// The number of frames in each standard analysis step. The standard analysis
/// output has a delay of this number of frames.
pub(crate) const ANALYSIS_FRAMES: usize = 441;
/// The number of frames in each causal low-latency analysis step.
const CAUSAL_ANALYSIS_FRAMES: usize = 128;
/// The order of the input LPC predictor and of the synthesis model without
/// changes.
const ORDER: usize = 50;
Expand Down Expand Up @@ -567,9 +571,34 @@ impl Formant {
self.input[reverse_write + HISTORY] = filtered;
}

self.design(periods, write, output_period_q6);
self.design(periods, write, output_period_q6, ANALYSIS_FRAMES);
self.inverse(write)
}
/// Stores the pre-emphasized input, tries a model design each 128 frames,
/// and filters the current frame without delay.
///
/// `write` and the period history must refer to the same full-size ring of
/// audio frames. `output_period_q6` is the kept period that sets the
/// analysis segments.
pub(crate) fn process_causal_analysis(
&mut self,
sample: i32,
previous: i32,
periods: &[Q6],
write: usize,
output_period_q6: i32,
) -> i32 {
self.dirty = true;
let filtered = self.remove_glottal(sample, previous);
let reverse_write = HISTORY - 1 - write;
self.input[reverse_write] = filtered;
if reverse_write < ORDER {
self.input[reverse_write + HISTORY] = filtered;
}

self.design(periods, write, output_period_q6, CAUSAL_ANALYSIS_FRAMES);
self.inverse_at(write)
}
/// Moves to the next bank and keeps the old bank for the blend.
///
/// The function clears the inverse coefficients, the forward coefficients
Expand Down Expand Up @@ -622,8 +651,8 @@ impl Formant {
}
self.smooth_index = (self.smooth_index + 1) % 2;
}
/// Tries a model that uses the pitch each ANALYSIS_FRAMES, and stamps
/// each frame.
/// Tries a model that uses the pitch each `step_frames`, and stamps each
/// frame.
///
/// If a pitch is available, the segment folds adjacent cycles and clamps
/// the period to `rate / 40`. If not, the segment is a window of
Expand All @@ -641,14 +670,20 @@ impl Formant {
///
/// If the Durbin analysis fails, smoothing starts again. The selected
/// bank keeps the inverse coefficients that the analysis wrote.
fn design(&mut self, periods: &[Q6], position: usize, output_period_q6: i32) {
fn design(
&mut self,
periods: &[Q6],
position: usize,
output_period_q6: i32,
step_frames: usize,
) {
let max_period = (self.rate.as_u32() as usize / 40).max(1);
let period = (output_period_q6.wrapping_shr(6).max(0) as usize).min(max_period);
let design_now = self.design_counter == 0;
self.design_counter += 1;
let one = 16384;
if design_now {
self.design_counter -= ANALYSIS_FRAMES as i32;
self.design_counter -= step_frames as i32;
let count;
if period == 0 {
count = (self.rate.as_u32() as usize + 50) / 100;
Expand Down Expand Up @@ -821,16 +856,21 @@ impl Formant {

/// Applies the blended 50th-order prediction-error filter to the delayed
/// input.
///
/// The full sum of Q28 products accumulates in `i64` before one signed
/// shift and an `i32` clamp. The function blends the coefficients for the
/// current transition. Then it multiplies them with the previous samples.
fn inverse(&self, position: usize) -> i32 {
let read = if position < ANALYSIS_FRAMES {
position + HISTORY - ANALYSIS_FRAMES
} else {
position - ANALYSIS_FRAMES
};
self.inverse_at(read)
}

/// Applies the blended 50th-order prediction-error filter to `input[read]`.
///
/// The full sum of Q28 products accumulates in `i64` before one signed
/// shift and an `i32` clamp. The function blends the coefficients for the
/// current transition. Then it multiplies them with the previous samples.
fn inverse_at(&self, read: usize) -> i32 {
let mut blended;
let coefficients = if let Some(slice) = self.stamp.steady_bank(&self.inverse, true, ORDER) {
slice
Expand Down
9 changes: 5 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@
//! 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
//! changes and effects have their own timing.
//! or the audio signal. [`Processor::latency_frames`] gives the nominal
//! resynthesis and dry delay: 1,593 frames in [`LatencyMode::Standard`] or 50
//! frames in [`LatencyMode::LowLatency`]. Voice delays, pitch changes and
//! effects have their own timing.
//!
//! [`Processor::control_activity`] and [`ProcessorConfig::control_activity`]
//! give [`ControlActivity`], which shows the active choir, harmony and reverb
Expand Down Expand Up @@ -148,5 +149,5 @@ pub use harmony::{
pub use midi::MidiEvent;
pub use pitch::PitchConfig;
pub use processor::{Feedback, Processor, Telemetry};
pub use resynthesis::{CorrectionConfig, MultiVoiceMode, ResynthesisConfig};
pub use resynthesis::{CorrectionConfig, LatencyMode, MultiVoiceMode, ResynthesisConfig};
pub use scale::{CorrectionScale, NoteMask, PitchClass};
Loading
Loading