caw_core 0.5.1

Core types for caw software-defined modular synthesizer
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
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
use crate::arith::signed_to_01;
use std::{
    fmt::Debug,
    iter,
    marker::PhantomData,
    sync::{Arc, RwLock},
};

#[derive(Clone, Copy, Debug)]
pub struct SigCtx {
    pub sample_rate_hz: f32,
    pub batch_index: u64,
    pub num_samples: usize,
}

pub trait Buf<T>
where
    T: Clone,
{
    fn iter(&self) -> impl Iterator<Item = T>;

    fn clone_to_vec(&self, out: &mut Vec<T>) {
        out.clear();
        for x in self.iter() {
            out.push(x.clone());
        }
    }

    /// Clone each sample into a slice with a given offset and stride. This is intended to be used
    /// to populate a single channel worth of samples into an audio buffer containing multiple
    /// interleaved channels.
    fn clone_to_slice(&self, stride: usize, offset: usize, out: &mut [T]) {
        let out_offset = &mut out[offset..];
        for (sample, out_chunk) in
            self.iter().zip(out_offset.chunks_mut(stride))
        {
            out_chunk[0] = sample;
        }
    }
}

impl<T> Buf<T> for &Vec<T>
where
    T: Clone,
{
    fn iter(&self) -> impl Iterator<Item = T> {
        (self as &[T]).iter().cloned()
    }

    fn clone_to_vec(&self, out: &mut Vec<T>) {
        if let Some(first) = self.first() {
            out.resize_with(self.len(), || first.clone());
            out.clone_from_slice(self);
        } else {
            // self is empty
            out.clear();
        }
    }
}

pub struct ConstBuf<T> {
    pub value: T,
    pub count: usize,
}

impl<T> Buf<T> for ConstBuf<T>
where
    T: Clone,
{
    fn iter(&self) -> impl Iterator<Item = T> {
        iter::repeat_n(&self.value, self.count).cloned()
    }

    fn clone_to_vec(&self, out: &mut Vec<T>) {
        out.resize_with(self.count, || self.value.clone());
        out.fill(self.value.clone());
    }
}

/// Used to implement `map` methods (but not `map_mut`) by deferring the mapped function until the
/// iteration of the following operation, preventing the need to buffer the result of the map.
pub struct MapBuf<B, F, I, O>
where
    I: Clone,
    O: Clone,
    B: Buf<I>,
    F: Fn(I) -> O,
{
    buf: B,
    f: F,
    phantom: PhantomData<(I, O)>,
}

impl<B, F, I, O> MapBuf<B, F, I, O>
where
    I: Clone,
    O: Clone,
    B: Buf<I>,
    F: Fn(I) -> O,
{
    pub fn new(buf: B, f: F) -> Self {
        Self {
            buf,
            f,
            phantom: PhantomData,
        }
    }
}

impl<B, F, I, O> Buf<O> for MapBuf<B, F, I, O>
where
    I: Clone,
    O: Clone,
    B: Buf<I>,
    F: Fn(I) -> O,
{
    fn iter(&self) -> impl Iterator<Item = O> {
        self.buf.iter().map(&self.f)
    }
}

/// Used to implement arithmetic operations by deferring the computation until the iteration of the
/// following operation, preventing the need to buffer the result of the map.
pub struct MapBuf2<BL, BR, F, L, R, O>
where
    L: Clone,
    R: Clone,
    O: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
    F: Fn(L, R) -> O,
{
    buf_left: BL,
    buf_right: BR,
    f: F,
    phantom: PhantomData<(L, R, O)>,
}

impl<BL, BR, F, L, R, O> MapBuf2<BL, BR, F, L, R, O>
where
    L: Clone,
    R: Clone,
    O: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
    F: Fn(L, R) -> O,
{
    pub fn new(buf_left: BL, buf_right: BR, f: F) -> Self {
        Self {
            buf_left,
            buf_right,
            f,
            phantom: PhantomData,
        }
    }
}

impl<BL, BR, F, L, R, O> Buf<O> for MapBuf2<BL, BR, F, L, R, O>
where
    L: Clone,
    R: Clone,
    O: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
    F: Fn(L, R) -> O,
{
    fn iter(&self) -> impl Iterator<Item = O> {
        self.buf_left
            .iter()
            .zip(self.buf_right.iter())
            .map(|(l, r)| (self.f)(l, r))
    }
}

