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
98 changes: 52 additions & 46 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,20 +97,20 @@ If you use the scoped package, import from `@bytelandtechnology/tunelet`.

```rust
use tunelet::{
CorrectionScale, NoteMask, PitchClass, PrepareConfig, Processor, ProcessorConfig,
SampleRate,
CorrectionConfig, CorrectionScale, PitchClass, PrepareConfig, Processor, ProcessorConfig,
ResynthesisConfig, SampleRate,
};

fn main() -> Result<(), tunelet::Error> {
// 1. Set the sample rate and the largest block.
let rate = SampleRate::try_from(48_000)?;
let preparation = PrepareConfig::new(rate, 1024)?;

// 2. Start from the default configuration and change fields.
let mut config = ProcessorConfig::default();
config.resynthesis.correction.notes =
NoteMask::from_key_scale(PitchClass::A, CorrectionScale::Minor);
config.resynthesis.correction.retune_ms = 20.0;
// 2. Build a configuration from presets and builders.
let correction =
CorrectionConfig::from_key_scale(PitchClass::A, CorrectionScale::Minor).with_retune_ms(20.0);
let config = ProcessorConfig::default()
.with_resynthesis(ResynthesisConfig::default().with_correction(correction));

// 3. Construct the processor. Only this step allocates memory.
let mut processor = Processor::new(preparation, config)?;
Expand All @@ -136,12 +136,12 @@ fn main() -> Result<(), tunelet::Error> {
### TypeScript

```ts
import { loadTunelet, Tunelet, defaultConfig } from "tunelet";
import { loadTunelet, Tunelet } from "tunelet";

await loadTunelet();
const config = defaultConfig();
config.resynthesis.pitchRatio = 1.25;
const processor = new Tunelet(48000, 1024, config);
const processor = new Tunelet(48000, 1024, {
resynthesis: { pitchRatio: 1.25 },
});

const input = new Int16Array(1024);
const left = new Int16Array(1024);
Expand Down Expand Up @@ -210,9 +210,10 @@ To prepare a processor, do these steps:
limit.
3. Create a `Processor` with that preparation and a `ProcessorConfig`.

Configuration structures implement `Default`. To select voices and effects,
edit their fields. To change the sample rate or the block limit, make a new
processor.
Configuration structures implement `Default`, `with_*` builders and stage
presets. To change active settings between blocks, call
`Processor::update_config` or `Processor::set_config`. To change the sample
rate or the block limit, make a new processor.

Select the process function for your output layout:

Expand Down Expand Up @@ -244,8 +245,9 @@ 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 or sub-stage event replaces all settings of that section.
`ControlEvent::Parameter` changes one parameter and keeps all other active
settings.

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 @@ -413,19 +415,20 @@ page that opens the JavaScript.

### TypeScript API

| Operation | TypeScript API |
| --------------------------------- | -------------------------------------------------------- |
| 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()` |
| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` |
| Feedback | `feedback()`, `takeFeedback()` |
| Telemetry | `telemetry()`, `takeTelemetry()` |
| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` |
| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` |
| Configured tail budget | `tailFrames()` |
| Reset or release memory | `reset()`, `free()` |
| Operation | TypeScript API |
| --------------------------------- | ---------------------------------------------------------------- |
| 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)`, `updateConfig(config)`, `defaultConfig()` |
| Scale masks and MIDI decode | `noteMaskFromKeyScale(key, scale)`, `parseMidiBytes(bytes)` |
| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` |
| Feedback | `feedback()`, `takeFeedback()` |
| Telemetry | `telemetry()`, `takeTelemetry()` |
| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` |
| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` |
| Configured tail budget | `tailFrames()` |
| Reset or release memory | `reset()`, `free()` |

### Audio buffers

Expand All @@ -443,34 +446,37 @@ 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:
Configuration objects use camelCase names and show enums as string literals.
`new Tunelet` and `updateConfig` accept `DeepPartial<ProcessorConfig>`:

1. Start from `defaultConfig()` or `config()`.
2. Edit the necessary fields.
3. Call `setConfig()`.
- In `new Tunelet` and `setConfig`, omitted fields use their defaults.
- In `updateConfig`, omitted fields keep their active values.
- `defaultConfig()` and `config()` return complete configuration snapshots.

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.
`noteMaskFromKeyScale(key, scale)` builds a 12-boolean `NoteMask` for any
`CorrectionScale` or `HarmonyScale` mode. If a field value is not valid, the
call throws a JavaScript `Error` before 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
`number`.
All numeric fields, `resynthesis.randomSeed` and `processedFrames` in feedback
and telemetry use `number`. Thus, `defaultConfig()`, `config()`, `feedback()`
and `telemetry()` work directly with `JSON.stringify`.

### 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. Stage and
sub-stage events replace that section, and `parameter` events update one field
without a `config()` copy:

```ts
{ offset: 0, event: { type: "outputGain", value: 0.5 } }
{ offset: 0, event: { type: "parameter", value: { type: "pitchRatio", value: 1.25 } } }
```

A harmony Note On event has this form:
`parseMidiBytes(bytes)` decodes a 3-byte `Uint8Array` into a `MidiEvent` or
`undefined` for unsupported valid messages, and throws an `Error` for invalid
bytes. 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
53 changes: 51 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,19 @@ impl PrepareConfig {
max_block_frames,
})
}

