oscen 0.1.4

A library for building modular synthesizers
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
use std::{
    any::Any,
    collections::HashMap,
    f64::consts::PI,
    ops::{Index, IndexMut},
    sync::{Arc, Mutex},
};
use uuid::Uuid;

pub const TAU: f64 = 2.0 * PI;
pub type Real = f64;
pub type Tag = Uuid;

/// Generate a unique tag for a synth module.
pub fn mk_tag() -> Tag {
    Uuid::new_v4()
}

/// Synth modules must implement the Signal trait. In fact one could define a
/// synth module as a struct that implements `Signal`. `as_any_mut` is necessary
/// so that modules can be downcast in order to access their specific fields.
pub trait Signal: Any {
    /// This method has the same trivial implementation for all implentors of
    /// the trait. We need it to downcast trait objects to their underlying
    /// type.
    fn as_any_mut(&mut self) -> &mut dyn Any;
    /// Responsible for updating the `phase` and returning the next signal
    /// value, i.e. `amplitude`.
    fn signal(&mut self, rack: &Rack, sample_rate: Real) -> Real;
    /// Synth modules must have a tag (name) to serve as their key in the rack.
    fn tag(&self) -> Tag;
}

/// Since `as_any_mut()` usually has the same implementation for any `Signal`
/// we provide this macro for coneniene.
#[macro_export]
macro_rules! as_any_mut {
   () => {
        fn as_any_mut(&mut self) -> &mut dyn Any {
            self
        }
    };
}

/// For `Signal`s that have a `tag` field implement `as_any_mut()` and `tag()`.
#[macro_export]
macro_rules! std_signal {
    () => {
        as_any_mut!();
        fn tag(&self) -> Tag {
            self.tag
        }
    };
}

/// Types that implement the gate type can be turned on and off from within a
///`Rack`, e.g. envelope generators.
pub trait Gate {
    fn gate_on(rack: &Rack, n: Tag);
    fn gate_off(rack: &Rack, n: Tag);
}

/// If your module has `on` and `off` methods you can use this macro to generate
/// the `Gate` trait.
#[macro_export]
macro_rules! gate {
    ($t:ty) => {
        impl Gate for $t {
            fn gate_on(rack: &Rack, n: Tag) {
                if let Some(v) = rack.modules[&n]
                    .module
                    .lock()
                    .unwrap()
                    .as_any_mut()
                    .downcast_mut::<Self>()
                {
                    v.on();
                }
            }

            fn gate_off(rack: &Rack, n: Tag) {
                if let Some(v) = rack.modules[&n]
                    .module
                    .lock()
                    .unwrap()
                    .as_any_mut()
                    .downcast_mut::<Self>()
                {
                    v.off();
                }
            }
        }
    };
}

/// Signals typically need to decalare that they are `Send` so that they are
/// thread safe.
pub type Sig = dyn Signal + Send;
pub type ArcMutex<T> = Arc<Mutex<T>>;

/// Convenience function for `Arc<Mutex<...>`.
pub fn arc<T>(x: T) -> Arc<Mutex<T>> {
    Arc::new(Mutex::new(x))
}

impl<T> Signal for ArcMutex<T>
where
    T: Signal,
{
    as_any_mut!();
    fn signal(&mut self, rack: &Rack, sample_rate: Real) -> Real {
        self.lock().unwrap().signal(rack, sample_rate)
    }

    fn tag(&self) -> Tag {
        self.lock().unwrap().tag()
    }
}

impl Signal for ArcMutex<dyn Signal + Send> {
    as_any_mut!();
    fn signal(&mut self, rack: &Rack, sample_rate: Real) -> Real {
        self.lock().unwrap().signal(rack, sample_rate)
    }

    fn tag(&self) -> Tag {
        self.lock().unwrap().tag()
    }
}

pub trait Builder {
    fn build(&mut self) -> Self
    where
        Self: Sized + Clone,
    {
        self.clone()
    }