/// Used to implement zip without the need for an explicit buffer for zipped values. The zipping
/// will take place in the iteration of the signal that consumes this buffer. Since zip operations
/// often follow map operations, and map operations use the `MapBuf` buffer type, sequences of zip
/// and map operations are fused without the need for intermediate buffers.
pub struct ZipBuf<BL, BR, L, R>
where
    L: Clone,
    R: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
{
    buf_left: BL,
    buf_right: BR,
    phantom: PhantomData<(L, R)>,
}

impl<BL, BR, L, R> ZipBuf<BL, BR, L, R>
where
    L: Clone,
    R: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
{
    pub fn new(buf_left: BL, buf_right: BR) -> Self {
        Self {
            buf_left,
            buf_right,
            phantom: PhantomData,
        }
    }
}

impl<BL, BR, L, R> Buf<(L, R)> for ZipBuf<BL, BR, L, R>
where
    L: Clone,
    R: Clone,
    BL: Buf<L>,
    BR: Buf<R>,
{
    fn iter(&self) -> impl Iterator<Item = (L, R)> {
        self.buf_left.iter().zip(self.buf_right.iter())
    }
}

/// Used to implement zip3 without the need for an explicit buffer for zipped values. The zipping
/// will take place in the iteration of the signal that consumes this buffer. Since zip operations
/// often follow map operations, and map operations use the `MapBuf` buffer type, sequences of zip
/// and map operations are fused without the need for intermediate buffers.
pub struct Zip3Buf<BA, BB, BC, A, B, C>
where
    A: Clone,
    B: Clone,
    C: Clone,
    BA: Buf<A>,
    BB: Buf<B>,
    BC: Buf<C>,
{
    buf_a: BA,
    buf_b: BB,
    buf_c: BC,
    phantom: PhantomData<(A, B, C)>,
}

impl<BA, BB, BC, A, B, C> Zip3Buf<BA, BB, BC, A, B, C>
where
    A: Clone,
    B: Clone,
    C: Clone,
    BA: Buf<A>,
    BB: Buf<B>,
    BC: Buf<C>,
{
    pub fn new(buf_a: BA, buf_b: BB, buf_c: BC) -> Self {
        Self {
            buf_a,
            buf_b,
            buf_c,
            phantom: PhantomData,
        }
    }
}

impl<BA, BB, BC, A, B, C> Buf<(A, B, C)> for Zip3Buf<BA, BB, BC, A, B, C>
where
    A: Clone,
    B: Clone,
    C: Clone,
    BA: Buf<A>,
    BB: Buf<B>,
    BC: Buf<C>,
{
    fn iter(&self) -> impl Iterator<Item = (A, B, C)> {
        self.buf_a
            .iter()
            .zip(self.buf_b.iter())
            .zip(self.buf_c.iter())
            .map(|((a, b), c)| (a, b, c))
    }
}

/// A signal with values produced for each audio sample. Values are produced in batches of a size
/// determined by the audio driver. This is suitable for audible audio signals or controls signals
/// that vary at the same rate as an audio signal (e.g. an envelope follower produced by analyzing
/// an audio signal). Low-frequency signals such as LFOs should still use this type, as their
/// value still changes smoothly at the audio sample rate despite the signal they represent
/// typically being below perceptible audio frequencies.
pub trait SigT {
    type Item: Clone;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item>;

    fn filter<F>(self, filter: F) -> Sig<F::Out<Self>>
    where
        F: Filter<ItemIn = Self::Item>,
        Self: Sized,
    {
        Sig(filter.into_sig(self))
    }
}

/// Similar to `SigT` but less flexible as it needs to populate a `Vec`. However this trait is
/// possible to be boxed allowing for type erasure.
pub trait SigSampleIntoBufT {
    type Item: Clone;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>);

    fn sample_into_slice(
        &mut self,
        ctx: &SigCtx,
        stride: usize,
        offset: usize,
        out: &mut [Self::Item],
    );
}

pub struct Const<T>(T)
where
    T: Clone;

impl<T> SigT for Const<T>
where
    T: Clone,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: self.0.clone(),
            count: ctx.num_samples,
        }
    }
}

impl SigT for f32 {
    type Item = f32;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: *self,
            count: ctx.num_samples,
        }
    }
}

impl SigT for u32 {
    type Item = u32;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: *self,
            count: ctx.num_samples,
        }
    }
}

