Skip to content
Merged
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
71 changes: 61 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,23 +259,68 @@ These rules apply to the offsets:
- An offset must not be less than the offset before it.

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
field, start from `processor.config()`.
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()`.

Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses
`ControlEvent::CorrectionMidi`. For example, this event starts a harmony note
at frame 256:
`ControlEvent::CorrectionMidi`. For example, these events change the resynthesis
dry mix at frame 0 and start a harmony note at frame 256:

```rust
use tunelet::{ControlEvent, MidiEvent, TimedEvent};

let events = [TimedEvent {
offset: 256,
event: ControlEvent::Midi(MidiEvent::NoteOn { channel: 0, note: 64, velocity: 100 }),
}];
use tunelet::{ControlEvent, MidiEvent, ParameterControl, TimedEvent};

let events = [
TimedEvent {
offset: 0,
event: ControlEvent::Parameter(ParameterControl::DryMix(0.25)),
},
TimedEvent {
offset: 256,
event: ControlEvent::Midi(MidiEvent::NoteOn { channel: 0, note: 64, velocity: 100 }),
},
];
processor.process(&input, &mut output, &events)?;
```

### Scalar parameters

`ControlEvent::Parameter` accepts these `ParameterControl` variants. All ranges
are inclusive, and `f32` values must be finite.

| Variant | TypeScript `type` | Configuration field | Range |
| ----------------------------- | ------------------------------- | --------------------------------------- | ----------------- |
| `PunchGainDb` | `"punchGainDb"` | `punch.gain_db` | `-96..=12` dB |
| `PunchImpact` | `"punchImpact"` | `punch.impact` | `0..=1` |
| `PunchCeilingDb` | `"punchCeilingDb"` | `punch.ceiling_db` | `-96..=0` dBFS |
| `PunchAttackMs` | `"punchAttackMs"` | `punch.attack_ms` | `0.01..=5000` ms |
| `WarmDriveDb` | `"warmDriveDb"` | `warm.drive_db` | `0..=6` dB |
| `PitchThreshold` | `"pitchThreshold"` | `resynthesis.pitch.threshold` | `0.002..=0.2` |
| `RetuneMs` | `"retuneMs"` | `resynthesis.correction.retune_ms` | `0..=400` ms |
| `Humanize` | `"humanize"` | `resynthesis.correction.humanize` | `0..=1` |
| `FlexTune` | `"flexTune"` | `resynthesis.correction.flex_tune` | `0..=1` |
| `PitchRatio` | `"pitchRatio"` | `resynthesis.pitch_ratio` | `0.25..=4` |
| `FormantWidth` | `"formantWidth"` | `resynthesis.formant.width` | `0.5..=2` |
| `FormantStretch` | `"formantStretch"` | `resynthesis.formant.stretch` | `0.5..=2` |
| `FormantAspirationMix` | `"formantAspirationMix"` | `resynthesis.formant.aspiration_mix` | `0..=1` |
| `FormantAspirationCutoffHz` | `"formantAspirationCutoffHz"` | `resynthesis.formant.aspiration_cutoff_hz` | `500..=10000` Hz |
| `ChoirVoices` | `"choirVoices"` | `resynthesis.choir_voices` | `1..=16` |
| `ChoirDetune` | `"choirDetune"` | `resynthesis.choir_detune` | `10..=100` |
| `ChoirDelay` | `"choirDelay"` | `resynthesis.choir_delay` | `20..=200` |
| `ChoirSpreadPercent` | `"choirSpreadPercent"` | `resynthesis.choir_spread_percent` | `0..=100`% |
| `HarmonyRegisterPercent` | `"harmonyRegisterPercent"` | `resynthesis.harmony.register_percent` | `0..=100`% |
| `HarmonyVoicingSpreadPercent` | `"harmonyVoicingSpreadPercent"` | `resynthesis.harmony.voicing_spread_percent` | `0..=100`% |
| `HarmonyPortamentoMs` | `"harmonyPortamentoMs"` | `resynthesis.harmony.portamento_ms` | `0..=10000` ms |
| `HarmonyVoices` | `"harmonyVoices"` | `resynthesis.harmony.voices` | `0..=4` |
| `HarmonyGain` | `"harmonyGain"` | `resynthesis.harmony_gain` | `0..=1` |
| `HarmonicModulation` | `"harmonicModulation"` | `resynthesis.harmonic_modulation` | `0..=24` |
| `DryMix` | `"dryMix"` | `resynthesis.dry_mix` | `0..=1` |
| `ReverbMix` | `"reverbMix"` | `reverb.mix` | `0..=1` |
| `ReverbDiffusion` | `"reverbDiffusion"` | `reverb.diffusion` | `0..=1` |
| `ReverbDecay` | `"reverbDecay"` | `reverb.decay` | `0..=1` |
| `ReverbBrightnessHz` | `"reverbBrightnessHz"` | `reverb.brightness_hz` | `80..=20000` Hz |

## Lifecycle

![The processor lifecycle: construction, process calls, drain and reset](docs/images/lifecycle.svg)
Expand Down Expand Up @@ -552,6 +597,12 @@ example, this event changes the final gain before the first frame:
{ offset: 0, event: { type: "outputGain", value: 0.5 } }
```

