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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
use rubato::{FftFixedIn, Resampler};
// crossbeam for the event queue
use crossbeam::atomic::AtomicCell;
use std::sync::Arc;
use crate::building_blocks::ambisonics::binauralizer_o1::BinauralizerO1;
use crate::building_blocks::delay::MultichannelDelay;
use crate::building_blocks::limiter::rockwall::RockWallLimiter;
use crate::building_blocks::reverb::convolution::MultichannelConvolutionReverb;
use crate::building_blocks::reverb::freeverb::MultichannelFreeverb;
use crate::building_blocks::{MultichannelFilter, MultichannelReverb, SampleBuffer, Synth};
use crate::ruffbox::{ControlMessage, ReverbMode, ScheduledEvent};
use crate::ruffbox::ScheduledSource;
pub(crate) struct FreezeAfterRec {
freeze_buffer_number: usize, // freeze to after recording
freeze_after: usize, // the number of samples to be recorded
recorded: usize, // the number of samples recorded
add: bool, // if true, add, if false, overwrite
}
pub(crate) struct LiveBufferMetadata<const BUFSIZE: usize> {
live_buffer_idx: usize,
//pub(crate) stitch_buffer_incoming: Vec<f32>,
pub(crate) stitch_buffer_previous: Vec<f32>,
accum_buf: [f32; BUFSIZE],
accum_buf_idx: usize,
freeze_after_recs: Vec<FreezeAfterRec>,
}
/// ambisonic encoder module
pub struct Ambisonic<const BUFSIZE: usize, const NCHAN: usize> {
running_instances: Vec<Box<dyn Synth<BUFSIZE, NCHAN> + Send + Sync>>,
// has to be n-channel unfotunately ..
pending_events: Vec<ScheduledEvent<BUFSIZE, NCHAN>>,
ambi_master: [[f32; BUFSIZE]; NCHAN],
ambi_reverb_in: [[f32; BUFSIZE]; NCHAN],
}
impl<const BUFSIZE: usize, const NCHAN: usize> Default for Ambisonic<BUFSIZE, NCHAN> {
fn default() -> Self {
Self::new()
}
}
impl<const BUFSIZE: usize, const NCHAN: usize> Ambisonic<BUFSIZE, NCHAN> {
pub fn new() -> Self {
Ambisonic {
running_instances: Vec::with_capacity(900),
pending_events: Vec::with_capacity(900),
ambi_master: [[0.0; BUFSIZE]; NCHAN],
ambi_reverb_in: [[0.0; BUFSIZE]; NCHAN],
}
}
}
// preliminary ambi binauralizer, currently limited to order 1
pub struct AmbisonicBinauralizer<const BUFSIZE: usize, const NCHAN: usize> {
binauralizer: BinauralizerO1<BUFSIZE, NCHAN>,
binauralizer_rev: BinauralizerO1<BUFSIZE, NCHAN>,
}
impl<const BUFSIZE: usize, const NCHAN: usize> AmbisonicBinauralizer<BUFSIZE, NCHAN> {
pub fn new(samplerate: f32) -> Self {
AmbisonicBinauralizer {
binauralizer: BinauralizerO1::default_filter(samplerate),
binauralizer_rev: BinauralizerO1::default_filter(samplerate),
}
}
}
/// This is the "Playhead", that is, the part you use in the
/// output callback funtion of your application
pub struct RuffboxPlayhead<const BUFSIZE: usize, const NCHAN: usize> {
running_instances: Vec<Box<dyn Synth<BUFSIZE, NCHAN> + Send + Sync>>,
pending_events: Vec<ScheduledEvent<BUFSIZE, NCHAN>>,
ambisonic: Option<Ambisonic<BUFSIZE, NCHAN>>,
ambisonic_binauralizer: Option<AmbisonicBinauralizer<BUFSIZE, NCHAN>>,
pub(crate) buffers: Vec<SampleBuffer>, // crate public for test
pub(crate) buffer_lengths: Vec<usize>, // crate public for test
max_buffers: usize,
stitch_size: usize,
pub(crate) fade_curve: Vec<f32>, // crate public for test
pub(crate) live_buffer_metadata: Vec<LiveBufferMetadata<BUFSIZE>>,
freeze_buffer_offset: usize,
num_live_buffers: usize,
num_freeze_buffers: usize,
samplerate: f32,
control_q_rec: crossbeam::channel::Receiver<ControlMessage<BUFSIZE, NCHAN>>,
block_duration: f64,
sec_per_sample: f64,
now: Arc<AtomicCell<f64>>,
global_reverb: Box<dyn MultichannelReverb<BUFSIZE, NCHAN> + Send + Sync>,
global_delay: MultichannelDelay<BUFSIZE, NCHAN>,
global_limiter: Option<RockWallLimiter<BUFSIZE, NCHAN>>,
global_hpf: MultichannelFilter<BUFSIZE, NCHAN>,
global_lpf: MultichannelFilter<BUFSIZE, NCHAN>,
}
impl<const BUFSIZE: usize, const NCHAN: usize> RuffboxPlayhead<BUFSIZE, NCHAN> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
live_buffers: usize,
live_buffer_time: f64,
reverb_mode: &ReverbMode,
samplerate: f64,
max_buffers: usize,
freeze_buffers: usize,
now: &Arc<AtomicCell<f64>>,
rx: crossbeam::channel::Receiver<ControlMessage<BUFSIZE, NCHAN>>,
) -> RuffboxPlayhead<BUFSIZE, NCHAN> {
// create reverb
let rev: Box<dyn MultichannelReverb<BUFSIZE, NCHAN> + Send + Sync> = match reverb_mode {
ReverbMode::FreeVerb => {
let mut mrev = MultichannelFreeverb::new(samplerate as f32);
// tweak some reverb values for freeverb
mrev.set_roomsize(0.65);
mrev.set_damp(0.43);
mrev.set_wet(1.0);
Box::new(mrev)
}
ReverbMode::Convolution(ir, sr) => {
let mut ir_clone = ir.clone();
// resample IR if needed ...
if *sr as f64 != samplerate {
// zero-pad for resampling blocks
if (ir.len() as f32 % 1024.0) > 0.0 {
let diff = 1024 - (ir.len() % 1024);
ir_clone.append(&mut vec![0.0; diff]);
}
let mut ir_resampled: Vec<f32> = Vec::new();
let mut resampler =
FftFixedIn::<f32>::new(*sr as usize, samplerate as usize, 1024, 1, 1)
.unwrap();
let num_chunks = ir.len() / 1024;
for chunk in 0..num_chunks {
let chunk = vec![ir_clone[(1024 * chunk)..(1024 * (chunk + 1))].to_vec()];
let mut waves_out = resampler.process(&chunk, None).unwrap();
ir_resampled.append(&mut waves_out[0]);
}
Box::new(MultichannelConvolutionReverb::with_ir(&ir_resampled))
} else {
Box::new(MultichannelConvolutionReverb::with_ir(ir))
}
}
};
// init buffer memory
let mut buffers = Vec::new();
for _ in 0..max_buffers {
// with placeholders ...
buffers.push(SampleBuffer::Placeholder);
}
// init buffer lengths
let mut buffer_lengths = vec![0; max_buffers];
//println!("max num buffers {} {}", buffers.len(), max_buffers);
let stitch_size = BUFSIZE / 4;
let mut live_buffer_metadata = Vec::new();
let mut fade_curve = Vec::new();
if live_buffers > 0 {
// pre-calculate a fade curve for live buffer stitching
let pi_inc = std::f32::consts::PI / stitch_size as f32;
let mut pi_idx: f32 = 0.0;
for _ in 0..stitch_size {
// FADE-IN-CURVE
fade_curve.push((-pi_idx.cos() + 1.0) / 2.0);
pi_idx += pi_inc;
}
// one stitch buffer per live buffer
for _ in 0..live_buffers {
live_buffer_metadata.push(LiveBufferMetadata {
live_buffer_idx: 2, // let room for interpolation
//stitch_buffer_incoming: vec![0.0; stitch_size],
stitch_buffer_previous: vec![0.0; stitch_size],
accum_buf: [0.0; BUFSIZE],
accum_buf_idx: 0,
freeze_after_recs: Vec::with_capacity(100),
});
}
// create live buffers and freeze buffers
for b in 0..live_buffers + freeze_buffers {
let buflen_norinterp = (samplerate * live_buffer_time) as usize;
// two interpolation samples in each direction ...
buffers[b] = SampleBuffer::Mono(vec![0.0; buflen_norinterp + 4]);
buffer_lengths[b] = buflen_norinterp;
}
println!("live buf time samples: {}", buffer_lengths[0]);
}
RuffboxPlayhead {
running_instances: Vec::with_capacity(600),
pending_events: Vec::with_capacity(600),
ambisonic: None,
ambisonic_binauralizer: None,
buffers,
buffer_lengths,
max_buffers,
live_buffer_metadata,
fade_curve,
stitch_size,
samplerate: samplerate as f32,
control_q_rec: rx,
// timing stuff
block_duration: BUFSIZE as f64 / samplerate,
sec_per_sample: 1.0 / samplerate,
now: Arc::clone(now),
global_reverb: rev,
global_delay: MultichannelDelay::new(samplerate as f32),
freeze_buffer_offset: live_buffers,
num_live_buffers: live_buffers,
num_freeze_buffers: freeze_buffers,
global_limiter: None,
global_hpf: MultichannelFilter::new(
crate::building_blocks::FilterType::BiquadHpf24dB,
samplerate as f32,
),
global_lpf: MultichannelFilter::new(
crate::building_blocks::FilterType::BiquadLpf24dB,
samplerate as f32,
),
}
}
pub fn enable_ambisonics(&mut self) {
println!("[ruffbox-synth] activate ambisonics module");
if let Some(lim) = self.global_limiter.as_mut() {
lim.ambi_mode = true;
}
self.ambisonic = Some(Ambisonic::new());
}
pub fn enable_ambisonic_binauralizer(&mut self) {
if let Some(lim) = self.global_limiter.as_mut() {
lim.ambi_mode = false;
}
println!("[ruffbox-synth] activate ambisonic binauralizer module");
self.ambisonic_binauralizer = Some(AmbisonicBinauralizer::new(self.samplerate));
}
pub fn enable_limiter(&mut self) {
println!("[ruffbox-synth] activate safety limiter");
self.global_limiter = Some(RockWallLimiter::new(
self.samplerate,
self.ambisonic.is_some() && self.ambisonic_binauralizer.is_none(),
));
}
pub fn write_samples_to_live_buffer(&mut self, bufnum: usize) {
// so far we only allow writing to a mono buffer, one input at a time
if let Some(SampleBuffer::Mono(buf)) = self.buffers.get_mut(bufnum) {
// WITHOUT interpolation samples
let buflen = self.buffer_lengths[bufnum];
let bufidx = self.live_buffer_metadata[bufnum].live_buffer_idx;
// make sure bufidx is always bigger than 1 and smaller than
// buflen + 2
// calculate start point, keeping interpolation samples in mind
let tmp_idx = bufidx - 2; // index is >= 2, always (interpolation)
let mut cur_idx = if tmp_idx >= self.stitch_size {
bufidx - self.stitch_size
} else {
let tmp = self.stitch_size - tmp_idx;
(buflen - tmp) + 2 // add interp. samples
};
/*
assert!(cur_idx >= 2);
assert!(
cur_idx - 2 < buflen,
"cur {cur_idx} len {buflen} tmp {tmp_idx}"
);*/
for i in 0..self.stitch_size {
buf[cur_idx] = self.live_buffer_metadata[bufnum].stitch_buffer_previous[i];
cur_idx += 1;
// flip if necessary
if cur_idx - 2 >= buflen {
//println!("FLIP 1");
cur_idx = 2;
}
}
//assert!(cur_idx >= 2);
//assert!(cur_idx - 2 < buflen);
// back to where we were ...
//assert!(cur_idx == bufidx, "curid {cur_idx} bufid {bufidx}");
let buf_head = BUFSIZE - self.stitch_size;
for i in 0..buf_head {
buf[cur_idx] = self.live_buffer_metadata[bufnum].accum_buf[i];
cur_idx += 1;
// flip if necessary
if cur_idx - 2 >= buflen {
//println!("FLIP 2");
cur_idx = 2;
}
}
//assert!(cur_idx >= 2);
//assert!(cur_idx - 2 < buflen);
// keep for later
for i in buf_head..BUFSIZE {
self.live_buffer_metadata[bufnum].stitch_buffer_previous[i - buf_head] =
self.live_buffer_metadata[bufnum].accum_buf[i]
}
for i in 0..self.stitch_size {
let gain = self.fade_curve[i];
buf[cur_idx] = buf[cur_idx] * gain
+ self.live_buffer_metadata[bufnum].accum_buf[buf_head + i] * (1.0 - gain);
cur_idx += 1;
// flip if necessary
if cur_idx - 2 >= buflen {
//println!("FLIP 3");
cur_idx = 2;
}
}
//assert!(cur_idx >= 2);
//assert!(cur_idx - 2 < buflen);
self.live_buffer_metadata[bufnum].live_buffer_idx = cur_idx;
// update freeze-after-recs
for far in self.live_buffer_metadata[bufnum]
.freeze_after_recs
.iter_mut()
{
far.recorded += BUFSIZE;
}
}
}
pub fn write_sample_to_live_buffer(&mut self, bufnum: usize, sample: f32) {
let mut idx = self.live_buffer_metadata[bufnum].accum_buf_idx;
self.live_buffer_metadata[bufnum].accum_buf[idx] = sample;
idx += 1;
if idx == BUFSIZE {
self.write_samples_to_live_buffer(bufnum);
self.live_buffer_metadata[bufnum].accum_buf_idx = 0;
} else {
self.live_buffer_metadata[bufnum].accum_buf_idx = idx;
}
}
fn handle_control_messages(&mut self, now: f64) {
for cm in self.control_q_rec.try_iter() {
match cm {
ControlMessage::ClearAllFreezeBuffers => {
for i in self.freeze_buffer_offset
..self.freeze_buffer_offset + self.num_freeze_buffers
{
if let Some(freezbuf) = self.buffers.get_mut(i) {
match freezbuf {
SampleBuffer::Mono(buf) => {
buf.fill(0.0);
}
SampleBuffer::Stereo(buf_l, buf_r) => {
buf_l.fill(0.0);
buf_r.fill(0.0);
}
SampleBuffer::Placeholder => { /* no-op */ }
}
}
}
}
ControlMessage::ClearAllLiveBuffers => {
for i in 0..self.num_live_buffers {
if let Some(livebuf) = self.buffers.get_mut(i) {
match livebuf {
SampleBuffer::Mono(buf) => {
buf.fill(0.0);
}
SampleBuffer::Stereo(buf_l, buf_r) => {
buf_l.fill(0.0);
buf_r.fill(0.0);
}
SampleBuffer::Placeholder => { /* no-op */ }
}
}
}
}
ControlMessage::ClearAllBuffers => {
for i in 0..self.freeze_buffer_offset + self.num_freeze_buffers {
if let Some(xbuf) = self.buffers.get_mut(i) {
match xbuf {
SampleBuffer::Mono(buf) => {
buf.fill(0.0);
}
SampleBuffer::Stereo(buf_l, buf_r) => {
buf_l.fill(0.0);
buf_r.fill(0.0);
}
SampleBuffer::Placeholder => { /* no-op */ }
}
}
}
}
ControlMessage::ClearLiveBuffer(bufnum) => {
if let Some(livebuf) = self.buffers.get_mut(bufnum) {
match livebuf {
SampleBuffer::Mono(buf) => {
buf.fill(0.0);
}
SampleBuffer::Stereo(buf_l, buf_r) => {
buf_l.fill(0.0);
buf_r.fill(0.0);
}
SampleBuffer::Placeholder => { /* no-op */ }
}
}
}
ControlMessage::ClearFreezeBuffer(bufnum) => {
if let Some(freezbuf) = self.buffers.get_mut(self.freeze_buffer_offset + bufnum)
{
match freezbuf {
SampleBuffer::Mono(buf) => {
buf.fill(0.0);
}
SampleBuffer::Stereo(buf_l, buf_r) => {
buf_l.fill(0.0);
buf_r.fill(0.0);
}
SampleBuffer::Placeholder => { /* no-op */ }
}
}
}
ControlMessage::SetGlobalParamOrModulator(fx, par, val) => match fx {
super::GlobalEffect::GlobalDelay => {
self.global_delay.set_param_or_modulator(par, val)
}
super::GlobalEffect::GlobalReverb => {
self.global_reverb.set_param_or_modulator(par, val.clone())
}
super::GlobalEffect::GlobalLpf => {
self.global_lpf.set_param_or_modulator(par, val.clone())
}
super::GlobalEffect::GlobalHpf => {
self.global_hpf.set_param_or_modulator(par, val.clone())
}
},
ControlMessage::ScheduleEvent(sched_event) => {
// add new instances
match sched_event.source {
ScheduledSource::Channel(src) => {
if sched_event.timestamp == 0.0 || sched_event.timestamp == now {
self.running_instances.push(src);
//println!("now");
} else if sched_event.timestamp < now {
// late events
self.running_instances.push(src);
// how to send out a late message ??
// some lock-free message queue to a printer thread or something ....
println!("late");
} else {
self.pending_events.push(ScheduledEvent {
timestamp: sched_event.timestamp,
source: ScheduledSource::Channel(src),
});
}
}
// handle ambisonic sources ...
ScheduledSource::Ambi(src) => {
if let Some(ambi_module) = self.ambisonic.as_mut() {
if sched_event.timestamp == 0.0 || sched_event.timestamp == now {
ambi_module.running_instances.push(src);
//println!("now");
} else if sched_event.timestamp < now {
// late events
ambi_module.running_instances.push(src);
// how to send out a late message ??
// some lock-free message queue to a printer thread or something ....
println!("ambi late");
} else {
ambi_module.pending_events.push(ScheduledEvent {
timestamp: sched_event.timestamp,
source: ScheduledSource::Ambi(src),
});
}
}
}
}
}
ControlMessage::LoadSample(id, len, content) => {
if id < self.max_buffers {
self.buffers[id] = content; // transfer to samples
self.buffer_lengths[id] = len;
}
}
ControlMessage::FreezeBuffer(fb, ib) => {
// start at one to account for interpolation sample.
if let Ok([SampleBuffer::Mono(inbuf), SampleBuffer::Mono(freezbuf)]) =
self.buffers.get_disjoint_mut([ib, fb])
{
freezbuf[2..(self.buffer_lengths[ib] + 2)]
.copy_from_slice(&inbuf[2..(self.buffer_lengths[ib] + 2)]);
}
}
ControlMessage::FreezeAddBuffer(fb, ib) => {
// start at one to account for interpolation sample.
if let Ok([SampleBuffer::Mono(inbuf), SampleBuffer::Mono(freezbuf)]) =
self.buffers.get_disjoint_mut([ib, fb])
{
for i in 2..(self.buffer_lengths[ib] + 2) {
freezbuf[i] += inbuf[i];
}
}
}
ControlMessage::FreezeAfterRec(fb, ib, num_samples, add) => {
// just checking ... don't need the actual data ...
if let Ok([SampleBuffer::Mono(_), SampleBuffer::Mono(_)]) =
self.buffers.get_disjoint_mut([ib, fb])
{
self.live_buffer_metadata[ib]
.freeze_after_recs
.push(FreezeAfterRec {
freeze_buffer_number: fb,
freeze_after: num_samples,
recorded: 0,
add,
});
}
}
}
}
}
// if limiter is activated, this will output unprocessed and limiter
// output, otherwise just the limited output ...
pub fn process(
&mut self,
stream_time: f64,
track_time_internally: bool,
) -> ([[f32; BUFSIZE]; NCHAN], Option<[[f32; BUFSIZE]; NCHAN]>) {
let mut out_buf: [[f32; BUFSIZE]; NCHAN] = [[0.0; BUFSIZE]; NCHAN];
let mut global_delay_in: [[f32; BUFSIZE]; NCHAN] = [[0.0; BUFSIZE]; NCHAN];
let mut global_reverb_in: [[f32; BUFSIZE]; NCHAN] = [[0.0; BUFSIZE]; NCHAN];
// clear ambi master if necessary
if let Some(ambi_module) = self.ambisonic.as_mut() {
ambi_module.ambi_master = [[0.0; BUFSIZE]; NCHAN];
ambi_module.ambi_reverb_in = [[0.0; BUFSIZE]; NCHAN];
}
let now = if !track_time_internally {
self.now.store(stream_time);
stream_time
} else {
self.now.load()
};
// remove finished instances ...
self.running_instances
.retain(|instance| !&instance.is_finished());
// in case we have ambisonic mode enabled
if let Some(ambi_module) = self.ambisonic.as_mut() {
ambi_module
.running_instances
.retain(|instance| !&instance.is_finished());
}
// handle incoming control messages ...
self.handle_control_messages(now);
// check synced freezes ...
for (bufnum, lbm) in self.live_buffer_metadata.iter_mut().enumerate() {
for far in lbm.freeze_after_recs.iter() {
//println!("{}", far.recorded);
if far.recorded >= far.freeze_after {
// freeze the number of recorded samples, copy to beginning of freezebuffer
if let Ok([SampleBuffer::Mono(inbuf), SampleBuffer::Mono(freezbuf)]) = self
.buffers
.get_disjoint_mut([bufnum, far.freeze_buffer_number])
{
if lbm.live_buffer_idx > far.freeze_after {
let ib_offset = (lbm.live_buffer_idx - far.freeze_after) + 1;
if far.add {
for i in 0..far.freeze_after {
freezbuf[i + 2] += inbuf[ib_offset + i];
}
} else {
freezbuf[2..(far.freeze_after + 2)].copy_from_slice(
&inbuf[ib_offset..(far.freeze_after + ib_offset)],
);
}
} else {
// always the same story ...
let buflen = self.buffer_lengths[bufnum];
let mut tmp_lbi =
buflen - (far.freeze_after - (lbm.live_buffer_idx - 1)) + 2;
if far.add {
for i in 0..far.freeze_after {
freezbuf[i + 2] += inbuf[tmp_lbi];
tmp_lbi += 1;
if tmp_lbi - 2 >= buflen {
tmp_lbi = 2;
}
}
} else {
for i in 0..far.freeze_after {
freezbuf[i + 2] = inbuf[tmp_lbi];
tmp_lbi += 1;
if tmp_lbi - 2 >= buflen {
tmp_lbi = 2;
}
}
}
}
}
}
}
// purge the ones that are donw ...
lbm.freeze_after_recs
.retain(|far| far.recorded < far.freeze_after);
}
#[cfg(feature = "no_denormals")]
let beacon = crate::ruffbox::flush_denormals::no_denormals_on();
// handle already running instances
for running_inst in self.running_instances.iter_mut() {
let block = running_inst.get_next_block(0, &self.buffers);
// this should benefit from unrolling outer loop with macro ...
for c in 0..NCHAN {
for s in 0..BUFSIZE {
out_buf[c][s] += block[c][s];
global_reverb_in[c][s] += block[c][s] * running_inst.reverb_level();
global_delay_in[c][s] += block[c][s] * running_inst.delay_level();
}
}
}
if let Some(ambi_module) = self.ambisonic.as_mut() {
for running_inst in ambi_module.running_instances.iter_mut() {
let ambi_block = running_inst.get_next_block(0, &self.buffers);
// this should benefit from unrolling outer loop with macro ...
for c in 0..NCHAN {
for s in 0..BUFSIZE {
ambi_module.ambi_master[c][s] += ambi_block[c][s];
ambi_module.ambi_reverb_in[c][s] +=
ambi_block[c][s] * running_inst.reverb_level();
}
}
}
}
// sort new events by timestamp, order of already sorted elements doesn't matter
self.pending_events.sort_unstable_by(|a, b| b.cmp(a));
let block_end = now + self.block_duration;
// fetch event if it belongs to this block, if any ...
while !self.pending_events.is_empty()
&& self.pending_events.last().unwrap().timestamp < block_end
{
let current_event = self.pending_events.pop().unwrap();
//println!("on time ts: {} st: {}", current_event.timestamp, self.now);
// calculate precise timing
let sample_offset = (current_event.timestamp - now) / self.sec_per_sample;
if let ScheduledSource::Channel(mut src) = current_event.source {
let block = src.get_next_block(sample_offset.round() as usize, &self.buffers);
for c in 0..NCHAN {
for s in 0..BUFSIZE {
out_buf[c][s] += block[c][s];
global_reverb_in[c][s] += block[c][s] * src.reverb_level();
global_delay_in[c][s] += block[c][s] * src.delay_level();
}
}
// if length of sample event is longer than the rest of the block,
// add to running instances
if !src.is_finished() {
self.running_instances.push(src);
}
}
}
if let Some(ambi_module) = self.ambisonic.as_mut() {
// sort new events by timestamp, order of already sorted elements doesn't matter
ambi_module.pending_events.sort_unstable_by(|a, b| b.cmp(a));
// fetch event if it belongs to this block, if any ...
while !ambi_module.pending_events.is_empty()
&& ambi_module.pending_events.last().unwrap().timestamp < block_end
{
let current_event = ambi_module.pending_events.pop().unwrap();
//println!("on time ts: {} st: {}", current_event.timestamp, self.now);
// calculate precise timing
let sample_offset = (current_event.timestamp - now) / self.sec_per_sample;
if let ScheduledSource::Ambi(mut src) = current_event.source {
let ambi_block =
src.get_next_block(sample_offset.round() as usize, &self.buffers);
for c in 0..NCHAN {
for s in 0..BUFSIZE {
ambi_module.ambi_master[c][s] += ambi_block[c][s];
ambi_module.ambi_reverb_in[c][s] +=
ambi_block[c][s] * src.reverb_level();
}
}
// if length of sample event is longer than the rest of the block,
// add to running instances
if !src.is_finished() {
ambi_module.running_instances.push(src);
}
}
}
if let Some(binaural) = self.ambisonic_binauralizer.as_mut() {
let block = binaural.binauralizer.binauralize(ambi_module.ambi_master);
// this has to do for a reverb until I manage to implement a proper ambisonic reverb ...
let block_rev = binaural
.binauralizer_rev
.binauralize(ambi_module.ambi_reverb_in);
// mix binauralized block in with master
for c in 0..2 {
for s in 0..BUFSIZE {
out_buf[c][s] += block[c][s];
global_reverb_in[c][s] += block_rev[c][s];
}
}
// mute HOA channels
for c in 2..NCHAN {
for s in 0..BUFSIZE {
out_buf[c][s] = 0.0;
global_reverb_in[c][s] = 0.0;
}
}
} else {
for c in 0..NCHAN {
for s in 0..BUFSIZE {
out_buf[c][s] += ambi_module.ambi_master[c][s];
global_reverb_in[c][s] += ambi_module.ambi_reverb_in[c][s];
}
}
}
}
let reverb_out = self.global_reverb.process(global_reverb_in);
let delay_out = self.global_delay.process(global_delay_in, &self.buffers);
for c in 0..NCHAN {
for s in 0..BUFSIZE {
out_buf[c][s] += reverb_out[c][s] + delay_out[c][s];
}
}
out_buf = self.global_hpf.process(out_buf, &self.buffers);
out_buf = self.global_lpf.process(out_buf, &self.buffers);
let out_buf_lim = self.global_limiter.as_mut().map(|lim| lim.process(out_buf));
#[cfg(feature = "no_denormals")]
crate::ruffbox::flush_denormals::no_denormals_off(beacon);
if track_time_internally {
self.now.store(now + self.block_duration);
}
(out_buf, out_buf_lim)
}
}