sim-lib-sound-core 0.2.0

Sound-domain frequency, envelope, partial, spectrum, tone, and sample models.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use std::ops::Add;
use std::time::Duration;

use sim_lib_pitch_core::Pitch;
use thiserror::Error;

/// Error raised when sound primitives are constructed with invalid values.
#[derive(Debug, Error, Clone, PartialEq)]
pub enum SoundCoreError {
    /// A frequency was zero, negative, or non-finite.
    #[error("frequency must be positive")]
    InvalidFrequency,
    /// An amplitude was negative or non-finite.
    #[error("amplitude must be non-negative")]
    InvalidAmplitude,
    /// A phase was non-finite.
    #[error("phase must be finite")]
    InvalidPhase,
    /// A partial tag carried an invalid kind/index combination.
    #[error("partial tag is invalid")]
    InvalidPartialTag,
    /// An envelope sustain level fell outside the `0.0..=1.0` range.
    #[error("envelope sustain must be between 0.0 and 1.0")]
    InvalidSustain,
    /// A tone duration was zero.
    #[error("tone duration must be positive")]
    InvalidDuration,
    /// A tone was built without any partials.
    #[error("tone must contain at least one partial")]
    EmptyPartials,
    /// A time-stretch factor was zero, negative, or non-finite.
    #[error("time-stretch factor must be positive")]
    InvalidStretch,
}

/// A positive frequency in hertz.
///
/// # Examples
///
/// ```
/// use sim_lib_sound_core::Frequency;
///
/// let a4 = Frequency::new(440.0).unwrap();
/// let a5 = Frequency::new(880.0).unwrap();
/// assert!((a5.cents_above(a4) - 1200.0).abs() < 1e-9);
/// assert!(Frequency::new(0.0).is_err());
/// ```
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Frequency(pub f64);

impl Frequency {
    /// Builds a frequency, returning [`SoundCoreError::InvalidFrequency`] when
    /// `hz` is not a positive, finite value.
    pub fn new(hz: f64) -> Result<Self, SoundCoreError> {
        if hz.is_finite() && hz > 0.0 {
            Ok(Self(hz))
        } else {
            Err(SoundCoreError::InvalidFrequency)
        }
    }

    /// Returns the linear ratio of this frequency to `other`.
    pub fn ratio(self, other: Frequency) -> f64 {
        self.0 / other.0
    }

    /// Returns the interval from `other` to this frequency, measured in cents.
    pub fn cents_above(self, other: Frequency) -> f64 {
        1200.0 * self.ratio(other).log2()
    }

    /// Returns this frequency shifted by `cents` (positive raises, negative
    /// lowers).
    pub fn shift_cents(self, cents: f64) -> Frequency {
        Frequency(self.0 * 2.0_f64.powf(cents / 1200.0))
    }
}

/// A non-negative linear amplitude.
///
/// # Examples
///
/// ```
/// use sim_lib_sound_core::Amplitude;
///
/// let unity = Amplitude::from_db(0.0);
/// assert!((unity.0 - 1.0).abs() < 1e-9);
/// assert!(Amplitude::new(-1.0).is_err());
/// ```
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Amplitude(pub f64);

impl Amplitude {
    /// Builds an amplitude, returning [`SoundCoreError::InvalidAmplitude`] when
    /// `linear` is negative or non-finite.
    pub fn new(linear: f64) -> Result<Self, SoundCoreError> {
        if linear.is_finite() && linear >= 0.0 {
            Ok(Self(linear))
        } else {
            Err(SoundCoreError::InvalidAmplitude)
        }
    }

    /// Builds an amplitude from a decibel value relative to unity gain.
    pub fn from_db(db: f64) -> Self {
        Self(10f64.powf(db / 20.0))
    }

    /// Returns this amplitude expressed in decibels relative to unity gain.
    pub fn to_db(self) -> f64 {
        20.0 * self.0.log10()
    }
}

