vedasynth/
lib.rs

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
use std::{
    cmp::Ordering, collections::HashMap, fmt::Debug, ops::BitOr, sync::mpsc::{self, Receiver, Sender}
};

use cpal::{
    traits::{DeviceTrait, HostTrait, StreamTrait},
    Device, FromSample, OutputCallbackInfo, Sample, SampleFormat, SampleRate, SizedSample, Stream,
    StreamConfig, SupportedStreamConfigRange,
};

#[derive(Debug)]
struct SynthBackend {
    commands: Receiver<SynthCommand>,
    sample_rate: u32,
    channels: usize,
    synths: HashMap<SynthId, SynthChannel>,
}

impl SynthBackend {
    fn new(rx: Receiver<SynthCommand>, sample_rate: u32, channels: usize) -> SynthBackend {
        SynthBackend {
            commands: rx,
            sample_rate,
            channels,
            synths: HashMap::new(),
        }
    }
    fn write_samples<T: Sample + FromSample<f32>>(
        &mut self,
        data: &mut [T],
        _info: &OutputCallbackInfo,
    ) {
        for sample in data.iter_mut() {
            *sample = T::EQUILIBRIUM;
        }
        while let Ok(cmd) = self.commands.try_recv() {
            let synth = self
                .synths
                .entry(cmd.synth)
                .or_insert_with(SynthChannel::default);
            match cmd.operation {
                SynthOp::SetVolume(vol) => synth.volume.tween_to(vol, cmd.lerp_time),
                SynthOp::SetPitch(pitch) => synth.frequency.tween_to(pitch, cmd.lerp_time),
                SynthOp::SetChannelMask(cm) => synth.channel_mask = cm,
            }
        }
        let timestep = 1.0 / (self.sample_rate as f32);
        /*if let Some(s) = self.synths.get(&SynthId(0)) {
            let o2 = s.oscillator + timestep*s.frequency.current();
            println!("O: {}, O2: {o2}, Dif: {}", s.oscillator, o2-s.oscillator);
        }*/
        for sample in 0..data.len() / self.channels {
            let mut channels = vec![0.0; self.channels];
            for synth in self.synths.values_mut() {
                let val = synth.next_sample(timestep);
                for i in 0..self.channels {
                    if synth.channel_mask.0 & (1 << i) != 0 {
                        channels[i] += val;
                    }
                }
            }
            for (i, channel) in channels.into_iter().enumerate() {
                data[sample * self.channels + i] = T::from_sample(channel);
            }
        }
    }
}

#[derive(Debug, Clone)]
struct SynthChannel {
    frequency: Tweenable,
    volume: Tweenable,
    channel_mask: ChannelMask,
    oscillator: f32,
}

impl Default for SynthChannel {
    fn default() -> Self {
        Self {
            frequency: Tweenable::new(220.0),
            volume: Tweenable::new(0.0),
            channel_mask: ChannelMask::STEREO,
            oscillator: 0.0,
        }
    }
}

impl SynthChannel {
    #[inline]
    fn next_sample(&mut self, amount: f32) -> f32 {
        let val = (self.oscillator * std::f32::consts::PI * 2.0).sin() * self.volume.current();
        self.oscillator = (self.oscillator + amount * self.frequency.current()) % 1.0;
        self.frequency.advance(amount);
        self.volume.advance(amount);
        val
    }
}

// TODO: Make this support more than linear interpolations
#[derive(Debug, Clone)]
pub struct Tweenable {
    current: f32,
    tween: Option<(f32, f32)>,
}

