sorceress 0.2.0

A Rust environment for making music and sounds with SuperCollider.
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
// Sorceress
// Copyright (C) 2021  Wesley Merkel
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Core types for creating synth definitions.
//!
//! Synth definitions are used by SuperCollider to create new synths. Synth definitions are formed
//! from directed acyclic graphs (DAGs) of UGens. UGens are primitives offered by SuperCollider
//! that generate and process sound.
//!
//! # Examples
//!
//! ```
//! use sorceress::{
//!     synthdef::SynthDef,
//!     ugen::{Out, Pan2, SinOsc},
//! };
//!
//! let synthdef = SynthDef::new("example", |params| {
//!     let freq = params.named("freq", 440.0);
//!     let pan = params.named("pan", 0.0);
//!     Out::ar().channels(Pan2::ar().input(SinOsc::ar().freq(freq)).pos(pan))
//! });
//! ```
use crate::vectree::VecTree;
use std::sync::Arc;

pub mod decoder;
pub mod encoder;

// IDEA: parameter to control ugen as a discrete phase

/// A named synth definition.
///
/// Synth definitions are used by SuperCollider to create new synths.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct SynthDef {
    name: String,
    graph: VecTree<Scalar>,
    params: Parameters,
}

impl SynthDef {
    /// Creates a new synth definition.
    ///
    /// The name given here is used when creating new synths after this synthdef definition has be
    /// registered with the server. This method does not register the synth definition with the
    /// SuperCollider server which must happen before synths can be created from it.
    ///
    /// You can refer to parameters by index or name in many server commands, The `Parameters`
    /// passed to the `ugen_fn` allow you to control the order of parameters in the synth
    /// definition. The order of calls to methods on passed [`Parameters`] determines the index of
    /// each parameter. For that reason it's recommend to declare all parameters up front at the
    /// top of the `ugen_fn`.
    ///
    /// # Examples
    ///
    /// ```
    /// use sorceress::{
    ///     synthdef::{Input, SynthDef},
    ///     ugen,
    /// };
    ///
    /// let synthdef = SynthDef::new("example", |params| {
    ///     let freq = params.named("name", 440.0); // index 0
    ///     let vol = params.named("vol", 1.0); // index 1
    ///     ugen::Out::ar().channels(ugen::SinOsc::ar().freq(freq).mul(vol))
    /// });
    /// ```
    pub fn new<F, T>(name: impl Into<String>, ugen_fn: F) -> SynthDef
    where
        F: FnOnce(&mut Parameters) -> T,
        T: Input,
    {
        let mut params = Parameters::empty();
        let graph = ugen_fn(&mut params).into_value().0;
        SynthDef {
            name: name.into(),
            graph,
            params,
        }
    }

    /// Returns the name of the synth definition.
    pub fn name(&self) -> &str {
        &self.name
    }
}

#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub(crate) struct UGenSpec<I> {
    name: String,
    rate: Rate,
    signal_range: SignalRange,
    special_index: i16,
    inputs: Vec<I>,
    outputs: Vec<Rate>,
}

impl<I> UGenSpec<I> {
    pub fn new(name: &'static str, rate: Rate) -> UGenSpec<I> {
        UGenSpec {
            name: name.to_owned(),
            rate,
            signal_range: SignalRange::Bipolar,
            special_index: 0,
            inputs: Vec::new(),
            outputs: vec![rate],
        }
    }

    pub fn signal_range(mut self, signal_range: SignalRange) -> Self {
        self.signal_range = signal_range;
        self
    }

    pub fn special_index(mut self, special_index: i16) -> Self {
        self.special_index = special_index;
        self
    }

    pub fn inputs(mut self, inputs: impl IntoIterator<Item = I>) -> Self {
        self.inputs.extend(inputs);
        self
    }

    pub fn input(mut self, input: I) -> Self {
        self.inputs.push(input);
        self
    }