/// A phase angle in radians.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct Phase(pub f64);

impl Phase {
    /// Builds a phase, rejecting non-finite values and normalizing the angle
    /// into the `0.0..TAU` range.
    pub fn new(radians: f64) -> Result<Self, SoundCoreError> {
        if radians.is_finite() {
            Ok(Self(radians).normalized())
        } else {
            Err(SoundCoreError::InvalidPhase)
        }
    }

    /// Returns this phase wrapped into the `0.0..TAU` range.
    pub fn normalized(self) -> Self {
        let tau = std::f64::consts::TAU;
        Self(self.0.rem_euclid(tau))
    }
}

/// Stable semantic source tag for a tone partial.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum PartialTag {
    /// The source or fundamental component.
    Source,
    /// The `n`th overtone harmonic above the source. The first harmonic is the
    /// fundamental itself.
    Harmonic(u32),
    /// The `n`th undertone below the source.
    Undertone(u32),
}

impl PartialTag {
    /// Builds a harmonic tag, rejecting zero as an invalid harmonic index.
    pub fn harmonic(index: u32) -> Result<Self, SoundCoreError> {
        if index > 0 {
            Ok(Self::Harmonic(index))
        } else {
            Err(SoundCoreError::InvalidPartialTag)
        }
    }

    /// Builds an undertone tag, rejecting zero as an invalid undertone index.
    pub fn undertone(index: u32) -> Result<Self, SoundCoreError> {
        if index > 0 {
            Ok(Self::Undertone(index))
        } else {
            Err(SoundCoreError::InvalidPartialTag)
        }
    }

    fn validate(self) -> Result<Self, SoundCoreError> {
        match self {
            Self::Source => Ok(self),
            Self::Harmonic(index) | Self::Undertone(index) if index > 0 => Ok(self),
            Self::Harmonic(_) | Self::Undertone(_) => Err(SoundCoreError::InvalidPartialTag),
        }
    }
}

/// A single sinusoidal component of a tone.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Partial {
    /// Frequency of the component.
    pub frequency: Frequency,
    /// Linear amplitude of the component.
    pub amplitude: Amplitude,
    /// Starting phase of the component.
    pub phase: Phase,
    /// Semantic source of the component within a tone.
    pub tag: PartialTag,
}

impl Partial {
    /// Builds a validated partial, normalizing the phase and rejecting invalid
    /// frequency or amplitude values.
    pub fn new(
        frequency: Frequency,
        amplitude: Amplitude,
        phase: Phase,
    ) -> Result<Self, SoundCoreError> {
        Self::tagged(frequency, amplitude, phase, PartialTag::Source)
    }

    /// Builds a validated tagged partial, normalizing the phase and rejecting
    /// invalid frequency, amplitude, phase, or tag values.
    pub fn tagged(
        frequency: Frequency,
        amplitude: Amplitude,
        phase: Phase,
        tag: PartialTag,
    ) -> Result<Self, SoundCoreError> {
        let _ = Frequency::new(frequency.0)?;
        let _ = Amplitude::new(amplitude.0)?;
        let phase = Phase::new(phase.0)?;
        let tag = tag.validate()?;
        Ok(Self {
            frequency,
            amplitude,
            phase,
            tag,
        })
    }
}

/// The interpolation curve applied across an [`Envelope`].
#[derive(Clone, Debug, PartialEq)]
pub enum EnvelopeShape {
    /// Straight-line segments between envelope stages.
    Linear,
    /// Linear segments raised to the given exponent for a curved response.
    Exponential(f64),
    /// A named custom shape, treated as linear by the built-in sampler.
    Custom(String),
}

/// An attack/decay/sustain/release amplitude envelope.
#[derive(Clone, Debug, PartialEq)]
pub struct Envelope {
    /// Time taken to rise from silence to full level.
    pub attack: Duration,
    /// Time taken to fall from full level to the sustain level.
    pub decay: Duration,
    /// Held level during the sustain phase, in `0.0..=1.0`.
    pub sustain: f64,
    /// Time taken to fall from the sustain level back to silence.
    pub release: Duration,
    /// Interpolation curve applied across the stages.
    pub shape: EnvelopeShape,
}

