twang 0.9.0

Library for pure Rust advanced audio synthesis.
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
// Copyright © 2018-2022 The Twang Contributors.
//
// Licensed under any of:
// - Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
// - Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt)
// - MIT License (https://mit-license.org/)
// At your choosing (See accompanying files LICENSE_APACHE_2_0.txt,
// LICENSE_MIT.txt and LICENSE_BOOST_1_0.txt).

//! Twang synthesis file format

use alloc::vec::Vec;
use fon::{Audio, Sink};
use fon::chan::{Channel, Ch32};

/*
/// A twang synthesis operation
enum Op {
    /// Pop last value on audio stack
    Pop,
    /// Push value onto audio stack
    Psh(Ch32),
    /// Swap by index 
    Swp(u32),
    /// Swap and pop by index
    Sap(u32),
    /// In-place oscillator transformation (in/out: frequency)
    Osc(Ch32),
    /// In-place bezier transformation (in/out: source, in:curve)
    Bez,
}

/// A synthesizer
pub struct Synth {
    // Audio stack
    stack: Vec<Chunk>,
    // Synthesis program
    ops: Vec<Op>,
}

impl Synth {
    /// Stream synthesized samples into a sink
    pub fn stream(&mut self) {
        const ONE: Ch32 = Ch32::new(1.0);

        let step = (48_000.0f32).recip();

        for op in self.ops.iter_mut() {
            match op {
                Op::Pop => { self.stack.pop(); }
                Op::Psh(ref chan) => self.stack.push(Chunk([*chan; 32])),
                Op::Swp(idx) => {
                    let tmp = self.stack.swap_remove(*idx as usize);
                    self.stack.push(tmp)
                },
                Op::Sap(idx) => { self.stack.swap_remove(*idx as usize); },
                Op::Osc(ref mut time) => {
                    let len = self.stack.len();
                    let a = self.stack.get_mut(len - 1).unwrap();
                    for rate in a.0.iter_mut() {
                        let delta = *rate * step;
                        *rate = *time;
                        *time += delta;
                    }
                }
                Op::Bez => {
                    let len = self.stack.len();
                    for i in 0..32 {
                        let curve = self.stack[len - 2].0[i];
                        let src = &mut self.stack[len - 1].0[i];
                        if src.to_f32().is_sign_negative() {
                            let v = *src + ONE;
                            *src = v - v * curve * (v - ONE) - ONE;
                        } else {
                            let w = ONE - *src;
                            *src = ONE - w + w * curve * (w - ONE);
                        }
                    }
                }
            }
        }
    }
}
*/

/// Node in the synthesis tree
#[derive(Debug)]
enum Node {
    Source(Chunk),
    Line(Value),

    WaveT(Table, Const),
    WaveC(Table, Chunk),
    WaveV(Table, Value),
    
    WaypointT(Table, Const),
    WaypointC(Table, Chunk),
    WaypointV(Table, Value),

    BezierTT(Const, Const),
    BezierTC(Const, Chunk),
    BezierTV(Const, Value),
    BezierCT(Chunk, Const),
    BezierCC(Chunk, Chunk),
    BezierCV(Chunk, Value),
    BezierVT(Value, Const),
    BezierVC(Value, Chunk),
    BezierVV(Value, Value),


    /// Frequency Counter
    ///
    /// A frequency counter is a sawtooth wave.
    Freq(Ch32, u32),
    /// Trapazoid wave
    ///
    /// Subtree params: fc, rise, hold, fall.
    Zoid(u32, u32, u32, u32),
}

/// Sample input
///
/// An input is 1 value.
#[derive(Copy, Clone, Debug)]
pub struct Value(pub u32);

/// Sample chunk input / cache
///
/// A chunk contains 32 samples.
#[derive(Copy, Clone, Debug)]
pub struct Chunk(pub u32);

/// Sample wavetable/waypoint input
///
/// A wavetable contains any number of samples.
#[derive(Copy, Clone, Debug)]
pub struct Table(pub u32);

/// Sample constant
#[derive(Copy, Clone, Debug)]
pub struct Const(pub Ch32);

impl Sampler for Value {
    fn to_any(self) -> Any {
        Any::Value(self)
    }
}

impl Sampler for Chunk {
    fn to_any(self) -> Any {
        Any::Chunk(self)
    }
}

impl Sampler for Const {
    fn to_any(self) -> Any {
        Any::Const(self)
    }
}

mod seal {
    use super::*;

    pub trait Sampler {
        fn to_any(self) -> Any;
    }

    #[derive(Debug, Copy, Clone)]
    pub enum Any {
        Value(Value),
        Chunk(Chunk),
        Const(Const),
    }
}

use self::seal::{Any, Sampler};


/// Builder for a synth
///
/// Inputs -> Program -> Output
#[derive(Debug)]
pub struct SynthBuilder {
    nodes: Vec<Node>,
    input_samples: Vec<f32>,
    input_buffers: Vec<[Ch32; 32]>,
    input_wtables: Vec<Vec<Ch32>>,
}

impl SynthBuilder {
    /// Add chunked audio from an external source
    pub fn mix_source(mut self, chunk: Chunk) -> Self {
        self.input_buffers.resize((chunk.0 + 1).try_into().unwrap(), [Ch32::default(); 32]);
        self.nodes.push(Node::Source(chunk));
        self
    }

    /// Add line wave
    ///
    /// A line wave is a horizontal line, silence to human ears.
    pub fn mix_line(mut self, value: Value) -> Self {
        self.input_samples.resize((value.0 + 1).try_into().unwrap(), 0.0);
        self.nodes.push(Node::Line(value));
        self
    }
    