impl Tweenable {
    pub fn new(val: f32) -> Tweenable {
        Tweenable {
            current: val,
            tween: None,
        }
    }
    #[inline(always)]
    pub fn current(&self) -> f32 {
        self.current
    }
    #[inline]
    pub fn advance(&mut self, amount: f32) -> f32 {
        if let Some((target, remaining)) = self.tween {
            if amount >= remaining {
                self.current = target;
                self.tween = None;
            } else {
                self.current += (target - self.current) * (amount / remaining);
                self.tween = Some((target, remaining - amount));
            }
        }
        self.current
    }
    #[inline]
    pub fn tween_to(&mut self, target: f32, time: f32) {
        self.tween = Some((target, time));
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ChannelMask(pub usize);

impl ChannelMask {
    pub const STEREO: Self = ChannelMask(3);
    pub const LEFT: Self = ChannelMask(1 << 0);
    pub const RIGHT: Self = ChannelMask(1 << 1);
    pub const CENTER: Self = ChannelMask(1 << 2);
    pub const SUB: Self = ChannelMask(1 << 3);
    pub const REAR_LEFT: Self = ChannelMask(1 << 4);
    pub const REAR_RIGHT: Self = ChannelMask(1 << 5);
    pub const SIDE_LEFT: Self = ChannelMask(1 << 6);
    pub const SIDE_RIGHT: Self = ChannelMask(1 << 7);
}

impl BitOr for ChannelMask {
    type Output = usize;

    fn bitor(self, rhs: Self) -> Self::Output {
        self.0.bitor(rhs.0)
    }
}

impl From<usize> for ChannelMask {
    fn from(value: usize) -> Self {
        ChannelMask(value)
    }
}

impl Default for ChannelMask {
    fn default() -> Self {
        Self::STEREO
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SynthId(pub usize);

#[derive(Debug, Clone, Copy)]
enum SynthOp {
    SetVolume(f32),
    SetPitch(f32),
    SetChannelMask(ChannelMask),
}

#[derive(Debug, Clone)]
struct SynthCommand {
    synth: SynthId,
    operation: SynthOp,
    lerp_time: f32,
}

pub struct Synth {
    _stream: Box<dyn StreamTrait>,
    command_channel: Sender<SynthCommand>,
    pub channel_count: usize,
    pub next_synth: usize,
}

const DEFAULT_LERP_TIME: f32 = 0.01;

pub struct AudioSink {
    pub host_name: String,
    pub device_name: String,
    pub device: Device,
}

impl Debug for AudioSink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AudioSink")
            .field("host_name", &self.host_name)
            .field("device_name", &self.device_name)
            .finish_non_exhaustive()
    }
}

#[derive(Debug)]
pub struct SinkList(pub Vec<AudioSink>);

impl From<SinkList> for Device {
    fn from(mut value: SinkList) -> Self {
        value.0.remove(0).device
    }
}

impl SinkList {
    pub fn get_sinks() -> SinkList {
        let mut list = Vec::new();
        for host_id in cpal::available_hosts() {
            let host = cpal::host_from_id(host_id).unwrap();
            for device in host.output_devices().unwrap() {
                list.push(AudioSink {
                    host_name: host_id.name().to_string(),
                    device_name: device.name().unwrap(),
                    device,
                });
            }
        }
        SinkList(list)
    }
    pub fn sort_default(mut self) -> Self {
        self.0.sort_by_cached_key(|dev| {
            -if dev.device_name.ends_with("_in") {
                -10
            } else if dev.host_name == "ALSA" {
                match dev.device_name.as_str() {
                    "pipewire" => -1,
                    "jack" => -2,
                    "pulse" => -3,
                    "default" => -4,
                    _ => -5,
                }
            } else if dev.host_name == "JACK" && dev.device_name.ends_with("_out") {
                1
            } else {
                0
            }
        });
        self
    }
}

fn device_sr(d: &SupportedStreamConfigRange) -> u32 {
    48000.clamp(d.min_sample_rate().0, d.max_sample_rate().0)
}

fn sr_score(a: u32) -> i32 {
    match a {
        88200 | 96000 | 24000 | 22050 => 1,
        44100..=48000 => 2,
        0..=44099 => 96000 - (a as i32) * 2,
        _ => 48000 - (a as i32),
    }
}
fn fmt_score(a: SampleFormat) -> i32 {
    match a {
        SampleFormat::I8 => -4,
        SampleFormat::I16 => -3,
        SampleFormat::I32 => -2,
        SampleFormat::I64 => -3,
        SampleFormat::U8 => -4,
        SampleFormat::U16 => -3,
        SampleFormat::U32 => -2,
        SampleFormat::U64 => -3,
        SampleFormat::F32 => 0,
        SampleFormat::F64 => -1,
        _ => -10,
    }
}
fn chan_score(a: u16) -> i32 {
    match a {
        2 => 14,
        3..=13 => a as i32,
        1 => 1,
        _ => -(a as i32),
    }
}

impl Synth {
    pub fn new() -> Synth {
        Synth::new_on_sink(Synth::get_sinks().sort_default())
    }
    pub fn get_sinks() -> SinkList {
        SinkList::get_sinks()
    }
    pub fn new_on_sink(audio_sink: impl Into<Device>) -> Synth {
        let device: Device = audio_sink.into();
        let selected_config = device
            .supported_output_configs()
            .unwrap()
            .reduce(|a, b| {
                match sr_score(device_sr(&a)).cmp(&sr_score(device_sr(&b))) {
                    Ordering::Less => return b,
                    Ordering::Greater => return a,
                    _ => {}
                }
                match fmt_score(a.sample_format()).cmp(&fmt_score(b.sample_format())) {
                    Ordering::Less => return b,
                    Ordering::Greater => return a,
                    _ => {}
                }
                match chan_score(a.channels()).cmp(&chan_score(b.channels())) {
                    Ordering::Less => return b,
                    Ordering::Greater => return a,
                    _ => {}
                }

                a
            })
            .unwrap();
        let sr = device_sr(&selected_config);
        let selected_config = selected_config.with_sample_rate(SampleRate(sr));
        fn build_stream<T: SizedSample + FromSample<f32>>(
            device: &Device,
            config: &StreamConfig,
            mut backend: SynthBackend,
        ) -> Stream {
            let err_fn = |e| eprintln!("CPAL Error: {e}");
            let stream = device
                .build_output_stream(
                    config,
                    move |data, info| backend.write_samples::<T>(data, info),
                    err_fn,
                    None,
                )
                .unwrap();
            stream.play().unwrap();
            stream
        }
        let (tx, rx) = mpsc::channel();
        let sample_rate = selected_config.sample_rate();
        let sample_format = selected_config.sample_format();
        let channel_count = selected_config.channels() as usize;
        let backend = SynthBackend::new(rx, sample_rate.0, channel_count);
        let stream = {
            let config = selected_config.into();
            match sample_format {
                SampleFormat::I8 => build_stream::<i8>(&device, &config, backend),
                SampleFormat::I16 => build_stream::<i16>(&device, &config, backend),
                SampleFormat::I32 => build_stream::<i32>(&device, &config, backend),
                SampleFormat::I64 => build_stream::<i64>(&device, &config, backend),
                SampleFormat::U8 => build_stream::<u8>(&device, &config, backend),
                SampleFormat::U16 => build_stream::<u16>(&device, &config, backend),
                SampleFormat::U32 => build_stream::<u32>(&device, &config, backend),
                SampleFormat::U64 => build_stream::<u64>(&device, &config, backend),
                SampleFormat::F32 => build_stream::<f32>(&device, &config, backend),
                SampleFormat::F64 => build_stream::<f64>(&device, &config, backend),
                _ => todo!(),
            }
        };
        Synth {
            _stream: Box::new(stream),
            command_channel: tx,
            channel_count,
            next_synth: 0,
        }
    }
    pub fn new_synth(&mut self, volume: f32, pitch: f32) -> SynthId {
        let synth = SynthId(self.next_synth);
        self.next_synth += 1;
        self.set_volume(synth, volume);
        self.set_pitch(synth, pitch);
        self.set_channel_mask(synth, ChannelMask::default());
        synth
    }
    pub fn set_volume(&mut self, synth: SynthId, volume: f32) {
        self.set_volume_lerp(synth, volume, DEFAULT_LERP_TIME);
    }
    pub fn set_volume_lerp(&mut self, synth: SynthId, volume: f32, lerp_time: f32) {
        self.command_channel
            .send(SynthCommand {
                synth,
                operation: SynthOp::SetVolume(volume),
                lerp_time,
            })
            .unwrap();
    }
    pub fn set_pitch(&mut self, synth: SynthId, pitch: f32) {
        self.set_pitch_lerp(synth, pitch, DEFAULT_LERP_TIME);
    }
    pub fn set_pitch_lerp(&mut self, synth: SynthId, pitch: f32, lerp_time: f32) {
        self.command_channel
            .send(SynthCommand {
                synth,
                operation: SynthOp::SetPitch(pitch),
                lerp_time,
            })
            .unwrap();
    }
    pub fn set_channel_mask(&mut self, synth: SynthId, channel_mask: ChannelMask) {
        self.set_channel_mask_lerp(synth, channel_mask, DEFAULT_LERP_TIME);
    }
    pub fn set_channel_mask_lerp(
        &mut self,
        synth: SynthId,
        channel_mask: ChannelMask,
        lerp_time: f32,
    ) {
        self.command_channel
            .send(SynthCommand {
                synth,
                operation: SynthOp::SetChannelMask(channel_mask),
                lerp_time,
            })
            .unwrap();
    }
    pub fn stop_all(&mut self) {
        for s in 0..self.next_synth {
            self.set_volume(SynthId(s), 0.0);
        }
    }
}