impl Envelope {
    /// Builds an envelope, returning [`SoundCoreError::InvalidSustain`] when
    /// `sustain` falls outside `0.0..=1.0`.
    pub fn new(
        attack: Duration,
        decay: Duration,
        sustain: f64,
        release: Duration,
        shape: EnvelopeShape,
    ) -> Result<Self, SoundCoreError> {
        if !sustain.is_finite() || !(0.0..=1.0).contains(&sustain) {
            return Err(SoundCoreError::InvalidSustain);
        }
        Ok(Self {
            attack,
            decay,
            sustain,
            release,
            shape,
        })
    }

    /// Returns the envelope level in `0.0..=1.0` at elapsed time `t` for a tone
    /// of length `total`.
    pub fn sample_level(&self, t: Duration, total: Duration) -> f64 {
        let elapsed = t.as_secs_f64();
        let attack = self.attack.as_secs_f64();
        let decay = self.decay.as_secs_f64();
        let release = self.release.as_secs_f64();
        let total_secs = total.as_secs_f64();
        let release_start = (total_secs - release).max(0.0);
        match &self.shape {
            EnvelopeShape::Linear | EnvelopeShape::Custom(_) => {
                if attack > 0.0 && elapsed < attack {
                    elapsed / attack
                } else if decay > 0.0 && elapsed < attack + decay {
                    let progress = (elapsed - attack) / decay;
                    1.0 + (self.sustain - 1.0) * progress
                } else if elapsed < release_start {
                    self.sustain
                } else if release > 0.0 && elapsed <= total_secs {
                    let progress = ((elapsed - release_start) / release).clamp(0.0, 1.0);
                    self.sustain * (1.0 - progress)
                } else {
                    0.0
                }
            }
            EnvelopeShape::Exponential(curve) => {
                let base = self.clone().with_shape(EnvelopeShape::Linear);
                base.sample_level(t, total).powf((*curve).max(0.01))
            }
        }
    }

    fn with_shape(mut self, shape: EnvelopeShape) -> Self {
        self.shape = shape;
        self
    }
}

/// A complete tone: a set of [`Partial`]s shaped by an [`Envelope`] over a
/// fixed duration.
#[derive(Clone, Debug, PartialEq)]
pub struct Tone {
    /// Sinusoidal components that sum to form the tone.
    pub partials: Vec<Partial>,
    /// Amplitude envelope applied across the tone.
    pub envelope: Envelope,
    /// Total sounding length of the tone.
    pub duration: Duration,
}

impl Tone {
    /// Builds a pure sine tone at `frequency` with the default envelope.
    pub fn sine(frequency: Frequency, duration: Duration) -> Self {
        Self::from_partials(
            vec![Partial {
                frequency,
                amplitude: Amplitude(1.0),
                phase: Phase(0.0),
                tag: PartialTag::Source,
            }],
            default_envelope(),
            duration,
        )
        .expect("sine tone is valid")
    }

    /// Builds a sawtooth tone from `partials` harmonics with `1/n` amplitudes.
    pub fn sawtooth(frequency: Frequency, duration: Duration, partials: usize) -> Self {
        Self::harmonic_series(frequency, duration, partials, |n| 1.0 / n as f64, |_| true)
    }

    /// Builds a square tone from the odd harmonics within `partials`, with
    /// `1/n` amplitudes.
    pub fn square(frequency: Frequency, duration: Duration, partials: usize) -> Self {
        Self::harmonic_series(
            frequency,
            duration,
            partials,
            |n| 1.0 / n as f64,
            |n| n % 2 == 1,
        )
    }