/// For gate and trigger signals
impl SigT for bool {
    type Item = bool;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: *self,
            count: ctx.num_samples,
        }
    }
}

pub struct SigConst<T: Clone>(T);
impl<T: Clone> SigT for SigConst<T> {
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            value: self.0.clone(),
            count: ctx.num_samples,
        }
    }
}

/// Wrapper type for the `SigT` trait to simplify some trait implementations for signals. For
/// example this allows arithmetic traits like `std::ops::Add` to be implemented for signals.
#[derive(Clone)]
pub struct Sig<S>(pub S)
where
    S: SigT;

impl<S: SigT> SigT for Sig<S> {
    type Item = S::Item;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.0.sample(ctx)
    }
}

impl<S: SigT> SigSampleIntoBufT for Sig<S> {
    type Item = S::Item;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>) {
        let buf_internal = self.0.sample(ctx);
        buf_internal.clone_to_vec(buf);
    }

    fn sample_into_slice(
        &mut self,
        ctx: &SigCtx,
        stride: usize,
        offset: usize,
        out: &mut [Self::Item],
    ) {
        let buf_internal = self.0.sample(ctx);
        buf_internal.clone_to_slice(stride, offset, out);
    }
}

pub struct SigBoxed<T>
where
    T: Clone,
{
    sig: Arc<RwLock<dyn SigSampleIntoBufT<Item = T> + Send + Sync + 'static>>,
    buf: Vec<T>,
}

impl<T> Clone for SigBoxed<T>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        SigBoxed {
            sig: Arc::clone(&self.sig),
            buf: Vec::new(),
        }
    }
}

impl<T> SigSampleIntoBufT for SigBoxed<T>
where
    T: Clone,
{
    type Item = T;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>) {
        self.sig.write().unwrap().sample_into_buf(ctx, buf);
    }

    fn sample_into_slice(
        &mut self,
        ctx: &SigCtx,
        stride: usize,
        offset: usize,
        out: &mut [Self::Item],
    ) {
        self.sig
            .write()
            .unwrap()
            .sample_into_slice(ctx, stride, offset, out);
    }
}

impl<T> SigT for SigBoxed<T>
where
    T: Clone,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.sig
            .write()
            .unwrap()
            .sample_into_buf(ctx, &mut self.buf);
        &self.buf
    }
}

impl<S> Sig<S>
where
    S: SigT<Item: Clone>,
{
    pub fn map_mut<T, F>(self, f: F) -> Sig<MapMut<S, T, F>>
    where
        T: Clone,
        F: FnMut(S::Item) -> T,
    {
        Sig(MapMut {
            sig: self.0,
            f,
            buf: Vec::new(),
        })
    }

    pub fn map_mut_ctx<T, F>(self, f: F) -> Sig<MapMutCtx<S, T, F>>
    where
        T: Clone,
        F: FnMut(S::Item, &SigCtx) -> T,
    {
        Sig(MapMutCtx {
            sig: self.0,
            f,
            buf: Vec::new(),
        })
    }

    pub fn map<T, F>(self, f: F) -> Sig<Map<S, T, F>>
    where
        T: Clone,
        F: Fn(S::Item) -> T,
    {
        Sig(Map { sig: self.0, f })
    }

    pub fn map_ctx<T, F>(self, f: F) -> Sig<MapCtx<S, T, F>>
    where
        T: Clone,
        F: Fn(S::Item, &SigCtx) -> T,
    {
        Sig(MapCtx { sig: self.0, f })
    }

    pub fn zip<O>(self, other: O) -> Sig<Zip<S, O>>
    where
        O: SigT,
    {
        Sig(Zip {
            a: self.0,
            b: other,
        })
    }

    pub fn zip3<O1, O2>(self, other1: O1, other2: O2) -> Sig<Zip3<S, O1, O2>>
    where
        O1: SigT,
        O2: SigT,
    {
        Sig(Zip3 {
            a: self.0,
            b: other1,
            c: other2,
        })
    }

    pub fn shared(self) -> Sig<SigShared<S>> {
        sig_shared(self.0)
    }

    pub fn debug<F: FnMut(&S::Item)>(
        self,
        mut f: F,
    ) -> Sig<impl SigT<Item = S::Item>> {
        self.map_mut(move |x| {
            f(&x);
            x
        })
    }
}