/// Sets the `sample_rate` and returns the preparation limits.
pub const fn with_sample_rate(mut self, sample_rate: SampleRate) -> Self {
self.sample_rate = sample_rate;
self
}

/// Sets the nonzero `max_block_frames` limit and returns the preparation
/// limits.
pub const fn with_max_block_frames(mut self, max_block_frames: NonZeroUsize) -> Self {
self.max_block_frames = max_block_frames;
self
}
}

/// The settings for the complete signal chain, in the order of the stages.
Expand All @@ -134,8 +147,7 @@ impl PrepareConfig {
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase"),
tsify(large_number_types_as_bigints)
serde(default, rename_all = "camelCase")
)]
pub struct ProcessorConfig {
/// The input dynamics and saturation stage, which applies first.
Expand Down Expand Up @@ -184,6 +196,43 @@ impl Default for ProcessorConfig {
}

impl ProcessorConfig {
/// Sets the `punch` stage configuration and returns the configuration.
pub const fn with_punch(mut self, punch: PunchConfig) -> Self {
self.punch = punch;
self
}

/// Sets the `warm` stage configuration and returns the configuration.
pub const fn with_warm(mut self, warm: WarmConfig) -> Self {
self.warm = warm;
self
}

/// Sets the `resynthesis` stage configuration and returns the
/// configuration.
pub const fn with_resynthesis(mut self, resynthesis: ResynthesisConfig) -> Self {
self.resynthesis = resynthesis;
self
}

/// Sets the `alien` stage configuration and returns the configuration.
pub const fn with_alien(mut self, alien: AlienConfig) -> Self {
self.alien = alien;
self
}

/// Sets the `reverb` stage configuration and returns the configuration.
pub const fn with_reverb(mut self, reverb: ReverbConfig) -> Self {
self.reverb = reverb;
self
}

/// Sets the final linear gain, 0..=64, and returns the configuration.
pub const fn with_output_gain(mut self, output_gain: f32) -> Self {
self.output_gain = output_gain;
self
}

/// Checks all stages and the final gain, and does not change state.
///
/// The validation uses the signal order: Punch, Warm, resynthesis, Alien,
Expand Down
29 changes: 26 additions & 3 deletions src/effects/alien.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const FADE_FRAMES: usize = 200;
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
serde(default, rename_all = "camelCase")
)]
pub struct AlienConfig {
/// Selects reversed playback instead of the direct input. The default is
Expand All @@ -36,13 +36,36 @@ pub struct AlienConfig {
}
impl Default for AlienConfig {
fn default() -> Self {
Self::new()
}
}
impl AlienConfig {
/// Returns the default disabled Alien settings.
const fn new() -> Self {
Self {
enabled: false,
loop_frames: 95_999,
}
}
}
impl AlienConfig {

/// Returns enabled Alien settings with the default loop length.
pub const fn enabled() -> Self {
Self::new().with_enabled(true)
}

/// Sets `enabled` and returns the configuration.
pub const fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}

/// Sets the loop length in frames, 1..=96000, and returns the
/// configuration.
pub const fn with_loop_frames(mut self, loop_frames: u32) -> Self {
self.loop_frames = loop_frames;
self
}

/// Validates all fields, also when Alien is disabled.
///
/// `loop_frames` must be in its documented inclusive range. Validation
Expand Down
49 changes: 46 additions & 3 deletions src/effects/punch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const TWO_OVER_PI: Q14 = Q14::from_bits(10430);
#[cfg_attr(
all(feature = "wasm", target_arch = "wasm32"),
derive(serde::Serialize, serde::Deserialize, tsify::Tsify),
serde(rename_all = "camelCase")
serde(default, rename_all = "camelCase")
)]
pub struct PunchConfig {
/// Enables this input stage. The default is `false`.
Expand Down Expand Up @@ -57,6 +57,12 @@ pub struct PunchConfig {
}
impl Default for PunchConfig {
fn default() -> Self {
Self::new()
}
}
impl PunchConfig {
/// Returns the default disabled Punch settings.
const fn new() -> Self {
Self {
enabled: false,
gain_db: 0.0,
Expand All @@ -65,8 +71,45 @@ impl Default for PunchConfig {
attack_ms: 10.0,
}
}
}
impl PunchConfig {

/// Returns enabled Punch settings with default controls.
pub const fn enabled() -> Self {
Self::new().with_enabled(true)
}

/// Sets `enabled` and returns the configuration.
pub const fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}

/// Sets the input gain in decibels, -96..=12, and returns the
/// configuration.
pub const fn with_gain_db(mut self, gain_db: f32) -> Self {
self.gain_db = gain_db;
self
}

/// Sets the transient emphasis, 0..=1, and returns the configuration.
pub const fn with_impact(mut self, impact: f32) -> Self {
self.impact = impact;
self
}

/// Sets the output ceiling in dBFS, -96..=0, and returns the
/// configuration.
pub const fn with_ceiling_db(mut self, ceiling_db: f32) -> Self {
self.ceiling_db = ceiling_db;
self
}

/// Sets the attack half-life in milliseconds, 0.01..=5000, and returns the
/// configuration.
pub const fn with_attack_ms(mut self, attack_ms: f32) -> Self {
self.attack_ms = attack_ms;
self
}

/// Validates all fields, also when Punch is disabled.
///
/// The floating-point controls must be finite and in their documented
Expand Down
Loading