    /// Builds a triangle tone from the odd harmonics within `partials`, with
    /// `1/n^2` amplitudes.
    pub fn triangle(frequency: Frequency, duration: Duration, partials: usize) -> Self {
        Self::harmonic_series(
            frequency,
            duration,
            partials,
            |n| 1.0 / ((n * n) as f64),
            |n| n % 2 == 1,
        )
    }

    /// Builds a tone from explicit partials, rejecting empty partial lists,
    /// zero durations, and invalid component values.
    pub fn from_partials(
        partials: Vec<Partial>,
        envelope: Envelope,
        duration: Duration,
    ) -> Result<Self, SoundCoreError> {
        if duration.is_zero() {
            return Err(SoundCoreError::InvalidDuration);
        }
        if partials.is_empty() {
            return Err(SoundCoreError::EmptyPartials);
        }
        let partials = partials
            .into_iter()
            .map(|partial| {
                Partial::tagged(
                    partial.frequency,
                    partial.amplitude,
                    partial.phase,
                    partial.tag,
                )
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self {
            partials,
            envelope,
            duration,
        })
    }

    /// Returns the tone with every partial shifted by `cents`.
    pub fn transpose_cents(mut self, cents: f64) -> Self {
        for partial in &mut self.partials {
            partial.frequency = partial.frequency.shift_cents(cents);
        }
        self
    }

    /// Returns the tone with every partial amplitude scaled by `gain`.
    pub fn amplify(mut self, gain: f64) -> Self {
        for partial in &mut self.partials {
            partial.amplitude = Amplitude(partial.amplitude.0 * gain);
        }
        self
    }

    /// Returns the tone with its duration and envelope stages scaled by
    /// `factor`, rejecting non-positive factors.
    pub fn time_stretch(mut self, factor: f64) -> Result<Self, SoundCoreError> {
        if !factor.is_finite() || factor <= 0.0 {
            return Err(SoundCoreError::InvalidStretch);
        }
        self.duration = Duration::from_secs_f64(self.duration.as_secs_f64() * factor);
        self.envelope.attack = Duration::from_secs_f64(self.envelope.attack.as_secs_f64() * factor);
        self.envelope.decay = Duration::from_secs_f64(self.envelope.decay.as_secs_f64() * factor);
        self.envelope.release =
            Duration::from_secs_f64(self.envelope.release.as_secs_f64() * factor);
        Ok(self)
    }

    fn harmonic_series(
        frequency: Frequency,
        duration: Duration,
        partial_count: usize,
        amp: impl Fn(usize) -> f64,
        include: impl Fn(usize) -> bool,
    ) -> Self {
        let partials = (1..=partial_count.max(1))
            .filter(|n| include(*n))
            .map(|n| Partial {
                frequency: Frequency(frequency.0 * n as f64),
                amplitude: Amplitude(amp(n)),
                phase: Phase(0.0),
                tag: PartialTag::Harmonic(n as u32),
            })
            .collect();
        Self::from_partials(partials, default_envelope(), duration)
            .expect("harmonic-series tone is valid")
    }
}

impl Add for Tone {
    type Output = Self;

    fn add(mut self, other: Self) -> Self::Output {
        self.partials.extend(other.partials);
        self.duration = self.duration.max(other.duration);
        self
    }
}

/// Returns a general-purpose default envelope (short attack and decay, high
/// sustain, moderate release, linear shape).
pub fn default_envelope() -> Envelope {
    Envelope::new(
        Duration::from_millis(10),
        Duration::from_millis(50),
        0.8,
        Duration::from_millis(100),
        EnvelopeShape::Linear,
    )
    .expect("default envelope is valid")
}

/// Returns the 12-tone equal-temperament frequency of `pitch`, with A4 (MIDI
/// 69) anchored at 440 Hz.
pub fn equal_temperament_frequency(pitch: Pitch) -> Frequency {
    let semitones = pitch.semitone() - 69;
    Frequency(440.0 * 2.0_f64.powf(semitones as f64 / 12.0))
}