impl<S, A, B> Sig<S>
where
    S: SigT<Item = (A, B)>,
    A: Clone,
    B: Clone,
{
    pub fn unzip(self) -> (Sig<impl SigT<Item = A>>, Sig<impl SigT<Item = B>>) {
        let shared = self.shared();
        let a = shared.clone().map(|(a, _)| a);
        let b = shared.clone().map(|(_, b)| b);
        (a, b)
    }
}

impl<S, A, B, C> Sig<S>
where
    S: SigT<Item = (A, B, C)>,
    A: Clone,
    B: Clone,
    C: Clone,
{
    pub fn unzip3(
        self,
    ) -> (
        Sig<impl SigT<Item = A>>,
        Sig<impl SigT<Item = B>>,
        Sig<impl SigT<Item = C>>,
    ) {
        let shared = self.shared();
        let a = shared.clone().map(|(a, _, _)| a);
        let b = shared.clone().map(|(_, b, _)| b);
        let c = shared.clone().map(|(_, _, c)| c);
        (a, b, c)
    }
}

impl<S, A, B, C, D> Sig<S>
where
    S: SigT<Item = (A, B, C, D)>,
    A: Clone,
    B: Clone,
    C: Clone,
    D: Clone,
{
    pub fn unzip4(
        self,
    ) -> (
        Sig<impl SigT<Item = A>>,
        Sig<impl SigT<Item = B>>,
        Sig<impl SigT<Item = C>>,
        Sig<impl SigT<Item = D>>,
    ) {
        let shared = self.shared();
        let a = shared.clone().map(|(a, _, _, _)| a);
        let b = shared.clone().map(|(_, b, _, _)| b);
        let c = shared.clone().map(|(_, _, c, _)| c);
        let d = shared.clone().map(|(_, _, _, d)| d);
        (a, b, c, d)
    }
}

pub fn sig_boxed<S>(sig: S) -> SigBoxed<S::Item>
where
    S: SigT + Send + Sync + 'static,
{
    Sig(sig).boxed()
}

impl<S> Sig<S>
where
    S: SigT + Send + Sync + 'static,
{
    pub fn boxed(self) -> SigBoxed<S::Item> {
        SigBoxed {
            sig: Arc::new(RwLock::new(self)),
            buf: Vec::new(),
        }
    }
}

impl<S> Sig<S>
where
    S: SigT<Item: Debug>,
{
    pub fn debug_print(self) -> Sig<impl SigT<Item = S::Item>> {
        self.debug(|x| println!("{:?}", x))
    }
}

impl<S> Sig<S>
where
    S: SigT<Item = f32>,
{
    /// clamp `x` between +/- `max_unsigned`
    pub fn clamp_symetric<C>(
        self,
        max_unsigned: C,
    ) -> Sig<impl SigT<Item = f32>>
    where
        C: SigT<Item = f32>,
    {
        self.zip(max_unsigned).map(|(s, max_unsigned)| {
            crate::arith::clamp_symetric(s, max_unsigned)
        })
    }

    /// The function f(x) =
    ///   k > 0  => exp(k * (x - a)) - b
    ///   k == 0 => x
    ///   k < 0  => -(ln(x + b) / k) + a
    /// ...where a and b are chosen so that f(0) = 0 and f(1) = 1.
    /// The k parameter controls how sharp the curve is.
    /// The functions when k != 0 are inverses of each other and zip approach linearity as k
    /// approaches 0.
    pub fn exp_01<K>(self, k: K) -> Sig<impl SigT<Item = f32>>
    where
        K: SigT<Item = f32>,
    {
        self.zip(k).map(|(x, k)| crate::arith::exp_01(x, k))
    }

    pub fn inv_01(self) -> Sig<impl SigT<Item = f32>> {
        1.0 - self
    }

    pub fn signed_to_01(self) -> Sig<SignedTo01<S>> {
        Sig(SignedTo01(self.0))
    }

    pub fn abs(self) -> Sig<SigAbs<S>> {
        Sig(SigAbs(self.0))
    }
}

pub struct GateToTrigRisingEdge<S>
where
    S: SigT<Item = bool>,
{
    sig: S,
    prev: bool,
    buf: Vec<bool>,
}

impl<S> SigT for GateToTrigRisingEdge<S>
where
    S: SigT<Item = bool>,
{
    type Item = bool;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.buf.resize(ctx.num_samples, false);
        for (out, sample) in
            self.buf.iter_mut().zip(self.sig.sample(ctx).iter())
        {
            *out = sample && !self.prev;
            self.prev = sample;
        }
        &self.buf
    }
}

