Skip to content
Closed
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
44 changes: 28 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,10 @@ 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. Scalar events
(`RetuneMs`, `PitchRatio`, `FormantShift`, `DryMix`, `ReverbMix` and
`OutputGain`) change only their target fields. Between blocks, use
`processor.update_config` or `processor.set_config`.

Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses
`ControlEvent::CorrectionMidi`. For example, this event starts a harmony note
Expand Down Expand Up @@ -418,7 +420,7 @@ page that opens the JavaScript.
| Shared initialization | `loadTunelet(source?)` |
| Mono PCM to planar stereo | `process(input, left, right, events?)` |
| In-place mono downmix | `processMono(audio, events?)` |
| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` |
| Configuration | `config()`, `setConfig(config)`, `updateConfig(patch)`, `defaultConfig()` |
| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` |
| Feedback | `feedback()`, `takeFeedback()` |
| Telemetry | `telemetry()`, `takeTelemetry()` |
Expand All @@ -443,18 +445,23 @@ audio device.

### Configuration objects

Configuration objects contain all required fields. They use camelCase names
and show enums as string literals. To change the configuration, do these steps:
`config()` and `defaultConfig()` return a complete `ProcessorConfig` object.
Field names use camelCase, and enums use string literals. The constructor and
`updateConfig(patch)` accept a `DeepPartial<ProcessorConfig>`:

1. Start from `defaultConfig()` or `config()`.
2. Edit the necessary fields.
3. Call `setConfig()`.
- In `new Tunelet(sampleRate, maxBlockFrames, config?)`, omitted or
`undefined` fields use their default values.
- In `updateConfig(patch)`, omitted or `undefined` fields keep their active
values from `config()`.
- `setConfig(config)` replaces the full configuration, and omitted or
`undefined` fields use their default values.
- Fixed-size arrays (`notes`, `chromaticIntervals` and `diatonicIntervals`)
replace the full array.

If a required field is absent or a value is not valid, the call throws a
JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults
to 4 if it is absent. The conversion ignores extra object properties. The
generated declarations contain the parameter documentation from the Rust
types.
If a field is `null`, has the wrong type or is out of range, the call throws a
JavaScript `Error` before the state changes. The conversion ignores extra
object properties. The generated declarations contain the parameter
documentation from the Rust types.

`resynthesis.randomSeed` and the `processedFrames` field of feedback and
telemetry use `bigint`. Frame offsets, block lengths and latency use
Expand All @@ -463,14 +470,19 @@ 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. The reset control has no payload. Scalar
controls (`retuneMs`, `pitchRatio`, `formantShift`, `dryMix`, `reverbMix` and
`outputGain`) change only their target fields. For example, these events
change the final gain and the formant shape before the first frame:

```ts
{ offset: 0, event: { type: "outputGain", value: 0.5 } }
{ offset: 0, event: { type: "formantShift", value: { width: 1.1, stretch: 0.9 } } }
```

A harmony Note On event has this form:
A stage control (`configure`, `resynthesis`, `punch`, `warm`, `alien` or
`reverb`) replaces that stage, and omitted fields use the stage defaults. A
harmony Note On event has this form:

```ts
{ offset: 0, event: { type: "midi", value: { type: "noteOn", channel: 0, note: 60, velocity: 100 } } }
Expand Down
9 changes: 5 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,15 @@ impl PrepareConfig {
/// configuration does active pitch processing. It is not a bypass with zero
/// latency.
///
/// Change a copy, then apply it with [`crate::Processor::set_config`] or
/// [`crate::ControlEvent::Configure`]. The validation examines all fields
/// before a change has an effect. This includes the fields of disabled stages.
/// Change a copy, then apply it with [`crate::Processor::set_config`],
/// [`crate::Processor::update_config`] or [`crate::ControlEvent::Configure`].
/// The validation examines all fields before a change has an effect. This
/// includes the fields of disabled stages.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase"),
tsify(large_number_types_as_bigints)
)]
Expand Down
2 changes: 1 addition & 1 deletion src/effects/alien.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const FADE_FRAMES: usize = 200;
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct AlienConfig {
Expand Down
2 changes: 1 addition & 1 deletion src/effects/punch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const TWO_OVER_PI: Q14 = Q14::from_bits(10430);
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct PunchConfig {
Expand Down
11 changes: 9 additions & 2 deletions src/effects/reverb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub enum ReverbMode {
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct ReverbConfig {
Expand Down Expand Up @@ -108,13 +108,20 @@ impl ReverbConfig {
/// Returns the first [`Error::InvalidConfig`] with its dotted field path
/// and the problem.
pub fn validate(self) -> Result<(), Error> {
check_range("reverb.mix", self.mix, 0.0, 1.0)?;
validate_reverb_mix(self.mix)?;
check_range("reverb.diffusion", self.diffusion, 0.0, 1.0)?;
check_range("reverb.decay", self.decay, 0.0, 1.0)?;
check_range("reverb.brightness_hz", self.brightness_hz, 80.0, 20000.0)
}
}

/// Checks the wet fraction range of the reverb.
///
/// `ReverbConfig` and `ControlEvent::ReverbMix` use the same range.
pub(crate) fn validate_reverb_mix(mix: f32) -> Result<(), Error> {
check_range("reverb.mix", mix, 0.0, 1.0)
}

/// The shared Q14 delay network with two low-pass damping filters that keep
/// state.
#[derive(Debug)]
Expand Down
2 changes: 1 addition & 1 deletion src/effects/warm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const WINDOW_FRAMES: usize = 100;
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct WarmConfig {
Expand Down
44 changes: 41 additions & 3 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@
use crate::config::validate_output_gain;
use crate::effects::alien::AlienConfig;
use crate::effects::punch::PunchConfig;
use crate::effects::reverb::ReverbConfig;
use crate::effects::reverb::{validate_reverb_mix, ReverbConfig};
use crate::effects::warm::WarmConfig;
use crate::formant::validate_formant_shift;
use crate::midi::MidiEvent;
use crate::resynthesis::{validate_dry_mix, validate_pitch_ratio, validate_retune_ms};
use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig};

/// A configuration or MIDI control that applies before a frame in the block.
///
/// Give controls to a process call as [`TimedEvent`] values. The call borrows
/// the slice only for that call. There is no heap allocation and no deferred
/// queue. A stage event replaces all settings of that stage. To change one
/// field, start from the current configuration of the processor.
/// queue. A stage event replaces all settings of that stage. Scalar events
/// change only their target fields in the active configuration.
/// Configuration changes have the same effects on state as
/// [`crate::Processor::set_config`].
#[derive(Clone, Copy, Debug, PartialEq)]
Expand All @@ -35,6 +37,37 @@ pub enum ControlEvent {
Alien(AlienConfig),
/// This event replaces the reverb configuration.
Reverb(ReverbConfig),
/// This event sets the retune half-life in milliseconds, 0..=400.
///
/// The target behavior is the same as for
/// [`CorrectionConfig::retune_ms`](crate::CorrectionConfig::retune_ms).
/// The value must be finite.
RetuneMs(f32),
/// This event sets the pitch multiplier, 0.25..=4.
///
/// The filter and voice behavior is the same as for
/// [`ResynthesisConfig::pitch_ratio`]. The value must be finite.
PitchRatio(f32),
/// This event sets the vocal-tract width and length factors.
///
/// The synthesis behavior is the same as for
/// [`FormantConfig`](crate::FormantConfig). Both values must be finite.
FormantShift {
/// The vocal-tract width factor, 0.5..=2.
width: f32,
/// The vocal-tract length factor, 0.5..=2.
stretch: f32,
},
/// This event sets the dry fraction at the resynthesis stage, 0..=1.
///
/// The quantization and the delay are the same as for
/// [`ResynthesisConfig::dry_mix`]. The value must be finite.
DryMix(f32),
/// This event sets the wet fraction of the reverb stage, 0..=1.
///
/// The quantization and the dry weight are the same as for
/// [`ReverbConfig::mix`]. The value must be finite.
ReverbMix(f32),
/// This event sets the final linear gain, 0..=64.
///
/// The quantization and the mute behavior are the same as for
Expand Down Expand Up @@ -80,6 +113,11 @@ impl ControlEvent {
Self::Warm(config) => config.validate(),
Self::Alien(config) => config.validate(),
Self::Reverb(config) => config.validate(),
Self::RetuneMs(retune_ms) => validate_retune_ms(retune_ms),
Self::PitchRatio(pitch_ratio) => validate_pitch_ratio(pitch_ratio),
Self::FormantShift { width, stretch } => validate_formant_shift(width, stretch),
Self::DryMix(dry_mix) => validate_dry_mix(dry_mix),
Self::ReverbMix(mix) => validate_reverb_mix(mix),
Self::OutputGain(gain) => validate_output_gain(gain),
Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(),
Self::Reset => Ok(()),
Expand Down
13 changes: 10 additions & 3 deletions src/formant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use crate::{Error, SampleRate};
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct FormantConfig {
Expand Down Expand Up @@ -95,15 +95,22 @@ impl FormantConfig {
/// Returns the first [`Error::InvalidConfig`], with the dotted path of the
/// field and the problem.
pub fn validate(self) -> Result<(), Error> {
check_range("resynthesis.formant.width", self.width, 0.5, 2.0)?;
check_range("resynthesis.formant.stretch", self.stretch, 0.5, 2.0)?;
validate_formant_shift(self.width, self.stretch)?;
let field = "resynthesis.formant.aspiration_mix";
check_range(field, self.aspiration_mix, 0.0, 1.0)?;
let field = "resynthesis.formant.aspiration_cutoff_hz";
check_range(field, self.aspiration_cutoff_hz, 500.0, 10000.0)
}
}

/// Checks the formant width and stretch ranges.
///
/// `FormantConfig` and `ControlEvent::FormantShift` use the same ranges.
pub(crate) fn validate_formant_shift(width: f32, stretch: f32) -> Result<(), Error> {
check_range("resynthesis.formant.width", width, 0.5, 2.0)?;
check_range("resynthesis.formant.stretch", stretch, 0.5, 2.0)
}

/// The number of frames of input history for analysis and synthesis. The
/// value is equal to the resynthesis history length.
pub(crate) const HISTORY_FRAMES: usize = 11568;
Expand Down
14 changes: 2 additions & 12 deletions src/harmony.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ pub enum Inversion {
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct HarmonyConfig {
Expand Down Expand Up @@ -322,20 +322,10 @@ pub struct HarmonyConfig {
/// other voices release with the usual gain envelope. The chord and MIDI
/// sources ignore this field. In JavaScript, the field is optional and
/// a missing value gives the default.
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
serde(default = "default_voices"),
tsify(optional)
)]
#[cfg_attr(all(feature = "wasm", target_arch = "wasm32"), tsify(optional))]
pub voices: u8,
}

/// The default count of interval voices: all of them.
#[cfg(all(feature = "wasm", target_arch = "wasm32"))]
fn default_voices() -> u8 {
HARMONY_VOICES as u8
}

impl Default for HarmonyConfig {
fn default() -> Self {
Self {
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
* `initSync` and the configuration, event and feedback types.
*/
import init from "../pkg/tunelet.js";
import type { InitInput, InitOutput } from "../pkg/tunelet.js";
import type { DeepPartial, InitInput, InitOutput } from "../pkg/tunelet.js";

export * from "../pkg/tunelet.js";
export type { DeepPartial };

/** The shared initialization promise, which a failure clears. */
let initialization: Promise<InitOutput> | undefined;
Expand Down
8 changes: 4 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
//! that are not active.
//!
//! A configuration value is a copy. If you change it, the processor does not
//! change until [`Processor::set_config`] or a configuration event applies it.
//! You can change settings between blocks, or at a frame offset with a
//! [`TimedEvent`]. To change the sample rate or the block limit, you
//! must make a new processor.
//! change until [`Processor::set_config`], [`Processor::update_config`] or a
//! configuration event applies it. You can change settings between blocks, or
//! at a frame offset with a [`TimedEvent`]. To change the sample rate or the
//! block limit, you must make a new processor.
//!
//! # Audio and timed controls
//!
Expand Down
2 changes: 1 addition & 1 deletion src/pitch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::Error;
#[non_exhaustive]
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
derive(serde::Serialize, tsify::Tsify),
serde(rename_all = "camelCase")
)]
pub struct PitchConfig {
Expand Down
40 changes: 34 additions & 6 deletions src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,9 +312,9 @@ impl Processor {
/// Returns a copy of the current settings and does not change state.
///
/// If you edit the copy, nothing changes until
/// [`set_config`](Self::set_config) or a configuration event applies it.
/// The temporary aspiration mute of a drain does not change the settings
/// that this method returns.
/// [`set_config`](Self::set_config), [`update_config`](Self::update_config)
/// or a configuration event applies it. The temporary aspiration mute of a
/// drain does not change the settings that this method returns.
pub fn config(&self) -> ProcessorConfig {
self.config
}
Expand Down Expand Up @@ -477,6 +477,26 @@ impl Processor {
Ok(())
}

/// Copies the active configuration, passes it to `update`, validates all
/// fields and applies the result.
///
/// This method does not allocate memory. State retention, validation of
/// disabled stages and drain cancellation are the same as in
/// [`set_config`](Self::set_config).
///
/// # Errors
///
/// Returns [`Error::InvalidConfig`] if a field is not valid. The method
/// returns this error before it changes any state, also an active drain.
pub fn update_config(
&mut self,
update: impl FnOnce(&mut ProcessorConfig),
) -> Result<(), Error> {
let mut config = self.config;
update(&mut config);
self.set_config(config)
}

/// Applies a configuration that the public setter or the preflight checked.
fn apply_config(&mut self, config: ProcessorConfig) {
if self.config.punch != config.punch {
Expand Down Expand Up @@ -574,9 +594,9 @@ impl Processor {

/// Applies a validated control immediately before its frame is rendered.
///
/// A partial configuration event replaces one stage in the active
/// configuration. MIDI and reset events act directly. A reset does not
/// discard later events in the block.
/// Stage and scalar configuration events update the active configuration.
/// MIDI and reset events act directly. A reset does not discard later
/// events in the block.
fn apply(&mut self, event: ValidatedEvent) {
let mut config = self.config;
match event.into_inner() {
Expand All @@ -586,6 +606,14 @@ impl Processor {
ControlEvent::Warm(value) => config.warm = value,
ControlEvent::Alien(value) => config.alien = value,
ControlEvent::Reverb(value) => config.reverb = value,
ControlEvent::RetuneMs(value) => config.resynthesis.correction.retune_ms = value,
ControlEvent::PitchRatio(value) => config.resynthesis.pitch_ratio = value,
ControlEvent::FormantShift { width, stretch } => {
config.resynthesis.formant.width = width;
config.resynthesis.formant.stretch = stretch;
}
ControlEvent::DryMix(value) => config.resynthesis.dry_mix = value,
ControlEvent::ReverbMix(value) => config.reverb.mix = value,
ControlEvent::OutputGain(value) => config.output_gain = value,
ControlEvent::Midi(event) => {
self.resynthesis.apply_midi(event);
Expand Down
Loading