    pub fn outputs(mut self, outputs: impl IntoIterator<Item = Rate>) -> Self {
        self.outputs = outputs.into_iter().collect();
        self
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub(crate) enum Rate {
    Scalar = 0,
    Control = 1,
    Audio = 2,
}

impl From<Rate> for i8 {
    fn from(rate: Rate) -> Self {
        rate as i8
    }
}

/// An action to invoke when a UGen is finished playing.
///
/// A number of UGens implement "done actions". These allow one to optionally free or pause the
/// enclosing synth and other related nodes when the UGen is finished.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DoneAction {
    /// Do nothing when the UGen is finished.
    None = 0,
    /// Pause the enclosing synth, but do not free it.
    PauseSelf = 1,
    /// Free the enclosing synth.
    FreeSelf = 2,
    /// Free both this synth and the preceding node.
    FreeSelfAndPrev = 3,
    /// Free both this synth and the following node.
    FreeSelfAndNext = 4,
    /// Free this synth; if the preceding node is a group then do g_freeAll on it, else free it.
    FreeSelfAndFreeAllInPrev = 5,
    /// Free this synth; if the following node is a group then do g_freeAll on it, else free it.
    FreeSelfAndFreeAllInNext = 6,
    /// Free this synth and all preceding nodes in this group.
    FreeSelfToHead = 7,
    /// Free this synth and all following nodes in this group.
    FreeSelfToTail = 8,
    /// Free this synth and pause the preceding node.
    FreeSelfPausePrev = 9,
    /// Free this synth and pause the following node.
    FreeSelfPauseNext = 10,
    /// Free this synth and if the preceding node is a group then deep free it, else free it.
    FreeSelfAndDeepFreePrev = 11,
    /// Free this synth and if the following node is a group then deep free it, else free it.
    FreeSelfAndDeepFreeNext = 12,
    /// Free this synth and all other nodes in this group (before and after).
    FreeAllInGroup = 13,
    /// Free the enclosing group and all nodes within it (including this synth).
    FreeGroup = 14,
    /// Free this synth and resume the following node.
    FreeSelfResumeNext = 15,
}

impl Default for DoneAction {
    fn default() -> DoneAction {
        DoneAction::None
    }
}

impl Input for DoneAction {
    fn into_value(self) -> Value {
        (self as i32).into_value()
    }
}

#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub(crate) enum Scalar {
    Const(f32),
    Parameter(Parameter),
    Ugen {
        output_index: i32,
        ugen_spec: Arc<UGenSpec<Scalar>>,
    },
}

impl Scalar {
    fn rate(&self) -> Rate {
        match self {
            Self::Const(_) => Rate::Scalar,
            Self::Parameter(_) => Rate::Control,
            Self::Ugen {
                ugen_spec,
                output_index,
            } => ugen_spec.outputs[*output_index as usize],
        }
    }
}

/// A factory for creating parameters in a synth definition.
///
/// A value of this type is passed to the `ugen_fn` closure given to [`SynthDef::new`]. See
/// [`SynthDef::new`] for more details.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct Parameters {
    initial_values: Vec<f32>,
    names: Vec<(String, usize)>,
}

impl Parameters {
    fn empty() -> Parameters {
        Parameters {
            initial_values: Vec::new(),
            names: Vec::new(),
        }
    }

    /// Defines a parameter within a synth definition.
    ///
    /// Creates a new named parameter with an initial value. If a value is not specified for this
    /// parameter when creating a new synth, the initial value will be used.
    pub fn named(&mut self, name: impl Into<String>, initial_value: f32) -> Parameter {
        let index = self.initial_values.len();
        self.initial_values.push(initial_value);
        self.names.push((name.into(), index));
        Parameter { index }
    }
}

/// A synth definition parameter.
///
/// Parameters allow synths to be controlled externally.
///
/// # Examples
/// ```
/// use sorceress::{
///     synthdef::SynthDef,
///     ugen::{Out, Pan2, SinOsc},
/// };
///
/// fn example_synth_def() -> SynthDef {
///     SynthDef::new("example", |params| {
///         let freq = params.named("freq", 440.0);
///         let pan = params.named("pan", 0.0);
///         Out::ar().channels(Pan2::ar().input(SinOsc::ar().freq(freq)).pos(pan))
///     })
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Parameter {
    index: usize,
}