    fn wrap(&mut self) -> ArcMutex<Self>
    where
        Self: Sized + Clone,
    {
        arc(self.clone())
    }

    fn rack(&mut self, rack: &mut Rack) -> ArcMutex<Self>
    where
        Self: Signal + Send + Sized + Clone,
    {
        let result = arc(self.clone());
        rack.append(result.clone());
        result
    }

    fn rack_pre(&mut self, rack: &mut Rack) -> ArcMutex<Self>
    where
        Self: Signal + Send + Sized + Clone,
    {
        let result = arc(self.clone());
        rack.preppend(result.clone());
        result
    }
}

/// Inputs to synth modules can either be constant (`Fix`) or a control voltage
/// from another synth module (`Cv`).
#[derive(Copy, Clone, Debug)]
pub enum In {
    Cv(Tag),
    Fix(Real),
}

impl In {
    /// Get the signal value. Look it up in the rack if it is `Cv`.
    pub fn val(rack: &Rack, inp: In) -> Real {
        match inp {
            In::Fix(x) => x,
            In::Cv(n) => rack.output(n),
        }
    }
}

impl From<Real> for In {
    fn from(x: Real) -> Self {
        In::Fix(x)
    }
}

impl From<Tag> for In {
    fn from(t: Tag) -> Self {
        In::Cv(t)
    }
}

impl From<i32> for In {
    fn from(i: i32) -> Self {
        In::Fix(i as Real)
    }
}

impl Default for In {
    fn default() -> Self {
        Self::Fix(0.0)
    }
}

/// Connect the `source` module to the `field` input of the `dest` module.
pub fn connect<T, U>(source: &T, dest: &mut U, field: &'static str)
where
    T: Signal,
    U: Index<&'static str, Output = In> + IndexMut<&'static str>,
{
    dest[field] = source.tag().into();
}

/// SynthModules for the rack will have both a module (i.e an implementor of
/// `Signal`) and will store their current signal value as `output`
#[derive(Clone)]
pub struct SynthModule {
    pub module: ArcMutex<Sig>,
    pub output: Real,
}

impl SynthModule {
    fn new(signal: ArcMutex<Sig>) -> Self {
        Self {
            module: signal,
            output: 0.0,
        }
    }
}

impl Signal for SynthModule {
    as_any_mut!();
    fn signal(&mut self, rack: &Rack, sample_rate: Real) -> Real {
        self.module.signal(rack, sample_rate)
    }

    fn tag(&self) -> Tag {
        self.module.tag()
    }
}

/// A `Rack` is basically a `HashMap` of synth modules to be visited in the specified order.
#[derive(Clone)]
pub struct Rack {
    pub modules: HashMap<Tag, SynthModule>,
    pub order: Vec<Tag>,
}

impl Rack {
    /// Create a `Rack` object whose order is set to the order of the `Signal`s
    /// in the input `ws`.
    pub fn new(ws: Vec<ArcMutex<Sig>>) -> Self {
        let mut nodes: HashMap<Tag, SynthModule> = HashMap::new();
        let mut order: Vec<Tag> = Vec::new();
        for s in ws {
            let t = s.lock().unwrap().tag();
            nodes.insert(t, SynthModule::new(s));
            order.push(t)
        }
        Rack { modules: nodes, order }
    }

    /// Convert a rack into an `Iter` - note: we don't need an `iter_mut` since
    /// we will mostly mutating a `Node` via it's `Mutex`.
    pub fn iter<'a>(&'a self) -> Iter<'a> {
        Iter {
            rack: self,
            index: 0,
        }
    }

    /// Convenience function get the `Tag` of the final node in the `Rack`.
    pub fn out_tag(&self) -> Tag {
        let n = self.modules.len() - 1;
        self.order[n]
    }

    /// Get the `output` of a `Node`.
    pub fn output(&self, n: Tag) -> Real {
        self.modules
            .get(&n)
            .expect("Function output could not find tag")
            .output
    }

    /// Add a `Node` (synth module) to the `Rack` and set it's order to be last.
    pub fn append(&mut self, sig: ArcMutex<Sig>) {
        let tag = sig.tag();
        let node = SynthModule::new(sig);
        self.modules.insert(tag, node);
        self.order.push(tag);
    }

    /// Add a `SynthModule` to the `Rack` and set it's order to be first`.
    pub fn preppend(&mut self, sig: ArcMutex<Sig>) {
        let tag = sig.tag();
        let node = SynthModule::new(sig);
        self.modules.insert(tag, node);
        self.order.insert(0, tag);
    }

    /// Add a `SynthModule` to the `Rack` at the position `before` was.
    pub fn before(&mut self, before: Tag, sig: ArcMutex<Sig>) {
        if let Some(pos) = self.order.iter().position(|&x| x == before) {
            let tag = sig.tag();
            let node = SynthModule::new(sig);
            self.modules.insert(tag, node);
            self.order.insert(pos, tag);
        } else {
            panic!("rack does not contain {} tag", before);
        }
    }

    /// Insert a sub-rack into the rack before node `loc`.
    pub fn insert(&mut self, rack: Rack, loc: usize) {
        let n = rack.modules.len() + self.modules.len();
        let mut new_order: Vec<Tag> = Vec::with_capacity(n);
        for i in 0..loc {
            new_order.push(self.order[i])
        }
        for i in 0..rack.order.len() {
            new_order.push(rack.order[i])
        }
        for i in loc..self.modules.len() {
            new_order.push(self.order[i])
        }
        self.order = new_order;
        self.modules.extend(rack.modules);
    }

    /// A `Rack` generates a signal by travesing the list of modules and
    /// updating each one's output in turn. The output of the last `Node` is
    /// returned.
    pub fn signal(&mut self, sample_rate: Real) -> Real {
        let mut outs: Vec<Real> = Vec::new();
        for node in self.iter() {
            outs.push(
                node.module
                    .lock()
                    .expect("Function rack::signal could not find tag in first loop")
                    .signal(&self, sample_rate),
            )
        }
        for (i, o) in self.order.iter().enumerate() {
            self.modules
                .get_mut(o)
                .expect("Function rack::signal could not find tag in second loop")
                .output = outs[i];
        }
        self.modules[&self.out_tag()].output
    }
}

