rill-lang 0.6.0-M2

rill-lang — a Faust-style functional streaming DSL compiled to rill Algorithm<T>
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
//! Self-registration for rill-lang's own builtins (mixer, eq, dry/wet, complex).

use rill_core::builtin::{BlockBuiltin, BuiltinKind, BuiltinSig, Registry};
#[cfg(feature = "router")]
use rill_core::builtin::{ParamType, RecordField, RecordSchema};
use rill_core::math::Transcendental;
use rill_core::traits::{Algorithm, ProcessResult};

// ============================================================================
// Complex number built-in structs
// ============================================================================

struct ComplexConjBuiltin;
impl<T: Transcendental> Algorithm<T> for ComplexConjBuiltin {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = inp.len().min(output.len()) / 2;
                for i in 0..n {
                    output[2 * i] = inp[2 * i];
                    output[2 * i + 1] = -inp[2 * i + 1];
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexConjBuiltin {}

struct ComplexReBuiltin;
impl<T: Transcendental> Algorithm<T> for ComplexReBuiltin {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = inp.len().min(output.len() * 2) / 2;
                for i in 0..n {
                    output[i] = inp[2 * i];
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexReBuiltin {}

struct ComplexImBuiltin;
impl<T: Transcendental> Algorithm<T> for ComplexImBuiltin {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = inp.len().min(output.len() * 2) / 2;
                for i in 0..n {
                    output[i] = inp[2 * i + 1];
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexImBuiltin {}

struct ComplexNormBuiltin;
impl<T: Transcendental> Algorithm<T> for ComplexNormBuiltin {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = inp.len().min(output.len() * 2) / 2;
                for i in 0..n {
                    let re = inp[2 * i];
                    let im = inp[2 * i + 1];
                    output[i] = (re * re + im * im).sqrt();
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexNormBuiltin {}

struct ComplexArgBuiltin;
impl<T: Transcendental> Algorithm<T> for ComplexArgBuiltin {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = inp.len().min(output.len() * 2) / 2;
                for i in 0..n {
                    let im = inp[2 * i + 1];
                    let re = inp[2 * i];
                    let arg = im.to_f64().atan2(re.to_f64()) as f32;
                    output[i] = T::from_f32(arg);
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexArgBuiltin {}

struct ComplexMulBuiltin;
impl<T: Transcendental> Algorithm<T> for ComplexMulBuiltin {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = inp.len().min(output.len() * 2) / 4;
                for i in 0..n {
                    let a_re = inp[4 * i];
                    let a_im = inp[4 * i + 1];
                    let b_re = inp[4 * i + 2];
                    let b_im = inp[4 * i + 3];
                    output[2 * i] = a_re * b_re - a_im * b_im;
                    output[2 * i + 1] = a_re * b_im + a_im * b_re;
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexMulBuiltin {}

struct ComplexAddBuiltin;
impl<T: Transcendental> Algorithm<T> for ComplexAddBuiltin {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = inp.len().min(output.len() * 2) / 4;
                for i in 0..n {
                    output[2 * i] = inp[4 * i] + inp[4 * i + 2];
                    output[2 * i + 1] = inp[4 * i + 1] + inp[4 * i + 3];
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexAddBuiltin {}

struct ComplexGenBuiltin<T: Transcendental> {
    re: T,
    im: T,
}
impl<T: Transcendental> Algorithm<T> for ComplexGenBuiltin<T> {
    fn process(&mut self, _input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        let n = output.len() / 2;
        for i in 0..n {
            output[2 * i] = self.re;
            output[2 * i + 1] = self.im;
        }
        Ok(())
    }
    fn reset(&mut self) {}
}
impl<T: Transcendental> BlockBuiltin<T> for ComplexGenBuiltin<T> {}

// ============================================================================
// Mixer built-in struct
// ============================================================================

#[cfg(feature = "router")]
struct MixerAlgorithmWrapper<T: Transcendental> {
    state: crate::builtins::mixer::MixerState<T, 512>,
    cfg: crate::builtins::mixer::MixerConfig,
}

#[cfg(feature = "router")]
impl<T: Transcendental> MixerAlgorithmWrapper<T> {
    fn new(config: crate::builtins::mixer::MixerConfig) -> Self {
        Self {
            state: crate::builtins::mixer::MixerState::<T, 512>::new(config.clone()),
            cfg: config,
        }
    }
}

#[cfg(feature = "router")]
impl<T: Transcendental> Algorithm<T> for MixerAlgorithmWrapper<T> {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        if let Some(inp) = input {
            output.copy_from_slice(inp);
        } else {
            output.fill(T::ZERO);
        }
        Ok(())
    }

    fn reset(&mut self) {
        self.state = crate::builtins::mixer::MixerState::<T, 512>::new(self.cfg.clone());
    }
}

#[cfg(feature = "router")]
impl<T: Transcendental> BlockBuiltin<T> for MixerAlgorithmWrapper<T> {}

// ============================================================================
// EQ built-in struct
// ============================================================================

#[cfg(feature = "router")]
struct EqBuiltin<T: Transcendental> {
    inner: crate::builtins::eq::EqState<T>,
}

#[cfg(feature = "router")]
impl<T: Transcendental> Algorithm<T> for EqBuiltin<T> {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => self.inner.process_slice(inp, output),
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}

#[cfg(feature = "router")]
impl<T: Transcendental> BlockBuiltin<T> for EqBuiltin<T> {}

// ============================================================================
// Dry/Wet built-in struct
// ============================================================================

#[cfg(feature = "router")]
struct DryWetBuiltin<T: Transcendental> {
    mix: T,
}

#[cfg(feature = "router")]
impl<T: Transcendental> Algorithm<T> for DryWetBuiltin<T> {
    fn process(&mut self, input: Option<&[T]>, output: &mut [T]) -> ProcessResult<()> {
        match input {
            Some(inp) => {
                let n = (inp.len() / 2).min(output.len() / 2);
                let dry_gain = T::ONE - self.mix;
                for i in 0..n {
                    let dry = inp[2 * i];
                    let wet = inp[2 * i + 1];
                    let out = dry * dry_gain + wet * self.mix;
                    output[2 * i] = out;
                    output[2 * i + 1] = out;
                }
            }
            None => output.fill(T::ZERO),
        }
        Ok(())
    }
    fn reset(&mut self) {}
}

#[cfg(feature = "router")]
impl<T: Transcendental> BlockBuiltin<T> for DryWetBuiltin<T> {}

// ============================================================================
// Registration functions
// ============================================================================

/// Register rill-lang core builtins. Call after rill_core_dsp::register_lang_builtins().
pub fn register_core_builtins<T: Transcendental + 'static>(reg: &mut Registry<T>) {
    register_complex(reg);

    #[cfg(feature = "router")]
    {
        register_mixer(reg);
        register_eq(reg);
        register_dry_wet(reg);
    }
}

/// Register complex number built-ins (dsl: complex, conj, re, im, norm, arg, cmul, cadd).
fn register_complex<T: Transcendental + 'static>(reg: &mut Registry<T>) {
    reg.register_block(
        BuiltinSig::simple("complex", 0, 2, 2, BuiltinKind::Block).with_names(vec!["re", "im"]),
        |p, _sr| {
            let re = T::from_f64(p[0]);
            let im = T::from_f64(p[1]);
            Box::new(ComplexGenBuiltin { re, im })
        },
    );
    reg.register_block(
        BuiltinSig::simple("conj", 2, 2, 0, BuiltinKind::Block),
        |_p, _sr| Box::new(ComplexConjBuiltin),
    );
    reg.register_block(
        BuiltinSig::simple("re", 2, 1, 0, BuiltinKind::Block),
        |_p, _sr| Box::new(ComplexReBuiltin),
    );
    reg.register_block(
        BuiltinSig::simple("im", 2, 1, 0, BuiltinKind::Block),
        |_p, _sr| Box::new(ComplexImBuiltin),
    );
    reg.register_block(
        BuiltinSig::simple("norm", 2, 1, 0, BuiltinKind::Block),
        |_p, _sr| Box::new(ComplexNormBuiltin),
    );
    reg.register_block(
        BuiltinSig::simple("arg", 2, 1, 0, BuiltinKind::Block),
        |_p, _sr| Box::new(ComplexArgBuiltin),
    );
    reg.register_block(
        BuiltinSig::simple("cmul", 4, 2, 0, BuiltinKind::Block),
        |_p, _sr| Box::new(ComplexMulBuiltin),
    );
    reg.register_block(
        BuiltinSig::simple("cadd", 4, 2, 0, BuiltinKind::Block),
        |_p, _sr| Box::new(ComplexAddBuiltin),
    );
}

/// Register the mixer built-in: `mixer(signal..., { buses, master_vol })`.
#[cfg(feature = "router")]
fn register_mixer<T: Transcendental + 'static>(reg: &mut Registry<T>) {
    use crate::builtins::mixer::MixerConfig;

    let mixer_sig = BuiltinSig {
        name: "mixer",
        params: vec![
            ParamType::Variadic(Box::new(ParamType::Signal)),
            ParamType::Record(RecordSchema::new(vec![
                RecordField {
                    name: "buses",
                    ty: ParamType::Int,
                    default: Some(0.0),
                },
                RecordField {
                    name: "master_vol",
                    ty: ParamType::Float,
                    default: Some(1.0),
                },
            ])),
        ],
        signal_outs: 2,
        kind: BuiltinKind::Block,
        param_names: Vec::new(),
    };

    reg.register_block(
        mixer_sig,
        |params: &[f64], _sample_rate: f32| -> Box<dyn BlockBuiltin<T>> {
            let num_channels = if params.len() > 1 {
                params.len() - 1
            } else {
                1
            };
            let num_buses = params.last().copied().unwrap_or(0.0) as usize;

            let config = MixerConfig::new(num_channels.max(1), num_buses);
            Box::new(MixerAlgorithmWrapper::<T>::new(config))
        },
    );
}

/// Register the EQ parametric built-in: `eq_parametric(signal, { bands })`.
#[cfg(feature = "router")]
fn register_eq<T: Transcendental + 'static>(reg: &mut Registry<T>) {
    use crate::builtins::eq::{EqConfig, EqState};

    let sig = BuiltinSig {
        name: "eq_parametric",
        params: vec![
            ParamType::Signal,
            ParamType::Record(RecordSchema::new(vec![RecordField {
                name: "bands",
                ty: ParamType::Variadic(Box::new(ParamType::Record(RecordSchema::new(vec![
                    RecordField {
                        name: "freq",
                        ty: ParamType::Float,
                        default: Some(1000.0),
                    },
                    RecordField {
                        name: "q",
                        ty: ParamType::Float,
                        default: Some(1.0),
                    },
                    RecordField {
                        name: "gain_db",
                        ty: ParamType::Float,
                        default: Some(0.0),
                    },
                    RecordField {
                        name: "band_type",
                        ty: ParamType::Int,
                        default: Some(0.0),
                    },
                ])))),
                default: None,
            }])),
        ],
        signal_outs: 1,
        kind: BuiltinKind::Block,
        param_names: Vec::new(),
    };

    reg.register_block(
        sig,
        |_params: &[f64], sample_rate: f32| -> Box<dyn BlockBuiltin<T>> {
            let inner = EqState::new(EqConfig { bands: vec![] }, sample_rate);
            Box::new(EqBuiltin { inner })
        },
    );
}

/// Register the dry/wet built-in: `dry_wet(dry, wet, { mix })`.
#[cfg(feature = "router")]
fn register_dry_wet<T: Transcendental + 'static>(reg: &mut Registry<T>) {
    let sig = BuiltinSig {
        name: "dry_wet",
        params: vec![
            ParamType::Signal,
            ParamType::Signal,
            ParamType::Record(RecordSchema::new(vec![RecordField {
                name: "mix",
                ty: ParamType::Float,
                default: Some(0.5),
            }])),
        ],
        signal_outs: 2,
        kind: BuiltinKind::Block,
        param_names: Vec::new(),
    };

    reg.register_block(
        sig,
        |_params: &[f64], _sr: f32| -> Box<dyn BlockBuiltin<T>> {
            Box::new(DryWetBuiltin {
                mix: T::from_f64(0.5),
            })
        },
    );
}