impl<S> Sig<S>
where
    S: SigT<Item = bool>,
{
    pub fn gate_to_trig_rising_edge(self) -> Sig<GateToTrigRisingEdge<S>> {
        Sig(GateToTrigRisingEdge {
            sig: self.0,
            prev: false,
            buf: Vec::new(),
        })
    }

    pub fn trig_to_gate<P>(self, period_s: P) -> Sig<impl SigT<Item = bool>>
    where
        P: SigT<Item = f32>,
    {
        let mut remaining_s = 0.0;
        self.zip(period_s).map_mut_ctx(move |(x, period_s), ctx| {
            if x {
                remaining_s = period_s;
            }
            remaining_s -= 1.0 / ctx.sample_rate_hz;
            remaining_s > 0.0
        })
    }

    pub fn trig<T>(self, triggerable: T) -> Sig<impl SigT<Item = T::Item>>
    where
        T: Triggerable,
    {
        Sig(triggerable.into_sig(self))
    }

    pub fn on<T, F>(self, mut f: F) -> Sig<impl SigT<Item = Option<T>>>
    where
        T: Clone,
        F: FnMut() -> T,
    {
        self.map_mut(move |x| if x { Some(f()) } else { None })
    }

    pub fn divide_with_offset<D, O>(
        self,
        divide: D,
        offset: O,
    ) -> Sig<impl SigT<Item = bool>>
    where
        D: SigT<Item = u32>,
        O: SigT<Item = u32>,
    {
        let mut prev = false;
        let mut count = 0u64;
        self.zip3(divide, offset)
            .map_mut(move |(current, divide, offset)| {
                let divide = divide as u64;
                let offset = offset as u64;
                let is_falling_edge = prev && !current;
                if is_falling_edge {
                    count += 1;
                }
                prev = current;
                if divide == 0 {
                    // degenerate case
                    true
                } else if count < offset {
                    // first few tick until count overtakes the offset
                    false
                } else if (count - offset) % divide == 0 {
                    current
                } else {
                    false
                }
            })
    }

    pub fn divide<B>(self, by: B) -> Sig<impl SigT<Item = bool>>
    where
        B: SigT<Item = u32>,
    {
        self.divide_with_offset(by, 0)
    }
}

struct OptionFirstSome<T>
where
    T: Clone,
{
    sigs: Vec<SigBoxed<Option<T>>>,
    tmp_buf: Vec<Option<T>>,
    out_buf: Vec<Option<T>>,
}

impl<T> SigT for OptionFirstSome<T>
where
    T: Clone,
{
    type Item = Option<T>;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.tmp_buf.resize(ctx.num_samples, None);
        self.out_buf.clear();
        self.out_buf.resize(ctx.num_samples, None);
        for sig in &mut self.sigs {
            sig.sample_into_buf(ctx, &mut self.tmp_buf);
            for (out, x) in self.out_buf.iter_mut().zip(self.tmp_buf.iter()) {
                if out.is_some() {
                    continue;
                }
                *out = x.clone();
            }
        }
        &self.out_buf
    }
}

pub fn sig_option_first_some<T: Clone>(
    s: impl IntoIterator<Item = SigBoxed<Option<T>>>,
) -> Sig<impl SigT<Item = Option<T>>> {
    Sig(OptionFirstSome {
        sigs: s.into_iter().collect(),
        out_buf: Vec::new(),
        tmp_buf: Vec::new(),
    })
}

impl<T, S> Sig<S>
where
    T: Clone,
    S: SigT<Item = Option<T>>,
{
    pub fn option_or<O>(self, other: O) -> Sig<impl SigT<Item = Option<T>>>
    where
        O: SigT<Item = Option<T>>,
    {
        self.zip(other).map(|(s, o)| s.or(o))
    }
}

pub struct MapMut<S, T, F>
where
    S: SigT,
    F: FnMut(S::Item) -> T,
{
    sig: S,
    f: F,
    buf: Vec<T>,
}

impl<S, T, F> SigT for MapMut<S, T, F>
where
    T: Clone,
    S: SigT,
    F: FnMut(S::Item) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        let buf = self.sig.sample(ctx);
        self.buf.clear();
        self.buf.extend(buf.iter().map(&mut self.f));
        &self.buf
    }
}