pub struct Iter<'a> {
    rack: &'a Rack,
    index: usize,
}

impl<'a> IntoIterator for &'a Rack {
    type Item = &'a SynthModule;
    type IntoIter = Iter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = &'a SynthModule;
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.rack.order.len() {
            return None;
        }
        let tag = self.rack.order[self.index];
        self.index += 1;
        self.rack.modules.get(&tag)
    }
}

/// Use to connect subracks to the main rack. Simply store the value of the
/// input node from the main rack as a link module, which will be the first
/// module in the subrack.
#[derive(Clone)]
pub struct Link {
    tag: Tag,
    value: In,
}

impl Link {
    pub fn new() -> Self {
        Self {
            tag: mk_tag(),
            value: 0.into(),
        }
    }

    pub fn value<T: Into<In>>(&mut self, arg: T) -> &mut Self {
        self.value = arg.into();
        self
    }
}

impl Builder for Link {}

impl Signal for Link {
    std_signal!();
    fn signal(&mut self, rack: &Rack, _sample_rate: Real) -> Real {
        In::val(rack, self.value)
    }
}

impl Index<&str> for Link {
    type Output = In;

    fn index(&self, index: &str) -> &Self::Output {
        match index {
            "value" => &self.value,
            _ => panic!("Link does not have a field named:  {}", index),
        }
    }
}

impl IndexMut<&str> for Link {
    fn index_mut(&mut self, index: &str) -> &mut Self::Output {
        match index {
            "value" => &mut self.value,
            _ => panic!("Link does not have a field named:  {}", index),
        }
    }
}