diff --git a/README.md b/README.md index a06715f..350a188 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ browsers and Node.js. [GitHub Packages](https://github.com/ByteLandTechnology/tunelet/pkgs/npm/tunelet) · [API documentation](https://docs.rs/tunelet) -![The tunelet signal chain: Punch, Warm, pitch tracking and resynthesis, Alien, reverb and the output gain](docs/images/signal-chain.svg) +![The tunelet signal chain: Punch, Warm, pitch tracking and resynthesis, Alien, reverb, the output gain, the global mix, the global bypass and the dry paths](docs/images/signal-chain.svg) ## Contents @@ -170,10 +170,12 @@ voice. It disables the effects and the formant stage. | Formant | Changes the vocal tract with an LPC model and aspiration | Disabled | `resynthesis.formant` | | Alien | Plays recent audio in reverse loops | 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 `-32767..=32767` wet clamp | 1 | `output_gain` | +| Global mix | Wet fraction, 0..=1, with 1,593-frame raw dry path | 1 | `mix` | +| Global bypass | 200-frame crossfade to 1,593-frame raw dry path | Disabled | `bypass` | The internal Q14 stages use `i64` products and saturate at the `i32` -limits. Decrease `output_gain` to prevent `-32767..=32767` clipping on +limits. Decrease `output_gain` to prevent `-32767..=32767` saturation on multi-voice mixes. `resynthesis.correction.humanize` sets the relaxation on sustained notes, in @@ -181,9 +183,12 @@ 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. +`punch.mix`, `warm.mix`, `alien.mix` and `reverb.mix` set the Q14 wet +fraction of each effect stage, in `0..=1`. In Warm, the 50 Hz high-pass +filter operates only on the wet path. All six reverb modes keep the stereo +dry signal. `resynthesis.dry_mix` sets the dry fraction after Warm, with a +delay of 1,593 frames. `mix` and `bypass` use the raw input before Punch, +with the same 1,593-frame delay. ### Harmony sources @@ -261,8 +266,9 @@ These rules apply to the offsets: Events with equal offsets execute in slice order. An empty block accepts no events. A stage event replaces all settings of that stage. To change one scalar field without a stage copy, use `ControlEvent::Parameter` with a -`ParameterControl` variant. For fields that are not scalar parameters, start -from `processor.config()`. +`ParameterControl` variant. `ControlEvent::OutputGain`, `ControlEvent::Mix` and +`ControlEvent::Bypass` update `output_gain`, `mix` and `bypass` directly. For +other fields, start from `processor.config()`. Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses `ControlEvent::CorrectionMidi`. For example, these events change the resynthesis @@ -579,7 +585,8 @@ 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 +default. `mix`, `punch.mix`, `warm.mix` and `alien.mix` default to 1, and +`bypass` defaults to `false`. `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 @@ -592,8 +599,10 @@ telemetry use `bigint`. Frame offsets, block lengths and latency use ### Events The optional event argument is a `TimedEvent[]`. Controls use a `type` -discriminant and a `value` payload. The reset control has no payload. For -example, this event changes the final gain before the first frame: +discriminant and a `value` payload (`configure`, `resynthesis`, `punch`, +`warm`, `alien`, `reverb`, `outputGain`, `mix`, `bypass`, `parameter`, `midi` +and `correctionMidi`). The `reset` control has no payload. For example, this +event changes the final gain before the first frame: ```ts { offset: 0, event: { type: "outputGain", value: 0.5 } } diff --git a/docs/images/signal-chain.svg b/docs/images/signal-chain.svg index 75025c6..8262774 100644 --- a/docs/images/signal-chain.svg +++ b/docs/images/signal-chain.svg @@ -1,6 +1,6 @@ - + The tunelet signal chain - Mono PCM goes through Punch, Warm, pitch tracking and resynthesis, Alien, reverb and the output gain. A dry path goes around the resynthesis stage. + Mono PCM goes through Punch, Warm, pitch tracking and resynthesis, Alien, reverb, the output gain, the global mix and the global bypass. One dry path goes around resynthesis, and a raw dry path before Punch feeds the global mix and the global bypass. diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..4810375 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -313,11 +313,21 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.ok(wasmExports.memory instanceof WebAssembly.Memory);", "", "const initialConfig = rootModule.defaultConfig();", + "initialConfig.mix = undefined;", + "initialConfig.bypass = undefined;", + "initialConfig.punch.mix = undefined;", + "initialConfig.warm.mix = undefined;", + "initialConfig.alien.mix = 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().mix, 1);", + " assert.equal(processor.config().bypass, false);", + " assert.equal(processor.config().punch.mix, 1);", + " assert.equal(processor.config().warm.mix, 1);", + " assert.equal(processor.config().alien.mix, 1);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", @@ -352,9 +362,19 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);", "", " const omittedCorrectionConfig = processor.config();", + " delete omittedCorrectionConfig.mix;", + " delete omittedCorrectionConfig.bypass;", + " delete omittedCorrectionConfig.punch.mix;", + " delete omittedCorrectionConfig.warm.mix;", + " delete omittedCorrectionConfig.alien.mix;", " delete omittedCorrectionConfig.resynthesis.correction.humanize;", " delete omittedCorrectionConfig.resynthesis.correction.flexTune;", " processor.setConfig(omittedCorrectionConfig);", + " assert.equal(processor.config().mix, 1);", + " assert.equal(processor.config().bypass, false);", + " assert.equal(processor.config().punch.mix, 1);", + " assert.equal(processor.config().warm.mix, 1);", + " assert.equal(processor.config().alien.mix, 1);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", "", @@ -365,7 +385,11 @@ function verifyRuntimeImport(consumerDir, packageName) { " eventResynthesis.harmony.voices = undefined;", " processor.processMono(mono, [", ' { offset: 0, event: { type: "resynthesis", value: eventResynthesis } },', + ' { offset: 1, event: { type: "mix", value: 0.5 } },', + ' { offset: 2, event: { type: "bypass", value: true } },', " ]);", + " assert.equal(processor.config().mix, 0.5);", + " assert.equal(processor.config().bypass, true);", " assert.equal(processor.config().resynthesis.correction.humanize, 0);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", @@ -772,6 +796,20 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const baseConfig: ProcessorConfig = defaultConfig();", " const configWithUndefined: ProcessorConfig = {", " ...baseConfig,", + " mix: optionalVoices,", + " bypass: undefined,", + " punch: {", + " ...baseConfig.punch,", + " mix: optionalVoices,", + " },", + " warm: {", + " ...baseConfig.warm,", + " mix: optionalVoices,", + " },", + " alien: {", + " ...baseConfig.alien,", + " mix: optionalVoices,", + " },", " resynthesis: {", " ...baseConfig.resynthesis,", " correction: {", @@ -856,6 +894,8 @@ function verifyTypeDeclarations(consumerDir, packageName) { " processor.processF32(inputF32, leftF32, rightF32);", " processor.processF32(inputF32, leftF32, rightF32, [", ' { offset: 0, event: { type: "outputGain", value: 1 } },', + ' { offset: 0, event: { type: "mix", value: 1 } },', + ' { offset: 0, event: { type: "bypass", value: false } },', " { offset: 0, event: parameterEvent },", " ]);", " processor.processMonoF32(inputF32);", diff --git a/src/config.rs b/src/config.rs index 741d08c..39a1311 100644 --- a/src/config.rs +++ b/src/config.rs @@ -163,16 +163,44 @@ 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). Zero mutes the wet output, while the internal + /// stages continue to advance. The gain is quantized in steps of 1/256 + /// before the fixed-point multiplication and the `-32767..=32767` wet clamp. + /// Thus, a positive value below 1/256 also mutes the wet output. pub output_gain: f32, + /// The global wet fraction after the output gain, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. The dry path + /// reads the raw mono input before Punch, with a delay of 1,593 frames. All + /// internal stages continue to advance at all mix values. In JavaScript, + /// this field is optional and an absent or `undefined` value gives 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "crate::wasm::default_mix", + deserialize_with = "crate::wasm::deserialize_mix" + ), + tsify(optional, type = "number | undefined") + )] + pub mix: f32, + /// Selects the 1,593-frame delayed raw input instead of the mixed output. + /// + /// The default is `false`. If `bypass` changes after construction, the + /// processor crossfades over 200 frames in Q14 while all internal stages + /// continue to advance. In JavaScript, this field is optional and an + /// absent or `undefined` value gives `false`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default, deserialize_with = "crate::wasm::deserialize_false"), + tsify(optional, type = "boolean | undefined") + )] + pub bypass: bool, } 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, full wet mix and + /// disabled bypass. fn default() -> Self { Self { punch: PunchConfig::default(), @@ -181,16 +209,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 and + /// the controls of voice modes that are not active. /// /// # Errors /// @@ -203,7 +234,8 @@ impl ProcessorConfig { self.resynthesis.validate()?; self.alien.validate()?; self.reverb.validate()?; - validate_output_gain(self.output_gain) + validate_output_gain(self.output_gain)?; + validate_mix(self.mix) } /// Returns which choir, harmony and reverb controls change the audio in @@ -332,3 +364,10 @@ pub struct ControlActivity { pub(crate) fn validate_output_gain(gain: f32) -> Result<(), Error> { check_range("output_gain", gain, 0.0, 64.0) } + +/// Checks the global wet mix range. +/// +/// `ProcessorConfig` and `ControlEvent::Mix` use the same range. +pub(crate) fn validate_mix(mix: f32) -> Result<(), Error> { + check_range("mix", mix, 0.0, 1.0) +} diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 271cae5..2291b54 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -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; @@ -24,8 +25,9 @@ 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 + /// Enables reversed loop playback. The default is `false`. + /// + /// The history buffer and the loop phase continue to advance in both /// states. pub enabled: bool, /// The loop length in frames, 1..=96000. The default is 95,999. @@ -33,27 +35,45 @@ pub struct AlienConfig { /// seconds changes with the sample rate. A short loop can be fully inside /// the fades. pub loop_frames: u32, + /// The wet fraction, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. While Alien is + /// enabled, a zero mix still advances the history buffer and the loop + /// phase. In JavaScript, this field is optional and an absent or + /// `undefined` value gives 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "crate::wasm::default_mix", + deserialize_with = "crate::wasm::deserialize_mix" + ), + tsify(optional, type = "number | undefined") + )] + pub mix: f32, } 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 its documented inclusive range. 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) } } @@ -63,11 +83,13 @@ impl AlienConfig { pub(crate) struct Alien { /// The validated controls, which include the selection of the wet output. config: AlienConfig, + /// The Q14 wet weight. The dry weight is `1 - mix`. + mix: Q14, /// 192,000 stereo Q14 frames, which are allocated one time at /// construction. buffer: Vec<[Q14; 2]>, - /// The current recording position. The position of the reverse reader - /// comes from this cursor. + /// The current write 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, @@ -82,6 +104,7 @@ impl Alien { pub(crate) fn new(config: AlienConfig) -> Self { Self { config, + mix: Q14::from_f64((config.mix * 100.0) as f64 / 100.0), buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES], read: 0, phase: 0, @@ -92,7 +115,11 @@ impl Alien { /// 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) { + let old = self.config; self.config = config; + if old.mix != config.mix { + self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); + } self.loop_len = config.loop_frames as usize; self.phase = self.phase.min(self.loop_len - 1); } @@ -135,6 +162,13 @@ impl Alien { .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); result = result.map(|sample| sample.mul::<14, 14>(gain)); } + let wet_w = i64::from(self.mix.to_bits()); + let dry_w = i64::from((Q14::ONE - self.mix).to_bits()); + for (channel, sample) in result.iter_mut().enumerate() { + let dry = i64::from(input[channel].to_bits()); + let wet = i64::from(sample.to_bits()); + *sample = Q14::from_bits(clamp_i32((dry * dry_w + wet * wet_w) >> 14)); + } result } else { input @@ -154,12 +188,12 @@ impl Alien { /// Returns the finite tail budget: two loop lengths plus the boundary /// fade. /// -/// The value is zero when Alien is disabled. It is a configured budget, -/// not a measured tail. +/// If Alien is disabled or the mix is zero, the value is zero. It is a +/// configured budget, not a measured tail. pub(crate) fn tail_frames(config: AlienConfig) -> usize { - if config.enabled { - 2 * config.loop_frames as usize + FADE_FRAMES - } else { + if !config.enabled || config.mix == 0.0 { 0 + } else { + 2 * config.loop_frames as usize + FADE_FRAMES } } diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 52b2777..c13b6d0 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -66,6 +66,21 @@ pub struct PunchConfig { /// The default is 10 ms. Each enabled frame updates both followers with /// per-sample coefficients. pub attack_ms: f32, + /// The wet fraction, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. If Punch is + /// enabled, a zero mix still advances the peak hold, the envelopes and the + /// drive. In JavaScript, this field is optional and an absent or + /// `undefined` value gives 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "crate::wasm::default_mix", + deserialize_with = "crate::wasm::deserialize_mix" + ), + tsify(optional, type = "number | undefined") + )] + pub mix: f32, } impl Default for PunchConfig { fn default() -> Self { @@ -75,6 +90,7 @@ impl Default for PunchConfig { impact: 0.5, ceiling_db: -3.0, attack_ms: 10.0, + mix: 1.0, } } } @@ -93,7 +109,8 @@ impl PunchConfig { validate_gain_db(self.gain_db)?; validate_impact(self.impact)?; validate_ceiling_db(self.ceiling_db)?; - validate_attack_ms(self.attack_ms) + validate_attack_ms(self.attack_ms)?; + validate_mix(self.mix) } } @@ -117,6 +134,11 @@ pub(crate) fn validate_attack_ms(attack_ms: f32) -> Result<(), Error> { check_range("punch.attack_ms", attack_ms, 0.01, 5000.0) } +/// Checks the range of the wet mix of Punch. +fn validate_mix(mix: f32) -> Result<(), Error> { + check_range("punch.mix", mix, 0.0, 1.0) +} + /// Two peak followers that control an arctangent saturator, with all buffers /// inline. #[derive(Debug)] @@ -148,6 +170,8 @@ pub(crate) struct Punch { gain: Q28, /// The linear output ceiling in Q28, nonzero across -96..=0 dBFS. ceiling_gain: Q28, + /// The Q14 wet weight. The dry weight is `1 - mix`. + mix: Q14, /// The smoothed Q24 drive: base drive × envelope ratio × input gain. drive: Q24, } @@ -172,6 +196,7 @@ impl Punch { drive_decay, gain: Q28::ONE, ceiling_gain: Q28::ONE, + mix: Q14::ONE, drive: BASE_DRIVE, }; result.configure_all(); @@ -217,12 +242,17 @@ impl Punch { self.ceiling_gain = Q28::from_f64(db_to_gain(self.config.ceiling_db as f64)).max(Q28::from_bits(1)); } + /// Updates the quantized wet mix. + fn configure_mix(&mut self) { + self.mix = Q14::from_f64((self.config.mix * 100.0) as f64 / 100.0); + } /// Initializes all configurable coefficients unconditionally. fn configure_all(&mut self) { self.configure_impact(); self.configure_attack_ms(); self.configure_gain_db(); self.configure_ceiling_db(); + self.configure_mix(); } /// Calculates the changed quantized controls again, and keeps the /// envelopes and the current drive. @@ -244,6 +274,9 @@ impl Punch { if old.ceiling_db != config.ceiling_db { self.configure_ceiling_db(); } + if old.mix != config.mix { + self.configure_mix(); + } } /// Stores the input gain. If the value changed, quantizes it again. pub(crate) fn set_gain_db(&mut self, gain_db: f32) { @@ -327,8 +360,8 @@ impl Punch { /// While the adaptive envelope is zero, the envelope ratio is 1. The stage /// limits this ratio to 16, then multiplies it by the input gain. Next, it /// divides the driven sample by the ceiling gain and clamps the quotient in - /// `i64` before the arctangent lookup. Finally, the PCM output clips - /// symmetrically. + /// `i64` before the arctangent lookup. Finally, it mixes the dry input and + /// the wet output in Q14 and clips the PCM output symmetrically. pub(crate) fn process_sample(&mut self, input: i16, context: &mut NumericContext) -> i16 { let sample: Q28 = Fixed::<15>::from_bits(i32::from(input)).rescale(); let held = self.push_hold(sample.abs()); @@ -357,6 +390,10 @@ impl Punch { } else { -((-scaled_bits + 4096) >> 13) }; - pcm.clamp(-32767, 32767) as i16 + let wet = pcm.clamp(-32767, 32767); + let dry = i64::from(input); + let wet_w = i64::from(self.mix.to_bits()); + let dry_w = i64::from((Q14::ONE - self.mix).to_bits()); + (((dry * dry_w + wet * wet_w) >> 14).clamp(-32767, 32767)) as i16 } } diff --git a/src/effects/warm.rs b/src/effects/warm.rs index a1e1a3c..4ab9b40 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -6,11 +6,12 @@ use crate::numeric::fixed::{Fixed, Q14, Q22, Q24, Q28, Q30}; use crate::numeric::{db_to_gain, envelope_decay}; use crate::{Error, SampleRate}; -/// Asymmetric input saturation, followed by a 50 Hz high-pass filter. +/// Asymmetric input saturation, with a 50 Hz high-pass filter on the wet path. /// /// Warm operates after Punch and before pitch detection. Its adaptive /// normalization updates on each enabled frame with an immediate attack and a -/// 200 ms release half-life. When Warm is disabled, the envelope and filter +/// 200 ms release half-life. The 50 Hz high-pass filter applies only to the wet +/// path, not to the dry path. When Warm is disabled, the envelope and filter /// histories do not change. When Warm is enabled again, they continue from /// their last state, unless the processor was reset. #[derive(Clone, Copy, Debug, PartialEq)] @@ -27,28 +28,46 @@ pub struct WarmConfig { /// The output gain changes by -0.35 dB for each dB of drive. At 0 dB, the /// envelope normalization and the output high-pass filter still operate. pub drive_db: f32, + /// The wet fraction, 0..=1. + /// + /// The default is 1. The dry weight is `1 - mix` in Q14. The 50 Hz + /// high-pass filter applies only to the wet signal before the blend. If + /// Warm is enabled, a zero mix still advances the envelope and the filter. + /// In JavaScript, this field is optional and an absent or `undefined` + /// value gives 1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde( + default = "crate::wasm::default_mix", + deserialize_with = "crate::wasm::deserialize_mix" + ), + tsify(optional, type = "number | undefined") + )] + pub mix: f32, } impl Default for WarmConfig { fn default() -> Self { Self { enabled: false, drive_db: 3.0, + mix: 1.0, } } } impl WarmConfig { /// Validates all fields, also when Warm is disabled. /// - /// `drive_db` must be finite and in its documented inclusive range. - /// Validation does not clamp values. It does not change the processor - /// state. + /// The floating-point controls must be finite and in their documented + /// inclusive ranges. 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> { - validate_drive_db(self.drive_db) + validate_drive_db(self.drive_db)?; + validate_mix(self.mix) } } @@ -57,6 +76,11 @@ pub(crate) fn validate_drive_db(drive_db: f32) -> Result<(), Error> { check_range("warm.drive_db", drive_db, 0.0, 6.0) } +/// Checks the range of the wet mix of Warm. +fn validate_mix(mix: f32) -> Result<(), Error> { + check_range("warm.mix", mix, 0.0, 1.0) +} + /// An adaptive asymmetric saturator with one persistent high-pass output /// filter. #[derive(Debug)] @@ -76,6 +100,8 @@ pub(crate) struct Warm { drive: Q24, /// The Q28 compensation from the configured drive. output_gain: Q28, + /// The Q14 wet weight. The dry weight is `1 - mix`. + mix: Q14, /// The Q28 threshold of -30 dB. If the peak envelope is not above it, the /// normalization targets a fixed headroom. input_threshold: Q28, @@ -83,8 +109,9 @@ pub(crate) struct Warm { output_headroom: Q22, } impl Warm { - /// Prepares the fixed high-pass filter and the initial normalization - /// state. + /// Prepares the fixed 50 Hz high-pass filter on the wet path and the + /// initial normalization state. The dry path does not go through this + /// filter. pub(crate) fn new(rate: SampleRate, config: WarmConfig) -> Self { let mut filter = Biquad::new(); filter.set_design(Design::high_pass_one_pole(rate.hz(), 50.0)); @@ -96,10 +123,12 @@ impl Warm { smooth: Q30::from_f64(envelope_decay(200.0, rate.hz() as f64, 1)), drive: Q24::ZERO, output_gain: Q28::ZERO, + mix: Q14::ONE, input_threshold: Q28::from_f64(db_to_gain(-30.0)), output_headroom: Q22::from_f64(db_to_gain(30.0)), }; result.configure_drive_db(); + result.configure_mix(); result } /// Returns the Q22 normalization gain as f32. The stage state does not @@ -112,14 +141,21 @@ impl Warm { self.drive = Q24::from_f64(db_to_gain(self.config.drive_db as f64)); self.output_gain = Q28::from_f64(db_to_gain(-(self.config.drive_db as f64) * 0.35)); } - /// Stores the configuration. If the drive changed, updates the drive and - /// the output compensation, and keeps the envelope and filter state. + /// Quantizes the wet mix unconditionally. + fn configure_mix(&mut self) { + self.mix = Q14::from_f64((self.config.mix * 100.0) as f64 / 100.0); + } + /// Stores the configuration. If the drive or the mix changed, updates the + /// changed coefficients and keeps the envelope and filter state. pub(crate) fn set_config(&mut self, config: WarmConfig) { let old = self.config; self.config = config; if old.drive_db != config.drive_db { self.configure_drive_db(); } + if old.mix != config.mix { + self.configure_mix(); + } } /// Stores the drive. If the value changed, updates the quantized drive and /// its output compensation. @@ -146,7 +182,7 @@ impl Warm { /// 2. Normalize the sample. /// 3. Shape the positive and negative halves differently. /// 4. Remove the normalization. - /// 5. Apply the high-pass filter and clip the result. + /// 5. Apply the high-pass filter to the wet signal, mix in Q14 and clip. /// /// If an attack increases the peak, the gain decreases immediately. /// During release, the gain moves smoothly toward the target. @@ -179,9 +215,15 @@ impl Warm { } sample = sample.div(self.compression.max(Q22::ONE)); let output = Q14::from_bits(self.output_gain.mul::<28, 15>(sample).to_bits()); - self.filter - .process_sample(output) - .to_bits() - .clamp(-32767, 32767) as i16 + let wet = i64::from( + self.filter + .process_sample(output) + .to_bits() + .clamp(-32767, 32767), + ); + let dry = i64::from(input); + let wet_w = i64::from(self.mix.to_bits()); + let dry_w = i64::from((Q14::ONE - self.mix).to_bits()); + (((dry * dry_w + wet * wet_w) >> 14).clamp(-32767, 32767)) as i16 } } diff --git a/src/events.rs b/src/events.rs index ef07dee..693193f 100644 --- a/src/events.rs +++ b/src/events.rs @@ -1,6 +1,6 @@ //! Controls for a block, which the processor validates before any change. -use crate::config::validate_output_gain; +use crate::config::{validate_mix, validate_output_gain}; use crate::effects::alien::AlienConfig; use crate::effects::punch::{self, PunchConfig}; use crate::effects::reverb::{self, ReverbConfig}; @@ -229,6 +229,16 @@ pub enum ControlEvent { /// The quantization and the mute behavior are the same as for /// [`ProcessorConfig::output_gain`]. The value must be finite. OutputGain(f32), + /// This event sets the global wet fraction, 0..=1. + /// + /// The quantization and the dry delay are the same as for + /// [`ProcessorConfig::mix`]. The value must be finite. + Mix(f32), + /// This event sets the global bypass state. + /// + /// If the value changes, the processor crossfades over 200 frames, as + /// [`ProcessorConfig::bypass`] describes. + Bypass(bool), /// This event updates one scalar parameter without a copy of the full stage /// structure. /// @@ -265,9 +275,9 @@ impl ControlEvent { /// # Errors /// /// Returns [`Error::InvalidConfig`] for an invalid configuration, scalar - /// parameter or gain. Returns [`Error::InvalidMidi`] for invalid MIDI - /// fields. Reset is always valid. The process call that contains the event - /// checks the offset and the order. + /// parameter, gain or mix. Returns [`Error::InvalidMidi`] for invalid MIDI + /// fields. Bypass and reset are always valid. The process call that + /// contains the event checks the offset and the order. pub fn validate(self) -> Result<(), Error> { match self { Self::Configure(config) => config.validate(), @@ -277,6 +287,8 @@ impl ControlEvent { Self::Alien(config) => config.validate(), Self::Reverb(config) => config.validate(), Self::OutputGain(gain) => validate_output_gain(gain), + Self::Mix(mix) => validate_mix(mix), + Self::Bypass(_) => Ok(()), Self::Parameter(parameter) => parameter.validate(), Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(), Self::Reset => Ok(()), @@ -419,6 +431,15 @@ fn validate_in_sequence(event: ControlEvent, config: &mut ProcessorConfig) -> Re config.output_gain = gain; Ok(()) } + ControlEvent::Mix(mix) => { + validate_mix(mix)?; + config.mix = mix; + Ok(()) + } + ControlEvent::Bypass(bypass) => { + config.bypass = bypass; + Ok(()) + } ControlEvent::Parameter(parameter) => parameter.apply_to(config), ControlEvent::Midi(midi) | ControlEvent::CorrectionMidi(midi) => midi.validate(), ControlEvent::Reset => Ok(()), diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..3c22b4c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 → global mix → global bypass. The default configuration enables +//! chromatic pitch correction, one choir voice and a full wet mix. The +//! optional effects, the formant stage and the global bypass are disabled. //! //! # Preparing and configuring //! diff --git a/src/processor.rs b/src/processor.rs index 9f8ae9b..f3dcd37 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -5,6 +5,7 @@ use crate::effects::punch::Punch; use crate::effects::reverb::{self, Reverb}; use crate::effects::warm::Warm; use crate::events::{ValidatedEvent, ValidatedEvents}; +use crate::numeric::fixed::{Fixed, Q14}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; @@ -13,6 +14,17 @@ use crate::{ TimedEvent, }; +/// The length in frames of the global bypass crossfade. +const BYPASS_FADE_FRAMES: u8 = 200; + +/// Allocates the 1,593-frame raw PCM delay buffer on the heap one time. +fn prepare_dry() -> Box<[i16; resynthesis::LATENCY_FRAMES]> { + vec![0_i16; resynthesis::LATENCY_FRAMES] + .into_boxed_slice() + .try_into() + .unwrap_or_else(|_| unreachable!("prepared dry buffer length")) +} + /// Selects the output channel layout for the downmix and the peak meters. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum OutputLayout { @@ -58,6 +70,16 @@ pub struct Processor { /// /// The temporary aspiration mute of a drain is not stored here. config: ProcessorConfig, + /// The 1,593-frame raw PCM ring before Punch, for global `mix` and + /// `bypass`. + dry: Box<[i16; resynthesis::LATENCY_FRAMES]>, + /// The current frame slot in `dry`, always less than 1,593. + dry_index: usize, + /// The quantized Q14 global wet weight. + mix: Q14, + /// The bypass crossfade position in `0..=200`. Zero is active and 200 is + /// bypassed. + bypass_fade: u8, /// The input dynamics stage, which advances only while it is enabled. punch: Punch, /// The input saturation stage, which advances only while it is enabled. @@ -123,8 +145,9 @@ impl Processor { /// /// # Errors /// - /// Returns [`Error::InvalidConfig`] if a stage field or the output gain is - /// not valid. This check occurs before the allocation of the histories. + /// Returns [`Error::InvalidConfig`] if a stage field, the output gain or the + /// global mix is not valid. This check occurs before the allocation of the + /// histories. /// The types of `preparation` already make sure that the block limit is /// not zero and that the sample rate is supported. pub fn new(preparation: PrepareConfig, config: ProcessorConfig) -> Result { @@ -133,6 +156,10 @@ impl Processor { Ok(Self { preparation, config, + dry: prepare_dry(), + dry_index: 0, + mix: Q14::from_f64((config.mix * 100.0) as f64 / 100.0), + bypass_fade: if config.bypass { BYPASS_FADE_FRAMES } else { 0 }, punch: Punch::new(rate, config.punch), warm: Warm::new(rate, config.warm), resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), @@ -512,9 +539,9 @@ impl Processor { /// Returns the nominal resynthesis latency: 1,593 frames 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 resynthesis dry path and the global `mix` and `bypass` dry path also + /// have a delay of 1,593 frames. 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 } @@ -730,6 +757,9 @@ impl Processor { if self.config.reverb != config.reverb { self.reverb.set_config(config.reverb); } + if self.config.mix != config.mix { + self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); + } self.config = config; self.drain_remaining = None; } @@ -737,11 +767,12 @@ impl Processor { /// Clears the audio histories, held notes, pitch feedback, peak and frame /// count. /// - /// This method cancels an active drain. It also clears the correction - /// ratio, the Punch envelopes, the Warm filters, the Alien recording and - /// the reverb delays. It releases the harmony MIDI notes and, in - /// MIDI-chord mode, the chord voices. It releases correction keys 0..=127 - /// and loads the configured correction notes again. It keeps these items: + /// This method cancels an active drain and settles the bypass crossfade. + /// It clears the global dry buffer, the correction ratio, the Punch + /// envelopes, the Warm filters, the Alien history and the reverb delays. + /// It releases the harmony MIDI notes and, in MIDI-chord mode, the chord + /// voices. It releases correction keys 0..=127 and loads the configured + /// correction notes again. It keeps these items: /// /// - the configuration /// - the random stream and the arctangent lookup position of Punch @@ -757,6 +788,13 @@ impl Processor { /// /// For a fully new state, make a new processor. pub fn reset(&mut self) { + self.dry.fill(0); + self.dry_index = 0; + self.bypass_fade = if self.config.bypass { + BYPASS_FADE_FRAMES + } else { + 0 + }; self.punch.reset(); self.warm.reset(); self.resynthesis.reset(); @@ -803,9 +841,9 @@ impl Processor { /// Applies a validated control immediately before its frame is rendered. /// /// A stage event replaces one stage in the active configuration. A scalar - /// parameter event updates one field and its quantized state. MIDI and - /// reset events act directly. A reset does not discard later events in the - /// block. + /// parameter, gain, mix or bypass event updates one field and its quantized + /// state. MIDI and reset events act directly. A reset does not discard + /// later events in the block. fn apply(&mut self, event: ValidatedEvent) { match event.into_inner() { ControlEvent::Configure(value) => self.apply_config(value), @@ -838,6 +876,17 @@ impl Processor { self.config.output_gain = value; self.drain_remaining = None; } + ControlEvent::Mix(value) => { + if self.config.mix != value { + self.mix = Q14::from_f64((value * 100.0) as f64 / 100.0); + } + self.config.mix = value; + self.drain_remaining = None; + } + ControlEvent::Bypass(value) => { + self.config.bypass = value; + self.drain_remaining = None; + } ControlEvent::Parameter(parameter) => self.apply_parameter(parameter), ControlEvent::Midi(event) => self.resynthesis.apply_midi(event), ControlEvent::CorrectionMidi(event) => self.resynthesis.apply_correction_midi(event), @@ -976,6 +1025,12 @@ impl Processor { /// In the mono layout, the downmix occurs before the peak measurement. fn next(&mut self, mut input: i16, layout: OutputLayout) -> [i16; 2] { self.input_peak = self.input_peak.max((input as i32).abs()); + let dry_sample = self.dry[self.dry_index]; + self.dry[self.dry_index] = input; + self.dry_index += 1; + if self.dry_index == resynthesis::LATENCY_FRAMES { + self.dry_index = 0; + } if self.config.punch.enabled { input = self.punch.process_sample(input, &mut self.numeric); } @@ -987,9 +1042,30 @@ impl Processor { let alien = self.alien.process_sample(voice); let reverb = self.reverb.process_sample(alien, layout); let gain = (self.config.output_gain as f64 * 256.0) as i64; - let mut result = reverb.map(|sample| { - (((i64::from(sample.to_bits()) * gain) >> 8) << 1).clamp(-32767, 32767) as i16 - }); + let wet = reverb + .map(|sample| (((i64::from(sample.to_bits()) * gain) >> 8) << 1).clamp(-32767, 32767)); + let mix_wet = i64::from(self.mix.to_bits()); + let mix_dry = i64::from((Q14::ONE - self.mix).to_bits()); + let dry = i64::from(dry_sample); + let mixed = wet.map(|channel| (dry * mix_dry + channel * mix_wet) >> 14); + if self.config.bypass { + if self.bypass_fade < BYPASS_FADE_FRAMES { + self.bypass_fade += 1; + } + } else if self.bypass_fade > 0 { + self.bypass_fade -= 1; + } + let mut result = if self.bypass_fade == 0 { + mixed.map(|channel| channel.clamp(-32767, 32767) as i16) + } else { + let bypass_wet: Q14 = Fixed::<0>::from_bits(i32::from(self.bypass_fade)) + .div(Fixed::<0>::from_bits(i32::from(BYPASS_FADE_FRAMES))); + let dry_w = i64::from(bypass_wet.to_bits()); + let active_w = i64::from((Q14::ONE - bypass_wet).to_bits()); + mixed.map(|channel| { + (((channel * active_w + dry * dry_w) >> 14).clamp(-32767, 32767)) as i16 + }) + }; if matches!(layout, OutputLayout::Mono) { let mono = downmix(result); result = [mono, mono]; @@ -1185,9 +1261,9 @@ pub struct Telemetry { /// The largest absolute clipped sample of the left and the right output /// in the window, divided by 32768. /// - /// The measurement is after the output gain. In mono calls, both entries - /// measure the mono sample after the downmix. Each value is in - /// 0..=32767/32768. + /// The measurement is after the output gain, the global mix and the bypass. + /// In mono calls, both entries measure the mono sample after the downmix. + /// Each value is in 0..=32767/32768. pub output_peak: [f32; 2], /// The largest absolute wet contribution of the reverb in the window, /// where 1 is full scale. diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..53b79ce 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -21,6 +21,9 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. +//! - If an optional field is absent or `undefined`, it gets its default. +//! - The optional `mix`, `punch.mix`, `warm.mix` and `alien.mix` fields +//! default to 1, and `bypass` defaults to `false`. //! - The optional correction `humanize` and `flexTune` fields default to 0. //! - The optional harmony `voices` field defaults to 4. //! @@ -74,10 +77,13 @@ pub struct BlockEvents(Vec); /// Returns a complete, independent default configuration for JavaScript. /// -/// Change its fields and give it to `Tunelet` or to `setConfig`. The -/// `randomSeed` field is a JavaScript `bigint`, so it keeps all 64 bits. After -/// the binding decodes them, floating-point controls have the precision of the -/// Rust `f32` type. +/// The returned object includes all optional fields (`mix`, `bypass`, +/// `punch.mix`, `warm.mix`, `alien.mix`, `resynthesis.correction.humanize`, +/// `resynthesis.correction.flexTune` and `resynthesis.harmony.voices`) with +/// their default values. Change its fields and give it to `Tunelet` or to +/// `setConfig`. The `randomSeed` field is a JavaScript `bigint`, so it keeps +/// all 64 bits. After the binding decodes them, floating-point controls have +/// the precision of the Rust `f32` type. /// /// # Errors /// @@ -88,6 +94,25 @@ pub fn default_config() -> Result, JsError> { Ok(ProcessorConfig::default().into_ts()?) } +/// Returns the default wet mix of 1.0 for optional JavaScript fields. +pub(crate) fn default_mix() -> f32 { + 1.0 +} + +/// Decodes an optional wet mix and maps an absent value to 1.0. +pub(crate) fn deserialize_mix<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_mix)) +} + +/// Decodes an optional boolean flag and maps an absent value to `false`. +pub(crate) fn deserialize_false<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + Ok(Option::::deserialize(deserializer)?.unwrap_or(false)) +} + /// A stateful vocal processor that JavaScript uses as the `Tunelet` class. /// /// The input is mono `Int16Array` PCM or mono `Float32Array` audio. The output @@ -260,9 +285,9 @@ impl WasmProcessor { /// The nominal resynthesis latency: 1,593 frames 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 resynthesis dry path and the global `mix` and `bypass` dry path also + /// have a delay of 1,593 frames. 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() @@ -858,6 +883,8 @@ struct EventKeys { midi: JsValue, correction_midi: JsValue, output_gain: JsValue, + mix: JsValue, + bypass: JsValue, parameter: JsValue, reset: JsValue, configure: JsValue, @@ -887,6 +914,8 @@ impl EventKeys { midi: JsValue::from_str("midi"), correction_midi: JsValue::from_str("correctionMidi"), output_gain: JsValue::from_str("outputGain"), + mix: JsValue::from_str("mix"), + bypass: JsValue::from_str("bypass"), parameter: JsValue::from_str("parameter"), reset: JsValue::from_str("reset"), configure: JsValue::from_str("configure"), @@ -1089,6 +1118,15 @@ fn decode_control_event(event: &JsValue, keys: &EventKeys) -> Result