impl Input for Parameter {
    fn into_value(self) -> Value {
        Value(VecTree::Leaf(Scalar::Parameter(self)))
    }
}

/// A value in a UGen graph.
///
/// Many different types can be converted into a `Value` using the [`Input`] trait, but there are
/// only 3 general kinds of values:
///
/// * Constants
/// * Parameters
/// * UGens
///
/// *Constants* are numeric values, either an [`i32`] or [`f32`], that are hardcoded into a synth
/// definition. Constant values cannot be changed later when creating a synth, for that you must
/// use a parameter.
///
/// *Parameters* are numeric values that can be controlled externally using server commands.
/// Parameters can be used to invoke a single synth definition in different ways, such as by
/// controlling the pitch or volume of the synth.
///
/// *UGens* are the building blocks of synth definitions. UGens are primitives that generate and
/// process audio and control signals. SuperCollider provides hundreds of UGens, all of which can
/// be found in the [`ugen`](super::ugen) module.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct Value(pub(crate) VecTree<Scalar>);

impl Value {
    /// Extracts two channels from a multichannel value.
    ///
    /// Takes a value with two channels, perhaps created via multichannel expansion
    /// or a UGen with two outputs, and returns each channel as a separate `Value`.
    ///
    /// # Panics
    ///
    /// Panics if the `Value` does not have exactly two channels.
    pub fn unwrap_stereo(self) -> (Value, Value) {
        match self.0 {
            VecTree::Leaf(_) => panic!("called `VecTree::unwrap_stereo` on a `Scalar` value"),
            VecTree::Branch(mut branch) => {
                if branch.len() != 2 {
                    panic!(
                        "called `VecTree::unwrap_stereo` on a signal with {} channels",
                        branch.len()
                    );
                }
                let b = branch.pop().unwrap();
                let a = branch.pop().unwrap();
                (Value(a), Value(b))
            }
        }
    }
}

impl Input for Value {
    fn into_value(self) -> Value {
        self
    }
}

impl Input for f32 {
    fn into_value(self) -> Value {
        Value(VecTree::Leaf(Scalar::Const(self)))
    }
}

impl Input for i32 {
    fn into_value(self) -> Value {
        Value(VecTree::Leaf(Scalar::Const(self as f32)))
    }
}

impl Input for usize {
    fn into_value(self) -> Value {
        Value(VecTree::Leaf(Scalar::Const(self as f32)))
    }
}

fn bin_op_ugen(special_index: i16, lhs: Value, rhs: Value) -> Value {
    let inputs = vec![UGenInput::Simple(lhs), UGenInput::Simple(rhs)];
    expand_inputs_with(inputs, &mut |inputs: Vec<Scalar>| {
        let rate = input_rate(&inputs);
        VecTree::Leaf(Scalar::Ugen {
            output_index: 0,
            ugen_spec: Arc::new(
                UGenSpec::new("BinaryOpUGen", rate)
                    .special_index(special_index)
                    .inputs(inputs),
            ),
        })
    })
}

fn mul_add(value: impl Input, mul: impl Input, add: impl Input) -> Value {
    let inputs = vec![
        UGenInput::Simple(value.into_value()),
        UGenInput::Simple(mul.into_value()),
        UGenInput::Simple(add.into_value()),
    ];
    expand_inputs_with(inputs, &mut |inputs: Vec<Scalar>| {
        let rate = input_rate(&inputs);
        VecTree::Leaf(Scalar::Ugen {
            output_index: 0,
            ugen_spec: Arc::new(UGenSpec::new("MulAdd", rate).inputs(inputs)),
        })
    })
}