pub struct MapMutCtx<S, T, F>
where
    S: SigT,
    F: FnMut(S::Item, &SigCtx) -> T,
{
    sig: S,
    f: F,
    buf: Vec<T>,
}

impl<S, T, F> SigT for MapMutCtx<S, T, F>
where
    T: Clone,
    S: SigT,
    F: FnMut(S::Item, &SigCtx) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        let buf = self.sig.sample(ctx);
        self.buf.clear();
        self.buf.extend(buf.iter().map(|x| (self.f)(x, ctx)));
        &self.buf
    }
}

pub struct Map<S, T, F>
where
    S: SigT,
    F: Fn(S::Item) -> T,
{
    sig: S,
    f: F,
}

impl<S, T, F> SigT for Map<S, T, F>
where
    T: Clone,
    S: SigT,
    F: Fn(S::Item) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.sig.sample(ctx), &self.f)
    }
}

pub struct MapCtx<S, T, F>
where
    S: SigT,
    F: Fn(S::Item, &SigCtx) -> T,
{
    sig: S,
    f: F,
}

impl<S, T, F> SigT for MapCtx<S, T, F>
where
    T: Clone,
    S: SigT,
    F: Fn(S::Item, &SigCtx) -> T,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.sig.sample(ctx), |x| (self.f)(x, ctx))
    }
}

pub struct Zip<A, B>
where
    A: SigT,
    B: SigT,
{
    a: A,
    b: B,
}

impl<A, B> SigT for Zip<A, B>
where
    A: SigT,
    B: SigT,
{
    type Item = (A::Item, B::Item);

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ZipBuf::new(self.a.sample(ctx), self.b.sample(ctx))
    }
}

pub struct Zip3<A, B, C>
where
    A: SigT,
    B: SigT,
    C: SigT,
{
    a: A,
    b: B,
    c: C,
}

impl<A, B, C> SigT for Zip3<A, B, C>
where
    A: SigT,
    B: SigT,
    C: SigT,
{
    type Item = (A::Item, B::Item, C::Item);

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        Zip3Buf::new(self.a.sample(ctx), self.b.sample(ctx), self.c.sample(ctx))
    }
}

pub struct SigAbs<S>(S)
where
    S: SigT<Item = f32>;

impl<S> SigT for SigAbs<S>
where
    S: SigT<Item = f32>,
{
    type Item = f32;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.0.sample(ctx), |x| x.abs())
    }
}

pub struct SignedTo01<S>(S)
where
    S: SigT<Item = f32>;

impl<S> SigT for SignedTo01<S>
where
    S: SigT<Item = f32>,
{
    type Item = f32;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        MapBuf::new(self.0.sample(ctx), signed_to_01)
    }
}

/// For signals yielding `f32`, this trait provides a general way of defining filters.
pub trait Filter {
    /// The type of the item of the input signal to this filter.
    type ItemIn;

    /// The type of the signal produced by this filter. Filters take an input signal (`S`) and wrap
    /// them it a new signal whose type is this associated type. The output type will usually be
    /// generic with a type parameter for the input signal, so this associated type must also have
    /// that type parameter.
    type Out<S>: SigT
    where
        S: SigT<Item = Self::ItemIn>;

    /// Create a new signal from an existing signal, consuming self in the process.
    fn into_sig<S>(self, sig: S) -> Self::Out<S>
    where
        S: SigT<Item = Self::ItemIn>;
}

/// Wrapper for a `Sig` that prevents recomputation of its value
/// for a particular point in time.
struct SigCached<S>
where
    S: SigT,
{
    sig: S,
    cache: Vec<S::Item>,
    next_batch_index: u64,
}

impl<S> SigCached<S>
where
    S: SigT,
{
    fn new(sig: S) -> Self {
        Self {
            sig,
            cache: Vec::new(),
            next_batch_index: 0,
        }
    }
}

/// A wrapper of a signal that can be shallow-cloned. It doesn't implement `SigT` that would be
/// less performant than iterating the underlying signal with a callback.
impl<S> SigT for SigCached<S>
where
    S: SigT,
{
    type Item = S::Item;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        if ctx.batch_index >= self.next_batch_index {
            self.next_batch_index = ctx.batch_index + 1;
            let buf = self.sig.sample(ctx);
            buf.clone_to_vec(&mut self.cache);
        }
        &self.cache
    }
}