    /// Add wavetable
    ///
    /// A wave table is a collection of samples that are slowed down or sped up
    /// to make the pitch higher or lower.
    pub fn mix_wave(mut self, table: Table, freq: impl Sampler) -> Self {
        self.input_wtables.resize((table.0 + 1).try_into().unwrap(), Vec::new());
        self.nodes.push(match freq.to_any() {
            Any::Value(x) => Node::WaveV(table, x),
            Any::Chunk(x) => Node::WaveC(table, x),
            Any::Const(x) => Node::WaveT(table, x),
        });
        self
    }

    /// Add waypoint input
    ///
    /// A ways table is almost the same thing as a wavetable, except allows
    /// aliasing.
    pub fn mix_ways(mut self, table: Table, freq: impl Sampler) -> Self {
        self.input_wtables.resize((table.0 + 1).try_into().unwrap(), Vec::new());
        self.nodes.push(match freq.to_any() {
            Any::Value(x) => Node::WaypointV(table, x),
            Any::Chunk(x) => Node::WaypointC(table, x),
            Any::Const(x) => Node::WaypointT(table, x),
        });
        self
    }

    /// Bezier wave
    ///
    /// A bezier wave is a waveform formed by two symmetrical bezier curves.
    pub fn bezier(mut self, fc: impl Sampler, speed: impl Sampler) -> Self {
        self.nodes.push(match fc.to_any() {
            Any::Value(x) => match speed.to_any() {
                Any::Value(y) => Node::BezierVV(x, y),
                Any::Chunk(y) => Node::BezierVC(x, y),
                Any::Const(y) => Node::BezierVT(x, y),
            },
            Any::Chunk(x) => match speed.to_any() {
                Any::Value(y) => Node::BezierCV(x, y),
                Any::Chunk(y) => Node::BezierCC(x, y),
                Any::Const(y) => Node::BezierCT(x, y),
            },
            Any::Const(x) => match speed.to_any() {
                Any::Value(y) => Node::BezierTV(x, y),
                Any::Chunk(y) => Node::BezierTC(x, y),
                Any::Const(y) => Node::BezierTT(x, y),
            },
        });
        self
    }
}




/*
#[derive(Debug)]
struct EnvelopeComponent {
    time: i32,
    gain: i32,
}

#[derive(Debug)]
enum Function {
    Sine {
        hz: i32,
        duty: Option<i32>,
        zero: Option<i32>,
        peak: Option<i32>,
    },
    White {
        seed: Option<u32>,
    },
    Pink {
        seed: Option<u32>,
    },
    Phase {
        func: i32,
        offset: i32,
    },
    Line(f32),
    Mix {
        func: i32,
        amt: i32,
    },
    Limit {
        func: i32,
        ceil: Option<i32>,
        ratio: Option<i32>,
        knee: Option<i32>,
    },
    Clamp {
        func: i32,
        min: Option<i32>,
        max: Option<i32>,
        shift: Option<i32>,
    },
    Envelope {
        func: i32,
        with: Vec<EnvelopeComponent>,
    },
    Reverb,
    Shape,
    Table,
}

#[derive(Debug)]
struct Sampler {
    // Input samplers
    args: i32,
    func: Function,
}

/// A Twang Synthesizer Instance
#[derive(Debug)]
pub struct Synth {
    def: Vec<Sampler>,
    synth: i32,
    buffer: Vec<Ch32>,
}

impl Synth {
    /// Get a builder to construct this synth
    pub fn builder() -> SynthBuilder {
        SynthBuilder::new()
    }

    /// Stream synthesized samples into a [`Sink`].
    pub fn stream(&mut self, sink: impl Sink<Ch32, 1>) {
        sink.sink_with(core::iter::from_fn(|| {
            if self.buffer.is_empty() {
                self.buffer.pop()
            } else {
                self.buffer.pop()
            }
        }));
    }

    /// Apply a function to a chunk of audio.
    fn apply(&self, chunk: &mut [Ch32; 32], f: Function) {
        use Function::*;
        match f {
            Zoid {
                hz,
                rise,
                hold,
                fall,
            } => {
                todo!()
            },
            Sine {
                hz,
                duty,
                zero,
                peak,
            } => {
                todo!()
            },
            White {
                seed,
            } => {
                todo!()
            },
            Pink {
                seed,
            } => {
                todo!()
            },
            Phase {
                func,
                offset,
            } => {
                todo!()
            },
            Line(value) => {
                for sample in chunk.iter_mut() {
                    *sample = value.into();
                }
            },
            Mix {
                func,
                amt,
            } => {
                todo!()
            },
            Limit {
                func,
                ceil,
                ratio,
                knee,
            } => {
                todo!()
            },
            Clamp {
                func,
                min,
                max,
                shift,
            } => {
                todo!()
            },
            Envelope {
                func,
                with,
            } => {
                todo!()
            },
            Reverb => todo!(),
            Shape => todo!(),
            Table => todo!(),
        }
    }
}

/// Builder for [`Synth`]
#[derive(Debug)]
pub struct SynthBuilder {
    synth: Synth,
}

impl SynthBuilder {
    fn new() -> Self {
        let synth = Synth {
            def: Vec::new(),
            synth: i32::MIN,
            buffer: [Ch32::new(0.0); 32],
        };

        Self { synth }
    }

    /// Create a line wave (constant, makes no sound)
    pub fn line(mut self, value: impl Into<Ch32>) -> Self {
        self.synth.def.push(Function::Line(value.into().to_f32()));
        self
    }


}
*/