fn unary_op_ugen(special_index: i16, value: Value) -> Value {
    let inputs = vec![UGenInput::Simple(value)];
    expand_inputs_with(inputs, &mut |inputs: Vec<Scalar>| {
        let rate = input_rate(&inputs);
        VecTree::Leaf(Scalar::Ugen {
            output_index: 0,
            ugen_spec: Arc::new(
                UGenSpec::new("UnaryOpUGen", rate)
                    .special_index(special_index)
                    .inputs(inputs),
            ),
        })
    })
}

fn input_rate(inputs: &[Scalar]) -> Rate {
    inputs
        .iter()
        .map(|input| input.rate())
        .max()
        .unwrap_or(Rate::Scalar)
}

/// A trait for values that can be used in UGen graphs.
///
/// This trait is primarily used as a bound on the arguments to UGen structs. This allows for a
/// wide range of types to be given as parameters. `Input` is implemented by:
///
/// * Numeric types - [`i32`], [`f32`], and [`usize`]
/// * Synth definition parameters - [`Parameter`]
/// * All UGen structs
/// * [`Value`]
/// * A [`Vec`] of other inputs
///
/// If a vector of `Input`s is passed to a unit generator, multichannel expansion will be applied.
///
/// # Examples
///
/// Multichannel expansion:
/// ```
/// use sorceress::{synthdef::SynthDef, ugen};
///
/// // The following two synth definitions are equivalent.
///
/// let synthdef1 = SynthDef::new("multichannel", |_| {
///     ugen::Out::ar().channels(ugen::SinOsc::ar().freq(vec![440, 220]))
/// });
///
/// let synthdef2 = SynthDef::new("multichannel", |_| {
///     ugen::Out::ar().channels(vec![
///         ugen::SinOsc::ar().freq(440),
///         ugen::SinOsc::ar().freq(220),
///     ])
/// });
/// ```
pub trait Input: Sized {
    /// Converts the input into a `Value`.
    fn into_value(self) -> Value;

    /// Adds an `Input` to another.
    fn add(self, rhs: impl Input) -> Value {
        bin_op_ugen(0, self.into_value(), rhs.into_value())
    }

    /// Subtracts an `Input` from another.
    fn sub(self, rhs: impl Input) -> Value {
        bin_op_ugen(1, self.into_value(), rhs.into_value())
    }

    /// Multiplies an `Input` by another.
    fn mul(self, rhs: impl Input) -> Value {
        bin_op_ugen(2, self.into_value(), rhs.into_value())
    }

    /// Divides an `Input` by another using floating point division.
    fn div(self, rhs: impl Input) -> Value {
        bin_op_ugen(3, self.into_value(), rhs.into_value())
    }

    /// Divides an `Input` by another using integer division.
    fn idiv(self, rhs: impl Input) -> Value {
        bin_op_ugen(4, self.into_value(), rhs.into_value())
    }

    /// Modulo operator.
    fn modulo(self, divisor: impl Input) -> Value {
        bin_op_ugen(5, self.into_value(), divisor.into_value())
    }

    /// Efficiently multiplies the signal by `mul` and adds `add`.
    ///
    /// Uses the `MulAdd` UGen under the hood.
    fn madd(self, mul: impl Input, add: impl Input) -> Value {
        mul_add(self, mul, add)
    }

    /// Converts midi note numbers into cycles per seconds (Hz).
    fn midicps(self) -> Value {
        unary_op_ugen(17, self.into_value())
    }

    /// Converts cycles per seconds (Hz) into midi note numbers.
    fn cpsmidi(self) -> Value {
        unary_op_ugen(18, self.into_value())
    }