/// A wrapper of a signal which can be shallow-cloned. Use this to split a signal into two copies
/// of itself without duplicating all the computations that produced the signal. Incurs a small
/// performance penalty as buffered values must be copied from the underlying signal into each
/// instance of the shared signal.
pub struct SigShared<S>
where
    S: SigT,
{
    shared_cached_sig: Arc<RwLock<SigCached<S>>>,
    buf: Vec<S::Item>,
}

impl<S> SigShared<S>
where
    S: SigT,
{
    fn new(sig: S) -> Self {
        SigShared {
            shared_cached_sig: Arc::new(RwLock::new(SigCached::new(sig))),
            buf: Vec::new(),
        }
    }

    /// Call a supplied function on the `SigT` implementation inside `self`.
    pub fn with_inner<T, F>(&self, mut f: F) -> T
    where
        F: FnMut(&S) -> T,
    {
        let inner_cached = self.shared_cached_sig.read().unwrap();
        f(&inner_cached.sig)
    }
}

impl<S> Clone for SigShared<S>
where
    S: SigT,
{
    fn clone(&self) -> Self {
        SigShared {
            shared_cached_sig: Arc::clone(&self.shared_cached_sig),
            buf: self.buf.clone(),
        }
    }
}

impl<S> SigT for SigShared<S>
where
    S: SigT,
{
    type Item = S::Item;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        let mut shared_cached_sig = self.shared_cached_sig.write().unwrap();
        // This will only actually run the underlying signal if it hasn't been computed yet this
        // frame. If it has already been computed this frame then the already-populated buffer will
        // be returned. We still need to copy the buffer to the buffer inside `self` so that the
        // buffer returned by _this_ function has the appropriate lifetime.
        let buf = shared_cached_sig.sample(ctx);
        buf.clone_to_vec(&mut self.buf);
        &self.buf
    }
}

pub fn sig_shared<S>(sig: S) -> Sig<SigShared<S>>
where
    S: SigT,
{
    Sig(SigShared::new(sig))
}

pub struct SigFn<F, T>
where
    F: FnMut(&SigCtx) -> T,
    T: Clone + Default,
{
    f: F,
    buf: Vec<T>,
}

impl<F, T> SigT for SigFn<F, T>
where
    F: FnMut(&SigCtx) -> T,
    T: Clone + Default,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.buf.resize_with(ctx.num_samples, Default::default);
        for out in self.buf.iter_mut() {
            *out = (self.f)(ctx);
        }
        &self.buf
    }
}

impl<F, T> Sig<SigFn<F, T>>
where
    F: FnMut(&SigCtx) -> T,
    T: Clone + Default,
{
    pub fn from_fn(f: F) -> Self {
        Self(SigFn { f, buf: Vec::new() })
    }
}

pub struct SigBufFn<F, T>
where
    F: FnMut(&SigCtx, &mut Vec<T>),
    T: Clone,
{
    f: F,
    buf: Vec<T>,
}

impl<F, T> SigT for SigBufFn<F, T>
where
    F: FnMut(&SigCtx, &mut Vec<T>),
    T: Clone,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        (self.f)(ctx, &mut self.buf);
        &self.buf
    }
}

impl<F, T> Sig<SigBufFn<F, T>>
where
    F: FnMut(&SigCtx, &mut Vec<T>),
    T: Clone,
{
    pub fn from_buf_fn(f: F) -> Self {
        Self(SigBufFn { f, buf: Vec::new() })
    }
}

#[derive(Default)]
pub struct SigVar<T>(Arc<RwLock<T>>);

impl<T> SigVar<T> {
    pub fn new(value: T) -> Self {
        Self(Arc::new(RwLock::new(value)))
    }

    pub fn set(&self, value: T) {
        *self.0.write().unwrap() = value;
    }
}

impl<T> Sig<SigVar<T>>
where
    T: Clone,
{
    pub fn set(&self, value: T) {
        self.0.set(value)
    }
}

pub fn sig_var<T: Clone>(value: T) -> Sig<SigVar<T>> {
    Sig(SigVar::new(value))
}

impl<T> Clone for SigVar<T> {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

impl<T> SigT for SigVar<T>
where
    T: Clone,
{
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        ConstBuf {
            count: ctx.num_samples,
            value: self.0.read().unwrap().clone(),
        }
    }
}

pub struct SigBoxedVarUnshared<T: Clone> {
    sig_boxed: Arc<RwLock<SigBoxed<T>>>,
    buf: Vec<T>,
}

