diff --git a/README.md b/README.md index a06715f..501b6de 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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()` @@ -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: @@ -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 diff --git a/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index 0f6a77f..df86dcc 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -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`"], @@ -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`"], diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..9262769 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -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);", @@ -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);", @@ -738,6 +749,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " TuneletAudioViews,", " type ControlActivity,", " type ControlEvent,", + " type LatencyMode,", " type ParameterControl,", " type ProcessorConfig,", " type ResynthesisConfig,", @@ -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,", @@ -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,", @@ -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}`, ); } diff --git a/src/formant.rs b/src/formant.rs index b4ea383..945d4b4 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -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; @@ -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; @@ -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 @@ -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 @@ -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; @@ -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 diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..7ac0044 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 @@ -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}; diff --git a/src/processor.rs b/src/processor.rs index 9f8ae9b..525dff2 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -510,13 +510,15 @@ impl Processor { self.config.control_activity() } - /// Returns the nominal resynthesis latency: 1,593 frames at both rates. + /// Returns the nominal resynthesis latency: 1,593 frames in + /// [`crate::LatencyMode::Standard`] or 50 frames in + /// [`crate::LatencyMode::LowLatency`] at both rates. /// - /// The dry path also has a delay of 1,593 frames. Resampled voices, choir - /// delays and effects have their own timing. Thus, this value does not - /// align all paths. + /// The dry path also uses this delay. Resampled voices, choir delays and + /// effects have their own timing. Thus, this value does not align all + /// paths. pub fn latency_frames(&self) -> usize { - resynthesis::LATENCY_FRAMES + resynthesis::latency_frames(self.config.resynthesis.latency_mode) } /// Returns the pitch, output peak and frame count, and does not clear them. @@ -683,12 +685,12 @@ impl Processor { /// Validates all configuration fields and applies them. /// /// The validation also examines the fields of disabled stages. A stage - /// that does not change keeps its state. A change of `stereo_output` - /// resets the resynthesis audio state, Alien, the reverb delays, the peak - /// and the reported ratio. It also releases the harmony MIDI notes. It - /// keeps Punch, Warm, the correction keys, the random stream, the reverb - /// low-pass memories and the frame count. A change of `random_seed` starts - /// the random stream again. + /// that does not change keeps its state. A change of `stereo_output` or + /// `latency_mode` resets the resynthesis audio state, Alien, the reverb + /// delays, the peak and the reported ratio. It also releases the harmony + /// MIDI notes. It keeps Punch, Warm, the correction keys, the random + /// stream, the reverb low-pass memories and the frame count. A change of + /// `random_seed` starts the random stream again. /// /// Each successful call cancels a drain, also for an identical /// configuration. A change of reverb mode keeps the delay contents. If you @@ -717,8 +719,11 @@ impl Processor { if self.config.resynthesis != config.resynthesis { self.resynthesis.apply_config(config.resynthesis); } - if self.config.resynthesis.stereo_output != config.resynthesis.stereo_output { - // Resynthesis resets its histories if its stereo setting changes. + if self.config.resynthesis.stereo_output != config.resynthesis.stereo_output + || self.config.resynthesis.latency_mode != config.resynthesis.latency_mode + { + // Resynthesis resets its histories if its stereo or latency mode + // changes. self.reset_post_resynthesis(); } if self.config.resynthesis.random_seed != config.resynthesis.random_seed { @@ -767,8 +772,8 @@ impl Processor { /// Clears the stages, the peak windows and the ratio after resynthesis. /// - /// Both a full reset and a change of stereo output clear this state. The - /// frame count does not change here. + /// A full reset, a stereo change or a latency-mode change clears this + /// state. The frame count does not change here. fn reset_post_resynthesis(&mut self) { self.alien.reset(); self.reverb.reset(); @@ -1096,7 +1101,7 @@ pub struct Feedback { /// /// It does not include the configured pitch shift or the ratios of /// individual voices. It is zero before processing, after a reset or after - /// a change of stereo output. + /// a change of stereo output or latency mode. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// @@ -1136,9 +1141,10 @@ pub struct Feedback { /// The largest absolute clipped output sample, divided by 32768. /// /// The peak window starts at construction, at a reset, at a change of - /// stereo output or at a call to [`Processor::take_feedback`]. The value - /// is in 0..=32767/32768. Mono calls measure the sample after the downmix. - /// [`Processor::feedback`] does not clear the value. + /// stereo output or latency mode, or at a call to + /// [`Processor::take_feedback`]. The value is in 0..=32767/32768. Mono + /// calls measure the sample after the downmix. [`Processor::feedback`] does + /// not clear the value. pub peak_level: f32, /// The number of frames processed since construction or the last reset, /// with drain frames included. @@ -1163,9 +1169,9 @@ pub struct Feedback { /// `Default` gives a snapshot with all zeros and no target. /// /// The three peak fields measure a window. The window starts at -/// construction, at a reset, at a change of stereo output or at a call to -/// [`Processor::take_telemetry`]. This window is independent of the peak -/// window of [`Feedback`]. +/// construction, at a reset, at a change of stereo output or latency mode, or +/// at a call to [`Processor::take_telemetry`]. This window is independent of +/// the peak window of [`Feedback`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -1202,7 +1208,7 @@ pub struct Telemetry { /// /// It does not include the configured pitch shift or the ratios of /// individual voices. It is zero before the first frame, after a reset or - /// after a change of stereo output. + /// after a change of stereo output or latency mode. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples, as /// [`Feedback::period_samples`] gives. @@ -1305,9 +1311,10 @@ pub struct Telemetry { pub alien_phase_frames: u32, /// The wrapping count of formant analyses since construction. /// - /// The count increases every 441 frames while the formant stage is - /// enabled. Compare two values to find if - /// [`Processor::formant_envelope`] can give a new result. + /// While the formant stage is enabled, the count increases every 441 + /// frames in standard mode and every 128 frames in low-latency mode. + /// Compare two values to find if [`Processor::formant_envelope`] can give + /// a new result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..7f684cd 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -4,11 +4,11 @@ //! the correction and control steps that are due. The raw input, the tracked //! periods and the correction ratios use the same history cursor. //! -//! The source comes from a fixed overlap buffer. If formants are enabled, -//! this buffer holds the output of the formant inverse analysis. If not, -//! it holds the raw input. Voice readers read this source at fractional -//! positions. If the shift is upward, prepared low-pass filters also -//! change the source. +//! In standard latency mode, the source comes from a fixed overlap buffer. In +//! low-latency mode, the source uses the current frame directly. If formants +//! are enabled, the source holds the output of the formant inverse analysis. +//! If not, it holds the raw input. Voice readers read this source at +//! fractional positions, after the prepared upward-shift filters. //! //! Choir renders the lead voice first. Then it makes delayed secondary voices //! with drift from the lead history. Harmony renders the lead voice and four @@ -58,6 +58,27 @@ pub enum MultiVoiceMode { Harmony, } +/// The latency and lookahead mode of resynthesis and formant analysis. +/// +/// A change to this mode resets the resynthesis audio histories and the stages +/// after resynthesis, in the same way as [`ResynthesisConfig::stereo_output`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum LatencyMode { + /// A nominal resynthesis and dry delay of 1,593 frames, with a + /// 1,543-frame source buffer. This is the default. + #[default] + Standard, + /// A causal nominal resynthesis and dry delay of 50 frames, with zero + /// source delay. + LowLatency, +} + /// The controls for pitch-class correction, with target selection in the /// period domain. /// @@ -202,15 +223,17 @@ pub(crate) fn validate_flex_tune(flex_tune: f32) -> Result<(), Error> { /// - No harmonic modulation. /// - No dry mix. /// - No stereo pan. +/// - Standard latency mode. /// /// Validation applies to all controls, also when their stage or voice mode /// is not active. /// /// The dry path takes the audio after Punch and Warm and delays it by 1,593 -/// frames. At unity pitch and zero choir delay, the wet voices have the same -/// nominal delay. Resampled voices and choir delays use different delays. -/// After this stage, the two paths go through Alien, reverb and the final -/// output gain. +/// frames in [`LatencyMode::Standard`] or 50 frames in +/// [`LatencyMode::LowLatency`]. At unity pitch and zero choir delay, the wet +/// voices have the same nominal delay. Resampled voices and choir delays use +/// different delays. After this stage, the two paths go through Alien, +/// reverb and the final output gain. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -292,9 +315,10 @@ pub struct ResynthesisConfig { /// The dry fraction at the resynthesis stage, 0..=1. The default is 0. /// /// The code truncates this value to Q8. The wet weight is 1.0 minus the - /// Q8 dry weight. The dry path starts after Punch and Warm and has a - /// delay of 1,593 frames. Alien, reverb and the output gain still occur - /// after this stage. + /// Q8 dry weight. The dry path starts after Punch and Warm. Its delay is + /// 1,593 frames in [`LatencyMode::Standard`] and 50 frames in + /// [`LatencyMode::LowLatency`]. Alien, reverb and the output gain still + /// occur after this stage. pub dry_mix: f32, /// The seed for choir drift and aspiration, which use the same stream. /// The default is `0x1234_abcd`. @@ -305,6 +329,30 @@ pub struct ResynthesisConfig { /// bits. Reset keeps the current position in the stream. The enabled /// stages set the number of random values that the code reads. pub random_seed: u64, + /// The latency and formant analysis mode. The default is + /// [`LatencyMode::Standard`]. + /// + /// [`LatencyMode::LowLatency`] bypasses the 1,543-frame overlap buffer and + /// uses causal formant analysis. A change to this field resets the same + /// audio histories and feedback state as `stereo_output`. In JavaScript, + /// the field is optional and an absent or `undefined` value gives the + /// default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default, deserialize_with = "deserialize_latency_mode"), + tsify(optional, type = "LatencyMode | undefined") + )] + pub latency_mode: LatencyMode, +} + +/// Decodes an optional latency mode and maps an absent value to +/// [`LatencyMode::Standard`]. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_latency_mode<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or_default()) } impl Default for ResynthesisConfig { @@ -325,6 +373,7 @@ impl Default for ResynthesisConfig { harmonic_modulation: 0.0, dry_mix: 0.0, random_seed: 0x1234_abcd, + latency_mode: LatencyMode::Standard, } } } @@ -425,11 +474,22 @@ const OVERLAP_FRAMES: usize = 1543; const FORMANT_OFFSET_FRAMES: i32 = (OVERLAP_FRAMES - ANALYSIS_FRAMES) as i32; /// The number of frames that a new reader stays behind the write position. const READER_LAG_FRAMES: i32 = 50; -/// The nominal latency of resynthesis. Each reader moves with the pitch and -/// the delay. +/// The nominal latency of resynthesis in [`LatencyMode::Standard`]. /// /// The dry path also uses `LATENCY_FRAMES`. pub(crate) const LATENCY_FRAMES: usize = OVERLAP_FRAMES + READER_LAG_FRAMES as usize; +/// The nominal latency of resynthesis in [`LatencyMode::LowLatency`]. +/// +/// The dry path also uses `LOW_LATENCY_FRAMES`. +pub(crate) const LOW_LATENCY_FRAMES: usize = READER_LAG_FRAMES as usize; + +/// Returns the nominal resynthesis latency in frames for `mode`. +pub(crate) const fn latency_frames(mode: LatencyMode) -> usize { + match mode { + LatencyMode::Standard => LATENCY_FRAMES, + LatencyMode::LowLatency => LOW_LATENCY_FRAMES, + } +} /// The counter value at which a control step runs. Usually, a step runs /// every 101 eligible frames. /// @@ -486,10 +546,12 @@ pub(crate) struct Resynthesis { /// The history of the rendered choir lead. All secondary choir voices /// read this history. lead: Box<[Q14; HISTORY]>, - /// The Q6 tracked periods, aligned to the audio. The lead voice can - /// replace a delayed entry with its resampled output period. This aligns - /// the secondary voices. + /// The Q6 tracked input periods, aligned to the audio. Formant analysis + /// and pitch feedback read these unmodified values. periods: Box<[Q6; HISTORY]>, + /// The Q6 periods of the rendered choir lead. The lead voice stores its + /// resampled output period here to align the secondary voices. + lead_periods: Box<[Q6; HISTORY]>, /// The last usable Q6 tracker periods. The code keeps them through /// unvoiced gaps. previous_periods: Box<[Q6; HISTORY]>, @@ -626,6 +688,7 @@ impl Resynthesis { filtered: prepare_history(Q14::ZERO), lead: prepare_history(Q14::ZERO), periods: prepare_history(Q6::ZERO), + lead_periods: prepare_history(Q6::ZERO), previous_periods: prepare_history(Q6::ZERO), ratios: prepare_history(Q14::ONE), overlap: [Q14::ZERO; OVERLAP_FRAMES], @@ -887,9 +950,9 @@ impl Resynthesis { if old.dry_mix != config.dry_mix { self.configure_dry_mix(); } - if old.stereo_output != config.stereo_output { - // A stereo change resets the audio state. The correction keyboard - // keeps its held keys. + if old.stereo_output != config.stereo_output || old.latency_mode != config.latency_mode { + // A stereo or latency-mode change resets the audio state. The + // correction keyboard keeps its held keys. self.reset_audio(); } } @@ -1108,16 +1171,17 @@ impl Resynthesis { clear_dirty_ring(self.raw.as_mut_slice(), written, Q14::ZERO); clear_dirty_ring(self.filtered.as_mut_slice(), written, Q14::ZERO); clear_dirty_ring(self.lead.as_mut_slice(), written, Q14::ZERO); + clear_dirty_ring(self.periods.as_mut_slice(), written, Q6::ZERO); if written > 0 { let lead_start = HISTORY - OVERLAP_FRAMES + 1; if written < OVERLAP_FRAMES { - self.periods[1..=written].fill(Q6::ZERO); - self.periods[lead_start..lead_start + written].fill(Q6::ZERO); + self.lead_periods[1..=written].fill(Q6::ZERO); + self.lead_periods[lead_start..lead_start + written].fill(Q6::ZERO); } else if written < HISTORY - OVERLAP_FRAMES { - self.periods[..=written].fill(Q6::ZERO); - self.periods[lead_start..].fill(Q6::ZERO); + self.lead_periods[..=written].fill(Q6::ZERO); + self.lead_periods[lead_start..].fill(Q6::ZERO); } else { - self.periods.fill(Q6::ZERO); + self.lead_periods.fill(Q6::ZERO); } } clear_dirty_ring(self.previous_periods.as_mut_slice(), written, Q6::ZERO); @@ -1460,6 +1524,30 @@ impl Resynthesis { } } + /// Selects the period for a secondary choir voice from the lead history. + /// + /// If the delayed lead frame is voiced, the function uses its resampled + /// period. If not, it uses the current lead period, or the last usable + /// delayed input period. The indices must be less than HISTORY. + fn lead_period_for(&self, delayed: usize, current: usize) -> Q6 { + if self.lead_periods[delayed] != Q6::ZERO { + self.lead_periods[delayed] + } else if self.lead_periods[current] != Q6::ZERO { + self.lead_periods[current] + } else { + self.previous_periods[delayed] + } + } + + /// Returns the frame offset from a reader position to its formant stamp. + #[inline] + fn formant_offset_frames(&self) -> i32 { + match self.config.latency_mode { + LatencyMode::Standard => FORMANT_OFFSET_FRAMES, + LatencyMode::LowLatency => 0, + } + } + /// Returns the upper limit, the lower limit and the Q14 period jump for a /// reader. /// @@ -1532,13 +1620,14 @@ impl Resynthesis { /// Advances one secondary choir reader and returns its position and ratio. /// - /// The function selects the delayed period, updates `current_output_period` - /// and moves the reader without a crossfade. `voice` must identify a - /// secondary choir slot, and `delayed` must be less than HISTORY. + /// The function selects the delayed lead period, updates + /// `current_output_period` and moves the reader without a crossfade. + /// `voice` must identify a secondary choir slot, and `delayed` must be + /// less than HISTORY. fn move_choir_reader(&mut self, voice: usize, delayed: usize) -> (Q14, Q14) { let offset = self.delays[voice]; let delay = ring(delayed as i32 - offset); - let (period, _) = self.period_for(delay, self.write); + let period = self.lead_period_for(delay, self.write); self.current_output_period = period; let ratio = self.drift_ratio[voice]; let position = self.move_reader(voice, ratio, period, offset, false); @@ -1579,7 +1668,7 @@ impl Resynthesis { ratio = Q14::ONE; } if ratio != Q14::ZERO { - self.periods[delay] = period.div(ratio); + self.lead_periods[delay] = period.div(ratio); } self.old_position = self.old_position + ratio; let position = self.move_reader(0, ratio, period, self.delays[0], true); @@ -1590,7 +1679,7 @@ impl Resynthesis { self.fade = (self.fade + FADE_STEP).min(Q14::ONE); } if self.config.formant.enabled { - self.formant_position = center - FORMANT_OFFSET_FRAMES; + self.formant_position = center - self.formant_offset_frames(); value = Q14::from_bits(self.formant.forward( value.to_bits(), self.formant_position, @@ -1667,29 +1756,49 @@ impl Resynthesis { } } self.periods[write] = step.period; + self.lead_periods[write] = step.period; self.previous_periods[write] = step.previous_period; self.ratios[write] = self.correction; - self.overlap_index += 1; - if self.overlap_index == OVERLAP_FRAMES { - self.overlap_index = 0; - } - self.overlap[self.overlap_index] = if self.config.formant.enabled { - let previous = self.raw[ring(write as i32 - 1)]; - Q14::from_bits(self.formant.process_analysis( - sample.to_bits(), - previous.to_bits(), - self.periods.as_slice(), - write, - step.previous_period.to_bits(), - )) + let (mut filtered, delayed) = if self.config.latency_mode == LatencyMode::LowLatency { + let source = if self.config.formant.enabled { + let previous = self.raw[ring(write as i32 - 1)]; + Q14::from_bits(self.formant.process_causal_analysis( + sample.to_bits(), + previous.to_bits(), + self.periods.as_slice(), + write, + step.previous_period.to_bits(), + )) + } else { + sample + }; + (source, write) } else { - self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] + self.overlap_index += 1; + if self.overlap_index == OVERLAP_FRAMES { + self.overlap_index = 0; + } + self.overlap[self.overlap_index] = if self.config.formant.enabled { + let previous = self.raw[ring(write as i32 - 1)]; + Q14::from_bits(self.formant.process_analysis( + sample.to_bits(), + previous.to_bits(), + self.periods.as_slice(), + write, + step.previous_period.to_bits(), + )) + } else { + self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] + }; + // The inverse analysis adds a delay of ANALYSIS_FRAMES. Read ahead by + // the same number of frames in the overlap ring. Then the total delay + // of the source is OVERLAP_FRAMES in the two formant modes. + let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; + ( + self.overlap[overlap_read], + ring(write as i32 - OVERLAP_FRAMES as i32), + ) }; - // The inverse analysis adds a delay of ANALYSIS_FRAMES. Read ahead by - // the same number of frames in the overlap ring. Then the total delay - // of the source is OVERLAP_FRAMES in the two formant modes. - let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; - let mut filtered = self.overlap[overlap_read]; if self.config.pitch_ratio > 1.0 { for filter in &mut self.post { filtered = filter.process_sample(filtered); @@ -1700,8 +1809,8 @@ impl Resynthesis { } } self.filtered[write] = filtered; - let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); - let dry = self.raw[ring(write as i32 - LATENCY_FRAMES as i32)]; + let dry_delay = latency_frames(self.config.latency_mode) as i32; + let dry = self.raw[ring(write as i32 - dry_delay)]; let mut mix = [Q14::ZERO; 2]; let mut mono = !self.config.stereo_output; let mut final_ratio = Q14::ONE; @@ -1825,7 +1934,8 @@ impl Resynthesis { } } if self.config.formant.enabled { - self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; + self.formant_position = + (self.positions[0].to_bits() >> 14) - self.formant_offset_frames(); // If Choir changed only channel zero before a switch to // Harmony, synthesize the two channels until their histories // are equal. diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..453c582 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -21,6 +21,7 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. +//! - The optional `latencyMode` field of resynthesis defaults to `"standard"`. //! - The optional correction `humanize` and `flexTune` fields default to 0. //! - The optional harmony `voices` field defaults to 4. //! @@ -258,11 +259,12 @@ impl WasmProcessor { self.input.len() } - /// The nominal resynthesis latency: 1,593 frames at both sample rates. + /// The nominal resynthesis latency: 1,593 frames in `"standard"` mode or + /// 50 frames in `"lowLatency"` mode at both sample rates. /// - /// The dry path also has a delay of 1,593 frames. Resampled voices, choir - /// delays and effects have their own timing. Thus, this value does not - /// align all paths. + /// The dry path also uses this delay. Resampled voices, choir delays and + /// effects have their own timing. Thus, this value does not align all + /// paths. #[wasm_bindgen(getter, js_name = latencyFrames)] pub fn latency_frames(&self) -> usize { self.processor.latency_frames()