    /// Scales the output of this UGen to be within the range of `lo` and `hi`.
    ///
    /// This Note that range expects the default output range, and thus should not be used in
    /// conjunction with mul and add arguments.
    fn range(self, lo: impl Input, hi: impl Input) -> Value {
        let value = self.into_value();
        let lo = lo.into_value();
        let hi = hi.into_value();

        // TODO: replace clone with with borrowing `.iter()` method
        let is_unipolar = value.clone().0.into_iter().all(|scalar| {
            matches!(
                scalar,
                Scalar::Ugen { ugen_spec, .. } if ugen_spec.signal_range == SignalRange::Unipolar
            )
        });

        let mul;
        let add;
        if is_unipolar {
            mul = hi.sub(lo.clone());
            add = lo;
        } else {
            mul = hi.sub(lo.clone()).mul(0.5);
            add = mul.clone().add(lo);
        }
        value.madd(mul, add)
    }

    // TODO: add all unary operators
}

impl<T> Input for Vec<T>
where
    T: Input,
{
    fn into_value(self) -> Value {
        Value(VecTree::Branch(
            self.into_iter().map(|value| value.into_value().0).collect(),
        ))
    }
}

#[derive(Debug, PartialEq, Clone)]
pub(crate) enum UGenInput {
    Simple(Value),
    Multi(Value),
}

impl UGenInput {
    fn expand(self) -> Vec<VecTree<Scalar>> {
        match self {
            UGenInput::Simple(Value(value)) => vec![value],
            UGenInput::Multi(Value(value)) => match value {
                VecTree::Leaf(expanded_value) => vec![VecTree::Leaf(expanded_value)],
                VecTree::Branch(xs) => xs,
            },
        }
    }
}

/// Describes the output range of a UGen.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub(crate) enum SignalRange {
    /// Between 0 and 1.
    Unipolar,

    /// Between -1 and 1.
    Bipolar,
}

fn mutlichannel_expand<I, F, U, A, B>(inputs: I, expand_one: F) -> VecTree<Vec<B>>
where
    I: IntoIterator<Item = A>,
    F: Fn(A) -> U,
    U: IntoIterator<Item = VecTree<B>>,
    B: Clone,
{
    let expanded_inputs = inputs.into_iter().flat_map(expand_one).collect::<Vec<_>>();
    let dimensions = VecTree::space(&expanded_inputs);
    transmute_trees(&expanded_inputs, &dimensions, &mut vec![])
}

fn transmute_trees<T>(
    input_trees: &[VecTree<T>],
    dimensions: &[usize],
    path: &mut Vec<usize>,
) -> VecTree<Vec<T>>
where
    T: Clone,
{
    match dimensions {
        [] => {
            let xs = input_trees
                .iter()
                .map(|tree| tree.get_path(path).unwrap().clone())
                .collect();
            VecTree::Leaf(xs)
        }
        [size, dimensions @ ..] => {
            let mut trees = vec![];
            for i in 0..*size {
                path.push(i);
                trees.push(transmute_trees(input_trees, dimensions, path));
                path.pop();
            }
            VecTree::Branch(trees)
        }
    }
}

fn expand_inputs_with<F>(inputs: Vec<UGenInput>, f: &mut F) -> Value
where
    F: FnMut(Vec<Scalar>) -> VecTree<Scalar>,
{
    Value(mutlichannel_expand(inputs, UGenInput::expand).flat_map(f))
}

impl Input for UGenSpec<UGenInput> {
    fn into_value(self) -> Value {
        let UGenSpec {
            name,
            rate,
            signal_range,
            special_index,
            inputs,
            outputs,
        } = self;

        expand_inputs_with(inputs, &mut |inputs| {
            let ugen_spec = Arc::new(UGenSpec {
                name: name.clone(),
                rate,
                signal_range,
                special_index,
                inputs,
                outputs: outputs.clone(),
            });
            if outputs.len() <= 1 {
                VecTree::Leaf(Scalar::Ugen {
                    output_index: 0,
                    ugen_spec,
                })
            } else {
                VecTree::Branch(
                    (0..outputs.len())
                        .into_iter()
                        .map(|output_index| {
                            VecTree::Leaf(Scalar::Ugen {
                                output_index: output_index as i32,
                                ugen_spec: ugen_spec.clone(),
                            })
                        })
                        .collect::<Vec<_>>(),
                )
            }
        })
    }
}