impl<T: Clone> Clone for SigBoxedVarUnshared<T> {
    fn clone(&self) -> Self {
        Self {
            sig_boxed: Arc::clone(&self.sig_boxed),
            buf: Vec::new(),
        }
    }
}

impl<T: Clone> SigBoxedVarUnshared<T> {
    pub fn new<S>(sig: S) -> Self
    where
        S: SigT<Item = T> + Sync + Send + 'static,
    {
        SigBoxedVarUnshared {
            sig_boxed: Arc::new(RwLock::new(sig_boxed(sig))),
            buf: Vec::new(),
        }
    }

    pub fn set<S>(&self, sig: S)
    where
        S: SigT<Item = T> + Sync + Send + 'static,
    {
        *self.sig_boxed.write().unwrap() = sig_boxed(sig);
    }
}

impl<T: Clone> Sig<SigBoxedVarUnshared<T>> {
    pub fn set<S>(&self, sig: S)
    where
        S: SigT<Item = T> + Sync + Send + 'static,
    {
        self.0.set(sig);
    }
}

impl<T> SigBoxedVarUnshared<T>
where
    T: Clone + Sync + Send + 'static,
{
    pub fn new_const(value: T) -> Self {
        SigBoxedVarUnshared {
            sig_boxed: Arc::new(RwLock::new(sig_boxed(Const(value)))),
            buf: Vec::new(),
        }
    }
}

impl<T> SigBoxedVarUnshared<T>
where
    T: Clone + Default + Sync + Send + 'static,
{
    pub fn new_default() -> Self {
        Self::new_const(T::default())
    }
}

impl<T: Clone> SigT for SigBoxedVarUnshared<T> {
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        let mut unlocked = self.sig_boxed.write().unwrap();
        unlocked.sample_into_buf(ctx, &mut self.buf);
        &self.buf
    }
}

impl<T: Clone> SigSampleIntoBufT for SigBoxedVarUnshared<T> {
    type Item = T;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>) {
        self.sig_boxed.write().unwrap().sample_into_buf(ctx, buf);
    }

    fn sample_into_slice(
        &mut self,
        ctx: &SigCtx,
        stride: usize,
        offset: usize,
        out: &mut [Self::Item],
    ) {
        self.sig_boxed
            .write()
            .unwrap()
            .sample_into_slice(ctx, stride, offset, out);
    }
}

pub fn sig_boxed_var<S>(sig: S) -> Sig<SigBoxedVar<S::Item>>
where
    S: SigT + Sync + Send + 'static,
{
    Sig(SigBoxedVar::new(sig))
}

#[derive(Clone)]
pub struct SigBoxedVar<T: Clone>(Sig<SigShared<SigBoxedVarUnshared<T>>>);

impl<T: Clone> SigT for SigBoxedVar<T> {
    type Item = T;

    fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
        self.0.sample(ctx)
    }
}

impl<T: Clone> SigBoxedVar<T> {
    pub fn new<S>(sig: S) -> Self
    where
        S: SigT<Item = T> + Sync + Send + 'static,
    {
        Self(sig_shared(SigBoxedVarUnshared::new(sig)))
    }

    pub fn set<S>(&self, sig: S)
    where
        S: SigT<Item = T> + Sync + Send + 'static,
    {
        let sig_cached = self.0 .0.shared_cached_sig.write().unwrap();
        sig_cached.sig.set(sig);
    }
}

impl<T: Clone> Sig<SigBoxedVar<T>> {
    pub fn set<S>(&self, sig: S)
    where
        S: SigT<Item = T> + Sync + Send + 'static,
    {
        self.0.set(sig);
    }
}

impl<T: Clone> SigSampleIntoBufT for SigBoxedVar<T> {
    type Item = T;

    fn sample_into_buf(&mut self, ctx: &SigCtx, buf: &mut Vec<Self::Item>) {
        self.0.sample_into_buf(ctx, buf);
    }

    fn sample_into_slice(
        &mut self,
        ctx: &SigCtx,
        stride: usize,
        offset: usize,
        out: &mut [Self::Item],
    ) {
        self.0.sample_into_slice(ctx, stride, offset, out);
    }
}

pub trait Triggerable {
    type Item: Clone;

    fn into_sig<T>(self, trig: T) -> impl SigT<Item = Self::Item>
    where
        T: SigT<Item = bool>;
}