A scalar parameter event nests a `ParameterControl` object:

```ts
{ offset: 0, event: { type: "parameter", value: { type: "dryMix", value: 0.25 } } }
```

A harmony Note On event has this form:

```ts
Expand Down
5 changes: 5 additions & 0 deletions scripts/normalize-jsdoc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ const EXACT_REPLACEMENTS = [
["[`HarmonyScale`]", "`HarmonyScale`"],
["[`Feedback`]", "`Feedback`"],
["[`HarmonyConfig`]", "`HarmonyConfig`"],
[
"[`ControlEvent::Parameter`]",
'`{ type: "parameter", value }` in `ControlEvent`',
],
["[`Self::Parameter`]", '`{ type: "parameter", value }`'],
["[`Self::I`]", '`"i"`'],
["[`Self::Echo`]", '`"echo"`'],
["[`ReverbMode::Echo`]", '`"echo"`'],
Expand Down
23 changes: 21 additions & 2 deletions scripts/verify-pack.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,14 @@ function verifyRuntimeImport(consumerDir, packageName) {
" const input = new Int16Array(128);",
" const left = new Int16Array(128);",
" const right = new Int16Array(128);",
" processor.process(input, left, right);",
' processor.process(input, left, right, [',
' { offset: 0, event: { type: "parameter", value: { type: "dryMix", value: 0.25 } } },',
' { offset: 0, event: { type: "parameter", value: { type: "humanize", value: 0.5 } } },',
' { offset: 0, event: { type: "parameter", value: { type: "flexTune", value: 0.25 } } },',
" ]);",
" assert.equal(processor.config().resynthesis.dryMix, 0.25);",
" assert.equal(processor.config().resynthesis.correction.humanize, 0.5);",
" assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);",
"} finally {",
" processor.free();",
"}",
Expand Down Expand Up @@ -724,6 +731,8 @@ function verifyTypeDeclarations(consumerDir, packageName) {
" Tunelet,",
" TuneletAudioViews,",
" type ControlActivity,",
" type ControlEvent,",
" type ParameterControl,",
" type ProcessorConfig,",
" type ResynthesisConfig,",
" type SyncInitInput as RootSyncInitInput,",
Expand All @@ -732,6 +741,7 @@ function verifyTypeDeclarations(consumerDir, packageName) {
" initSync as wasmInitSync,",
" type InitInput,",
" type InitOutput,",
" type ParameterControl as WasmParameterControl,",
" type SyncInitInput,",
`} from ${wasmLiteral};`,
"",
Expand Down Expand Up @@ -816,7 +826,15 @@ function verifyTypeDeclarations(consumerDir, packageName) {
" processor.processMono(input, [",
' { offset: 0, event: { type: "resynthesis", value: resynthesisUpdate } },',
" ]);",
" processor.process(input, left, right);",
' const dryMixParameter: ParameterControl & WasmParameterControl = { type: "dryMix", value: 0.25 };',
' const humanizeParameter: ParameterControl & WasmParameterControl = { type: "humanize", value: 0.5 };',
' const flexTuneParameter: ParameterControl & WasmParameterControl = { type: "flexTune", value: 0.25 };',
' const parameterEvent: ControlEvent = { type: "parameter", value: dryMixParameter };',
" processor.process(input, left, right, [",
" { offset: 0, event: parameterEvent },",
' { offset: 0, event: { type: "parameter", value: humanizeParameter } },',
' { offset: 0, event: { type: "parameter", value: flexTuneParameter } },',
" ]);",
" processor.beginDrain();",
" const drained: number = processor.drain(left, right);",
" const drainedMono: number = processor.drainMono(input);",
Expand All @@ -826,6 +844,7 @@ function verifyTypeDeclarations(consumerDir, packageName) {
" processor.processF32(inputF32, leftF32, rightF32);",
" processor.processF32(inputF32, leftF32, rightF32, [",
' { offset: 0, event: { type: "outputGain", value: 1 } },',
" { offset: 0, event: parameterEvent },",
" ]);",
" processor.processMonoF32(inputF32);",
" processor.beginDrain();",
Expand Down
128 changes: 110 additions & 18 deletions src/effects/punch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,19 +90,41 @@ impl PunchConfig {
/// Returns the first [`Error::InvalidConfig`] with its dotted field path
/// and the problem.
pub fn validate(self) -> Result<(), Error> {
check_range("punch.gain_db", self.gain_db, -96.0, 12.0)?;
check_range("punch.impact", self.impact, 0.0, 1.0)?;
check_range("punch.ceiling_db", self.ceiling_db, -96.0, 0.0)?;
check_range("punch.attack_ms", self.attack_ms, 0.01, 5000.0)
validate_gain_db(self.gain_db)?;
validate_impact(self.impact)?;
validate_ceiling_db(self.ceiling_db)?;
validate_attack_ms(self.attack_ms)
}
}

/// Checks the range of the input gain of Punch.
pub(crate) fn validate_gain_db(gain_db: f32) -> Result<(), Error> {
check_range("punch.gain_db", gain_db, -96.0, 12.0)
}

/// Checks the range of the transient emphasis of Punch.
pub(crate) fn validate_impact(impact: f32) -> Result<(), Error> {
check_range("punch.impact", impact, 0.0, 1.0)
}

/// Checks the range of the output ceiling of Punch.
pub(crate) fn validate_ceiling_db(ceiling_db: f32) -> Result<(), Error> {
check_range("punch.ceiling_db", ceiling_db, -96.0, 0.0)
}

/// Checks the range of the attack half-life of Punch.
pub(crate) fn validate_attack_ms(attack_ms: f32) -> Result<(), Error> {
check_range("punch.attack_ms", attack_ms, 0.01, 5000.0)
}

/// Two peak followers that control an arctangent saturator, with all buffers
/// inline.
#[derive(Debug)]
pub(crate) struct Punch {
/// The prepared rate, which converts the envelope times to sample counts.
rate: SampleRate,
/// The validated controls that set the quantized coefficients.
config: PunchConfig,
/// The number of frames in the 6 ms peak-hold window at `rate`.
hold_frames: usize,
/// The write offset into the leaf half of `hold_tree`.
Expand Down Expand Up @@ -134,23 +156,25 @@ impl Punch {
/// settings.
pub(crate) fn new(rate: SampleRate, config: PunchConfig) -> Self {
let hold_frames = (rate.as_u32() as usize * HOLD_MS).div_ceil(1000);
let fast_decay = Q30::from_f64(envelope_decay(FAST_RELEASE_MS, rate.hz() as f64, 1));
let drive_decay = Q30::from_f64(envelope_decay(DRIVE_SMOOTH_MS, rate.hz() as f64, 1));
let mut result = Self {
rate,
config,
hold_frames,
hold_cursor: 0,
hold_tree: [Q28::ZERO; MAX_HOLD_FRAMES * 2],
slow: Q28::ZERO,
fast: Q28::ZERO,
slow_decay: Q30::ZERO,
fast_decay: Q30::ZERO,
fast_decay,
attack_decay: Q30::ZERO,
drive_decay,
gain: Q28::ONE,
ceiling_gain: Q28::ONE,
drive: BASE_DRIVE,
};
result.set_config(config);
result.configure_all();
result.reset();
result
}
Expand All @@ -171,21 +195,89 @@ impl Punch {
let out = ceiling * two_over_pi * (drive * env / ceiling).atan();
(out / env) as f32
}
/// Calculates the quantized controls again, and keeps the envelopes and
/// the current drive.
/// Quantizes a per-sample decay half-life in milliseconds.
fn decay(&self, milliseconds: f64) -> Q30 {
Q30::from_f64(envelope_decay(milliseconds, self.rate.hz() as f64, 1))
}
/// Updates the release coefficient of the adaptive follower.
fn configure_impact(&mut self) {
let impact = coefficient_to_exp_value(1.0, 250.0, 5000.0, 1.0 - self.config.impact);
self.slow_decay = self.decay(impact as f64);
}
/// Updates the shared attack coefficient of the two followers.
fn configure_attack_ms(&mut self) {
self.attack_decay = self.decay(self.config.attack_ms as f64);
}
/// Updates the quantized input gain.
fn configure_gain_db(&mut self) {
self.gain = Q28::from_f64(db_to_gain(self.config.gain_db as f64));
}
/// Updates the quantized output ceiling.
fn configure_ceiling_db(&mut self) {
self.ceiling_gain =
Q28::from_f64(db_to_gain(self.config.ceiling_db as f64)).max(Q28::from_bits(1));
}
/// 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();
}
/// Calculates the changed quantized controls again, and keeps the
/// envelopes and the current drive.
///
/// The processor controls the bypass. This stage never reads an enabled
/// flag.
pub(crate) fn set_config(&mut self, config: PunchConfig) {
let impact = coefficient_to_exp_value(1.0, 250.0, 5000.0, 1.0 - config.impact);
let decay = |milliseconds: f64| {
Q30::from_f64(envelope_decay(milliseconds, self.rate.hz() as f64, 1))
};
self.slow_decay = decay(impact as f64);
self.fast_decay = decay(FAST_RELEASE_MS);
self.attack_decay = decay(config.attack_ms as f64);
self.gain = Q28::from_f64(db_to_gain(config.gain_db as f64));
self.ceiling_gain =
Q28::from_f64(db_to_gain(config.ceiling_db as f64)).max(Q28::from_bits(1));
let old = self.config;
self.config = config;
if old.impact != config.impact {
self.configure_impact();
}
if old.attack_ms != config.attack_ms {
self.configure_attack_ms();
}
if old.gain_db != config.gain_db {
self.configure_gain_db();
}
if old.ceiling_db != config.ceiling_db {
self.configure_ceiling_db();
}
}
/// Stores the input gain. If the value changed, quantizes it again.
pub(crate) fn set_gain_db(&mut self, gain_db: f32) {
let changed = self.config.gain_db != gain_db;
self.config.gain_db = gain_db;
if changed {
self.configure_gain_db();
}
}
/// Stores the transient emphasis. If the value changed, updates the
/// release coefficient.
pub(crate) fn set_impact(&mut self, impact: f32) {
let changed = self.config.impact != impact;
self.config.impact = impact;
if changed {
self.configure_impact();
}
}
/// Stores the output ceiling. If the value changed, quantizes it again.
pub(crate) fn set_ceiling_db(&mut self, ceiling_db: f32) {
let changed = self.config.ceiling_db != ceiling_db;
self.config.ceiling_db = ceiling_db;
if changed {
self.configure_ceiling_db();
}
}
/// Stores the attack half-life. If the value changed, updates the attack
/// coefficient.
pub(crate) fn set_attack_ms(&mut self, attack_ms: f32) {
let changed = self.config.attack_ms != attack_ms;
self.config.attack_ms = attack_ms;
if changed {
self.configure_attack_ms();
}
}
/// Clears the peak hold and both envelopes, then sets the drive from the
/// base drive and the input gain.
Expand Down
Loading
Loading