-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathklang.h
4698 lines (3862 loc) · 144 KB
/
klang.h
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
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <array>
#include <memory>
#include <vector>
#include <string>
#include <cstdarg>
#include <algorithm>
#include <type_traits>
#include <mutex>
#include <functional>
#include <float.h>
#ifdef __wasm__
#define THREAD_LOCAL
static inline float _sqrt(float x) { return __builtin_sqrtf(x); }
static inline float _abs(float x) { return __builtin_fabsf(x); }
#define SQRT _sqrt
#define SQRTF _sqrt
#define ABS _abs
#define FABS _abs
#endif
#ifdef __APPLE__
#define THREAD_LOCAL
#define SQRT ::sqrt
#define SQRTF ::sqrtf
#define ABS ::abs
#define FABS ::fabsf
#endif
#if defined(__WIN32__) || defined(WIN32)
#define THREAD_LOCAL thread_local
#define SQRT ::sqrt
#define SQRTF ::sqrtf
#define ABS ::abs
#define FABS ::fabsf
#endif
#if defined(DEBUG) || defined(_DEBUG)
#define KLANG_DEBUG 1
#else
#define KLANG_DEBUG 0
#endif
#ifndef GRAPH_SIZE
#define GRAPH_SIZE 44100
#endif
#define GRAPH_SERIES 4
// provide access to original math functions through std:: prefix
namespace std {
namespace klang {
template<typename TYPE> TYPE sqrt(TYPE x) { return SQRT(x); }
template<typename TYPE> TYPE abs(TYPE x) { return ABS(x); }
}
};
#define IS_SIMPLE_TYPE(type) \
static_assert(!std::is_polymorphic_v<type>, "signal has virtual table"); \
static_assert(!std::has_virtual_destructor_v<type>, "signal has virtual destructor"); \
static_assert(std::is_trivially_copyable_v<type>, "signal is not trivially copyable"); \
static_assert(std::is_trivially_copy_assignable_v<type>, "signal is not trivially copy assignable"); \
static_assert(std::is_trivially_copy_constructible_v<type>, "signal is not trivially copy assignable"); \
static_assert(std::is_trivially_destructible_v<type>, "signal is not trivially copy assignable"); \
static_assert(std::is_trivially_move_assignable_v<type>, "signal is not trivially copy assignable"); \
static_assert(std::is_trivially_move_constructible_v<type>, "signal is not trivially copy assignable");
namespace klang {
/// Klang language version (major.minor.build.debug)
struct Version {
unsigned char major, minor, build, extra;
bool isDebug() const { return extra & 1; }
bool atLeast(unsigned char M, unsigned char m, unsigned char b) const {
return M < major || (M == major && m < minor) || (M == major && m == minor && b <= build);
}
bool below(unsigned char M, unsigned char m, unsigned char b) const { return !atLeast(M, m, b); }
}
static constexpr version = { 0, 7, 2, KLANG_DEBUG };
/// Klang mode identifiers (e.g. averages, level following)
enum Mode { Peak, RMS, Mean };
#define DENORMALISE 1.175494e-38f
/// Constant scalar (pre-converted to double, float and int).
struct constant {
/// Create a constant from the given value.
constexpr constant(double value) noexcept
: d(value), f(static_cast<float>(value)), i(static_cast<int>(value)), inv(value == 0.0f ? 0.0f : static_cast<float>(1.0 / value)) { }
const double d; //!< Constant as double
const float f; //!< Constant as float
const int i; //!< Constant as integer
const float inv; //!< Inverse of constant
constexpr operator float() const noexcept { return f; }
/// Constant raised to the power, x.
float operator^(float x) const { return std::pow(f, x); }
float operator^(int x) const { return static_cast<float>(std::pow(d, x)); }
float operator^(double x) const { return static_cast<float>(std::pow(d, x)); }
};
#define CONSTANT constexpr constant
#if __cplusplus == 201703L
#pragma warning(disable:4996) // disable deprecated warning
/// @internal
template <typename T>
inline constexpr bool is_literal = std::is_literal_type_v<T>;
#else
/// @internal
template <typename T>
inline constexpr bool is_literal = std::is_trivially_constructible_v<T> && std::is_trivially_copyable_v<T> && std::is_trivially_destructible_v<T>;
#endif
/// @internal
template<typename Base, typename Derived>
constexpr bool is_derived_from() {
return std::is_base_of_v<Base, Derived>;
}
/// @internal
template<typename Head, typename... Tail>
constexpr bool are_scalars(Head&& head, Tail&&... tail) {
using T = std::decay_t<decltype(head)>;
return std::is_scalar_v<T> && ((sizeof... (Tail)) == 0 || are_scalars(std::forward<decltype(tail)>(tail)...));
}
/// @internal
template <typename BASE, int EXP>
inline constexpr BASE poweri(BASE base) {
BASE result = 1;
constexpr bool negative = EXP < 0;
int exp = negative ? -EXP : EXP;
while (exp > 0) {
if (exp % 2 == 1)
result *= base;
base *= base;
exp >>= 1;
}
return negative ? 1 / result : result;
}
/// @internal
template <typename BASE, typename EXP>
using power_t = typename std::conditional_t<std::is_integral_v<BASE>, float, BASE>;
/// Raise @a base to the power @a exp.
template <typename BASE, typename EXP, std::enable_if_t < is_literal<EXP>, bool>>
inline constexpr power_t<BASE, EXP> power(BASE base, EXP exp) {
if constexpr (std::is_integral_v<EXP>) {
switch (exp) {
case 0: return (BASE)1;
case 1: return base;
case 2: return base * base;
case 3: return base * base * base;
case 4: return base * base * base * base;
case -1: return (BASE)1 / base;
case -2: return (BASE)1 / (base * base);
case -3: return (BASE)1 / (base * base * base);
case -4: return (BASE)1 / (base * base * base * base);
default:
return poweri<BASE, exp>(base);
}
}
else if constexpr (std::is_floating_point_v<EXP>) {
if constexpr (exp == (EXP)0) return 1;
else if constexpr (exp == (EXP)1) return base;
else if constexpr (exp == (EXP)2) return base * base;
else if constexpr (exp == (EXP)3) return base * base * base;
else if constexpr (exp == (EXP)4) return base * base * base * base;
else if constexpr (exp == (EXP)-1) return 1 / base;
else if constexpr (exp == (EXP)-2) return 1 / (base * base);
else if constexpr (exp == (EXP)-3) return 1 / (base * base * base);
else if constexpr (exp == (EXP)-4) return 1 / (base * base * base * base);
}
return (BASE)std::pow(base, exp);;
}
/// Raise @a base to the power @a exp.
template <typename BASE, typename EXP>
inline constexpr power_t<BASE, EXP> power(BASE base, EXP exp) {
if constexpr (std::is_integral_v<BASE>) {
return power(float(base), exp);
}
else if constexpr (std::is_integral_v<EXP>) {
switch (exp) {
case 0: return (BASE)1;
case 1: return base;
case 2: return base * base;
case 3: return base * base * base;
case 4: return base * base * base * base;
case -1: return (BASE)1 / base;
case -2: return (BASE)1 / (base * base);
case -3: return (BASE)1 / (base * base * base);
case -4: return (BASE)1 / (base * base * base * base);
}
}
else if constexpr (std::is_floating_point_v<EXP>) {
if (base == (BASE)10) return (power_t<BASE, EXP>)::exp(exp * (EXP)2.3025850929940456840179914546843642076011014886287729760333279009);
else if (exp == (EXP)0) return (power_t<BASE, EXP>)1;
else if (exp == (EXP)1) return base;
else if (exp == (EXP)2) return base * base;
else if (exp == (EXP)3) return base * base * base;
else if (exp == (EXP)4) return base * base * base * base;
else if (exp == (EXP)-1) return (power_t<BASE, EXP>)1 / base;
else if (exp == (EXP)-2) return (power_t<BASE, EXP>)1 / (base * base);
else if (exp == (EXP)-3) return (power_t<BASE, EXP>)1 / (base * base * base);
else if (exp == (EXP)-4) return (power_t<BASE, EXP>)1 / (base * base * base * base);
}
return power_t<BASE, EXP>(std::pow(base, exp));
}
/// Return the minimum of two values.
template<typename TYPE1, typename TYPE2> inline TYPE1 min(TYPE1 a, TYPE2 b) { return a < b ? a : (TYPE1)b; };
/// Return the minimum of two values.
template<typename TYPE1, typename TYPE2> inline TYPE1 max(TYPE1 a, TYPE2 b) { return a > b ? a : (TYPE1)b; };
/// The mathematical constant, pi (and it's inverse).
constexpr constant pi = { 3.1415926535897932384626433832795 };
/// The natural logorithm of 2 (and it's inverse).
constexpr constant ln2 = { 0.6931471805599453094172321214581 };
/// The square root of 2 (and it's inverse).
constexpr constant root2 = { 1.4142135623730950488016887242097 };
/// Generates a random number between min and max. Use an integer types for whole numbers.
template<typename TYPE>
inline static TYPE random(const TYPE min, const TYPE max) { return rand() * ((max - min) / (TYPE)RAND_MAX) + min; }
/// Set the random seed (to allow repeatable random generation).
inline static void random(const unsigned int seed) { srand(seed); }
/// A function that handles an event.
typedef void event;
/// Variable-sized array, pre-allocated to a max. capacity.
template<typename TYPE, int CAPACITY>
struct Array {
unsigned int count = 0;
TYPE items[CAPACITY];
/// The maximum capacity of the array.
static int capacity() { return CAPACITY; }
/// The current number of items in the array.
unsigned int size() const { return count; }
/// Add the specified item to the end of the array.
void add(const TYPE& item) {
if (count < CAPACITY)
items[count++] = item;
}
/// Add a blank item to the end of the array, returning a pointer that allows the item to be modified.
TYPE* add() {
if (count < CAPACITY)
return &items[count++];
return nullptr;
}
/// Clear the array contents. Only resets the item count, without wiping memory.
void clear() { count = 0; }
/// Find the maximum value in the array.
float max() const {
float max = 0.f;
for (unsigned int i = 0; i < count; i++)
if (abs(items[i]) > max)
max = items[i];
return max;
}
/// Find the mean average of values in the array.
float mean() const {
float sum = 0.f;
for (unsigned int i = 0; i < count; i++)
sum += abs(items[i]);
return sum / count;
}
/// Find the root mean squared (RMS) average of values in the array.
float rms() const {
float sum = 0.f;
for (unsigned int i = 0; i < count; i++)
sum += items[i] * items[i];
return sqrt(sum / count);
}
/// Normalises values in the array to the specified @a target, based on peak, mean, or RMS value;
void normalise(float target = 1.f, int mode = Peak) {
if (!count) return;
const float current = (mode == Peak) ? max() : (mode == Mean) ? mean() : rms();
const float scale = current == 0.f ? 0.f : target / current;
for (int i = 0; i < count; i++)
items[i] *= scale;
}
/// Returns a reference to the array item at the given index.
TYPE& operator[](int index) { return items[index]; }
/// Returns a read-only reference to the array item at the given index.
const TYPE& operator[](int index) const { return items[index]; }
/// Construct an array given the specified values.
Array(std::initializer_list<TYPE> init_list) {
count = std::min(static_cast<unsigned int>(init_list.size()), static_cast<unsigned int>(CAPACITY));
std::copy_n(init_list.begin(), count, items);
}
/// Construct an empty array.
Array() = default; // Default constructor to allow empty initialization
};
/// String of characters representing text.
template<int SIZE>
struct Text {
/// The character buffer.
char string[SIZE + 1] = { 0 };
/// Maximum size of the string.
int capacity() const { return SIZE; }
/// Automatic cast to constant C-string.
operator const char* () const { return string; }
/// Return constant C-string.
const char* c_str() const { return string; }
/// Create a new Text object from a C-string.
static Text from(const char* in) {
Text text;
text = in;
return text;
}
/// Assign C-String to Text object.
void operator=(const char* in) {
memcpy(string, in, SIZE);
string[SIZE] = 0;
}
/// Returns true if Text matches the given C-string.
bool operator==(const char* in) const {
return strcmp(string, in) == 0;
}
/// Returns true if Text does not matches the given C-string.
bool operator!=(const char* in) const {
return !operator==(in);
}
};
/// A short Text object used to label controls.
typedef Text<32> Caption;
struct Output;
struct relative;
/// A mono audio signal (equivalent to a float).
struct signal {
float value;
/// Create signal from a constant.
signal(constant initial) : value(initial.f) { }
/// Create signal from a 32-bit float..
signal(const float initial = 0.f) : value(initial) { }
/// Create signal from a 64-bit double.
signal(const double initial) : value((const float)initial) { }
/// Create signal from an 32-bit signed integer.
signal(const int value) : value((const float)value) { }
/// Feedback operator (prevents further processing of returned value).
const signal& operator<<(const signal& input) {
value = input;
return *this;
}
/// Stream operator (feedforward; allows further processing)
signal& operator>>(signal& destination) const {
destination.value = value;
return destination;
}
/// Assign processed output of \a in to signal.
signal& operator=(Output& in);
/// Adds processed output of \a in to signal.
signal& operator+=(Output& in);
/// Add (mix) another signal to the signal.
signal& operator+=(const signal& x) { value += x.value; return *this; }
/// Subtract another signal from the signal.
signal& operator-=(const signal& x) { value -= x.value; return *this; }
/// Multiply (modulate) signal by another signal.
signal& operator*=(const signal& x) { value *= x.value; return *this; }
/// Divide signal by another signal.
signal& operator/=(const signal& x) { value /= x.value; return *this; }
/// Add the specified amount to the signal.
signal& operator+=(float x) { value += x; return *this; }
/// Subtract the specified amount from the signal.
signal& operator-=(float x) { value -= x; return *this; }
/// Multiply signal by the specified amount.
signal& operator*=(float x) { value *= x; return *this; }
/// Divide signal by the specified amount.
signal& operator/=(float x) { value /= x; return *this; }
/// Add the specified amount to the signal.
signal& operator+=(double x) { value += (float)x; return *this; }
/// Subtract the specified amount from the signal.
signal& operator-=(double x) { value -= (float)x; return *this; }
/// Multiply signal by the specified amount.
signal& operator*=(double x) { value *= (float)x; return *this; }
/// Divide signal by the specified amount.
signal& operator/=(double x) { value /= (float)x; return *this; }
/// Add the specified amount to the signal.
signal& operator+=(int x) { value += (float)x; return *this; }
/// Subtract the specified amount from the signal.
signal& operator-=(int x) { value -= (float)x; return *this; }
/// Multiply signal by the specified amount.
signal& operator*=(int x) { value *= (float)x; return *this; }
/// Divide signal by the specified amount.
signal& operator/=(int x) { value /= (float)x; return *this; }
/// Add two signals together.
signal operator+(float x) const { return value + x; }
/// Subtract one signal from another.
signal operator-(float x) const { return value - x; }
/// Multiply (modulate) two signals.
signal operator*(float x) const { return value * x; }
/// Divide one signal by another.
signal operator/(float x) const { return value / x; }
/// Return a copy of the signal offset by x.
signal operator+(double x) const { return value + (float)x; }
/// Return a copy of the signal offset by -x.
signal operator-(double x) const { return value - (float)x; }
/// Return a copy of the signal scaled by x.
signal operator*(double x) const { return value * (float)x; }
/// Return a copy of the signal divided by.
signal operator/(double x) const { return value / (float)x; }
/// Return a copy of the signal offset by x.
signal operator+(int x) const { return value + (float)x; }
/// Return a copy of the signal offset by -x.
signal operator-(int x) const { return value - (float)x; }
/// Return a copy of the signal scaled by x.
signal operator*(int x) const { return value * (float)x; }
/// Return a copy of the signal divided by x.
signal operator/(int x) const { return value / (float)x; }
/// Return a copy of the signal raised to the power of x.
signal operator^(float x) const { return power(value, x); }
/// Return a copy of the signal raised to the power of x.
signal operator^(double x) const { return power(value, x); }
/// Return a copy of the signal raised to the power of x.
signal operator^(int x) const { return power(value, x); }
operator const float() const { return value; }
operator float& () { return value; }
/// Check if the signal contains a denormal value.
bool isDenormal() const {
const unsigned int bits = *(const unsigned int*)&value;
return !(bits & 0x7F800000) && (bits & 0x007FFFFF);
}
/// Returns the number of channels (1 = mono).
int channels() const { return 1; }
/// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
relative operator+() const; // unary + operator produces relative signal
/// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
relative relative() const; //
};
/// @internal signal MUST compile as a float
static_assert(sizeof(signal) == sizeof(float), "signal != float");
IS_SIMPLE_TYPE(signal)
/// A signal used as an offset relative to another signal.
struct relative : public signal { };
/// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
inline relative signal::operator+() const { return { value }; }
/// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
inline relative signal::relative() const { return { value }; }
/// Stream a literal / constant / scalar type into a signal.
inline static signal& operator>>(float input, signal& destination) { // CHECK: should this be signal, rather than float?
destination << signal(input);
return destination;
}
/// A multi-channel audio signal (e.g. stereo).
template<int CHANNELS = 2>
struct signals {
/// @cond
union {
signal value[CHANNELS]; ///< Array of channel values.
struct {
signal l; ///< Left channel
signal r; ///< Right channel
};
};
/// @endcond
/// Return the mono mix of a stereo channel.
signal mono() const { return (l + r) * 0.5f; }
/// Return a reference to the signal at the specified index (0 = left, 1 = right).
signal& operator[](int index) { return value[index]; }
/// Return a read-only reference to the signal at the specified index (0 = left, 1 = right).
const signal& operator[](int index) const { return value[index]; }
/// Create a stereo signal with the given value.
signals(float initial = 0.f) : l(initial), r(initial) { }
/// Create a stereo signal with the given value.
signals(double initial) : l((float)initial), r((float)initial) { }
/// Create a stereo signal with the given value.
signals(int initial) : l((float)initial), r((float)initial) { }
/// Create a stereo signal with the given left and right value.
signals(float left, float right) : l(left), r(right) { }
/// Create a stereo signal with the given left and right value.
signals(double left, double right) : l((float)left), r((float)right) { }
/// Create a stereo signal with the given left and right value.
signals(int left, int right) : l((float)left), r((float)right) { }
/// Create a multi-channel signal with the given channel values.
template <typename... Args, typename = std::enable_if_t<(std::is_convertible_v<Args, signal> && ...)>>
signals(Args&... initial) : value{ initial... } { }
/// Create a multi-channel signal with the given channel values.
template <typename... Args, typename = std::enable_if_t<(std::is_scalar_v<Args> && ...)>>
signals(Args... initial) : value{ initial... } { }
/// Returns the number of channels in the signal.
int channels() const { return CHANNELS; }
/// Feedback operator (prevents further processing of returned value).
const signals& operator<<(const signals& input) {
return this->operator=(input);
}
/// Stream operator (feedforward; allows further processing).
signals& operator>>(signals& destination) const {
destination = *this;
return destination;
}
/// Add (mix) another signal to the signal.
signals& operator+=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] += x[v]; return *this; }
/// Subtract another signal from the signal.
signals& operator-=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] -= x[v]; return *this; }
/// Multiply (modulate) signal by another signal.
signals& operator*=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] *= x[v]; return *this; }
/// Divide signal by another signal.
signals& operator/=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] /= x[v]; return *this; }
/// Add two multi-channel signals together.
signals operator+(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x[v]; return s; }
/// Subtract one multi-channel signal from another.
signals operator-(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x[v]; return s; }
/// Multiply (modulate) two multi-channel signals.
signals operator*(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x[v]; return s; }
/// Divide one multi-channel signal by another.
signals operator/(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x[v]; return s; }
//signals& operator+=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] += x; return *this; }
//signals& operator-=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] -= x; return *this; }
//signals& operator*=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] *= x; return *this; }
//signals& operator/=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] /= x; return *this; }
/// Return a copy of the multi-channel signal, adding a mono signal to each channel.
signals operator+(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
/// Return a copy of the multi-channel signal, subtracting a mono signal from each channel.
signals operator-(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
/// Return a copy of the multi-channel signal, multiplying (modulating) each channel by a mono signal.
signals operator*(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
/// Return a copy of the multi-channel signal, dividing each channel by a mono signal.
signals operator/(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
/// Return a copy of the signal with each channel offset by x.
signals operator+(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
/// Return a copy of the signal with each channel offset by -x.
signals operator-(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
/// Return a copy of the signal with each channel scaled by x.
signals operator*(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
/// Return a copy of the signal with each channel divided by x.
signals operator/(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
/// Return a copy of the signal with each channel offset by x.
signals operator+(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
/// Return a copy of the signal with each channel offset by -x.
signals operator-(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
/// Return a copy of the signal with each channel scaled by x.
signals operator*(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
/// Return a copy of the signal with each channel divided by x.
signals operator/(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
/// Return a copy of the signal with each channel offset by x.
signals operator+(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
/// Return a copy of the signal with each channel offset by -x.
signals operator-(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
/// Return a copy of the signal with each channel scaled by x.
signals operator*(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
/// Return a copy of the signal with each channel divided by x.
signals operator/(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
};
/// Return a copy of the signal with each channel offset by x.
template<int CHANNELS = 2> inline signals<CHANNELS> operator+(float x, const signals<CHANNELS>& y) { return y + x; }
/// Return a copy of the signal with each channel subtracted from x.
template<int CHANNELS = 2> inline signals<CHANNELS> operator-(float x, const signals<CHANNELS>& y) { return -y + x; }
/// Return a copy of the signal with each channel scaled by x.
template<int CHANNELS = 2> inline signals<CHANNELS> operator*(float x, const signals<CHANNELS>& y) { return y * x; }
/// Return a copy of the signal with each channel divided into x.
template<int CHANNELS = 2> inline signals<CHANNELS> operator/(float x, const signals<CHANNELS>& y) {
signals<CHANNELS> s = { 0.f };
for (int c = 0; c < CHANNELS; c++)
s[c] = x / y[c];
return std::move(s);
}
/// @cond
/// Helper class for converting units / quantities
struct Conversion : public signal {
using signal::signal;
// operator klang::signal& () { return signal; };
};
/// @endcond
/// A phase or wavetable increment.
struct increment {
float amount; ///< The current phase.
const float size; ///< The length of a a full cycle (e.g. 2 pi or wavetable size)
/// Create a phase increment (default to radians).
increment(float amount, const float size = 2 * pi) : amount(amount), size(size) { }
/// Create a phase increment (wavetable size).
increment(float amount, int size) : amount(amount), size((float)size) { }
/// Create a phase increment.
increment(float amount, double size) : amount(amount), size((float)size) { }
/// Set current phase.
increment& operator=(float in) { amount = in; return *this; }
};
struct Control;
/// A signal used as a control parameter.
struct param : public signal {
param(constant in) : signal(in.f) { }
param(const float initial = 0.f) : signal(initial) { }
param(const signal& in) : signal(in) { }
param(signal& in) : signal(in) { }
param(Control& in); // see Control declaration
param& operator+=(const increment& increment) {
value += increment.amount;
if (value >= increment.size)
value -= increment.size;
return *this;
}
};
// param should also be binary compatible with float / signal
static_assert(sizeof(param) == sizeof(float), "param != float");
// support left-to-right and right-to-left signal flow
inline static param& operator>>(param& from, param& to) {
to << from;
return to;
}
/// @cond
struct params {
param* parameters;
const int size;
params(param p) : parameters(new param[1]), size(1) { parameters[0] = p; }
params(std::initializer_list<param> params) : parameters(new param[params.size()]), size((int)params.size()) {
int index = 0;
for (param p : params)
parameters[index++] = p;
}
param& operator[](int index) { return parameters[index]; }
};
/// @endcond
inline float fast_mod(float x, float y) {
const unsigned int i = (((unsigned int)(x * (float(UINT_MAX) + 1.f) / y)) >> 9) | 0x3f800000;
return (*(const float*)&i - 1.f) * y;
}
inline double fast_mod(double x, double y) {
const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0) / y)) >> 12ULL) | 0x7FF0000000000000ULL;
return (*(const double*)&i - 1.0) * y;
}
inline float fast_mod1(float x) {
const unsigned int i = ((unsigned int)(x * (float(UINT_MAX) + 1.f)) >> 9) | 0x3f800000;
return *(const float*)&i - 1.f;
}
inline double fast_mod1(double x) {
const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0))) >> 12ULL) | 0x7FF0000000000000ULL;
return (*(const double*)&i - 1.0);
}
inline float fast_mod2pi(float x) {
constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
const unsigned int i = (((unsigned int)(x * (float(UINT_MAX) + 1.f) / twoPi)) >> 9) | 0x3f800000;
return (*(const float*)&i - 1.f) * twoPi;
}
inline float fast_modp(unsigned int x) {
constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
const unsigned int i = (x >> 9) | 0x3f800000;
return (*(const float*)&i - 1.f) * twoPi;
}
inline double fast_mod2pi(double x) {
constexpr double twoPi = (2.0 * 3.1415926535897932384626433832795);
const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0) / twoPi)) >> 12ULL) | 0x7FF0000000000000ULL;
return (*(const double*)&i - 1.0) * twoPi;
}
template<int SIZE>
inline double fast_modi(double x) {
constexpr double size = double(SIZE);
constexpr double sizeInv = 1.0 / double(SIZE);
const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0) * sizeInv)) >> 12ULL) | 0x7FF0000000000000ULL;
return (*(const double*)&i - 1.0) * size;
}
/// Matrix processor
//template<int X, int Y = X>
struct Matrix {
float v[4][4] = { 0 };
float* operator[](int col) { return v[col]; }
const float* operator[](int col) const { return v[col]; }
float& operator()(int col, int row) { return v[col][row]; }
float operator()(int col, int row) const { return v[col][row]; }
signals<4> operator<<(const signals<4>& in) const {
return { v[0][0] * in[0] + v[0][1] * in[1] + v[0][2] * in[2] + v[0][3] * in[3],
v[1][0] * in[0] + v[1][1] * in[1] + v[1][2] * in[2] + v[1][3] * in[3],
v[2][0] * in[0] + v[2][1] * in[1] + v[2][2] * in[2] + v[2][3] * in[3],
v[3][0] * in[0] + v[3][1] * in[1] + v[3][2] * in[2] + v[3][3] * in[3] };
}
};
inline signals<4> operator*(const signals<4>& in, const Matrix& m) {
return { m[0][0] * in[0] + m[0][1] * in[1] + m[0][2] * in[2] + m[0][3] * in[3],
m[1][0] * in[0] + m[1][1] * in[1] + m[1][2] * in[2] + m[1][3] * in[3],
m[2][0] * in[0] + m[2][1] * in[1] + m[2][2] * in[2] + m[2][3] * in[3],
m[3][0] * in[0] + m[3][1] * in[1] + m[3][2] * in[2] + m[3][3] * in[3] };
}
inline signals<4> operator>>(const signals<4>& in, const Matrix& m) { return operator*(in, m); }
/// @cond
template<typename TYPE, typename _TYPE>
struct phase {
static constexpr TYPE twoPi = TYPE(2.0 * 3.1415926535897932384626433832795);
// represent phase using full range of uint32
// (integer math, no conditionals, free oversampling)
_TYPE i = 0;
// convert float [0, 2pi) to uint32
phase(TYPE phase = 0) {
if constexpr (std::is_same<TYPE, double>()) {
constexpr TYPE FUINTMAX = TYPE(ULLONG_MAX + 1.0) / twoPi; // (float)INT_MAX + 1.f;
phase *= FUINTMAX;
i = (_TYPE)phase;
}
else if constexpr (std::is_same<TYPE, float>()) {
constexpr TYPE FUINTMAX = TYPE(UINT_MAX + 1.0) / twoPi; // (float)INT_MAX + 1.f;
phase *= FUINTMAX;
i = (_TYPE)phase;
}
}
// convert uint32 to float [0, 1)
operator TYPE() const {
const _TYPE phase = (i >> 12ULL) | 0x3FF0000000000000ULL;
return (*(const TYPE*)&phase - TYPE(1.0)) * twoPi;
}
//static void test() {
// phase p;
// assert((float)(p = 0.f).radians() == 0.f);
// assert((float)(p = pi / 2).radians() == pi / 2);
// assert((float)(p = pi).radians() == pi);
// assert((float)(p = 3 * pi / 2).radians() == 3 * pi / 2);
// assert((float)(p = 2 * pi).radians() == 0.f);
//}
};
/// @endcond
/// Control parameter (phase)
struct Phase : public param {
//INFO("Phase", 0.f, 0.f, 1.0f)
using param::param;
/*Phase(const float p = 0.f) : param(p) { };*/
param& operator+=(float increment) {
if (increment >= (2 * pi))
return *this;
value += increment;
if (value > (2 * pi))
value -= (2 * pi);
return *this;
}
param& operator+=(const increment& increment) {
if (increment.amount >= increment.size)
return *this;
value += increment.amount;
if (value > increment.size)
value -= increment.size;
return *this;
}
Phase operator+(const increment& increment) const {
if (increment.amount >= increment.size)
return value;
Phase value = Phase::value + increment.amount;
if (value > increment.size)
value -= increment.size;
return value;
}
Phase operator%(float modulus) {
return fast_mod(value, modulus);
}
};
struct Frequency;
/// Control parameter (pitch)
struct Pitch : public param {
//INFO("Pitch", 60.f, 0.f, 127.f)
using param::param;
//Pitch(float p = 60.f) : param(p) { };
//Pitch(int p) : param((float)p) { };
// convert note number to pitch class and octave (e.g. C#5)
const char* text() const {
THREAD_LOCAL static char buffer[32] = { 0 };
const char* const notes[12] = { "C", "C#/Db", "D", "D#/Eb", "E", "F", "F#/Gb", "G", "G#/Ab", "A", "A#/Bb", "B" };
snprintf(buffer, 32, "%s%d", notes[(int)value % 12], (int)value / 12);
return buffer;
}
const Pitch* operator->() {
Frequency = 440.f * power(2.f, (value - 69.f) / 12.f);
return this;
}
THREAD_LOCAL static Conversion Frequency;
template<typename TYPE> Pitch operator+(TYPE in) { return value + in; }
template<typename TYPE> Pitch operator-(TYPE in) { return value - in; }
template<typename TYPE> Pitch operator*(TYPE in) { return value * in; }
template<typename TYPE> Pitch operator/(TYPE in) { return value / in; }
};
THREAD_LOCAL inline Conversion Pitch::Frequency;
// inline THREAD_LOCAL Pitch::Convert Pitch::Frequency;
/// Control parameter (frequency)
struct Frequency : public param {
//INFO("Frequency", 1000.f, -FLT_MAX, FLT_MAX)
using param::param;
Frequency(float f = 1000.f) : param(f) { };
};
/// Sample rate constants
static struct SampleRate {
float f; ///< sample rate (float)
int i; ///< sample rate (integer)
double d; ///< sample rate (double)
float inv; ///< 1 / sample rate (inverse)
float w; ///< angular frequency (omega)
float nyquist; ///< nyquist frequency (f / 2)
SampleRate(float sr) : f(sr), i(int(sr + 0.001f)), d((double)sr), inv(1.f / sr), w(2.0f * pi * inv), nyquist(sr / 2.f) { }
operator float() { return f; }
} fs(44100); // sample rate
struct Amplitude;
/// Control parameter (idecibels)
struct dB : public param {
//INFO("dB", 0.f, -FLT_MAX, FLT_MAX)
using param::param;
dB(float gain = 0.f) : param(gain) { };
const dB* operator->() const {
Amplitude = power(10, value * 0.05f);
return this;
}
THREAD_LOCAL static Conversion Amplitude;
};
/// Control parameter (linear amplitude)
struct Amplitude : public param {
//INFO("Gain", 1.f, -FLT_MAX, FLT_MAX)
using param::param;
Amplitude(float a = 1.f) : param(a) { };
Amplitude(const dB& db) {
value = power(10, db.value * 0.05f); // 10 ^ (db * 0.05f);
};
//dB operator >> (dB) const {
// return 20.f * log10f(value);
//}
//operator dB() const {
// return 20.f * log10f(value);
//}
const Amplitude* operator->() const {
dB = 20.f * log10f(value);
return this;
}
THREAD_LOCAL static Conversion dB;
};
THREAD_LOCAL inline Conversion dB::Amplitude;
THREAD_LOCAL inline Conversion Amplitude::dB;
/// Control parameter (velocity)
typedef Amplitude Velocity;
/// UI control / parameter
struct Control
{
enum Type
{
NONE, // no control (list terminator)
ROTARY, // rotary knob (dial/pot)
BUTTON, // push button (trigger)
TOGGLE, // on/off switch (toggle)
SLIDER, // linear slider (fader)
MENU, // drop-down list (menu; up to 128 items)
METER, // level meter (read-only: use setParameter() to set value)
WHEEL, // MIDI control (Pitch Bend / Mod Wheel only)
};
/// Control size
struct Size
{
Size(int x = -1, int y = -1, int width = -1, int height = -1)
: x(x), y(y), width(width), height(height) { }
int x;
int y;
int width;
int height;
bool isAuto() const { return x == -1 && y == -1 && width == -1 && height == -1; }
bool isRelative() const { return x != -1 && y != -1; }
};
// Control Group
struct Group { // 48 bytes
Caption name; // 36 bytes (32+1 aligned)
Control::Size size; // 4 bytes
unsigned int start = 0; // 4 bytes
unsigned int length = 0; // 4 bytes
bool contains(unsigned int c) const { return c >= start && c < (start + length); }
};