Klang C++ 0.7.15
Language Reference (draft)
Loading...
Searching...
No Matches
klang.h
1#define KLANG_CONTROL_REFERENCES 1
2#ifdef abs
3#undef abs
4#endif
5#ifdef sqrt
6#undef sqrt
7#endif
8#ifdef min
9#undef min
10#endif
11#ifdef max
12#undef max
13#endif
14#ifdef clamp
15#undef clamp
16#endif
17
18#ifndef _CRT_SECURE_NO_WARNINGS
19#define _CRT_SECURE_NO_WARNINGS
20#endif
21
22#include <stdio.h>
23#include <stdlib.h>
24#include <cmath>
25#if defined(__WAJIC__) && !defined(_LIBCPP_HAS_NO_LOCALIZATION)
26#pragma push_macro("_LIBCPP_HAS_NO_LOCALIZATION")
27#define _LIBCPP_HAS_NO_LOCALIZATION
28#include <complex>
29#pragma pop_macro("_LIBCPP_HAS_NO_LOCALIZATION")
30#else
31#include <complex>
32#endif
33#include <math.h>
34#include <limits>
35#include <assert.h>
36#include <array>
37#include <memory>
38#include <optional>
39#include <vector>
40#include <string>
41#include <cstdarg>
42#include <cstring>
43#include <climits>
44#include <thread>
45#include <algorithm>
46#include <type_traits>
47#include <mutex>
48#include <functional>
49#include <float.h>
50#include <utility>
51#include <chrono>
52#include <cstdint>
53#include <stdexcept>
54
55#define HAS_KLANG 1
56
57// Set to 1 before including Klang to restore compiler warnings suppressed for
58// compatibility with the supported host/plugin builds.
59#ifndef KLANG_STRICT
60#define KLANG_STRICT 0
61#endif
62
63#if defined(_MSC_VER) && !KLANG_STRICT
64#pragma warning(push)
65#pragma warning(disable: 4587 4263 4264 4996)
66#define KLANG_WARNING_SCOPE 1
67#endif
68
69// Studio wrappers define KLANG in both Release and Debug builds.
70// Other hosts may opt in explicitly; use one setting throughout a module.
71#ifndef HAS_KLANG_DEBUG
72#if defined(KLANG) && KLANG
73#define HAS_KLANG_DEBUG 1
74#else
75#define HAS_KLANG_DEBUG 0
76#endif
77#endif
78
79#pragma once
80
81#ifdef __wasm__
82#define THREAD_LOCAL
83static inline float _sqrt(float x) { return __builtin_sqrtf(x); }
84static inline float _abs(float x) { return __builtin_fabsf(x); }
85#define SQRT _sqrt
86#define SQRTF _sqrt
87#define ABS _abs
88#define FABS _abs
89
90#elif defined(__APPLE__)
91#define THREAD_LOCAL
92#define SQRT ::sqrt
93#define SQRTF ::sqrtf
94#define ABS ::abs
95#define FABS ::fabsf
96
97#elif defined(_MSC_VER)
98#define THREAD_LOCAL thread_local
99#define SQRT ::sqrt
100#define SQRTF ::sqrtf
101#define ABS ::abs
102#define FABS ::fabsf
103
104#else
105#define THREAD_LOCAL thread_local
106#define SQRT ::sqrt
107#define SQRTF ::sqrtf
108#define ABS ::abs
109#define FABS ::fabsf
110#endif
111
112#if defined(DEBUG) || defined(_DEBUG)
113#define KLANG_DEBUG 1
114#else
115#define KLANG_DEBUG 0
116#endif
117
118#ifndef GRAPH_SIZE
119#define GRAPH_SIZE 44100
120#endif
121
122#define GRAPH_SERIES 4
123
124#define IS_SIMPLE_TYPE(type) \
125 static_assert(!std::is_polymorphic_v<type>, "signal has virtual table"); \
126 static_assert(!std::has_virtual_destructor_v<type>, "signal has virtual destructor"); \
127 static_assert(std::is_trivially_copyable_v<type>, "signal is not trivially copyable"); \
128 static_assert(std::is_trivially_copy_assignable_v<type>, "signal is not trivially copy assignable"); \
129 static_assert(std::is_trivially_copy_constructible_v<type>, "signal is not trivially copy assignable"); \
130 static_assert(std::is_trivially_destructible_v<type>, "signal is not trivially copy assignable"); \
131 static_assert(std::is_trivially_move_assignable_v<type>, "signal is not trivially copy assignable"); \
132 static_assert(std::is_trivially_move_constructible_v<type>, "signal is not trivially copy assignable");
133
134namespace klang {
135 typedef unsigned char byte;
136
137 /// Klang language version (major.minor.build.debug)
138 struct Version {
139 unsigned char major, minor, build, extra;
140 bool isDebug() const { return extra & 1; }
141 bool atLeast(unsigned char M, unsigned char m, unsigned char b) const {
142 return M < major || (M == major && m < minor) || (M == major && m == minor && b <= build);
143 }
144 bool below(unsigned char M, unsigned char m, unsigned char b) const { return !atLeast(M, m, b); }
145 }
146 static constexpr version = { 0, 7, 15, KLANG_DEBUG };
147
148 /// Klang mode identifiers (e.g. averages, level following)
149 enum Mode { Peak, RMS, Mean };
150
151#define DENORMALISE 1.175494e-38f
152
153 /// Constant scalar (pre-converted to double, float and int).
154 struct constant {
155
156 /// Create a constant from the given value.
157 constexpr constant(double value) noexcept
158 : d(value), f(static_cast<float>(value)), i(static_cast<int>(value)), inv(value == 0.0f ? 0.0f : static_cast<float>(1.0 / value)) {
159 }
160
161 const double d; //!< Constant as double
162 const float f; //!< Constant as float
163 const int i; //!< Constant as integer
164 const float inv; //!< Inverse of constant
165
166 constexpr operator float() const noexcept { return f; }
167
168 /// Constant raised to the power, x.
169 float operator^(float x) const { return std::pow(f, x); }
170 float operator^(int x) const { return static_cast<float>(std::pow(d, x)); }
171 float operator^(double x) const { return static_cast<float>(std::pow(d, x)); }
172 };
173
174#define CONSTANT constexpr constant
175
176#if __cplusplus == 201703L
177 /// @internal
178 template <typename T>
179 inline constexpr bool is_literal = std::is_literal_type_v<T>;
180#else
181 /// @internal
182 template <typename T>
183 inline constexpr bool is_literal = std::is_trivially_constructible_v<T> && std::is_trivially_copyable_v<T> && std::is_trivially_destructible_v<T>;
184#endif
185 /// @internal
186 template<typename Base, typename Derived>
187 constexpr bool is_derived_from() {
188 return std::is_base_of_v<Base, Derived>;
189 }
190 /// @internal
191 template<typename Head, typename... Tail>
192 constexpr bool are_scalars(Head&& head, Tail&&... tail) {
193 using T = std::decay_t<decltype(head)>;
194 return std::is_scalar_v<T> && ((sizeof... (Tail)) == 0 || are_scalars(std::forward<decltype(tail)>(tail)...));
195 }
196 /// @internal
197 template <typename BASE, int EXP>
198 inline constexpr BASE poweri(BASE base) {
199 BASE result = 1;
200 constexpr bool negative = EXP < 0;
201 int exp = negative ? -EXP : EXP;
202 while (exp > 0) {
203 if (exp % 2 == 1)
204 result *= base;
205 base *= base;
206 exp >>= 1;
207 }
208 return negative ? 1 / result : result;
209 }
210 /// @internal
211 template <typename BASE, typename EXP>
212 using power_t = typename std::conditional_t<std::is_integral_v<BASE>, float, BASE>;
213
214 /// Raise @a base to the power @a exp.
215 template <typename BASE, typename EXP, std::enable_if_t < is_literal<EXP>, bool>>
216 inline constexpr power_t<BASE, EXP> power(BASE base, EXP exp) {
217 if constexpr (std::is_integral_v<EXP>) {
218 switch (exp) {
219 case 0: return (BASE)1;
220 case 1: return base;
221 case 2: return base * base;
222 case 3: return base * base * base;
223 case 4: return base * base * base * base;
224 case -1: return (BASE)1 / base;
225 case -2: return (BASE)1 / (base * base);
226 case -3: return (BASE)1 / (base * base * base);
227 case -4: return (BASE)1 / (base * base * base * base);
228 default:
229 return poweri<BASE, exp>(base);
230 }
231 }
232 else if constexpr (std::is_floating_point_v<EXP>) {
233 if constexpr (exp == (EXP)0) return 1;
234 else if constexpr (exp == (EXP)1) return base;
235 else if constexpr (exp == (EXP)2) return base * base;
236 else if constexpr (exp == (EXP)3) return base * base * base;
237 else if constexpr (exp == (EXP)4) return base * base * base * base;
238 else if constexpr (exp == (EXP)-1) return 1 / base;
239 else if constexpr (exp == (EXP)-2) return 1 / (base * base);
240 else if constexpr (exp == (EXP)-3) return 1 / (base * base * base);
241 else if constexpr (exp == (EXP)-4) return 1 / (base * base * base * base);
242 }
243 return (BASE)std::pow(base, exp);;
244 }
245
246 /// Raise @a base to the power @a exp.
247 template <typename BASE, typename EXP>
248 inline constexpr power_t<BASE, EXP> power(BASE base, EXP exp) {
249 if constexpr (std::is_integral_v<BASE>) {
250 return power(float(base), exp);
251 }
252 else if constexpr (std::is_integral_v<EXP>) {
253 switch (exp) {
254 case 0: return (BASE)1;
255 case 1: return base;
256 case 2: return base * base;
257 case 3: return base * base * base;
258 case 4: return base * base * base * base;
259 case -1: return (BASE)1 / base;
260 case -2: return (BASE)1 / (base * base);
261 case -3: return (BASE)1 / (base * base * base);
262 case -4: return (BASE)1 / (base * base * base * base);
263 }
264 }
265 else if constexpr (std::is_floating_point_v<EXP>) {
266 if (base == (BASE)10) return (power_t<BASE, EXP>)::exp(exp * (EXP)2.3025850929940456840179914546843642076011014886287729760333279009);
267 else if (exp == (EXP)0) return (power_t<BASE, EXP>)1;
268 else if (exp == (EXP)1) return base;
269 else if (exp == (EXP)2) return base * base;
270 else if (exp == (EXP)3) return base * base * base;
271 else if (exp == (EXP)4) return base * base * base * base;
272 else if (exp == (EXP)-1) return (power_t<BASE, EXP>)1 / base;
273 else if (exp == (EXP)-2) return (power_t<BASE, EXP>)1 / (base * base);
274 else if (exp == (EXP)-3) return (power_t<BASE, EXP>)1 / (base * base * base);
275 else if (exp == (EXP)-4) return (power_t<BASE, EXP>)1 / (base * base * base * base);
276 }
277 return power_t<BASE, EXP>(std::pow(base, exp));
278 }
279
280 /// Return the minimum of two values.
281 using std::min;
282
283 /// Return the maximum of two values.
284 using std::max;
285
286 /// The mathematical constant, pi (and it's inverse).
287 constexpr constant pi = { 3.1415926535897932384626433832795 };
288
289 /// The natural logorithm of 2 (and it's inverse).
290 constexpr constant ln2 = { 0.6931471805599453094172321214581 };
291
292 /// The square root of 2 (and it's inverse).
293 constexpr constant root2 = { 1.4142135623730950488016887242097 };
294
295 /// Generates a random number between min and max. Use an integer types for whole numbers.
296 template<typename TYPE>
297 inline static TYPE random(const TYPE min, const TYPE max) { return rand() * ((max - min) / (TYPE)RAND_MAX) + min; }
298
299 /// Set the random seed (to allow repeatable random generation).
300 inline static void random(const unsigned int seed) { srand(seed); }
301
302 /// A function that handles an event.
303 typedef void event;
304
305 /// Variable-sized array, pre-allocated to a max. capacity.
306 template<typename TYPE, int CAPACITY>
307 struct Array {
308 unsigned int count = 0;
309 TYPE items[CAPACITY];
310
311 /// The maximum capacity of the array.
312 static int capacity() { return CAPACITY; }
313
314 /// The current number of items in the array.
315 unsigned int size() const { return count; }
316
317 /// Add the specified item to the end of the array.
318 void add(const TYPE& item) {
319 if (count < CAPACITY)
320 items[count++] = item;
321 }
322
323 /// Add a blank item to the end of the array, returning a pointer that allows the item to be modified.
324 TYPE* add() {
325 if (count < CAPACITY)
326 return &items[count++];
327 return nullptr;
328 }
329
330 /// Clear the array contents. Only resets the item count, without wiping memory.
331 void clear() { count = 0; }
332
333 /// Find the maximum value in the array.
334 float max() const {
335 float max = 0.f;
336 for (unsigned int i = 0; i < count; i++)
337 if (abs(items[i]) > max)
338 max = items[i];
339 return max;
340 }
341
342 /// Find the mean average of values in the array.
343 float mean() const {
344 float sum = 0.f;
345 for (unsigned int i = 0; i < count; i++)
346 sum += abs(items[i]);
347 return sum / count;
348 }
349
350 /// Find the root mean squared (RMS) average of values in the array.
351 float rms() const {
352 float sum = 0.f;
353 for (unsigned int i = 0; i < count; i++)
354 sum += items[i] * items[i];
355 return sqrt(sum / count);
356 }
357
358 /// Normalises values in the array to the specified @a target, based on peak, mean, or RMS value;
359 void normalise(float target = 1.f, int mode = Peak) {
360 if (!count) return;
361
362 const float current = (mode == Peak) ? max() : (mode == Mean) ? mean() : rms();
363 const float scale = current == 0.f ? 0.f : target / current;
364 for (int i = 0; i < count; i++)
365 items[i] *= scale;
366 }
367
368 /// Returns a reference to the array item at the given index.
369 TYPE& operator[](int index) { return items[index]; }
370
371 /// Returns a read-only reference to the array item at the given index.
372 const TYPE& operator[](int index) const { return items[index]; }
373
374 /// Construct an array given the specified values.
375 Array(std::initializer_list<TYPE> init_list) {
376 count = std::min(static_cast<unsigned int>(init_list.size()), static_cast<unsigned int>(CAPACITY));
377 std::copy_n(init_list.begin(), count, items);
378 }
379
380 /// Construct an empty array.
381 Array() = default; // Default constructor to allow empty initialization
382 };
383
384 struct Memory
385 {
386 typedef unsigned char Byte;
387 typedef Byte* Pointer;
388
390 size_t size;
391 bool owned;
392
394 detach();
395 }
396
397 Memory(size_t size) {
398 create(size);
399 }
400
402 free();
403 }
404
405 // attach to an existing buffer
406 void attach(unsigned char* data, size_t size, bool own = false) {
408 start = ptr = data;
409 end = start + size;
410 owned = own;
411 }
412
413 // detach from the buffer (without freeing it)
414 void detach() {
415 start = ptr = end = nullptr;
416 size = 0;
417 owned = false;
418 }
419
420 // allocate memory
421 bool create(size_t size) {
422 free();
423 start = ptr = new Byte[size];
424 if (start) {
426 end = start + size;
427 owned = true;
428 return true;
429 }
430 return false;
431 }
432
433 // clear memory
434 void clear() {
435 memset(start, 0, size);
436 }
437
438 // rewind memory to start
439 void rewind() {
440 ptr = start;
441 }
442
443 // rewind memory
444 void rewind(int bytes) {
445 ptr -= bytes;
446 }
447
448 // skip / fastforward memory
449 void skip(int bytes) {
450 ptr += bytes;
451 }
452
453 // release memory
454 void free() {
455 if (owned && start) {
456 ptr = end = nullptr;
457 delete[] start;
458 start = nullptr;
459 size = 0;
460 }
461 }
462
463 // check if pointer is at end of memory
464 bool finished() const {
465 return ptr >= end;
466 }
467
468 // return memory-mapped file pointer
469 FILE* file() {
470 FILE* f = fopen("/dev/null", "wt");
471 if (!f) f = fopen("nul", "wt");
472 setvbuf(f, (char*)start, _IOFBF, size);
473 return f;
474 }
475
476 bool load(const char* path) {
477 FILE* f = fopen(path, "rb");
478 if (!f) return false;
479
480 // find out length of file
481 fseek(f, 0, SEEK_END);
482 size_t length = ftell(f);
483 fseek(f, 0, SEEK_SET);
484
485 // allocate memory and read file
486 if (!create(length)) {
487 fclose(f);
488 return false;
489 }
490 fread(start, 1, length, f);
491 fclose(f);
492
493 return true;
494 }
495
496 // retrieve the next value from memory
497 template<typename TYPE>
498 bool get(TYPE& value) {
499 if (ptr + sizeof(TYPE) > end) {
500 ptr = end;
501 return false;
502 }
503 value = *(TYPE*)ptr;
504 ptr += sizeof(TYPE);
505 return true;
506 }
507
508 // retrieve the next value from memory
509 template<typename TYPE>
510 operator TYPE() {
511 TYPE value;
512 get(value);
513 return value;
514 }
515
516 // add a value to the memory
517 template<typename TYPE>
518 bool add(const TYPE& value) {
519 if (ptr + sizeof(TYPE) > end)
520 return false;
521 *(TYPE*)ptr = value;
522 ptr += sizeof(TYPE);
523 return true;
524 }
525
526 // add a value to the memory
527 template<typename TYPE>
528 Memory& operator+=(const TYPE& value) {
529 add(value);
530 return *this;
531 }
532
533 // check if memory is equal to a value
534 template<typename TYPE>
535 bool operator==(const TYPE& value) const {
536 if (ptr + sizeof(TYPE) > end)
537 return false;
538 return value == *(TYPE*)ptr;
539 }
540
541 // copy memory from another memory object (with resize)
542 Memory& operator=(const Memory& memory) {
543 if (ptr + memory.size > end)
544 return *this;
545 create(memory.size);
546 memcpy(start, memory.start, memory.size);
547 return *this;
548 }
549
550 // attach memory to another memory object
552 free();
553 attach(memory->start, memory->size);
554 return *this;
555 }
556
557 // add memory data from another memory object
558 Memory& operator+=(const Memory& memory) {
559 if (ptr + memory.size > end)
560 return *this;
561 memcpy(ptr, memory.start, memory.size);
562 ptr += memory.size;
563 return *this;
564 }
565
566 //operator int() {
567 // if (ptr + sizeof(int) > end) {
568 // ptr = end;
569 // return 0;
570 // }
571 // ptr += sizeof(int);
572 // return *(int*)(ptr - sizeof(int));
573 //}
574
575 //operator float() {
576 // if (ptr + sizeof(float) > end) {
577 // ptr = end;
578 // return 0;
579 // }
580 // ptr += sizeof(float);
581 // return *(float*)(ptr - sizeof(float));
582 //}
583
584 // int geti1() {
585 // if ((++_ptr) > _end) {
586 // if (_ptr == _end)
587 // return (*(BYTE*)(_ptr - 1));
588 // _ptr = _end;
589 // return 0;
590 // }
591 // return (*(int*)(_ptr - 1)) & 0xFF;
592 // }
593
594 // int geti2() {
595 // if ((_ptr += 2) >/*=*/ _end) {
596 // // if(_ptr == _end)
597 // // return (*(short*)(_ptr - 2));
598 // _ptr = _end;
599 // return 0;
600 // }
601 // return (*(int*)(_ptr - 2)) & 0xFFFF;
602 // }
603
604 // // int geti3() {
605 // // if ((_ptr += 3) > _end) {
606 // // _ptr = _end;
607 // // return 0;
608 // // }
609 // // return (*(int*)(_ptr - 3)) & 0xFFFFFF;
610 // // }
611
612 // int geti4() {
613 // if ((_ptr += 4) > _end) {
614 // _ptr = _end;
615 // return 0;
616 // }
617 // return (*(int*)(_ptr - 4)) & 0xFFFFFFFF;
618 // }
619
620 // int geti(const int size) {
621 // switch (size) {
622 // case 1: return geti1();
623 // case 2: return geti2();
624 // // case 3: return geti3();
625 // case 4: return geti4();
626 // default:
627 // int number = getc();
628 // for (int i = 1; i < size; i++) // (collate bytes into multi-byte integer)
629 // number += (1 << (i * 8)) * getc(); // pow(256.0, i) * getc(); //
630 // return number; // (return results)
631 // }
632 // }
633
634 // int getbe(int size) {
635 // int number = getc();
636 // while (--size) {
637 // number <<= 8;
638 // number += getc();
639 // }
640 // return number;
641 // }
642
643 // bool putc(char c) {
644 // if (_ptr < _end) {
645 // *_ptr++ = c;
646 // return true;
647 // }
648 // return false;
649 // }
650
651 // size_t write(const void* src, const size_t size, const size_t count) {
652 // if ((_ptr + size * count) <= _end) {
653 // memcpy(_ptr, src, size * count);
654 // _ptr += size * count;
655 // return size;
656 // }
657 // else {
658 // _ptr = _end;
659 // }
660 // return 0;
661 // }
662
663 // /*int getshort(){
664 // _ptr+=sizeof(short);
665 // if(_ptr > _end){
666 // _ptr = _end;
667 // return 0;
668 // }
669 // return *(int*)(_ptr-sizeof(short));
670 // }
671
672 // int getint(){
673 // _ptr+=sizeof(int);
674 // if(_ptr > _end){
675 // _ptr = _end;
676 // return 0;
677 // }
678 // return *(int*)(_ptr-sizeof(int));
679 // }*/
680
681 // bool eof() const {
682 // return _ptr >= _end;
683 // }
684
685 // int getvari(void)
686 // {
687 // int value;
688 // short c;
689
690 // if ((value = getc()) & 0x80) {
691 // value &= 0x7f;
692 // do {
693 // value = (value << 7) + ((c = getc()) & 0x7f);
694 // } while (c & 0x80);
695 // }
696 // return value;
697 // }
698
699 // char* gets(int length) {
700 // if ((_ptr + length) >= _end) {
701 // _ptr = _end;
702 // _string[0] = 0;
703 // }
704 // else {
705 // memcpy(_string, _ptr, MIN(length, 255));
706 // _string[MIN(length, 255)] = 0;
707 // _ptr += length;
708 // }
709 // return _string;
710 // }
711
712 // char* gets0(int length) {
713 // if ((_ptr + length) >= _end) {
714 // _ptr = _end;
715 // _string[0] = 0;
716 // }
717 // else {
718 // memcpy(_string, _ptr, MIN(length, 255));
719 // _string[MIN(length, 255)] = 0;
720 // if (!_string[0])
721 // _string[0] = ' ';
722 // _ptr += length;
723 // }
724 // return _string;
725 // }
726
727 // char* gets_any(const char* const of) {
728 // _string[0] = 0;
729
730 // int length = 0;
731 // while (!eof() && length < 255) {
732 // unsigned char ch = *_ptr;
733 // if (strchr(of, ch)) { // valid character
734 // _string[length++] = ch;
735 // _ptr++;
736 // }
737 // else {
738 // _string[length] = 0;
739 // return _string;
740 // }
741 // }
742 // _string[length] = 0;
743 // return _string;
744 // }
745
746 // static bool isNumeric(char x) {
747 // return (x >= '0' && x <= '9');
748 // }
749
750 // char* gets_numeric() {
751 // _string[0] = 0;
752
753 // int length = 0;
754 // while (!eof() && length < 255) {
755 // unsigned char ch = *_ptr;
756 // if (isNumeric(ch)) { // valid character
757 // _string[length++] = ch;
758 // _ptr++;
759 // }
760 // else {
761 // _string[length] = 0;
762 // return _string;
763 // }
764 // }
765 // _string[length] = 0;
766 // return _string;
767 // }
768
769 // static bool isHexadecimal(char x) {
770 // return (x >= 'A' && x <= 'F') || (x >= '0' && x <= '9');
771 // }
772
773 // char* gets_hex() {
774 // _string[0] = 0;
775
776 // int length = 0;
777 // while (!eof() && length < 255) {
778 // unsigned char ch = *_ptr;
779 // if (isHexadecimal(ch)) { // valid character
780 // _string[length++] = ch;
781 // _ptr++;
782 // }
783 // else {
784 // _string[length] = 0;
785 // return _string;
786 // }
787 // }
788 // _string[length] = 0;
789 // return _string;
790 // }
791
792 // void gets(char* string, int length) {
793 // if ((_ptr + length) >= _end) {
794 // _ptr = _end;
795 // return;
796 // }
797 // memcpy(string, _ptr, length);
798 // string[length] = 0;
799 // _ptr += length;
800 // }
801
802 // /* void gets(std::string& string, int length){
803 // if((_ptr + length) >= _end){
804 // _ptr = _end;
805 // return;
806 // }
807
808 // // memcpy(string, _ptr, length);
809 // // string[length] = 0;
810 // string.copy((char*)_ptr, length);
811 // string.append(0);
812
813 // _ptr += length;
814 // }*/
815
816 // void gets(char* string) {
817 // if (eof()) return;
818 // gets(string, getc());
819 // }
820
821 // /*void gets0(char* string, int length){
822 // if((_ptr + length) >= _end){
823 // _ptr = _end;
824 // return;
825 // }
826 // memcpy(string, _ptr, length);
827 // string[length] = 0;
828 // if(string[0] == 0)
829 // string[0] = ' ';
830 // _ptr += length;
831 // }*/
832
833 // void gets(char* string, char terminator, unsigned int length) {
834 // const BYTE_PTR _end = std::min(_ptr + length, this->_end);
835 // BYTE_PTR _offset;
836 // for (_offset = _ptr; _offset < _end; _offset++) {
837 // if (*_offset == terminator)
838 // break;
839 // }
840 // // if(_offset != _end){
841 // const unsigned int _len = (unsigned int)(_offset - _ptr);
842 // memcpy(string, _ptr, _len);
843 // string[std::min(length - 1, _len)] = 0;
844 // // }
845 // _ptr = _offset;
846 // }
847
848 // static bool isAlphaNumeric(char x) {
849 // return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || (x >= '0' && x <= '9');
850 // }
851
852 // void gettag(char* string) {
853 // while (isAlphaNumeric(*_ptr)) {
854 // *string++ = *_ptr++;
855 // }
856 // *string = 0;
857 // }
858
859 // void getcs(char* string) {
860 // if (_ptr > _end) {
861 // string[0] = 0;
862 // return;
863 // }
864 // const int length = *_ptr;
865 // if ((_ptr + length) > _end) {
866 // string[0] = 0;
867 // return;
868 // }
869 // _ptr++;
870 // memcpy(string, _ptr, length);
871 // _ptr += length;
872 // }
873
874 // int read(void* to, const int size) {
875 // if ((_ptr + size) > _end) {
876 // _ptr = _end;
877 // return 0;
878 // }
879 // memcpy(to, _ptr, size);
880 // _ptr += size;
881 // return size;
882 // }
883
884 // void skip(const int size) {
885 // if ((_ptr + size) > _end) {
886 // _ptr = _end;
887 // return;
888 // }
889 // _ptr += size;
890 // }
891
892 // void skip_any(char token) {
893 // while (!eof()) {
894 // if (*_ptr != token)
895 // return;
896 // _ptr++;
897 // }
898 // }
899
900 // void skip_any(const char* tokens) {
901 // while (!eof()) {
902 // const char* pTokens = tokens;
903 // while (*pTokens != '\0') {
904 // if (*_ptr == *pTokens)
905 // break;
906 // pTokens++;
907 // }
908 // if (*pTokens)
909 // _ptr++;
910 // else
911 // return;
912 // }
913 // }
914
915 // bool skip_to(char token) {
916 // while (!eof()) {
917 // if (*_ptr == token)
918 // return true;
919 // _ptr++;
920 // }
921 // return false;
922 // }
923
924 // bool skip_to(const char* token) {
925 // size_t length = strlen(token);
926 // while (!eof()) {
927 // if (!memcmp(token, _ptr, length)) {
928 // _ptr += length;
929 // return true;
930 // }
931 // _ptr++;
932 // }
933 // return false;
934 // }
935
936 // void skip_to_any(const char* tokens) {
937 // while (!eof()) {
938 // const char* pTokens = tokens;
939 // while (*pTokens != '\0') {
940 // if (*_ptr == *pTokens++)
941 // return;
942 // }
943 // _ptr++;
944 // }
945 // }
946
947 // bool match_i(const char* stuff) { // matches given text with file
948 // size_t length = strlen(stuff); // (reset expectation)
949 // if (!_strnicmp(stuff, (const char*)_ptr, length)) {
950 // _ptr += length;
951 // return true;
952 // }
953 // return false;
954 // }
955
956 // bool match(const char* stuff) { // matches given text with file
957 // size_t length = strlen(stuff); // (reset expectation)
958 // if (!memcmp(stuff, _ptr, length)) {
959 // _ptr += length;
960 // return true;
961 // }
962 // return false;
963 // } //
964
965 // bool match(char stuff) { // matches given text with file
966 // if (*_ptr == stuff) {
967 // _ptr++;
968 // return true;
969 // }
970 // return false;
971 // }
972
973 // // in-place character replacement
974 // int replace(BYTE find, BYTE replace) {
975 // int nbReplaced = 0;
976 // BYTE_PTR ptr = _buf;
977 // while (ptr < _end) {
978 // if (*ptr == find)
979 // *ptr = replace;
980 // nbReplaced++;
981 // ptr++;
982 // }
983 // return nbReplaced;
984 // }
985
986 // // in-place phrase replacement
987 // int replace_fast(const char* find, const char* replace) {
988 // // build new string
989 // const char* str = (const char*)_buf;
990 // const char* end = (const char*)_end;
991 // const int length = (int)strlen(replace);
992 // int nbReplaced = 0;
993
994 // while (str < end) {
995 // if (!memcmp(str, find, length)) { // match
996 // memcpy((void*)str, replace, length);
997 // str += length;
998 // nbReplaced++;
999 // }
1000 // else {
1001 // str++;
1002 // }
1003 // }
1004 // return nbReplaced;
1005 // }
1006
1007 // int replace(const char* find, const char* replace) {
1008 // const int cbFind = (int)strlen(find);
1009 // const int cbReplace = (int)strlen(replace);
1010 // if (cbFind == cbReplace) // no memory re-allocation required
1011 // return replace_fast(find, replace);
1012
1013 // // build new string
1014 // std::string new_str;
1015 // const char* str = (const char*)_buf;
1016 // const char* last = str;
1017 // const char* end = (const char*)_end;
1018 // int nbReplaced = 0;
1019
1020 // while (str < end) {
1021 // if (!memcmp(str, find, cbFind)) { // match
1022 // new_str.append(last, str - last); // catch-up
1023 // new_str += replace;
1024 // str += cbFind;
1025 // last = str;
1026 // nbReplaced++;
1027 // }
1028 // else {
1029 // str++;
1030 // }
1031 // }
1032 // if (last < end)
1033 // new_str.append(last, end - last);
1034
1035 // // replace buffer with new string
1036 // create((int)new_str.length());
1037 // memcpy(_buf, new_str.data(), new_str.length());
1038 // return nbReplaced;
1039 // }
1040
1041 // bool match_any(const char* stuffs) {
1042 // while (*stuffs != '\0') {
1043 // if (*_ptr == *stuffs++) {
1044 // _ptr++;
1045 // return true;
1046 // }
1047 // }
1048 // return false;
1049 // }
1050
1051 // unsigned int length() const { return _len; }
1052 // const BYTE_PTR buffer() const { return _buf; }
1053 // BYTE_PTR buffer() { return _buf; }
1054 // BYTE_PTR pointer() { return _ptr; }
1055 // BYTE_PTR* ppointer() { return &_ptr; }
1056
1057 // unsigned int offset() const { return (unsigned int)(_ptr - _buf); }
1058 // bool seek(unsigned int offset) {
1059 // _ptr = _buf + offset;
1060 // if (_ptr > _end) {
1061 // _ptr = _end;
1062 // return false;
1063 // }
1064 // else return true;
1065 // }
1066 //protected:
1067 // BYTE_PTR _buf;
1068 // unsigned int _len;
1069
1070 // BYTE_PTR _end;
1071 // BYTE_PTR _ptr;
1072
1073 // char _string[256];
1074 };
1075
1076 /// String of characters representing text.
1077 template<int SIZE>
1078 struct Text {
1079 /// The character buffer.
1080 char string[SIZE + 1] = { 0 };
1081
1082 /// Maximum size of the string.
1083 int capacity() const { return SIZE; }
1084
1085 /// Automatic cast to constant C-string.
1086 operator const char* () const { return string; }
1087
1088 /// Return constant C-string.
1089 const char* c_str() const { return string; }
1090
1091 /// Create a new Text object from a C-string.
1092 static Text from(const char* in) {
1093 Text text;
1094 text = in;
1095 return text;
1096 }
1097
1098 /// Assign C-String to Text object.
1099 void operator=(const char* in) {
1100 memcpy(string, in, SIZE);
1101 string[SIZE] = 0;
1102 }
1103
1104 /// Returns true if Text matches the given C-string.
1105 bool operator==(const char* in) const {
1106 return strcmp(string, in) == 0;
1107 }
1108
1109 /// Returns true if Text does not matches the given C-string.
1110 bool operator!=(const char* in) const {
1111 return !operator==(in);
1112 }
1113 };
1114
1115 /// A short Text object used to label controls.
1117
1118 struct Output;
1119
1120 struct relative;
1121
1122 /// A mono audio signal (equivalent to a float).
1123 struct signal {
1124 float value;
1125
1126 /// Create signal from a constant.
1127 signal(constant initial) : value(initial.f) {}
1128
1129 /// Create signal from a 32-bit float..
1130 signal(const float initial = 0.f) : value(initial) {}
1131
1132 /// Create signal from a 64-bit double.
1133 signal(const double initial) : value((const float)initial) {}
1134
1135 /// Create signal from an 32-bit signed integer.
1136 signal(const int value) : value((const float)value) {}
1137
1138 /// Feedback operator (prevents further processing of returned value).
1139 const signal& operator<<(const signal& input) {
1140 value = input;
1141 return *this;
1142 }
1143
1144 /// Stream operator (feedforward; allows further processing)
1145 signal& operator>>(signal& destination) const {
1146 destination.value = value;
1147 return destination;
1148 }
1149
1150 /// Assign processed output of \a in to signal.
1151 signal& operator=(Output& in);
1152 /// Adds processed output of \a in to signal.
1153 signal& operator+=(Output& in);
1154
1155 /// Add (mix) another signal to the signal.
1156 signal& operator+=(const signal& x) { value += x.value; return *this; }
1157 /// Subtract another signal from the signal.
1158 signal& operator-=(const signal& x) { value -= x.value; return *this; }
1159 /// Multiply (modulate) signal by another signal.
1160 signal& operator*=(const signal& x) { value *= x.value; return *this; }
1161 /// Divide signal by another signal.
1162 signal& operator/=(const signal& x) { value /= x.value; return *this; }
1163
1164 /// Add the specified amount to the signal.
1165 signal& operator+=(float x) { value += x; return *this; }
1166 /// Subtract the specified amount from the signal.
1167 signal& operator-=(float x) { value -= x; return *this; }
1168 /// Multiply signal by the specified amount.
1169 signal& operator*=(float x) { value *= x; return *this; }
1170 /// Divide signal by the specified amount.
1171 signal& operator/=(float x) { value /= x; return *this; }
1172
1173 /// Add the specified amount to the signal.
1174 signal& operator+=(double x) { value += (float)x; return *this; }
1175 /// Subtract the specified amount from the signal.
1176 signal& operator-=(double x) { value -= (float)x; return *this; }
1177 /// Multiply signal by the specified amount.
1178 signal& operator*=(double x) { value *= (float)x; return *this; }
1179 /// Divide signal by the specified amount.
1180 signal& operator/=(double x) { value /= (float)x; return *this; }
1181
1182 /// Add the specified amount to the signal.
1183 signal& operator+=(int x) { value += (float)x; return *this; }
1184 /// Subtract the specified amount from the signal.
1185 signal& operator-=(int x) { value -= (float)x; return *this; }
1186 /// Multiply signal by the specified amount.
1187 signal& operator*=(int x) { value *= (float)x; return *this; }
1188 /// Divide signal by the specified amount.
1189 signal& operator/=(int x) { value /= (float)x; return *this; }
1190
1191 /// Add two signals together.
1192 signal operator+(float x) const { return value + x; }
1193 /// Subtract one signal from another.
1194 signal operator-(float x) const { return value - x; }
1195 /// Multiply (modulate) two signals.
1196 signal operator*(float x) const { return value * x; }
1197 /// Divide one signal by another.
1198 signal operator/(float x) const { return value / x; }
1199
1200 /// Return a copy of the signal offset by x.
1201 signal operator+(double x) const { return value + (float)x; }
1202 /// Return a copy of the signal offset by -x.
1203 signal operator-(double x) const { return value - (float)x; }
1204 /// Return a copy of the signal scaled by x.
1205 signal operator*(double x) const { return value * (float)x; }
1206 /// Return a copy of the signal divided by.
1207 signal operator/(double x) const { return value / (float)x; }
1208
1209 /// Return a copy of the signal offset by x.
1210 signal operator+(int x) const { return value + (float)x; }
1211 /// Return a copy of the signal offset by -x.
1212 signal operator-(int x) const { return value - (float)x; }
1213 /// Return a copy of the signal scaled by x.
1214 signal operator*(int x) const { return value * (float)x; }
1215 /// Return a copy of the signal divided by x.
1216 signal operator/(int x) const { return value / (float)x; }
1217
1218 /// Return a copy of the signal raised to the power of x.
1219 signal operator^(float x) const { return power(value, x); }
1220 /// Return a copy of the signal raised to the power of x.
1221 signal operator^(double x) const { return power(value, x); }
1222 /// Return a copy of the signal raised to the power of x.
1223 signal operator^(int x) const { return power(value, x); }
1224
1225 operator const float() const { return value; }
1226 operator float& () { return value; }
1227
1228 /// Check if the signal contains a denormal value.
1229 bool isDenormal() const {
1230 const unsigned int bits = *(const unsigned int*)&value;
1231 return !(bits & 0x7F800000) && (bits & 0x007FFFFF);
1232 }
1233
1234 /// Returns the number of channels (1 = mono).
1235 int channels() const { return 1; }
1236
1237 /// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
1238 relative operator+() const; // unary + operator produces relative signal
1239 /// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
1240 relative relative() const; //
1241 };
1242
1243 /// @internal signal MUST compile as a float
1244 static_assert(sizeof(signal) == sizeof(float), "signal != float");
1245 IS_SIMPLE_TYPE(signal)
1246
1247 /// A signal used as an offset relative to another signal.
1248 struct relative : public signal {};
1249
1250 /// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
1251 inline relative signal::operator+() const { return { value }; }
1252 /// Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
1253 inline relative signal::relative() const { return { value }; }
1254
1255 /// Stream a built-in arithmetic value into a signal, narrowing at the signal boundary.
1256 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
1257 inline signal& operator>>(TYPE input, signal& destination) {
1258 destination << signal(static_cast<float>(input));
1259 return destination;
1260 }
1261 /// Stream a Klang constant into a signal.
1262 inline signal& operator>>(const constant& input, signal& destination) {
1263 destination << signal(input.f);
1264 return destination;
1265 }
1266
1267 /// A stateless unary C/C++ function that maps one float sample to another.
1268 using UnaryFunction = float(float);
1269
1270 /// Apply an ordinary unary function within a signal-flow expression.
1271 inline signal operator>>(signal input, UnaryFunction& function) {
1272 return function(float(input));
1273 }
1274
1275
1276 /// A multi-channel audio signal (e.g. stereo).
1277 template<int CHANNELS = 2>
1278 struct signals {
1279 static_assert(CHANNELS > 0, "signals requires at least one channel");
1280#if !defined(__GNUC__) || defined(__clang__) // non-GNU compilers support anonymous unions; GNU compilers do not (and produce warnings/errors)
1281 /// @cond
1282 union {
1283 signal value[CHANNELS]; ///< Array of channel values.
1284 struct {
1285 signal l; ///< Left channel
1286 signal r; ///< Right channel
1287 };
1288 };
1289 /// @endcond
1290
1291 /// Create a multi-channel signal by broadcasting the given value.
1292 signals(float initial = 0.f) { for (int channel = 0; channel < CHANNELS; channel++) value[channel] = initial; }
1293 /// Create a multi-channel signal by broadcasting the given value.
1294 signals(double initial) : signals((float)initial) {}
1295 /// Create a multi-channel signal by broadcasting the given value.
1296 signals(int initial) : signals((float)initial) {}
1297 /// Create a multi-channel signal by broadcasting the given signal.
1298 signals(const klang::signal& initial) { for (int channel = 0; channel < CHANNELS; channel++) value[channel] = initial; }
1299
1300 /// Create a multi-channel signal with the first two channel values; remaining channels are zero.
1301 signals(float left, float right) : signals(0.f) { l = left; r = right; }
1302 /// Create a multi-channel signal with the first two channel values; remaining channels are zero.
1303 signals(double left, double right) : signals((float)left, (float)right) {}
1304 /// Create a multi-channel signal with the first two channel values; remaining channels are zero.
1305 signals(int left, int right) : signals((float)left, (float)right) {}
1306
1307 /// Create a multi-channel signal with the given channel values.
1308 template <typename... Args, typename = std::enable_if_t<sizeof...(Args) == CHANNELS && (std::is_convertible_v<Args, signal> && ...)>>
1309 signals(Args&... initial) : value{ initial... } {}
1310 /// Create a multi-channel signal with the given channel values.
1311 template <typename... Args, typename = std::enable_if_t<sizeof...(Args) == CHANNELS && (std::is_scalar_v<Args> && ...)>>
1312 signals(Args... initial) : value{ initial... } {}
1313#else
1314 signal value[CHANNELS]; ///< Array of channel values.
1315 signal& l = value[0]; ///< Left channel
1316 signal& r = value[1]; ///< Right channel
1317
1318 /// Create a multi-channel signal by broadcasting the given value.
1319 signals(float initial = 0.f) { for (int v = 0; v < CHANNELS; v++) value[v] = initial; }
1320 /// Create a multi-channel signal by broadcasting the given value.
1321 signals(double initial) : signals((float)initial) {}
1322 /// Create a multi-channel signal by broadcasting the given value.
1323 signals(int initial) : signals((float)initial) {}
1324 /// Create a multi-channel signal by broadcasting the given signal.
1325 signals(const klang::signal& initial) { for (int v = 0; v < CHANNELS; v++) value[v] = initial; }
1326
1327 /// Create a multi-channel signal with the first two channel values; remaining channels are zero.
1328 signals(float left, float right) { l = left; r = right; for (int v = 2; v < CHANNELS; v++) value[v] = 0.f; }
1329 /// Create a multi-channel signal with the first two channel values; remaining channels are zero.
1330 signals(double left, double right) : signals((float)left, (float)right) {}
1331 /// Create a multi-channel signal with the first two channel values; remaining channels are zero.
1332 signals(int left, int right) : signals((float)left, (float)right) {}
1333
1334 /// Create a multi-channel signal with the given channel values.
1335 template <typename... Args, typename = std::enable_if_t<sizeof...(Args) == CHANNELS && (std::is_convertible_v<Args, signal> && ...)>>
1336 signals(Args&... initial) : value{ initial... } {}
1337 /// Create a multi-channel signal with the given channel values.
1338 template <typename... Args, typename = std::enable_if_t<sizeof...(Args) == CHANNELS && (std::is_scalar_v<Args> && ...)>>
1339 signals(Args... initial) : value{ initial... } {}
1340
1341 signals& operator=(const signals& input) { for (int v = 0; v < CHANNELS; v++) value[v] = input[v]; return *this; }
1342#endif
1343 /// Evaluate a mono Klang object once and broadcast its signal to every channel.
1344 template<typename TYPE, std::enable_if_t<!std::is_arithmetic_v<std::decay_t<TYPE>> &&
1345 !std::is_same_v<std::decay_t<TYPE>, klang::signal> && std::is_convertible_v<TYPE&, klang::signal>, int> = 0>
1346 signals(TYPE& initial) {
1347 const klang::signal mono = initial;
1348 for (int channel = 0; channel < CHANNELS; channel++)
1349 value[channel] = mono;
1350 }
1351
1352 /// Return the sum of all channels.
1354 klang::signal result = 0;
1355 for (int channel = 0; channel < CHANNELS; channel++)
1356 result += value[channel];
1357 return result;
1358 }
1359
1360 /// Return the arithmetic mean of all channels.
1361 klang::signal average() const { return sum() / float(CHANNELS); }
1362
1363 /// Return the default mono downmix: the arithmetic mean of all channels.
1364 klang::signal mono() const { return average(); }
1365
1366 /// Return a reference to the signal at the specified index (0 = left, 1 = right).
1367 signal& operator[](int index) { return value[index]; }
1368 /// Return a read-only reference to the signal at the specified index (0 = left, 1 = right).
1369 const signal& operator[](int index) const { return value[index]; }
1370
1371 /// Returns the number of channels in the signal.
1372 int channels() const { return CHANNELS; }
1373
1374 /// Feedback operator (prevents further processing of returned value).
1375 const signals& operator<<(const signals& input) {
1376 return this->operator=(input);
1377 }
1378
1379 /// Stream operator (feedforward; allows further processing).
1380 signals& operator>>(signals& destination) const {
1381 destination = *this;
1382 return destination;
1383 }
1384
1385 /// Add (mix) another signal to the signal.
1386 signals& operator+=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] += x[v]; return *this; }
1387 /// Subtract another signal from the signal.
1388 signals& operator-=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] -= x[v]; return *this; }
1389 /// Multiply (modulate) signal by another signal.
1390 signals& operator*=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] *= x[v]; return *this; }
1391 /// Divide signal by another signal.
1392 signals& operator/=(const signals x) { for (int v = 0; v < CHANNELS; v++) value[v] /= x[v]; return *this; }
1393
1394 /// Add two multi-channel signals together.
1395 signals operator+(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x[v]; return s; }
1396 /// Subtract one multi-channel signal from another.
1397 signals operator-(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x[v]; return s; }
1398 /// Multiply (modulate) two multi-channel signals.
1399 signals operator*(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x[v]; return s; }
1400 /// Divide one multi-channel signal by another.
1401 signals operator/(const signals x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x[v]; return s; }
1402
1403 //signals& operator+=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] += x; return *this; }
1404 //signals& operator-=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] -= x; return *this; }
1405 //signals& operator*=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] *= x; return *this; }
1406 //signals& operator/=(const signal x) { for (int v = 0; v < CHANNELS; v++) value[v] /= x; return *this; }
1407
1408 /// Return a copy of the multi-channel signal, adding a mono signal to each channel.
1409 signals operator+(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
1410 /// Return a copy of the multi-channel signal, subtracting a mono signal from each channel.
1411 signals operator-(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
1412 /// Return a copy of the multi-channel signal, multiplying (modulating) each channel by a mono signal.
1413 signals operator*(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
1414 /// Return a copy of the multi-channel signal, dividing each channel by a mono signal.
1415 signals operator/(const signal x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
1416
1417 /// Return a copy of the signal with each channel offset by x.
1418 signals operator+(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
1419 /// Return a copy of the signal with each channel offset by -x.
1420 signals operator-(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
1421 /// Return a copy of the signal with each channel scaled by x.
1422 signals operator*(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
1423 /// Return a copy of the signal with each channel divided by x.
1424 signals operator/(float x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
1425
1426 /// Return a copy of the signal with each channel offset by x.
1427 signals operator+(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
1428 /// Return a copy of the signal with each channel offset by -x.
1429 signals operator-(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
1430 /// Return a copy of the signal with each channel scaled by x.
1431 signals operator*(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
1432 /// Return a copy of the signal with each channel divided by x.
1433 signals operator/(double x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
1434
1435 /// Return a copy of the signal with each channel offset by x.
1436 signals operator+(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] += x; return s; }
1437 /// Return a copy of the signal with each channel offset by -x.
1438 signals operator-(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] -= x; return s; }
1439 /// Return a copy of the signal with each channel scaled by x.
1440 signals operator*(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] *= x; return s; }
1441 /// Return a copy of the signal with each channel divided by x.
1442 signals operator/(int x) const { signals s = *this; for (int v = 0; v < CHANNELS; v++) s[v] /= x; return s; }
1443 };
1444
1445 /// Return a copy of the signal with each channel offset by x.
1446 template<int CHANNELS = 2> inline signals<CHANNELS> operator+(float x, const signals<CHANNELS>& y) { return y + x; }
1447 /// Return a copy of the signal with each channel subtracted from x.
1448 template<int CHANNELS = 2> inline signals<CHANNELS> operator-(float x, const signals<CHANNELS>& y) { return -y + x; }
1449 /// Return a copy of the signal with each channel scaled by x.
1450 template<int CHANNELS = 2> inline signals<CHANNELS> operator*(float x, const signals<CHANNELS>& y) { return y * x; }
1451 /// Return a copy of the signal with each channel divided into x.
1452 template<int CHANNELS = 2> inline signals<CHANNELS> operator/(float x, const signals<CHANNELS>& y) {
1453 signals<CHANNELS> s = { 0.f };
1454 for (int c = 0; c < CHANNELS; c++)
1455 s[c] = x / y[c];
1456 return std::move(s);
1457 }
1458
1459 /// @cond
1460 /// Helper class for converting units / quantities
1461 struct Conversion : public signal {
1462 using signal::signal;
1463 // operator klang::signal& () { return signal; };
1464 };
1465 /// @endcond
1466
1467 /// A phase or wavetable increment.
1468 struct increment {
1469 float amount; ///< The current phase.
1470 const float size; ///< The length of a a full cycle (e.g. 2 pi or wavetable size)
1471
1472 /// Create a phase increment (default to radians).
1473 increment(float amount, const float size = 2 * pi) : amount(amount), size(size) {}
1474 /// Create a phase increment (wavetable size).
1475 increment(float amount, int size) : amount(amount), size((float)size) {}
1476 /// Create a phase increment.
1477 increment(float amount, double size) : amount(amount), size((float)size) {}
1478
1479 /// Set current phase.
1480 increment& operator=(float in) { amount = in; return *this; }
1481 };
1482
1483 struct Control;
1484
1485 /// A signal used as a control parameter.
1486 struct param : public signal {
1487 param(constant in) : signal(in.f) {}
1488 param(const float initial = 0.f) : signal(initial) {}
1489 param(const signal& in) : signal(in) {}
1490 param(signal& in) : signal(in) {}
1491 param(Control& in); // see Control declaration
1492 template<typename SOURCE, std::enable_if_t<!std::is_arithmetic_v<std::decay_t<SOURCE>> &&
1493 !std::is_base_of_v<signal, std::decay_t<SOURCE>> &&
1494 !std::is_same_v<std::decay_t<SOURCE>, Control> &&
1495 std::is_convertible_v<SOURCE&&, const signal&>, int> = 0>
1496 param(SOURCE&& source)
1497 : signal(static_cast<const signal&>(std::forward<SOURCE>(source))) {}
1498
1500 value += increment.amount;
1501 if (value >= increment.size)
1502 value -= increment.size;
1503 return *this;
1504 }
1505 };
1506
1507 // param should also be binary compatible with float / signal
1508 static_assert(sizeof(param) == sizeof(float), "param != float");
1509
1510 // support left-to-right and right-to-left signal flow
1511 inline static param& operator>>(param& from, param& to) {
1512 to << from;
1513 return to;
1514 }
1515
1516 /// @cond
1517 struct params {
1518 param* parameters;
1519 const int size;
1520
1521 params(param p) : parameters(new param[1]), size(1) { parameters[0] = p; }
1522 params(std::initializer_list<param> params) : parameters(new param[params.size()]), size((int)params.size()) {
1523 int index = 0;
1524 for (param p : params)
1525 parameters[index++] = p;
1526 }
1527
1528 param& operator[](int index) { return parameters[index]; }
1529 };
1530 /// @endcond
1531
1532 inline float fast_mod(float x, float y) {
1533 const unsigned int i = (((unsigned int)(x * (float(UINT_MAX) + 1.f) / y)) >> 9) | 0x3f800000;
1534 return (*(const float*)&i - 1.f) * y;
1535 }
1536
1537 inline double fast_mod(double x, double y) {
1538 const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0) / y)) >> 12ULL) | 0x7FF0000000000000ULL;
1539 return (*(const double*)&i - 1.0) * y;
1540 }
1541
1542 inline float fast_mod1(float x) {
1543 const unsigned int i = ((unsigned int)(x * (float(UINT_MAX) + 1.f)) >> 9) | 0x3f800000;
1544 return *(const float*)&i - 1.f;
1545 }
1546
1547 inline double fast_mod1(double x) {
1548 const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0))) >> 12ULL) | 0x7FF0000000000000ULL;
1549 return (*(const double*)&i - 1.0);
1550 }
1551
1552 inline float fast_mod2pi(float x) {
1553 constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
1554 const unsigned int i = (((unsigned int)(x * (float(UINT_MAX) + 1.f) / twoPi)) >> 9) | 0x3f800000;
1555 return (*(const float*)&i - 1.f) * twoPi;
1556 }
1557
1558 inline float fast_modp(unsigned int x) {
1559 constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
1560 const unsigned int i = (x >> 9) | 0x3f800000;
1561 return (*(const float*)&i - 1.f) * twoPi;
1562 }
1563
1564 inline double fast_mod2pi(double x) {
1565 constexpr double twoPi = (2.0 * 3.1415926535897932384626433832795);
1566 const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0) / twoPi)) >> 12ULL) | 0x7FF0000000000000ULL;
1567 return (*(const double*)&i - 1.0) * twoPi;
1568 }
1569
1570 template<int SIZE>
1571 inline double fast_modi(double x) {
1572 constexpr double size = double(SIZE);
1573 constexpr double sizeInv = 1.0 / double(SIZE);
1574 const unsigned long long i = (((unsigned long long)(x * (double(ULLONG_MAX) + 1.0) * sizeInv)) >> 12ULL) | 0x7FF0000000000000ULL;
1575 return (*(const double*)&i - 1.0) * size;
1576 }
1577
1578 /// Matrix processor
1579 //template<int X, int Y = X>
1580 struct Matrix {
1581 float v[4][4] = { 0 };
1582
1583 float* operator[](int col) { return v[col]; }
1584 const float* operator[](int col) const { return v[col]; }
1585
1586 float& operator()(int col, int row) { return v[col][row]; }
1587 float operator()(int col, int row) const { return v[col][row]; }
1588
1589 signals<4> operator<<(const signals<4>& in) const {
1590 return { v[0][0] * in[0] + v[0][1] * in[1] + v[0][2] * in[2] + v[0][3] * in[3],
1591 v[1][0] * in[0] + v[1][1] * in[1] + v[1][2] * in[2] + v[1][3] * in[3],
1592 v[2][0] * in[0] + v[2][1] * in[1] + v[2][2] * in[2] + v[2][3] * in[3],
1593 v[3][0] * in[0] + v[3][1] * in[1] + v[3][2] * in[2] + v[3][3] * in[3] };
1594 }
1595 };
1596
1597 inline signals<4> operator*(const signals<4>& in, const Matrix& m) {
1598 return { m[0][0] * in[0] + m[0][1] * in[1] + m[0][2] * in[2] + m[0][3] * in[3],
1599 m[1][0] * in[0] + m[1][1] * in[1] + m[1][2] * in[2] + m[1][3] * in[3],
1600 m[2][0] * in[0] + m[2][1] * in[1] + m[2][2] * in[2] + m[2][3] * in[3],
1601 m[3][0] * in[0] + m[3][1] * in[1] + m[3][2] * in[2] + m[3][3] * in[3] };
1602 }
1603
1604 inline signals<4> operator>>(const signals<4>& in, const Matrix& m) { return operator*(in, m); }
1605
1606 /// @cond
1607 template<typename TYPE, typename _TYPE>
1608 struct phase {
1609 static constexpr TYPE twoPi = TYPE(2.0 * 3.1415926535897932384626433832795);
1610
1611 // represent phase using full range of uint32
1612 // (integer math, no conditionals, free oversampling)
1613 _TYPE i = 0;
1614
1615 // convert float [0, 2pi) to uint32
1616 phase(TYPE phase = 0) {
1617 if constexpr (std::is_same<TYPE, double>()) {
1618 constexpr TYPE FUINTMAX = TYPE(ULLONG_MAX + 1.0) / twoPi; // (float)INT_MAX + 1.f;
1619 phase *= FUINTMAX;
1620 i = (_TYPE)phase;
1621 }
1622 else if constexpr (std::is_same<TYPE, float>()) {
1623 constexpr TYPE FUINTMAX = TYPE(UINT_MAX + 1.0) / twoPi; // (float)INT_MAX + 1.f;
1624 phase *= FUINTMAX;
1625 i = (_TYPE)phase;
1626 }
1627 }
1628
1629 // convert uint32 to float [0, 1)
1630 operator TYPE() const {
1631 const _TYPE phase = (i >> 12ULL) | 0x3FF0000000000000ULL;
1632 return (*(const TYPE*)&phase - TYPE(1.0)) * twoPi;
1633 }
1634
1635 //static void test() {
1636 // phase p;
1637 // assert((float)(p = 0.f).radians() == 0.f);
1638 // assert((float)(p = pi / 2).radians() == pi / 2);
1639 // assert((float)(p = pi).radians() == pi);
1640 // assert((float)(p = 3 * pi / 2).radians() == 3 * pi / 2);
1641 // assert((float)(p = 2 * pi).radians() == 0.f);
1642 //}
1643 };
1644 /// @endcond
1645
1646 /// Control parameter (phase)
1647 struct Phase : public param {
1648 //INFO("Phase", 0.f, 0.f, 1.0f)
1649 using param::param;
1650 /*Phase(const float p = 0.f) : param(p) { };*/
1651
1652 /// Wrap a finite phase to [0, cycle); invalid values become zero.
1653 static float wrap(float phase, float cycle = 2 * pi) {
1654 if (!std::isfinite(phase) || !std::isfinite(cycle) || cycle <= 0) return 0;
1655 const float turn = cycle;
1656 if (phase >= 0 && phase < turn) return phase;
1657 phase = std::fmod(phase, turn);
1658 return phase < 0 ? phase + turn : phase;
1659 }
1660
1661 /// Return this phase plus an optional offset, wrapped to one turn.
1662 float wrapped(float offset = 0) const { return wrap(value + offset); }
1663
1664 param& operator+=(float step) {
1665 value += step;
1666 if (value < 0 || value >= (2 * pi))
1667 value = wrap(value);
1668 return *this;
1669 }
1670
1672 value += step.amount;
1673 if (value < 0 || value >= step.size)
1674 value = wrap(value, step.size);
1675 return *this;
1676 }
1677
1678 Phase operator+(const increment& step) const {
1679 return wrap(value + step.amount, step.size);
1680 }
1681
1682 Phase operator%(float modulus) {
1683 return fast_mod(value, modulus);
1684 }
1685 };
1686
1687 struct Frequency;
1688
1689 /// Control parameter (pitch)
1690 struct Pitch : public param {
1691 //INFO("Pitch", 60.f, 0.f, 127.f)
1692 using param::param;
1693
1694 //Pitch(float p = 60.f) : param(p) { };
1695 //Pitch(int p) : param((float)p) { };
1696
1697 // convert note number to pitch class and octave (e.g. C#5)
1698 const char* text() const {
1699 THREAD_LOCAL static char buffer[32] = { 0 };
1700 const char* const notes[12] = { "C", "C#/Db", "D", "D#/Eb", "E", "F", "F#/Gb", "G", "G#/Ab", "A", "A#/Bb", "B" };
1701 snprintf(buffer, 32, "%s%d", notes[(int)value % 12], (int)value / 12);
1702 return buffer;
1703 }
1704
1706 Frequency = 440.f * power(2.f, (value - 69.f) / 12.f);
1707 return this;
1708 }
1709
1710 THREAD_LOCAL static Conversion Frequency;
1711
1712 template<typename TYPE> Pitch operator+(TYPE in) { return value + in; }
1713 template<typename TYPE> Pitch operator-(TYPE in) { return value - in; }
1714 template<typename TYPE> Pitch operator*(TYPE in) { return value * in; }
1715 template<typename TYPE> Pitch operator/(TYPE in) { return value / in; }
1716 };
1717
1718 THREAD_LOCAL inline Conversion Pitch::Frequency;
1719
1720 // inline THREAD_LOCAL Pitch::Convert Pitch::Frequency;
1721
1722 /// Control parameter (frequency)
1723 struct Frequency : public param {
1724 //INFO("Frequency", 1000.f, -FLT_MAX, FLT_MAX)
1725 using param::param;
1726 Frequency(float f = 1000.f) : param(f) {};
1727
1728 /// Convert a positive frequency in Hz to MIDI pitch.
1729 const Frequency* operator->() const {
1730 Pitch = 69.0 + 12.0 * std::log2(double(value) / 440.0);
1731 return this;
1732 }
1733
1734 THREAD_LOCAL static Conversion Pitch;
1735 };
1736
1737 THREAD_LOCAL inline Conversion Frequency::Pitch;
1738
1739 /// Frequency in hertz.
1740 using Hz = Frequency;
1741
1742 /// Sample rate constants
1743 static struct SampleRate {
1744 float f; ///< sample rate (float)
1745 int i; ///< sample rate (integer)
1746 double d; ///< sample rate (double)
1747 float inv; ///< 1 / sample rate (inverse)
1748 float w; ///< angular frequency (omega)
1749 float nyquist; ///< nyquist frequency (f / 2)
1750
1751 SampleRate(float sr) : f(sr), i(int(sr + 0.001f)), d((double)sr), inv(sr != 0 ? 1.f / sr : 0.f), w(2.0f * pi * inv), nyquist(sr / 2.f) {}
1752
1753 operator float() { return f; }
1754 } fs(44100); // sample rate
1755
1756 struct Amplitude;
1757
1758 /// Control parameter (idecibels)
1759 struct dB : public param {
1760 //INFO("dB", 0.f, -FLT_MAX, FLT_MAX)
1761 using param::param;
1762
1763 dB(float gain = 0.f) : param(gain) {};
1764
1765 const dB* operator->() const {
1766 Amplitude = power(10, value * 0.05f);
1767 return this;
1768 }
1769
1770 THREAD_LOCAL static Conversion Amplitude;
1772
1773 /// Control parameter (linear amplitude)
1774 struct Amplitude : public param {
1775 //INFO("Gain", 1.f, -FLT_MAX, FLT_MAX)
1776 using param::param;
1777
1778 Amplitude(float a = 1.f) : param(a) {};
1779 Amplitude(const dB& db) {
1780 value = power(10, db.value * 0.05f); // 10 ^ (db * 0.05f);
1781 };
1782
1783 //dB operator >> (dB) const {
1784 // return 20.f * log10f(value);
1785 //}
1786 //operator dB() const {
1787 // return 20.f * log10f(value);
1788 //}
1789
1790 const Amplitude* operator->() const {
1791 dB = 20.f * log10f(value);
1792 return this;
1793 }
1794
1795 THREAD_LOCAL static Conversion dB;
1796 };
1797
1798 THREAD_LOCAL inline Conversion dB::Amplitude;
1799 THREAD_LOCAL inline Conversion Amplitude::dB;
1800
1801 /// Control parameter (velocity)
1803
1804 /// UI control / parameter
1805 struct Control
1806 {
1807 enum Type
1808 {
1809 NONE, // no control (list terminator)
1810 ROTARY, // rotary knob (dial/pot)
1811 BUTTON, // push button (trigger)
1812 TOGGLE, // on/off switch (toggle)
1813 SLIDER, // linear slider (fader)
1814 MENU, // drop-down list (menu; up to 128 items)
1815 METER, // level meter (read-only: use setParameter() to set value)
1816 WHEEL, // MIDI control (Pitch Bend / Mod Wheel only)
1817 };
1818
1819 /// Control size
1820 struct Size
1821 {
1822 Size(int x = -1, int y = -1, int width = -1, int height = -1)
1823 : x(x), y(y), width(width), height(height) {
1824 }
1825
1826 int x;
1827 int y;
1830
1831 bool isAuto() const { return x == -1 && y == -1 && width == -1 && height == -1; }
1832 bool isRelative() const { return x != -1 && y != -1; }
1833 };
1834
1835 // Control Group
1836 struct Group { // 48 bytes
1837 Caption name; // 36 bytes (32+1 aligned)
1839 unsigned int start = 0; // 4 bytes
1840 unsigned int length = 0; // 4 bytes
1841
1842 bool contains(unsigned int c) const { return c >= start && c < (start + length); }
1843 };
1844
1846
1847 Caption name; // name for control label / saved parameter
1848 Type type = NONE; // control type (see above)
1849
1850 float min; // minimum control value (e.g. 0.0)
1851 float max; // maximum control value (e.g. 1.0)
1852 float initial; // initial value for control (e.g. 0.0)
1853
1854 Size size; // position (x,y) and size (height, width) of the control (use AUTO_SIZE for automatic layout)
1855 Options options; // text options for menus and group buttons
1856
1857 signal value; // current control value
1858 signal smoothed; // smoothed control value (filtered)
1859
1860 operator signal& () { return value; }
1861 operator signal () const { return value; }
1862 operator param() const { return value; }
1863 operator float() const { return value.value; }
1864
1865 static constexpr float smoothing = 0.999f;
1866 signal smooth() { return smoothed = smoothed * smoothing + (1.f - smoothing) * value; }
1867
1868 float range() const { return max - min; }
1869 float normalise(float value) const { return range() ? (value - min) / range() : std::clamp(value, 0.f, 1.f); }
1870 float normalised() const { return range() ? (value.value - min) / range() : std::clamp(value.value, 0.f, 1.f); }
1871 void setNormalised(float norm) { value.value = norm * range() + min; }
1872
1873 operator Control* () { return this; }
1874
1875 Control& set(float x) {
1876 value = std::clamp(x, min, max);
1877 return *this;
1878 }
1879
1880 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
1881 Control& operator=(TYPE input) { return set(static_cast<float>(input)); }
1882 template<typename TYPE, std::enable_if_t<!std::is_arithmetic_v<std::decay_t<TYPE>> &&
1883 !std::is_same_v<std::decay_t<TYPE>, Control> && std::is_convertible_v<TYPE&&, signal>, int> = 0>
1884 Control& operator=(TYPE&& input) {
1885 const signal sample = std::forward<TYPE>(input);
1886 return set(sample);
1887 }
1888
1889 Control& operator+=(float x) { value += x; return *this; }
1890 Control& operator*=(float x) { value *= x; return *this; }
1891 Control& operator-=(float x) { value -= x; return *this; }
1892 Control& operator/=(float x) { value /= x; return *this; }
1893
1894 //float operator+(float x) const { return value + x; }
1895 //float operator*(float x) const { return value * x; }
1896 //float operator-(float x) const { return value - x; }
1897 //float operator/(float x) const { return value / x; }
1898
1899 template<typename TYPE> signal operator+(const Control& x) const { return value + x.operator klang::signal(); }
1900 template<typename TYPE> signal operator*(const Control& x) const { return value * x.operator klang::signal(); }
1901 template<typename TYPE> signal operator-(const Control& x) const { return value - x.operator klang::signal(); }
1902 template<typename TYPE> signal operator/(const Control& x) const { return value / x.operator klang::signal(); }
1903
1904 template<typename TYPE> float operator+(TYPE& x) const { return value + (signal)x; }
1905 template<typename TYPE> float operator*(TYPE& x) const { return value * (signal)x; }
1906 template<typename TYPE> float operator-(TYPE& x) const { return value - (signal)x; }
1907 template<typename TYPE> float operator/(TYPE& x) const { return value / (signal)x; }
1908
1909 Control& operator<<(const signal& input) { return operator=(input); }
1910 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
1911 Control& operator<<(TYPE input) { return operator=(input); }
1912 };
1913
1914 const Control::Size Automatic = { -1, -1, -1, -1 };
1916
1917 /// Return a copy of the signal with each channel offset by x.
1918 template<int CHANNELS = 2> inline signals<CHANNELS> operator+(const Control& x, const signals<CHANNELS>& y) { return y + x.value; }
1919 /// Return a copy of the signal with each channel subtracted from x.
1920 template<int CHANNELS = 2> inline signals<CHANNELS> operator-(const Control& x, const signals<CHANNELS>& y) { return -y + x.value; }
1921 /// Return a copy of the signal with each channel scaled by x.
1922 template<int CHANNELS = 2> inline signals<CHANNELS> operator*(const Control& x, const signals<CHANNELS>& y) { return y * x.value; }
1923 /// Return a copy of the signal with each channel divided into x.
1924 template<int CHANNELS = 2> inline signals<CHANNELS> operator/(const Control& x, const signals<CHANNELS>& y) {
1925 signals<CHANNELS> s = { 0.f };
1926 for (int c = 0; c < CHANNELS; c++)
1927 s[c] = x.value / y[c];
1928 return std::move(s);
1929 }
1930
1931 /// Mapped UI control
1932 struct ControlMap {
1934
1935 ControlMap() : control(nullptr) {};
1936 ControlMap(Control& control) : control(&control) {};
1937
1938 operator Control& () { return *control; }
1939 operator signal& () { return control->value; }
1940 operator const signal& () const { return control->value; }
1941 operator param() const { return control->value; }
1942 operator float() const { return control->value; }
1943 signal smooth() { return control->smooth(); }
1944
1945 ControlMap& operator=(Control& mapped) { control = &mapped; return *this; }
1946 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
1947 ControlMap& operator=(TYPE input) { *control = input; return *this; }
1948 template<typename TYPE, std::enable_if_t<!std::is_arithmetic_v<std::decay_t<TYPE>> &&
1949 !std::is_same_v<std::decay_t<TYPE>, ControlMap> && !std::is_same_v<std::decay_t<TYPE>, Control> &&
1950 std::is_convertible_v<TYPE&&, signal>, int> = 0>
1951 ControlMap& operator=(TYPE&& input) { *control = std::forward<TYPE>(input); return *this; }
1952
1953 Control& operator<<(const signal& input) { return *control << input; }
1954 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
1955 Control& operator<<(TYPE input) { return *control << input; }
1956 };
1957
1958 IS_SIMPLE_TYPE(Control);
1959
1960 inline param::param(Control& in) : signal(in.value) {}
1961
1962 inline static Control Dial(const char* name, float min = 0.f, float max = 1.f, float initial = 0.f, Control::Size size = Automatic)
1963 {
1964 return { Caption::from(name), Control::ROTARY, min, max, initial, size, NoOptions, initial };
1965 }
1966
1967 inline static Control Button(const char* name, Control::Size size = Automatic)
1968 {
1969 return { Caption::from(name), Control::BUTTON, 0, 1, 0.f, size, NoOptions, 0.f };
1970 }
1971
1972 inline static Control Toggle(const char* name, bool initial = false, Control::Size size = Automatic)
1973 {
1974 return { Caption::from(name), Control::TOGGLE, 0, 1, initial ? 1.f : 0.f, size, NoOptions, initial ? 1.f : 0.f };
1975 }
1976
1977 inline static Control Slider(const char* name, float min = 0.f, float max = 1.f, float initial = 0.f, Control::Size size = Automatic)
1978 {
1979 return { Caption::from(name), Control::SLIDER, min, max, initial, size, NoOptions, initial };
1980 }
1981
1982 template<typename... Options>
1983 static Control Menu(const char* name, const Options... options)
1984 {
1985 Control::Options menu;
1986 const char* strings[] = { options... };
1987 int nbValues = sizeof...(options);
1988 for (int p = 0; p < nbValues; p++)
1989 menu.add(Caption::from(strings[p]));
1990 return { Caption::from(name), Control::MENU, 0, menu.size() - 1.f, 0, Automatic, menu, 0 };
1991 }
1992
1993 template<typename... Options>
1994 static Control Menu(const char* name, Control::Size size, const Options... options)
1995 {
1996 Control::Options menu;
1997 const char* strings[] = { options... };
1998 int nbValues = sizeof...(options);
1999 for (int p = 0; p < nbValues; p++)
2000 menu.add(Caption::from(strings[p]));
2001 return { Caption::from(name), Control::MENU, 0, menu.size() - 1.f, 0, size, menu, 0 };
2002 }
2003
2004 inline static Control Meter(const char* name, float min = 0.f, float max = 1.f, float initial = 0.f, Control::Size size = Automatic)
2005 {
2006 return { Caption::from(name), Control::METER, min, max, initial, size, NoOptions, initial };
2007 }
2008
2010 {
2011 return { { "PITCH\nBEND" }, Control::WHEEL, 0.f, 16384.f, 8192.f, size, NoOptions, 8192.f };
2012 }
2013
2015 {
2016 return { { "MOD\nWHEEL" }, Control::WHEEL, 0.f, 127.f, 0.f, size, NoOptions, 0.f };
2017 }
2018
2019 struct Controls;
2020
2021 /// Construction-time entry: temporary controls are owned; mutable lvalues are borrowed.
2025 Control* reference = nullptr;
2027
2028 ControlEntry(Control&& control) : owned(std::move(control)) {}
2029 ControlEntry(const Control& control) : owned(control) {}
2030 ControlEntry(Control& control) : kind(Reference), reference(&control) {}
2031 ControlEntry(Controls& controls) : kind(Collection), collection(&controls) {}
2033 };
2034
2035 /// Optional presentation grouping, independent of value ownership.
2036 struct Group {
2037 const char* name;
2039 std::vector<ControlEntry> controls;
2040
2041 Group(const char* name, std::initializer_list<ControlEntry> controls)
2043 Group(const char* name, Control::Size size, std::initializer_list<ControlEntry> controls)
2045 // Typed legacy initializer_list<Control> variables remain value copies;
2046 // inline braced entries keep the new lvalue/rvalue distinction.
2047 template<class List, std::enable_if_t<std::is_same_v<std::decay_t<List>, std::initializer_list<Control>>, int> = 0>
2048 Group(const char* name, List&& list) : name(name), size(Automatic) {
2049 for (const auto& control : list) controls.emplace_back(control);
2050 }
2051 template<class List, std::enable_if_t<std::is_same_v<std::decay_t<List>, std::initializer_list<Control>>, int> = 0>
2052 Group(const char* name, Control::Size size, List&& list) : name(name), size(size) {
2053 for (const auto& control : list) controls.emplace_back(control);
2054 }
2055 template<class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...), int> = 0>
2056 Group(const char* name, Entries&&... entries)
2057 : name(name), size(Automatic), controls { ControlEntry(std::forward<Entries>(entries))... } {}
2058 template<class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...), int> = 0>
2059 Group(Entries&&... entries)
2060 : name(""), size(Automatic), controls { ControlEntry(std::forward<Entries>(entries))... } {}
2061 template<class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...), int> = 0>
2062 Group(const char* name, Control::Size size, Entries&&... entries)
2063 : name(name), size(size), controls { ControlEntry(std::forward<Entries>(entries))... } {}
2064 template<class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...), int> = 0>
2065 Group(Control::Size size, Entries&&... entries)
2066 : name(""), size(size), controls { ControlEntry(std::forward<Entries>(entries))... } {}
2067 };
2068
2069 struct Preset;
2070
2071 /** An owned control collection with optional borrowed value entries.
2072 * Mutable Control and Controls lvalues in a declaration borrow their values;
2073 * temporary factory results are owned. Referenced schemas are fixed while
2074 * borrowed. An individual borrowed Control must outlive this collection.
2075 * DSP code normally continues reading the child's original Controls object.
2076 * The legacy count/items/value/groups prefix and Control layout are retained;
2077 * the binding sidecar is internal, never the MiniPlugin host ABI record.
2078 */
2079 struct Controls : Array<Control, 128> {
2080 float value[128] = { 0 };
2082
2083 private:
2084 [[noreturn]] static void invalid(const char* message) {
2085#if defined(__cpp_exceptions) || defined(_CPPUNWIND)
2086 throw std::logic_error(message);
2087#else
2088 (void)message;
2089 std::abort();
2090#endif
2091 }
2092 struct Construction { std::uint64_t ordinal = 0; };
2093 static const std::shared_ptr<Construction>& construction() {
2094 static THREAD_LOCAL auto stream = std::make_shared<Construction>();
2095 return stream;
2096 }
2097 struct Lifetime {
2098 bool alive = true;
2099 std::uint64_t birth;
2100 std::shared_ptr<Construction> creator;
2101 std::vector<std::shared_ptr<Lifetime>> dependencies;
2102 explicit Lifetime(const std::shared_ptr<Construction>& stream) : birth(++stream->ordinal), creator(stream) {}
2103 };
2104 struct Alias {
2105 Control* target = nullptr;
2106 std::shared_ptr<Lifetime> lifetime;
2107 };
2108 struct Scope {
2109 std::string name;
2110 unsigned int start = 0, length = 0;
2111 };
2112 Alias aliases[128];
2113 bool borrowed = false;
2114 bool input[128] {};
2115 unsigned int scopeIndex[128] {};
2116 Scope scopes[129];
2117 unsigned int scopeCount = 1;
2118 std::string sourceKeys[128];
2119 mutable std::string keys[128];
2120 mutable bool metadataDirty = true;
2121 mutable std::shared_ptr<Lifetime> lifetime;
2122
2123 struct Registry {
2124 struct Entry { Controls* owner; Control* first; const Construction* creator; };
2125 std::mutex mutex;
2126 std::vector<Entry> collections;
2127 };
2128 static Registry& registry() { static Registry value; return value; }
2129 struct Origin { Alias alias; Controls* owner = nullptr; unsigned int index = 0; };
2130 static Origin capture(Control& control, bool& isInput) {
2131 auto& owners = registry();
2132 const std::lock_guard<std::mutex> lock(owners.mutex);
2133 for (const auto& entry : owners.collections) {
2134 if (entry.creator != construction().get()) {
2135 // Inspect only immutable registry addresses, never another
2136 // construction stream's changing count or metadata.
2137 const auto address = reinterpret_cast<std::uintptr_t>(&control);
2138 const auto first = reinterpret_cast<std::uintptr_t>(entry.first);
2139 if (address >= first && address - first < sizeof(Control) * 128 &&
2140 (address - first) % sizeof(Control) == 0)
2141 invalid("An individual Control reference cannot cross construction threads");
2142 continue;
2143 }
2144 auto* owner = entry.owner;
2145 for (unsigned int i = 0; i < owner->count; ++i)
2146 if (&owner->items[i] == &control) {
2147 isInput = owner->isInput(i);
2148 return { { &control, owner->token() }, owner, i };
2149 }
2150 }
2151 // Standalone Control lvalues use ordinary C++ reference lifetime.
2152 return { { &control, {} }, nullptr, 0 };
2153 }
2154
2155 void mutableSchema() const {
2156 if (lifetime && lifetime.use_count() > 1)
2157 invalid("Cannot change a Controls schema while it is referenced");
2158 }
2159 std::shared_ptr<Lifetime> token() const {
2160 return lifetime;
2161 }
2162 static bool live(const std::shared_ptr<Lifetime>& state) {
2163 if (!state) return true;
2164 if (!state->alive) return false;
2165 for (const auto& dependency : state->dependencies)
2166 if (!live(dependency)) return false;
2167 return true;
2168 }
2169 static bool dependsOn(const std::shared_ptr<Lifetime>& state, const Lifetime* target) {
2170 if (state.get() == target) return true;
2171 for (const auto& dependency : state->dependencies)
2172 if (dependsOn(dependency, target)) return true;
2173 return false;
2174 }
2175 void pin(const std::shared_ptr<Lifetime>& source) {
2176 if (!source) return;
2177 if (dependsOn(source, lifetime.get())) invalid("Cyclic Controls schema reference");
2178 for (const auto& dependency : lifetime->dependencies)
2179 if (dependency == source) return;
2180 lifetime->dependencies.push_back(source);
2181 }
2182 std::string childIdentity(const Controls& child, char kind) const {
2183 if (child.lifetime->creator != lifetime->creator || child.lifetime->birth <= lifetime->birth)
2184 return {};
2185 return std::string(1, kind) + std::to_string(child.lifetime->birth - lifetime->birth);
2186 }
2187 void room(unsigned int entries) const {
2188 if (entries > 128 - count) invalid("Controls capacity exceeded");
2189 }
2190 bool owns(const Control* control) const {
2191 for (const auto& item : items) if (&item == control) return true;
2192 return false;
2193 }
2194 unsigned int newScope(unsigned int length, const std::string& identity) {
2195 if (scopeCount == 129) invalid("Controls reference capacity exceeded");
2196 const auto index = scopeCount++;
2197 const std::string base = identity.empty() ? "external:" + std::to_string(index) : identity;
2198 std::string name = base;
2199 unsigned int duplicate = 0;
2200 bool exists = true;
2201 while (exists) {
2202 exists = false;
2203 for (unsigned int previous = 1; previous < index; ++previous)
2204 if (scopes[previous].name == name) { exists = true; break; }
2205 if (exists) name = base + "@" + std::to_string(++duplicate);
2206 }
2207 scopes[index] = { name, count, length };
2208 return index;
2209 }
2210 void appendOwned(const Control& control) {
2211 room(1);
2212 items[count] = control;
2213 aliases[count] = {};
2214 input[count] = false;
2215 scopeIndex[count] = 0;
2216 sourceKeys[count].clear();
2217 ++count;
2218 metadataDirty = true;
2219 }
2220 void appendReference(Control& control) {
2221 room(1);
2222 if (owns(&control)) invalid("A Controls collection cannot reference its own storage");
2223 Origin origin = capture(control, input[count]);
2224 std::string identity;
2225 if (origin.owner) {
2226 identity = childIdentity(*origin.owner, 'v');
2227 const char* localKey = origin.owner->key(origin.index);
2228 if (!identity.empty() && localKey[0]) identity += std::string("/") + localKey;
2229 else identity.clear();
2230 } else {
2231 identity = std::string("control/") + control.name.c_str();
2232 // Distinct standalone controls with identical names provide no
2233 // unambiguous construction identity. Do not cross-restore them.
2234 bool ambiguous = false;
2235 for (unsigned int i = 0; i < count; ++i)
2236 if (aliases[i].target && !aliases[i].lifetime &&
2237 std::strcmp(aliases[i].target->name.c_str(), control.name.c_str()) == 0 &&
2238 aliases[i].target != &control) {
2239 scopes[scopeIndex[i]].name = "external:" + std::to_string(scopeIndex[i]);
2240 ambiguous = true;
2241 }
2242 if (ambiguous) identity.clear();
2243 }
2244 const auto scope = newScope(1, identity);
2245 pin(origin.alias.lifetime);
2246 items[count] = control; // Dense legacy metadata snapshot, not the value authority.
2247 aliases[count] = std::move(origin.alias);
2248 scopeIndex[count] = scope;
2249 sourceKeys[count] = scopes[scope].name;
2250 ++count;
2251 borrowed = metadataDirty = true;
2252 }
2253 void appendCollection(Controls& controls) {
2254 if (&controls == this) invalid("A Controls collection cannot reference itself");
2255 room(controls.count);
2256 const auto scope = newScope(controls.count, childIdentity(controls, 'c'));
2257 pin(controls.token());
2258 for (unsigned int i = 0; i < controls.count; ++i) {
2259 Control& target = controls[i];
2260 if (owns(&target)) invalid("Cyclic Controls reference");
2261 items[count] = target;
2262 aliases[count].target = &target;
2263 aliases[count].lifetime = controls.token();
2264 input[count] = controls.isInput(i);
2265 scopeIndex[count] = scope;
2266 const char* localKey = controls.key(i);
2267 sourceKeys[count] = localKey[0] ? scopes[scope].name + "/" + localKey : "";
2268 ++count;
2269 }
2270 borrowed = metadataDirty = true;
2271 }
2272 void append(const ControlEntry& entry) {
2273 if (entry.kind == ControlEntry::Collection) appendCollection(*entry.collection);
2274 else if (entry.kind == ControlEntry::Reference) appendReference(*entry.reference);
2275 else appendOwned(entry.owned);
2276 }
2277 void refreshMetadata() const {
2278 if (!metadataDirty) return;
2279 for (unsigned int i = 0; i < count; ++i) {
2280 if (scopeIndex[i] && (scopes[scopeIndex[i]].name.compare(0, 9, "external:") == 0 || sourceKeys[i].empty())) {
2281 keys[i].clear();
2282 continue;
2283 }
2284 if (!sourceKeys[i].empty()) {
2285 keys[i] = sourceKeys[i];
2286 continue;
2287 }
2288 std::string path = "root";
2289 for (unsigned int g = 0; g < groups.count; ++g)
2290 if (groups[g].contains(i)) path += std::string("/") + groups[g].name.c_str();
2291 path += std::string("/") + items[i].name.c_str();
2292 unsigned int duplicate = 0;
2293 for (unsigned int j = 0; j < i; ++j)
2294 if (!scopeIndex[j] && std::string(items[j].name.c_str()) == items[i].name.c_str()) {
2295 bool sameGroups = true;
2296 for (unsigned int g = 0; g < groups.count; ++g)
2297 sameGroups = sameGroups && groups[g].contains(j) == groups[g].contains(i);
2298 if (sameGroups) ++duplicate;
2299 }
2300 keys[i] = path + "/" + std::to_string(duplicate);
2301 }
2302 bool collision[128] {};
2303 for (unsigned int i = 0; i < count; ++i)
2304 for (unsigned int j = i + 1; j < count; ++j)
2305 if (!keys[i].empty() && keys[i] == keys[j]) collision[i] = collision[j] = true;
2306 for (unsigned int i = 0; i < count; ++i) if (collision[i]) keys[i].clear();
2307 metadataDirty = false;
2308 }
2309
2310 public:
2312 lifetime = std::make_shared<Lifetime>(construction());
2313 scopes[0].name = "root";
2314 auto& owners = registry();
2315 const std::lock_guard<std::mutex> lock(owners.mutex);
2316 owners.collections.push_back({ this, items, lifetime->creator.get() });
2317 }
2318 Controls(const Controls& other) : Controls() { *this = other; }
2319 Controls(Controls&& other) : Controls(static_cast<const Controls&>(other)) {}
2321 if (lifetime) lifetime->alive = false;
2322 auto& owners = registry();
2323 const std::lock_guard<std::mutex> lock(owners.mutex);
2324 owners.collections.erase(std::remove_if(owners.collections.begin(), owners.collections.end(),
2325 [this](const Registry::Entry& entry) { return entry.owner == this; }), owners.collections.end());
2326 }
2327
2328 /// Resolve one actual control; ordinary owned collections take the direct path.
2329 Control& operator[](int index) {
2330 if (!borrowed || !aliases[index].target) return items[index];
2331 auto& alias = aliases[index];
2332 if (!live(alias.lifetime))
2333 invalid("Referenced Controls owner has been destroyed");
2334 return *alias.target;
2335 }
2336 const Control& operator[](int index) const {
2337 if (!borrowed || !aliases[index].target) return items[index];
2338 const auto& alias = aliases[index];
2339 if (!live(alias.lifetime))
2340 invalid("Referenced Controls owner has been destroyed");
2341 return *alias.target;
2342 }
2343 void clear() {
2344 mutableSchema();
2345 count = 0;
2346 groups.clear();
2347 for (auto& alias : aliases) alias = {};
2348 lifetime->dependencies.clear();
2349 for (auto& flag : input) flag = false;
2350 for (auto& index : scopeIndex) index = 0;
2351 borrowed = false;
2352 scopeCount = 1;
2353 metadataDirty = true;
2354 }
2355 // A normal copy-assignment overload also captures `controls = { child }`
2356 // before initializer-list conversion. Suppress that implicit overload;
2357 // ordinary lvalue/rvalue copying still uses this constrained template.
2358 Controls& operator=(const Controls&) && = delete;
2359 template<class Source, std::enable_if_t<std::is_same_v<std::decay_t<Source>, Controls>, int> = 0>
2360 Controls& operator=(Source&& source) & {
2361 const Controls& other = source;
2362 if (this == &other) return *this;
2363 clear();
2364 for (unsigned int i = 0; i < other.count; ++i) appendOwned(other[i]);
2365 groups = other.groups;
2366 for (unsigned int i = 0; i < count; ++i) input[i] = other.isInput(i);
2367 return *this;
2368 }
2369 Controls& operator=(std::initializer_list<klang::Group> declaration) {
2370 mutableSchema();
2371 unsigned int entries = 0, headings = 0;
2372 for (const auto& group : declaration) {
2373 for (const auto& entry : group.controls) {
2374 if (entry.kind == ControlEntry::Collection) {
2375 if (entry.collection == this) invalid("A Controls collection cannot reference itself");
2376 for (unsigned int i = 0; i < entry.collection->count; ++i)
2377 if (owns(&(*entry.collection)[i])) invalid("Cyclic Controls reference");
2378 entries += entry.collection->count;
2379 } else {
2380 if (entry.kind == ControlEntry::Reference && owns(entry.reference))
2381 invalid("A Controls collection cannot reference its own storage");
2382 ++entries;
2383 }
2384 }
2385 if (group.name && group.name[0]) ++headings;
2386 }
2387 if (entries > 128 || headings > 10) invalid("Controls declaration capacity exceeded");
2388 clear();
2389 for (const auto& group : declaration) {
2390 const auto start = count;
2391 for (const auto& entry : group.controls) append(entry);
2392 if (group.name && group.name[0]) groups.add({ Caption::from(group.name), group.size, start, count - start });
2393 }
2394 metadataDirty = true;
2395 return *this;
2396 }
2397 void operator+=(Control& control) { mutableSchema(); appendReference(control); }
2398 void operator+=(const Control& control) { mutableSchema(); appendOwned(control); }
2399 void operator+=(Control&& control) { mutableSchema(); appendOwned(control); }
2400 void operator+=(Controls& controls) { mutableSchema(); appendCollection(controls); }
2401 void add(const Control& control) { mutableSchema(); appendOwned(control); }
2403 mutableSchema();
2404 if (count == 128) return nullptr;
2405 appendOwned(Control{});
2406 return &items[count - 1];
2407 }
2408 void add(const char* name, Control::Type type = Control::ROTARY, float min = 0.f,
2409 float max = 1.f, float initial = 0.f, Control::Size size = Automatic) {
2410 mutableSchema();
2411 Control control {};
2412 control.name = name; control.type = type;
2413 control.min = min; control.max = max; control.initial = initial;
2414 control.size = size; control.value = initial;
2415 appendOwned(control);
2416 }
2417 void add(const char* name, Control::Type type, std::initializer_list<const char*> options,
2419 mutableSchema();
2420 room(1);
2421 if (options.size() > 128) invalid("Control options capacity exceeded");
2422 Control control {};
2423 control.name = name; control.type = type;
2424 control.min = 0; control.max = static_cast<float>(options.size()) - 1;
2425 control.initial = 0; control.value = 0; control.size = size;
2426 for (const char* option : options) control.options.add(Caption::from(option));
2427 appendOwned(control);
2428 }
2429 bool inGroup(int index) const {
2430 for (unsigned int group = 0; group < groups.count; ++group)
2431 if (groups[group].contains(index)) return true;
2432 return false;
2433 }
2434 const Control::Group* getGroup(int index) const {
2435 for (unsigned int group = 0; group < groups.count; ++group)
2436 if (groups[group].contains(index)) return &groups[group];
2437 return nullptr;
2438 }
2439 bool changed() {
2440 bool result = false;
2441 for (unsigned int i = 0; i < count; ++i) {
2442 const float current = (*this)[i];
2443 if (current != value[i]) { value[i] = current; result = true; }
2444 }
2445 return result;
2446 }
2447 float max() const {
2448 float result = 0;
2449 for (unsigned int i = 0; i < count; ++i) result = std::max(result, std::abs(float((*this)[i])));
2450 return result;
2451 }
2452 float mean() const {
2453 float result = 0;
2454 for (unsigned int i = 0; i < count; ++i) result += std::abs(float((*this)[i]));
2455 return result / count;
2456 }
2457 float rms() const {
2458 float result = 0;
2459 for (unsigned int i = 0; i < count; ++i) { const float sample = (*this)[i]; result += sample * sample; }
2460 return std::sqrt(result / count);
2461 }
2462 void normalise(float target = 1, int mode = Peak) {
2463 if (!count) return;
2464 const float current = mode == Peak ? max() : mode == Mean ? mean() : rms();
2465 const float scale = current == 0 ? 0 : target / current;
2466 for (unsigned int i = 0; i < count; ++i) {
2467 bool duplicate = false;
2468 if (borrowed) for (unsigned int previous = 0; previous < i; ++previous)
2469 duplicate = duplicate || &(*this)[previous] == &(*this)[i];
2470 if (!duplicate) (*this)[i] *= scale;
2471 }
2472 }
2473 void group(const char* name, unsigned int start, unsigned int length, Control::Size size = Automatic) {
2474 mutableSchema();
2475 if (groups.count == 10 || start > count || length > count - start)
2476 invalid("Invalid Controls group");
2477 groups.add({ Caption::from(name), size, start, length });
2478 metadataDirty = true;
2479 }
2480 template<class... Args> void set(Args... args) {
2481 static_assert((std::is_arithmetic_v<Args> && ...), "Controls::set() accepts scalar arguments");
2482 const float values[] = { static_cast<float>(args)... };
2483 const unsigned int n = std::min(count, static_cast<unsigned int>(sizeof...(Args)));
2484 for (unsigned int i = 0; i < n; ++i) (*this)[i].set(values[i]);
2485 }
2486 void set(const Preset& preset);
2487 Controls& operator=(const Preset& preset);
2488
2489 /// Stable declaration key for metadata/retention; never a pointer or a default value.
2490 const char* key(int index) const { refreshMetadata(); return keys[index].c_str(); }
2491 const char* scope(int index) const { return scopes[scopeIndex[index]].name.c_str(); }
2492 int scopeStart(int index) const { return scopeIndex[index] ? static_cast<int>(scopes[scopeIndex[index]].start) : 0; }
2493 int scopeSize(int index) const { return scopeIndex[index] ? static_cast<int>(scopes[scopeIndex[index]].length) : static_cast<int>(count); }
2494 bool isInput(int index) const { return input[index]; }
2495 void markInput(int index, bool state = true) {
2496 if (index < 0 || index >= static_cast<int>(count)) return;
2497 mutableSchema();
2498 const Control* target = &(*this)[index];
2499 for (unsigned int i = 0; i < count; ++i)
2500 if (&(*this)[i] == target) input[i] = state;
2501 }
2502 bool hasReferences() const { return borrowed; }
2503
2504 /// Preserve original identities when a proxy reconstructs a flat schema.
2505 void setMetadata(int index, const char* identity, const char* block, int start, int length, bool gameInput) {
2506 mutableSchema();
2507 if (index < 0 || index >= static_cast<int>(count) || !identity ||
2508 !block || !block[0] || start < 0 || length <= 0 || start > index ||
2509 index >= start + length || start + length > static_cast<int>(count))
2510 invalid("Invalid Controls metadata");
2511 unsigned int scope = 0;
2512 std::string scopeName = !identity[0] && std::strcmp(block, "root") == 0
2513 ? "external:metadata" + std::to_string(index) : block;
2514 if (scopeName != "root") {
2515 for (scope = 1; scope < scopeCount && scopes[scope].name != scopeName; ++scope) {}
2516 if (scope == scopeCount) {
2517 if (scopeCount == 129) invalid("Controls scope capacity exceeded");
2518 ++scopeCount;
2519 }
2520 scopes[scope] = { scopeName, static_cast<unsigned int>(start), static_cast<unsigned int>(length) };
2521 }
2522 scopeIndex[index] = scope;
2523 sourceKeys[index] = identity;
2524 markInput(index, gameInput);
2525 metadataDirty = true;
2526 }
2527
2528 /// Reconstruct an earlier canonical slot when a proxy flattens aliases.
2529 void bindAlias(int index, int canonicalIndex) {
2530 mutableSchema();
2531 if (index <= 0 || index >= static_cast<int>(count) || canonicalIndex < 0 || canonicalIndex >= index)
2532 invalid("Invalid proxy control alias");
2533 Control* target = &(*this)[canonicalIndex];
2534 const auto state = aliases[canonicalIndex].lifetime;
2535 items[index] = *target;
2536 aliases[index] = { target, state };
2537 pin(state); // Null for this collection's own canonical storage.
2538 borrowed = true;
2539 markInput(canonicalIndex, input[canonicalIndex]);
2540 metadataDirty = true;
2541 }
2542
2543 /// Refresh only the legacy contiguous metadata/value snapshot before raw ABI export.
2545 for (unsigned int i = 0; i < count; ++i)
2546 if (aliases[i].target) items[i] = (*this)[i];
2547 return items;
2548 }
2549 const Control* snapshot() const { return const_cast<Controls*>(this)->snapshot(); }
2550 };
2551
2552
2554
2555 /// Factory preset
2556 struct Preset {
2557 Caption name = { 0 };
2559 };
2560
2561 inline void Controls::set(const Preset& preset) {
2562 for (unsigned int p = 0; p < preset.values.count && p < count; p++)
2563 if (!isInput(p)) operator[](p).set(preset.values[p]);
2564 }
2565
2566 inline Controls& Controls::operator=(const Preset& preset) {
2567 set(preset);
2568 return *this;
2569 }
2570
2571 //template<typename... Settings>
2572 //static Program Preset(const char* name, const Settings... settings)
2573 //{ Values values;
2574 // float preset[] = { (float)settings... };
2575 // int nbSettings = sizeof...(settings);
2576 // for(int s=0; s<nbSettings; s++)
2577 // values.add(preset[s]);
2578 // return { Caption::from(name), values };
2579 //}
2580
2581 /// Factory presets
2582 struct Presets : Array<Preset, 128> {
2583 void operator += (const Preset& preset) {
2584 items[count++] = preset;
2585 }
2586
2587 void operator= (const Presets& presets) {
2588 for (int p = 0; p < 128 && presets[p].name[0]; p++)
2589 operator+=(presets[p]);
2590 }
2591
2592 void operator=(std::initializer_list<Preset> presets) {
2593 for (auto preset : presets)
2594 operator+=(preset);
2595 }
2596
2597 template<typename... Values>
2598 void add(const char* name, const Values... values) {
2599 items[count].name = name;
2600
2601 const float preset[] = { values... };
2602 int nbValues = sizeof...(values);
2603 for (int p = 0; p < nbValues; p++)
2604 items[count].values.add(preset[p]);
2605 count++;
2606 }
2607 };
2608
2609 /// Audio buffer (mono)
2610 class buffer {
2611 protected:
2612 constexpr unsigned int capacity(unsigned int n) {
2613 // Decrement n to handle the case where n is already a power of 2
2614 n--;
2615 n |= n >> 1;
2616 n |= n >> 2;
2617 n |= n >> 4;
2618 n |= n >> 8;
2619 n |= n >> 16;
2620 // Increment n to get the next power of 2
2621 n++;
2622 return n;
2623 }
2624 const unsigned int mask = 0xFFFFFFFF;
2625 const bool owned = false;
2626 float* samples;
2629 public:
2631 const int size;
2632
2633 buffer(float* buffer, int size)
2634 : owned(false), samples(buffer), size(size) {
2635 rewind();
2636 }
2637
2638 buffer(float* buffer, int size, float initial)
2639 : owned(false), samples(buffer), size(size) {
2640 rewind();
2641 set(initial);
2642 }
2643
2644 buffer(int size = 1, float initial = 0)
2645 : mask(capacity(size) - 1), owned(true), samples(new float[capacity(size)]), size(size) {
2646 rewind();
2647 set(initial);
2648 }
2649
2650 buffer(const buffer& buf) : mask(buf.mask), owned(false), samples(buf.samples), size(buf.size) {
2651 rewind();
2652 }
2653
2654 virtual ~buffer() {
2655 if (owned)
2656 delete[] samples;
2657 }
2658
2659 void attach(const buffer& buffer, int size = 0) {
2661 rewind();
2662 end = (signal*)&samples[size];
2663 }
2664
2665 void rewind(int offset = 0) {
2666#ifdef _MSC_VER
2667 _controlfp_s(nullptr, _DN_FLUSH, _MCW_DN);
2668#endif
2669 ptr = (signal*)&samples[offset];
2670 end = (signal*)&samples[size];
2671 }
2672
2673 void clear() {
2674 memset(samples, 0, sizeof(float) * size);
2675 }
2676
2677 void clear(int size) {
2678 memset(samples, 0, sizeof(float) * (size < buffer::size ? size : buffer::size));
2679 }
2680
2681 int offset() const {
2682 return int((signal*)&samples[0] - ptr);
2683 }
2684
2685 void set(float value = 0) {
2686 if (value == 0)
2687 clear();
2688 else for (int s = 0; s < size; s++)
2689 samples[s] = value;
2690 }
2691
2693 return *(signal*)&samples[offset & mask]; // owned array can't write beyond allocation
2694 }
2695
2696 signal& operator[](unsigned int offset) {
2697 return *(signal*)&samples[offset & mask]; // owned array can't write beyond allocation
2698 }
2699
2701 return ((const buffer*)this)->operator[](offset);
2702 }
2703
2704 signal operator[](float offset) const {
2705 const float f = floorf(offset);
2706 const float frac = offset - f;
2707
2708 const int i = (int)offset;
2709 const int j = (i == (size - 1)) ? 0 : (i + 1);
2710
2711 return samples[i] * (1.f - frac) + samples[j] * frac;
2712 }
2713
2714 const signal& operator[](int index) const {
2715 return *(const signal*)&samples[index];
2716 }
2717
2718 operator signal& () {
2719 return *ptr;
2720 }
2721
2722 operator const signal& () const {
2723 return *ptr;
2724 }
2725
2726 explicit operator double() const {
2727 return *ptr;
2728 }
2729
2730 bool finished() const {
2731 return ptr == end;
2732 }
2733
2735 return *ptr++;
2736 }
2737
2739 return *ptr = in;
2740 }
2741
2743 *ptr += in;
2744 return *this;
2745 }
2746
2748 *ptr *= in;
2749 return *this;
2750 }
2751
2753 memcpy(samples, in.samples, min(size, in.size) * sizeof(float));
2754 return *this;
2755 }
2756
2758 *ptr = in;
2759 return *this;
2760 }
2761
2762 float* data() { return samples; }
2763 const float* data() const { return samples; }
2764
2765 float level() const {
2766 float level = 0.f;
2767 for (int s = 0; s < size; s++)
2768 level += FABS(samples[s]);
2769 return level / size;
2770 }
2771
2772 float rms() const {
2773 float rms = 0.f;
2774 for (int s = 0; s < size; s++)
2775 rms += samples[s] * samples[s];
2776 return sqrtf(rms / size);
2777 }
2778 };
2779
2780 namespace variable {
2781 class buffer {
2782 std::unique_ptr<klang::buffer> ptr;
2783 public:
2784 int size = 0;
2785
2786 buffer(int size = 1, float initial = 0.f) : size(size), ptr(new klang::buffer(size, initial)) {}
2788 //buffer(klang::buffer* buffer) : size(buffer->size), ptr(new klang::buffer(buffer->data(), buffer->size)) { };
2789 virtual ~buffer() { ptr.reset(); };
2790
2791 operator klang::buffer& () { return *ptr; }
2792 operator const klang::buffer& () const { return *ptr; }
2793 void resize(int size) {
2794 if (size != ptr->size)
2795 ptr = std::unique_ptr<klang::buffer>(new klang::buffer(buffer::size = size));
2796 }
2797
2798 void rewind(int offset = 0) { ptr->rewind(offset); }
2799 void clear() { ptr->clear(); }
2800 void clear(int size) { ptr->clear(size); }
2801 int offset() const { return ptr->offset(); }
2802 void set(float value = 0) { ptr->set(value); }
2803 signal& operator[](int offset) { return ptr->operator[](offset); }
2804 signal& operator[](unsigned int offset) { return ptr->operator[](offset); }
2805 signal operator[](float offset) { return ptr->operator[](offset); }
2806 signal operator[](float offset) const { return ptr->operator[](offset); }
2807 const signal& operator[](int index) const { return ptr->operator[](index); }
2808 operator signal& () { return ptr->operator signal & (); }
2809 operator const signal& () const { return ptr->operator const signal & (); }
2810 explicit operator double() const { return ptr->operator double(); }
2811 bool finished() const { return ptr->finished(); }
2812 signal& operator++(int) { return ptr->operator++(1); }
2813 //signal& operator=(const signal& in) { return ptr->operator=(in); }
2814 //signal& operator+=(const signal& in) { return ptr->operator+=(in); }
2815 //signal& operator*=(const signal& in) { return ptr->operator*=(in); }
2816
2818 resize(in.size); *ptr = in; return *this;
2819 }
2820
2822 resize(in.size); *ptr = *in.ptr; return *this;
2823 }
2824
2825 float* data() { return ptr->data(); }
2826 const float* data() const { return ptr->data(); }
2827
2828 float level() const { return ptr->level(); }
2829 float rms() const { return ptr->rms(); }
2830 };
2831 }
2832
2833 namespace interleaved {
2834 /** Interleaved frames: L,R,L,R for two channels. Sizes and offsets are frames.
2835 * A float-pointer constructor borrows host storage; the size constructor owns
2836 * storage rounded up to a power of two. Copies borrow the same storage and
2837 * rewind; the original owner must outlive them. Assignment copies audio.
2838 * Owned integer indexing wraps at allocated frame capacity, like mono buffer.
2839 * Example: interleaved::buffer<2> audio(hostSamples, frameCount);
2840 */
2841 template<int CHANNELS = 2>
2842 class buffer {
2843 public:
2845 static_assert(CHANNELS > 0);
2846 static_assert(std::is_trivially_copyable_v<signal>);
2847 static_assert(std::is_standard_layout_v<signal>);
2848 static_assert(sizeof(signal) == sizeof(float) * CHANNELS);
2849 static_assert(alignof(signal) == alignof(float));
2850 private:
2851 static unsigned int capacity(unsigned int size) {
2852 if (size == 0) return 1;
2853 --size;
2854 size |= size >> 1;
2855 size |= size >> 2;
2856 size |= size >> 4;
2857 size |= size >> 8;
2858 size |= size >> 16;
2859 return size + 1;
2860 }
2861 const unsigned int mask = 0xFFFFFFFF;
2862 const bool owned = false;
2863 float* samples;
2864 signal* ptr;
2865 signal* end;
2866 public:
2867 const int size;
2868 buffer(float* samples, int size) : samples(samples), size(size) {
2869 assert(size >= 0 && (samples || size == 0));
2870 rewind();
2871 }
2872 buffer(float* samples, int size, float initial) : buffer(samples, size) {
2873 set(initial);
2874 }
2875 buffer(int size = 1, float initial = 0)
2876 : mask(capacity(size) - 1), owned(true),
2877 samples(reinterpret_cast<float*>(new signal[capacity(size)])), size(size) {
2878 assert(size >= 0);
2879 rewind();
2880 set(initial);
2881 }
2882 buffer(const buffer& other)
2883 : mask(other.mask), samples(other.samples), size(other.size) { rewind(); }
2885 if (owned) delete[] reinterpret_cast<signal*>(samples);
2886 }
2887 void rewind(int offset = 0) {
2888 assert(offset >= 0 && offset <= size);
2889 ptr = samples ? reinterpret_cast<signal*>(samples) + offset : nullptr;
2890 end = samples ? reinterpret_cast<signal*>(samples) + size : nullptr;
2891 }
2892 int offset() const { return samples ? int(ptr - reinterpret_cast<signal*>(samples)) : 0; }
2893 void clear() { clear(size); }
2894 void clear(int count) {
2895 assert(count >= 0);
2896 if (count > 0 && size > 0) std::memset(samples, 0, sizeof(signal) * std::min(count, size));
2897 }
2898 void set(float value = 0) {
2899 if (value == 0) clear();
2900 else for (size_t i = 0; i < size_t(size) * CHANNELS; ++i) samples[i] = value;
2901 }
2902 signal& operator[](int index) {
2903 return reinterpret_cast<signal*>(samples)[static_cast<unsigned int>(index) & mask];
2904 }
2905 const signal& operator[](int index) const {
2906 return reinterpret_cast<const signal*>(samples)[static_cast<unsigned int>(index) & mask];
2907 }
2908 signal operator[](float offset) const {
2909 const float whole = std::floor(offset);
2910 const float fraction = offset - whole;
2911 const int i = int(whole), j = i == size - 1 ? 0 : i + 1;
2912 return (*this)[i] * (1.f - fraction) + (*this)[j] * fraction;
2913 }
2914 signal operator[](float offset) { return static_cast<const buffer&>(*this)[offset]; }
2915 operator signal& () { return *ptr; }
2916 operator const signal& () const { return *ptr; }
2917 bool finished() const { return ptr == end; }
2918 signal& operator++(int) { return *ptr++; }
2919 signal& operator=(const signal& value) { return *ptr = value; }
2920 signal& operator+=(const signal& value) { return *ptr += value; }
2921 signal& operator*=(const signal& value) { return *ptr *= value; }
2922 buffer& operator=(const buffer& other) {
2923 if (size > 0 && other.size > 0)
2924 std::memmove(samples, other.samples, std::min(size, other.size) * sizeof(signal));
2925 return *this;
2926 }
2927 buffer& operator<<(const signal& value) { *ptr = value; return *this; }
2928 float* data() { return samples; }
2929 const float* data() const { return samples; }
2930 };
2931 }
2932
2933
2934 struct Graph;
2935 struct GraphPtr;
2936
2937 /// Templates supporting common audio functionality
2938 namespace Generic {
2939
2940 /// Audio input object
2941 template<typename SIGNAL>
2942 struct Input {
2943 virtual ~Input() {}
2944 SIGNAL in = { 0.f };
2945
2946 // retrieve current input
2947 virtual const SIGNAL& input() const { return in; }
2948
2949 // feedback input (include pre-processing, if any)
2950 virtual void operator<<(const SIGNAL& source) { in = source; this->input(); }
2951 virtual void input(const SIGNAL& source) { in = source; this->input(); }
2952
2953 protected:
2954 // preprocess input (default: none)
2955 virtual void input() {}
2956 };
2957
2958 /// Audio output object
2959 template<typename SIGNAL>
2960 struct Output {
2961 SIGNAL out = { 0.f };
2962
2963 // returns previous output (without processing)
2964 virtual const SIGNAL& output() const { return out; }
2965
2966 // pass output to destination (with processing)
2967 template<typename TYPE, class = decltype(
2968 std::declval<TYPE&>() = std::declval<SIGNAL&>())>
2969 TYPE& operator>>(TYPE& destination) { this->process(); return destination = out; }
2970
2971 // returns output (with processing)
2972 virtual operator const SIGNAL& () { this->process(); return out; } // return processed output
2973 virtual operator const SIGNAL& () const { return out; } // return last output
2974
2975 // arithmetic operations produce copies
2976 template<typename TYPE> SIGNAL operator+(TYPE& other) { this->process(); return out + SIGNAL(other); }
2977 template<typename TYPE> SIGNAL operator*(TYPE& other) { this->process(); return out * SIGNAL(other); }
2978 template<typename TYPE> SIGNAL operator-(TYPE& other) { this->process(); return out - SIGNAL(other); }
2979 template<typename TYPE> SIGNAL operator/(TYPE& other) { this->process(); return out / SIGNAL(other); }
2980
2981 void reset() { out = 0; }
2982
2983 protected:
2984 // signal processing
2985 virtual void process() = 0;
2986 };
2987
2988 //template<typename TYPE> inline signal operator+(TYPE other, Output& output) { return signal(output) + other; }
2989 //template<typename TYPE> inline signal operator*(TYPE other, Output& output) { return signal(output) * other; }
2990 //template<typename TYPE> inline signal operator-(TYPE other, Output& output) { return signal(other) - signal(output); }
2991 //template<typename TYPE> inline signal operator/(TYPE other, Output& output) { return signal(other) / signal(output); }
2992
2993 // in-place arithmetic operations (CHECK: can these just be SIGNAL?)
2994 template<typename SIGNAL> inline SIGNAL operator+(float other, Output<SIGNAL>& output) { return SIGNAL(output) + other; }
2995 template<typename SIGNAL> inline SIGNAL operator*(float other, Output<SIGNAL>& output) { return SIGNAL(output) * other; }
2996 template<typename SIGNAL> inline SIGNAL operator-(float other, Output<SIGNAL>& output) { return SIGNAL(other) - SIGNAL(output); }
2997 template<typename SIGNAL> inline SIGNAL operator/(float other, Output<SIGNAL>& output) { return SIGNAL(other) / SIGNAL(output); }
2998
2999 // Supply scalar and matching signal temporaries without competing with lvalue arithmetic
3000 // or Function's existing implicit float conversion. Keep the float DSP path.
3001 template<typename OBJECT> using OutputSignal = std::decay_t<decltype(std::declval<OBJECT&>().out)>;
3002 template<typename OBJECT, typename SCALAR> using ScalarOutput = std::enable_if_t<
3003 (std::is_arithmetic_v<SCALAR> ||
3004 (std::is_same_v<std::decay_t<SCALAR>, OutputSignal<OBJECT>> &&
3005 !std::is_lvalue_reference_v<SCALAR>)) && !std::is_const_v<OBJECT> &&
3006 std::is_base_of_v<Output<OutputSignal<OBJECT>>, OBJECT> &&
3007 !std::is_convertible_v<OBJECT&, float>, OutputSignal<OBJECT>>;
3008
3009 template<typename OBJECT, typename SCALAR>
3010 inline ScalarOutput<OBJECT, SCALAR> operator+(OBJECT& output, SCALAR&& other) {
3011 if constexpr (std::is_arithmetic_v<SCALAR>)
3012 return OutputSignal<OBJECT>(output) + float(other);
3013 else
3014 return OutputSignal<OBJECT>(output) + other;
3015 }
3016 template<typename OBJECT, typename SCALAR>
3017 inline ScalarOutput<OBJECT, SCALAR> operator*(OBJECT& output, SCALAR&& other) {
3018 if constexpr (std::is_arithmetic_v<SCALAR>)
3019 return OutputSignal<OBJECT>(output) * float(other);
3020 else
3021 return OutputSignal<OBJECT>(output) * other;
3022 }
3023 template<typename OBJECT, typename SCALAR>
3024 inline ScalarOutput<OBJECT, SCALAR> operator-(OBJECT& output, SCALAR&& other) {
3025 if constexpr (std::is_arithmetic_v<SCALAR>)
3026 return OutputSignal<OBJECT>(output) - float(other);
3027 else
3028 return OutputSignal<OBJECT>(output) - other;
3029 }
3030 template<typename OBJECT, typename SCALAR>
3031 inline ScalarOutput<OBJECT, SCALAR> operator/(OBJECT& output, SCALAR&& other) {
3032 if constexpr (std::is_arithmetic_v<SCALAR>)
3033 return OutputSignal<OBJECT>(output) / float(other);
3034 else
3035 return OutputSignal<OBJECT>(output) / other;
3036 }
3037
3038 //inline signal operator+(Output& other, Output& output) { return signal(output) + signal(other); }
3039 //inline signal operator*(Output& other, Output& output) { return signal(output) * signal(other); }
3040 //inline signal operator-(Output& other, Output& output) { return signal(other) - signal(output); }
3041 //inline signal operator/(Output& other, Output& output) { return signal(other) / signal(output); }
3042
3043 /// Signal generator object (output only)
3044 template<typename SIGNAL>
3045 struct Generator : public Output<SIGNAL> {
3046 using Output<SIGNAL>::out;
3047
3048 // inline parameter(s) support
3049 template<typename... params>
3050 Output<SIGNAL>& operator()(params&&... p) {
3051 set(std::forward<params>(p)...); return *this;
3052 }
3053
3054 using Output<SIGNAL>::operator>>;
3055 using Output<SIGNAL>::process;
3056 operator const SIGNAL& () override { this->process(); return out; } // return processed output
3057 operator const SIGNAL& () const override { return out; } // return last output
3058
3059 protected:
3060 // overrideable parameter setting (up to 8 parameters)
3061 /// @cond
3062 virtual void set(param) {};
3063 virtual void set(relative) {}; // relative alternative
3064 virtual void set(param, param) {};
3065 virtual void set(param, relative) {}; // relative alternative
3066 virtual void set(param, param, param) {};
3067 virtual void set(param, param, relative) {}; // relative alternative
3068 virtual void set(param, param, param, param) {};
3069 virtual void set(param, param, param, relative) {}; // relative alternative
3070 virtual void set(param, param, param, param, param) {};
3071 virtual void set(param, param, param, param, relative) {}; // relative alternative
3072 virtual void set(param, param, param, param, param, param) {};
3073 virtual void set(param, param, param, param, param, relative) {}; // relative alternative
3074 virtual void set(param, param, param, param, param, param, param) {};
3075 virtual void set(param, param, param, param, param, param, relative) {}; // relative alternative
3076 virtual void set(param, param, param, param, param, param, param, param) {};
3077 virtual void set(param, param, param, param, param, param, param, relative) {}; // relative alternative
3078 /// @endcond
3079 };
3080
3081 /// Signal modifier object (input-output)
3082 template<typename SIGNAL>
3083 struct Modifier : public Input<SIGNAL>, public Output<SIGNAL> {
3084 using Input<SIGNAL>::in;
3085 using Output<SIGNAL>::out;
3086
3087 virtual ~Modifier() {}
3088
3089 // signal processing (input-output)
3090 operator const SIGNAL& () override { this->process(); return out; } // return processed output
3091 operator const SIGNAL& () const override { return out; } // return last output
3092
3093 using Input<SIGNAL>::input;
3094 virtual void process() override { out = in; } // default to pass-through
3095
3096 // inline parameter(s) support
3097 template<typename... params>
3099 set(std::forward<params>(p)...); return *this;
3100 }
3101 protected:
3102 // overrideable parameter setting (up to 8 parameters)
3103 /// @cond
3104 virtual void set(param) {};
3105 virtual void set(relative) {}; // relative alternative
3106 virtual void set(param, param) {};
3107 virtual void set(param, relative) {}; // relative alternative
3108 virtual void set(param, param, param) {};
3109 virtual void set(param, param, relative) {}; // relative alternative
3110 virtual void set(param, param, param, param) {};
3111 virtual void set(param, param, param, relative) {}; // relative alternative
3112 virtual void set(param, param, param, param, param) {};
3113 virtual void set(param, param, param, param, relative) {}; // relative alternative
3114 virtual void set(param, param, param, param, param, param) {};
3115 virtual void set(param, param, param, param, param, relative) {}; // relative alternative
3116 virtual void set(param, param, param, param, param, param, param) {};
3117 virtual void set(param, param, param, param, param, param, relative) {}; // relative alternative
3118 virtual void set(param, param, param, param, param, param, param, param) {};
3119 virtual void set(param, param, param, param, param, param, param, relative) {}; // relative alternative
3120 /// @endcond
3121 };
3122
3123 /// Applies a function to a signal (input-output)
3124 template<typename SIGNAL, typename... Args>
3125 struct Function : public Generic::Modifier<SIGNAL> {
3126 virtual ~Function() {}
3127
3128 using Modifier<SIGNAL>::in;
3129 using Modifier<SIGNAL>::out;
3130
3131 operator SIGNAL() {
3132 if (function)
3133 return out = evaluate();
3134 this->process();
3135 return out;
3136 };
3137 operator param() {
3138 if (function)
3139 return out = evaluate();
3140 return out;
3141 }
3142 operator float() {
3143 if (function)
3144 return out = evaluate();
3145 return out;
3146 }
3147
3148 /// @cond
3149 // Helper to combine hash values
3150 template <typename T>
3151 inline void hash_combine(std::size_t& seed, const T& value) const {
3152 std::hash<T> hasher;
3153 seed ^= hasher(value) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
3154 }
3155
3156 // Recursive function to hash each element of a tuple
3157 template <typename Tuple, std::size_t Index = 0>
3158 std::size_t hash_tuple(const Tuple& tuple) const {
3159 if constexpr (Index < std::tuple_size<Tuple>::value) {
3160 std::size_t seed = hash_tuple<Tuple, Index + 1>(tuple);
3161 hash_combine(seed, std::get<Index>(tuple));
3162 return seed;
3163 }
3164 else {
3165 return 0;
3166 }
3167 }
3168
3169 operator void* () { return this; }
3170 uint64_t hash() const { return hash_tuple(tail(inputs)); }
3171 /// @endcond
3172
3173 std::function<float(Args...)> function;
3174
3175 static constexpr unsigned int ARGS = sizeof...(Args);
3176 unsigned int args() const { return ARGS; }
3177
3178 std::tuple<Args...> inputs;
3179
3180 // Helper function to extract the tail of a tuple
3181 template <typename First, typename... Rest>
3182 std::tuple<Rest...> tail(const std::tuple<First, Rest...>& t) const {
3183 return std::apply([](const First&, const Rest&... rest) { return std::make_tuple(rest...); }, t);
3184 }
3185
3186 template<typename FunctionPtr>
3187 Function() : function(nullptr) {}
3188
3189 template<typename FunctionPtr>
3190 Function(FunctionPtr function)
3191 : function(std::forward<FunctionPtr>(function)) {
3192 }
3193
3194 template<typename FunctionPtr, typename... OtherArgs>
3195 Function(FunctionPtr function, OtherArgs... args)
3196 : function(std::forward<FunctionPtr>(function)) {
3197 with(args...);
3198 }
3199
3200 void input() override {
3201 std::get<0>(inputs) = in.value;
3202 }
3203
3204 // get the first argument
3205 template <typename First, typename... Rest>
3206 First& first(First& first, Rest...) { return first; }
3207
3208 // get the first argument
3209 template <typename First, typename... Rest>
3210 const First& first(const First& first, Rest...) const { return first; }
3211
3212 // Configure callable function's arguments
3213 template<typename... FuncArgs>
3214 Function<SIGNAL, Args...>& operator()(const FuncArgs&... args) {
3215
3216 //// single argument supplied, more than one expected -> use cached inputs or use as input?
3217 // if constexpr (ARGS > 1 && sizeof...(FuncArgs) == 1){
3218 // //in = first(args...);
3219 // std::get<1>(inputs) = in.value;
3220 // return *this;
3221 // } else
3222
3223 // Calling: full set of arguments supplied (overwrite live input)
3224 if constexpr (ARGS == sizeof...(FuncArgs)) {
3225 in = float(first(args...));
3226 inputs = std::tuple<Args...>(args...);
3227 return *this;
3228
3229 // Streaming: all but first argument supplied (use live input as x)
3230 }
3231 else if constexpr (sizeof...(FuncArgs) == (ARGS - 1)) {
3232 inputs = std::tuple<Args...>(in.value, args...);
3233 return *this;
3234
3235 // Invalid: insufficents arguments
3236 }
3237 else {
3238 static_assert(sizeof...(FuncArgs) < (ARGS - 1), "Insufficient arguments: can only omit first argument");
3239 //in = first(args...);
3240 //std::get<0>(inputs) = in.value;
3241 return *this;
3242 }
3243 }
3244
3245 // Configure and call function
3246 template<typename... FuncArgs>
3247 const float operator()(const FuncArgs&... args) const {
3248 signal in = this->in;
3249 std::tuple<Args...> inputs = this->inputs;
3250
3251 // configure inputs
3252 if constexpr (ARGS > 1 && sizeof...(FuncArgs) == 1) {
3253 in = first(args...);
3254 std::get<0>(inputs) = in.value;
3255 }
3256 else if constexpr (ARGS == sizeof...(FuncArgs)) {
3257 in = first(args...);
3258 inputs = std::tuple<Args...>(args...);
3259 }
3260 else if constexpr (sizeof...(FuncArgs) == (ARGS - 1)) {
3261 inputs = std::tuple<Args...>(in.value, args...);
3262 }
3263 else {
3264 in = first(args...);
3265 std::get<0>(inputs) = in.value;
3266 }
3267
3268 // return outputs
3269 if (function) {
3270 if constexpr (ARGS > 1)
3271 return std::apply(function, inputs);
3272 else
3273 return function(in);
3274 }
3275 else {
3276 // NOT YET IMPLEMENTED (needs non-const status)
3277 return out;
3278 }
3279 }
3280
3281 template<typename... FuncArgs>
3282 Function<SIGNAL, Args...>& with(FuncArgs... args) {
3283 static_assert(sizeof...(FuncArgs) == (ARGS - 1), "with() arguments must have all but first argument.");
3284 inputs = std::tuple<Args...>(in.value, args...);
3285
3286 return *this;
3287 }
3288
3290 if (!function)
3291 return 0.f;
3292 if constexpr (ARGS > 1)
3293 return std::apply(function, inputs);
3294 else
3295 return (signal)function(in);
3296 }
3297
3298 virtual void process() override {
3299 out = evaluate();
3300 }
3301
3303 klang::GraphPtr& operator>>(klang::GraphPtr& graph);
3304
3305 using Generic::Output<SIGNAL>::operator+;
3306 using Generic::Output<SIGNAL>::operator-;
3307 using Generic::Output<SIGNAL>::operator*;
3308 using Generic::Output<SIGNAL>::operator/;
3309 };
3310
3311 // deduction guide for functions
3312 template <typename... Args>
3313 Function(float(*)(Args...)) -> Function<signal, Args...>;
3314
3315 template <typename... Args>
3316 Function() -> Function<signal, Args...>;
3317
3318 template<typename TYPE, typename SIGNAL, typename... Args> SIGNAL operator+(TYPE& x, Function<SIGNAL, float>& func) { return func + (SIGNAL)x; }
3319 template<typename TYPE, typename SIGNAL, typename... Args> SIGNAL operator-(TYPE& x, Function<SIGNAL, float>& func) { return -func + (SIGNAL)x; }
3320 template<typename TYPE, typename SIGNAL, typename... Args> SIGNAL operator*(TYPE& x, Function<SIGNAL, float>& func) { return func * (SIGNAL)x; }
3321 template<typename TYPE, typename SIGNAL, typename... Args> SIGNAL operator/(TYPE& x, Function<SIGNAL, float>& func) {
3322 SIGNAL y = (SIGNAL)func;
3323 return (SIGNAL)x / y;
3324 }
3325
3326 /// A line graph plotter
3327 template<int SIZE>
3328 struct Graph {
3329 virtual ~Graph() {};
3330
3331 size_t capacity() const { return SIZE; }
3332
3333 struct Series;
3334
3335 /// A data point
3336 struct Point {
3337 double x, y;
3338 bool valid() const { return !::isnan(x) && !::isinf(x) && !::isnan(y); } // NB: y can be +/- inf
3339
3341 };
3342
3343 struct Axis;
3344
3345 /// Data series
3346 struct Series : public Array<Point, SIZE + 1>, Input<signal> {
3347 virtual ~Series() {}
3348
3349 const void* function = nullptr;
3350 uint64_t hash = 0;
3351
3353 using Array::add;
3354 using Array::count;
3355 using Array::items;
3356
3357 void add(double y) {
3358 add({ (double)Array::size(), y });
3359 }
3360
3361 template<typename SIGNAL, typename... Args>
3362 void plot(const Generic::Function<SIGNAL, Args...>& f, const Axis& x_axis) {
3363 constexpr int size = SIZE > 1024 ? 1024 : SIZE;
3364
3365 if (function != (const void*)&f || hash != f.hash()) {
3366 clear();
3367 function = (const void*)&f;
3368 hash = f.hash();
3369 double x = 0;
3370 const double dx = x_axis.range() / size;
3371 for (int i = 0; i <= size; i++) {
3372 x = x_axis.min + i * dx;
3373 add({ x, (double)(signal)f(x) });
3374 }
3375 }
3376 }
3377
3378 template<typename RETURN, typename ARG>
3379 void plot(RETURN(*f)(ARG), const Axis& x_axis) {
3380 constexpr int size = SIZE > 1024 ? 1024 : SIZE;
3381
3382 if (function != (void*)f) {
3383 clear();
3384 function = (void*)f;
3385 hash = 0;
3386 double x = 0;
3387 const double dx = x_axis.range() / size;
3388 for (int i = 0; i <= size; i++) {
3389 x = x_axis.min + i * dx;
3390 add({ x, (double)(signal)f((float)x) });
3391 }
3392 }
3393 }
3394
3395 bool operator==(const Series& in) const {
3396 if (count != in.count) return false;
3397 for (unsigned int i = 0; i < count; i++)
3398 if (items[i].x != in.items[i].x || items[i].y != in.items[i].y)
3399 return false;
3400 return true;
3401 }
3402
3403 bool operator!=(const Series& in) const {
3404 return !operator==(in);
3405 }
3406
3407 void clear() {
3408 function = nullptr;
3409 Array::clear();
3410 }
3411
3413 void input() override {
3414 add(in);
3415 }
3416 };
3417
3418 /// Graph axis
3419 struct Axis {
3420 double min = 0, max = 0;
3421 bool valid() const { return max != min; }
3422 double range() const { return max - min; }
3423 bool contains(double value) const { return value >= min && value <= max; }
3424 void clear() { min = max = 0; }
3425
3426 void from(const Series& series, double Point::* axis) {
3427 if (!series.count) return;
3428 int points = 0;
3429 for (unsigned int p = 0; p < series.count; p++) {
3430 const Point& pt = series[p];
3431 if (pt.valid() && !::isinf(pt.*axis)) {
3432 if (!points || pt.*axis < min) min = pt.*axis;
3433 if (!points || pt.*axis > max) max = pt.*axis;
3434 points++;
3435 }
3436 }
3437 if (std::abs(max) < 0.0000000001) max = 0;
3438 if (std::abs(min) < 0.0000000001) min = 0;
3439 if (std::abs(max) > 1000000000.0) max = 0;
3440 if (std::abs(min) > 1000000000.0) min = 0;
3441 if (min > max) max = min = 0;
3442 }
3443 };
3444
3445 /// Graph axes (x/y)
3446 struct Axes {
3448 bool valid() const { return x.valid() && y.valid(); }
3449 void clear() { x = { 0,0 }; y = { 0,0 }; }
3450 bool contains(const Point& pt) const { return x.contains(pt.x) && y.contains(pt.y); }
3451 };
3452
3453 void clear() {
3454 dirty = true;
3455 axes.clear();
3456 for (int s = 0; s < GRAPH_SERIES; s++)
3457 data[s].clear();
3458 data.clear();
3459 }
3460
3461 /// @cond
3462 bool isActive() const {
3463 if (data.count)
3464 return true;
3465 for (int s = 0; s < GRAPH_SERIES; s++)
3466 if (data[s].count)
3467 return true;
3468 return false;
3469 }
3470 /// @endcond
3471
3472 /// Graph data
3473 struct Data : public Array<Series, GRAPH_SERIES> {
3474 using Array<Series, GRAPH_SERIES>::items;
3475
3476 Series* find(void* function) {
3477 for (int s = 0; s < GRAPH_SERIES; s++)
3478 if (this->operator[](s).function == function)
3479 return &items[s];
3480 return nullptr;
3481 }
3482 };
3483
3484 Graph& operator()(double min, double max) {
3485 dirty = true;
3486 axes.x.min = min; axes.x.max = max;
3487 return *this;
3488 }
3489
3491 dirty = true;
3492 return data[index];
3493 }
3494
3495 const Graph::Series& operator[](int index) const {
3496 return data[index];
3497 }
3498
3499 Graph& operator()(double x_min, double x_max, double y_min, double y_max) {
3500 dirty = true;
3501 axes.x.min = x_min; axes.x.max = x_max;
3502 axes.y.min = y_min; axes.y.max = y_max;
3503 return *this;
3504 }
3505
3506 operator Series& () {
3507 dirty = true;
3508 return data[0];
3509 }
3510
3511 /// Plot the given Function
3512 template<typename SIGNAL, typename... Args>
3514 Graph::Series* series = Graph::data.find((void*)function);
3515 if (!series)
3516 series = Graph::data.add();
3517 if (series) {
3518 dirty = true;
3519 if (!axes.x.valid())
3520 axes.x = { -1, 1 };
3521 series->plot(function, axes.x);
3522 }
3523 }
3524
3525 /// Plot the given function of x
3526 template<typename TYPE>
3527 void plot(TYPE(*function)(TYPE)) {
3528 Graph::Series* series = Graph::data.find((void*)function);
3529 if (!series)
3530 series = Graph::data.add();
3531 if (series) {
3532 dirty = true;
3533 if (!axes.x.valid())
3534 axes.x = { -1, 1 };
3535 series->plot(function, axes.x);
3536 }
3537 }
3538
3539 /// Plot the given function for x plus additional arguments
3540 template<typename FUNCTION, typename... VALUES>
3541 void plot(FUNCTION f, VALUES... values) {
3542 thread_local static Function fun(f);
3543 Graph::Series* series = Graph::data.find((void*)fun);
3544 if (!series)
3545 series = Graph::data.add();
3546 if (series) {
3547 dirty = true;
3548 if (!axes.x.valid())
3549 axes.x = { -1, 1 };
3550 series->plot(fun.with(values...), axes.x);
3551 }
3552 }
3553
3554 /// Add a data point (incrementing x)
3555 template<typename TYPE>
3556 void add(TYPE y) { data[0].add(y); dirty = true; }
3557 /// Add a data point
3558 void add(const Point pt) { data[0].add(pt); dirty = true; }
3559
3560 /// Add a data point (incrementing x)
3561 template<typename TYPE>
3562 Graph& operator+=(TYPE y) { add(y); return *this; }
3563 /// Add a data point
3564 Graph& operator+=(const Point pt) { add(pt); return *this; }
3565
3566 /// Plot the given function of x
3567 template<typename TYPE>
3568 Graph& operator=(TYPE(*function)(TYPE)) {
3569 plot(function);
3570 return *this;
3571 }
3572
3573 /// Plot the given data points
3574 Graph& operator=(std::initializer_list<Point> values) {
3575 clear(); return operator+=(values);
3576 }
3577
3578 /// Plot the given data points
3579 Graph& operator+=(std::initializer_list<Point> values) {
3580 for (const auto& value : values)
3581 add(value);
3582 return *this;
3583 }
3584
3585 /// Plot the given function for x plus additional arguments
3586 template<typename... Args> Graph& operator<<(Function<Args...>& function) {
3587 plot(function.with());
3588 return *this;
3589 }
3590
3591 template<typename TYPE> Graph& operator<<(TYPE& in) { add(in); return *this; } // with processing
3592 template<typename TYPE> Graph& operator<<(const TYPE& in) { add(in); return *this; } // without/after processing
3593
3594 // returns the user-defined axes
3595 const Axes& getAxes() const { return axes; }
3596
3597 // calculates axes based on data
3598 void getAxes(Axes& axes) const {
3599 if (!axes.x.valid()) {
3600 axes.x.clear();
3601 for (int s = 0; s < GRAPH_SERIES; s++)
3602 axes.x.from(data[s], &Point::x);
3603 if (!axes.y.valid() && axes.y.max != 0)
3604 axes.y.min = 0;
3605 }
3606 if (!axes.y.valid()) {
3607 axes.y.clear();
3608 for (int s = 0; s < GRAPH_SERIES; s++)
3609 axes.y.from(data[s], &Point::y);
3610 if (!axes.y.valid() && axes.y.max != 0)
3611 axes.y.min = 0;
3612 }
3613 }
3614
3615 const Data& getData() const { return data; }
3616 bool isDirty() const { return dirty; }
3618
3619 void truncate(unsigned int count) {
3620 if (count < data.count)
3621 data.count = count;
3622
3623 for (int s = 0; s < GRAPH_SERIES; s++)
3624 if (count < data[s].count)
3625 data[s].count = count;
3626 }
3627
3628 protected:
3631 bool dirty = false;
3632 };
3633
3634 template<int SIZE>
3636 series.add(*this);
3637 return series;
3638 }
3639
3640 /// Audio oscillator object (output)
3641 template<typename SIGNAL>
3642 struct Oscillator : public Generator<SIGNAL> {
3643 protected:
3644 Phase increment; // phase increment (per sample, in seconds or samples)
3645 Phase position = 0; // phase position (in radians or wavetable size)
3646 public:
3647 Frequency frequency = 1000.f; // fundamental frequency of oscillator (in Hz)
3648 Phase offset = 0; // phase offset (in radians - e.g. for modulation)
3649
3650 virtual ~Oscillator() {}
3651 virtual void reset() { position = 0; }
3652
3653 using Generator<SIGNAL>::set;
3654 virtual void set(param frequency) {
3655 Oscillator::frequency = frequency;
3656 increment = frequency * 2.f * pi.f / fs;
3657 }
3658
3659 virtual void set(param frequency, param phase) {
3660 position = phase;
3661 set(frequency);
3662 }
3663
3664 virtual void set(param frequency, relative phase) {
3665 set(frequency);
3666 set(phase);
3667 }
3668
3669 virtual void set(relative phase) {
3670 offset = phase * (2 * pi);
3671 }
3672 };
3673 }
3674
3675 /// Audio input object (mono)
3676 struct Input : Generic::Input<signal> {};
3677 /// Audio output object (mono)
3678 struct Output : Generic::Output<signal> {};
3679 /// Signal generator object (mono)
3680 struct Generator : Generic::Generator<signal> {};
3681 /// Signal modifier object (mono input-output)
3682 struct Modifier : public Generic::Modifier<signal> {};
3683 /// Audio oscillator object (mono output)
3684 struct Oscillator : Generic::Oscillator<signal> {};
3685
3686 /// @cond
3687 template <typename TYPE, typename SIGNAL>
3688 using GeneratorOrModifier = typename std::conditional<std::is_base_of<Generator, TYPE>::value, Generic::Generator<SIGNAL>,
3689 typename std::conditional<std::is_base_of<Modifier, TYPE>::value, Generic::Modifier<SIGNAL>, void>::type>::type;
3690 /// @endcond
3691
3692 /// A parallel bank of multiple audio objects
3693 template<typename TYPE, int COUNT>
3694 struct Bank : public GeneratorOrModifier<TYPE, signals<COUNT>> {
3695 using GeneratorOrModifier<TYPE, signals<COUNT>>::in;
3696 using GeneratorOrModifier<TYPE, signals<COUNT>>::out;
3697 using GeneratorOrModifier<TYPE, signals<COUNT>>::operator>>;
3698
3699 TYPE items[COUNT];
3700
3701 TYPE& operator[](int index) { return items[index]; }
3702 const TYPE& operator[](int index) const { return items[index]; }
3703
3704 template<typename... Args>
3705 void set(Args... args) {
3706 for (int n = 0; n < COUNT; n++)
3707 items[n].set(args...);
3708 }
3709
3710 void input() override {
3711 for (int n = 0; n < COUNT; n++)
3712 in[n] >> items[n];
3713 }
3714
3715 void process() override {
3716 for (int n = 0; n < COUNT; n++)
3717 items[n] >> out[n];
3718 }
3719
3720 /// Return the sum of the cached parallel outputs.
3721 signal sum() const { return out.sum(); }
3722
3723 /// Return the Bank's default mono reduction: the sum of its parallel outputs.
3724 signal mono() const { return sum(); }
3725
3726 /// Process every item once and route their summed output to mono.
3727 signal& operator>>(signal& destination) {
3728 process();
3729 return destination = mono();
3730 }
3731 };
3732
3733 /// Applies a function to a signal (input-output)
3734 template<typename... Args>
3735 struct Function : public Generic::Function<signal, Args...> {
3736
3737 //static float Identity(float x) { return x; }
3738
3739 //Function() : Generic::Function<signal, float>([](float x) -> float { return x; }) { }
3740
3741 Function() : Generic::Function<signal, Args...>(nullptr) {}
3742
3743 Function(std::function<float(Args...)> function) : Generic::Function<signal, Args...>(function) {}
3744
3745 using Generic::Function<signal, Args...>::operator>>;
3746 };
3747
3748 /// A line graph plotter
3749 struct Graph : public Generic::Graph<GRAPH_SIZE> {
3750 using Generic::Graph<GRAPH_SIZE>::operator=;
3751 using Generic::Graph<GRAPH_SIZE>::plot;
3752
3753 /// Plot the given function for x plus additional arguments
3754 template<typename... Args> Graph& operator<<(Function<Args...>& function) {
3755 plot(function.with());
3756 return *this;
3757 }
3758 };
3759
3760 /// @cond
3761 struct GraphPtr {
3762 std::unique_ptr<Graph> ptr;
3763
3764 void init() {
3765 if (ptr.get() == nullptr)
3766 ptr = std::make_unique<Graph>();
3767 }
3768
3769 Graph* operator->() { init(); return (klang::Graph*)ptr.get(); }
3770 operator Graph* () { init(); return (klang::Graph*)ptr.get(); }
3771 operator Graph& () { init(); return *(klang::Graph*)ptr.get(); }
3772
3773 void clear() { init(); ptr->clear(); }
3774 bool isActive() const { return ptr ? ptr->isActive() : false; }
3775
3776 Graph& operator()(double min, double max) { init(); return (Graph&)ptr->operator()(min, max); }
3777
3778 Graph::Series& operator[](int index) { init(); return ptr->operator[](index); }
3779 const Graph::Series& operator[](int index) const { static const Graph::Series none = Graph::Series(); return ptr ? ptr->operator[](index) : none; }
3780
3781 Graph& operator()(double x_min, double x_max, double y_min, double y_max) { init(); return (Graph&)ptr->operator()(x_min, x_max, y_min, y_max); }
3782
3783 operator Graph::Series& () { init(); return ptr->operator Graph::Series & (); }
3784
3785 template<typename SIGNAL, typename... Args>
3786 void plot(Generic::Function<SIGNAL, Args...>& function) { init(); ((Graph*)(ptr.get()))->plot(function); }
3787
3788 template<typename TYPE>
3789 void plot(TYPE(*function)(TYPE)) { init(); ((Graph*)(ptr.get()))->plot(function); }
3790
3791 template<typename FUNCTION, typename... VALUES>
3792 void plot(FUNCTION f, VALUES... values) { init(); ((Graph*)(ptr.get()))->plot(f, values...); }
3793
3794 template<typename TYPE> void add(TYPE y) { init(); ptr->add(y); }
3795 void add(const Graph::Point pt) { init(); ptr->add(pt); }
3796
3797 template<typename TYPE> Graph& operator+=(TYPE y) { init(); return ptr->operator+=(y); }
3798 Graph& operator+=(const Graph::Point pt) { init(); return (Graph&)ptr->operator+=(pt); }
3799
3800 template<typename TYPE> Graph& operator=(TYPE(*function)(TYPE)) { init(); return (Graph&)ptr->operator=(function); }
3801
3802 Graph& operator=(std::initializer_list<Graph::Point> values) { init(); return (Graph&)ptr->operator=(values); }
3803 Graph& operator+=(std::initializer_list<Graph::Point> values) { init(); return (Graph&)ptr->operator+=(values); }
3804
3805 template<typename... Args> Graph& operator<<(Generic::Function<Args...>& function) { plot(function.with()); return *this; }
3806 template<typename TYPE> Graph& operator<<(TYPE& in) { add(in); return *this; } // with processing
3807 template<typename TYPE> Graph& operator<<(const TYPE& in) { add(in); return *this; } // without/after processing
3808
3809 const Graph::Axes& getAxes() const { static const Graph::Axes none; return ptr ? ptr->getAxes() : none; }
3810 void getAxes(Graph::Axes& axes) { init(); ptr->getAxes(axes); }
3811
3812 const Graph::Data& getData() { init(); return ptr->getData(); }
3813 bool isDirty() const { return ptr ? ptr->isDirty() : false; }
3814 void setDirty(bool dirty) { if (ptr) ptr->setDirty(dirty); }
3815
3816 void truncate(unsigned int count) { init(); ptr->truncate(count); }
3817 };
3818 /// @endcond
3819
3820
3821
3822 // deduction guide for functions
3823 template <typename... Args>
3824 Function(float(*)(Args...)) -> Function<Args...>;
3825
3826 //// deduction guide for functions
3827 //Function() -> Function<float>;
3828
3829 THREAD_LOCAL static GraphPtr graph;
3830
3831 template<typename SIGNAL, typename... Args>
3832 inline GraphPtr& Generic::Function<SIGNAL, Args...>::operator>>(klang::GraphPtr& graph) {
3833 graph.plot(*this);
3834 return graph;
3835 }
3836
3837 inline static GraphPtr& operator>>(UnaryFunction& function, klang::GraphPtr& graph) {
3838 graph->plot(static_cast<float(*)(float)>(function));
3839 return graph;
3840 }
3841
3842 template<typename TYPE>
3843 static GraphPtr& operator>>(TYPE(*function)(TYPE), klang::GraphPtr& graph) {
3844 graph->plot(function);
3845 return graph;
3846 }
3847
3848 template<typename SIGNAL, typename... Args>
3853
3854 inline static Graph& operator>>(UnaryFunction& function, Graph& graph) {
3855 graph.plot(static_cast<float(*)(float)>(function));
3856 return graph;
3857 }
3858
3859 template<typename TYPE>
3860 static Graph& operator>>(TYPE(*function)(TYPE), Graph& graph) {
3861 graph.plot(function);
3862 return graph;
3863 }
3864
3865 // syntax equivalence: a = b is the same as b >> a
3867 b >> *this;
3868 return *this;
3869 }
3870
3871 // supports summing of multiple outputs
3872 inline signal& signal::operator+=(Output& in) { // e.g. out += osc;
3873 value += signal(in);
3874 return *this;
3875 }
3876
3877 // Extend common standard unary maths overload sets for Klang wrapper types.
3878 /// Return the C++ remainder for integers and the floating-point remainder otherwise.
3879 template<typename LEFT, typename RIGHT, std::enable_if_t<
3880 std::is_arithmetic_v<LEFT> && std::is_arithmetic_v<RIGHT>, int> = 0>
3881 inline auto mod(LEFT left, RIGHT right) {
3882 if constexpr (std::is_integral_v<LEFT> && std::is_integral_v<RIGHT>)
3883 return left % right;
3884 else {
3885 using Float = std::conditional_t<
3886 std::is_same_v<LEFT, long double> || std::is_same_v<RIGHT, long double>, long double,
3887 std::conditional_t<std::is_same_v<LEFT, double> || std::is_same_v<RIGHT, double>, double, float>>;
3888 return std::fmod(Float(left), Float(right));
3889 }
3890 }
3891
3892
3893// Shared numeric, parameter-inlet and math-stage implementation.
3894namespace detail {
3895 template<class T>
3896 inline constexpr bool is_control_v =
3897 std::is_same_v<std::decay_t<T>, Control> ||
3898 std::is_same_v<std::decay_t<T>, ControlMap>;
3899
3900 /// Arithmetic values, signal subclasses and controls support scalar snapshots.
3901 template<class T>
3902 inline constexpr bool is_math_value_v = std::is_arithmetic_v<std::decay_t<T>> ||
3903 std::is_base_of_v<signal, std::decay_t<T>> ||
3904 std::is_same_v<std::decay_t<T>, constant> ||
3905 is_control_v<T>;
3906
3907 template<class... Values>
3908 inline constexpr bool are_math_values_v = (is_math_value_v<Values> && ...);
3909
3910 template<class... Values>
3911 inline constexpr bool has_control_v = (is_control_v<Values> || ...);
3912
3913 /// Read one float without advancing a control, generator, or function.
3914 template<class T, std::enable_if_t<is_math_value_v<T>, int> = 0>
3915 inline float numeric_snapshot(const T& value) { return float(value); }
3916
3917 template<class TARGET, class VALUE, class = void>
3918 struct has_native_template_inlet : std::false_type {};
3919
3920 template<class TARGET, class VALUE>
3921 struct has_native_template_inlet<TARGET, VALUE, std::void_t<decltype(
3922 std::declval<TARGET&>().template operator<< <>(std::declval<VALUE>()))>>
3923 : std::true_type {};
3924
3925 template<class TARGET>
3926 using param_inlet_result = decltype(std::declval<TARGET&>().operator<<(std::declval<param>()));
3927
3928 template<class TARGET, class = void>
3929 struct has_param_inlet : std::false_type {};
3930
3931 template<class TARGET>
3932 struct has_param_inlet<TARGET, std::void_t<decltype(
3933 static_cast<param_inlet_result<TARGET> (TARGET::*)(param)>(&TARGET::operator<<))>>
3934 : std::true_type {};
3935
3936 template<class TARGET, class VALUE>
3937 using route_param_inlet = std::conjunction<
3938 std::is_convertible<VALUE, param>,
3939 std::negation<std::is_same<std::decay_t<VALUE>, param>>,
3940 std::negation<has_native_template_inlet<TARGET, VALUE>>,
3941 has_param_inlet<TARGET>>;
3942
3943 // Function objects retain the float boundaries of the existing math adapters.
3944 #define KLANG_BINARY_OPERATION(function, evaluate) \
3945 struct function##_operation { \
3946 float operator()(float left, float right) const { \
3947 return float(evaluate(left, right)); \
3948 } \
3949 };
3950
3951 #define KLANG_TERNARY_OPERATION(function, evaluate) \
3952 struct function##_operation { \
3953 float operator()(float left, float middle, float right) const { \
3954 return float(evaluate(left, middle, right)); \
3955 } \
3956 };
3957
3958 KLANG_BINARY_OPERATION(min, std::min)
3959 KLANG_BINARY_OPERATION(max, std::max)
3960 KLANG_BINARY_OPERATION(pow, std::pow)
3961 KLANG_BINARY_OPERATION(atan2, std::atan2)
3962 KLANG_BINARY_OPERATION(hypot, std::hypot)
3963 KLANG_BINARY_OPERATION(fmod, std::fmod)
3964 KLANG_BINARY_OPERATION(remainder, std::remainder)
3965 KLANG_BINARY_OPERATION(copysign, std::copysign)
3966 KLANG_BINARY_OPERATION(fdim, std::fdim)
3967 KLANG_BINARY_OPERATION(mod, klang::mod)
3968 KLANG_TERNARY_OPERATION(clamp, std::clamp)
3969
3970 #undef KLANG_BINARY_OPERATION
3971 #undef KLANG_TERNARY_OPERATION
3972
3973 /// A stateless binary maths operation with its right argument bound for signal flow.
3974 template<class OPERATION>
3975 struct BinaryMath {
3976 float right;
3977 };
3978
3979 /// A stateless ternary maths operation with its final two arguments bound for signal flow.
3980 template<class OPERATION>
3981 struct TernaryMath {
3982 float middle, right;
3983 };
3984
3985 template<class OPERATION>
3986 inline signal operator>>(signal left, const BinaryMath<OPERATION>& stage) {
3987 return OPERATION{}(float(left), stage.right);
3988 }
3989
3990 template<class OPERATION>
3991 inline signal operator>>(signal left, const TernaryMath<OPERATION>& stage) {
3992 return OPERATION{}(float(left), stage.middle, stage.right);
3993 }
3994
3995 /// Route values to parameter inlets while preserving native template sinks.
3996 template<class TARGET, class VALUE, std::enable_if_t<
3997 detail::route_param_inlet<TARGET, VALUE&&>::value, int> = 0>
3998 inline auto operator<<(TARGET& target, VALUE&& value)
3999 -> decltype(target.operator<<(std::forward<VALUE>(value))) {
4000 return target.operator<<(std::forward<VALUE>(value));
4001 }
4002
4003 template<class SOURCE, class DESTINATION>
4004 auto flow_destination(std::true_type)
4005 -> decltype(std::declval<DESTINATION&>().input(std::declval<SOURCE>()));
4006
4007 template<class SOURCE, class DESTINATION>
4008 auto flow_destination(std::false_type)
4009 -> decltype(std::declval<DESTINATION&>() << std::declval<SOURCE>());
4010}
4011
4012using detail::operator<<;
4013
4014// Extend a scalar unary function with the Klang value and signal-flow interface.
4015#define KLANG_UNARY_ADAPTER(function, evaluate) \
4016 inline signal function(signal input) { return evaluate(input.value); } \
4017 template<class Input, std::enable_if_t<detail::is_control_v<Input>, int> = 0> \
4018 inline signal function(const Input& input) { \
4019 return evaluate(detail::numeric_snapshot(input)); \
4020 }
4021
4022// Shared adapters only participate when a control is present. Existing scalar,
4023// signal, unit-wrapper, Output and Function overloads retain their own dispatch.
4024#define KLANG_CONTROL_BINARY_MATH(function) \
4025 template<class Right, std::enable_if_t<detail::is_control_v<Right>, int> = 0> \
4026 inline detail::BinaryMath<detail::function##_operation> function(const Right& right) { \
4027 return {detail::numeric_snapshot(right)}; \
4028 } \
4029 template<class Left, class Right, std::enable_if_t< \
4030 detail::are_math_values_v<Left, Right> && \
4031 detail::has_control_v<Left, Right>, int> = 0> \
4032 inline signal function(const Left& left, const Right& right) { \
4033 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4034 detail::numeric_snapshot(right)); \
4035 } \
4036 inline signal function(const Control& left, const Control& right) { \
4037 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4038 detail::numeric_snapshot(right)); \
4039 } \
4040 inline signal function(const ControlMap& left, const ControlMap& right) { \
4041 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4042 detail::numeric_snapshot(right)); \
4043 }
4044
4045// Standard min/max require matching types; promote mixed arithmetic arguments.
4046#define KLANG_MIXED_ARITHMETIC_MATH(function) \
4047 template<class Left, class Right, std::enable_if_t< \
4048 std::is_arithmetic_v<Left> && std::is_arithmetic_v<Right> && \
4049 !std::is_same_v<Left, Right>, int> = 0> \
4050 inline auto function(Left left, Right right) { \
4051 using Value = std::common_type_t<Left, Right>; \
4052 return std::function(Value(left), Value(right)); \
4053 }
4054
4055// std::clamp's same-type template otherwise wins over the mixed-type adapter.
4056// Two non-template bridges make the numeric rule apply equally to const controls.
4057#define KLANG_CONTROL_TERNARY_MATH(function) \
4058 template<class Middle, class Right, std::enable_if_t< \
4059 detail::are_math_values_v<Middle, Right> && \
4060 detail::has_control_v<Middle, Right>, int> = 0> \
4061 inline detail::TernaryMath<detail::function##_operation> function( \
4062 const Middle& middle, const Right& right) { \
4063 return {detail::numeric_snapshot(middle), detail::numeric_snapshot(right)}; \
4064 } \
4065 template<class Left, class Middle, class Right, std::enable_if_t< \
4066 detail::are_math_values_v<Left, Middle, Right> && \
4067 detail::has_control_v<Left, Middle, Right>, int> = 0> \
4068 inline signal function(const Left& left, const Middle& middle, const Right& right) { \
4069 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4070 detail::numeric_snapshot(middle), detail::numeric_snapshot(right)); \
4071 } \
4072 inline signal function(const Control& left, const Control& middle, const Control& right) { \
4073 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4074 detail::numeric_snapshot(middle), detail::numeric_snapshot(right)); \
4075 } \
4076 inline signal function(const ControlMap& left, const ControlMap& middle, const ControlMap& right) { \
4077 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4078 detail::numeric_snapshot(middle), detail::numeric_snapshot(right)); \
4079 }
4080
4081#define KLANG_UNARY_MATH(function) \
4082 using std::function; \
4083 KLANG_UNARY_ADAPTER(function, std::function)
4084
4085 KLANG_UNARY_MATH(abs)
4086 KLANG_UNARY_MATH(sqrt)
4087 KLANG_UNARY_MATH(cbrt)
4088 KLANG_UNARY_MATH(sin)
4089 KLANG_UNARY_MATH(cos)
4090 KLANG_UNARY_MATH(tan)
4091 KLANG_UNARY_MATH(asin)
4092 KLANG_UNARY_MATH(acos)
4093 KLANG_UNARY_MATH(atan)
4094 KLANG_UNARY_MATH(sinh)
4095 KLANG_UNARY_MATH(cosh)
4096 KLANG_UNARY_MATH(tanh)
4097 KLANG_UNARY_MATH(asinh)
4098 KLANG_UNARY_MATH(acosh)
4099 KLANG_UNARY_MATH(atanh)
4100 KLANG_UNARY_MATH(exp)
4101 KLANG_UNARY_MATH(exp2)
4102 KLANG_UNARY_MATH(expm1)
4103 KLANG_UNARY_MATH(log)
4104 KLANG_UNARY_MATH(log2)
4105 KLANG_UNARY_MATH(log10)
4106 KLANG_UNARY_MATH(log1p)
4107 KLANG_UNARY_MATH(floor)
4108 KLANG_UNARY_MATH(ceil)
4109 KLANG_UNARY_MATH(trunc)
4110 KLANG_UNARY_MATH(round)
4111 KLANG_UNARY_MATH(erf)
4112 KLANG_UNARY_MATH(erfc)
4113
4114 /// Alias for trunc, including signal-flow use.
4115 inline float truncate(float input) { return std::trunc(input); }
4116 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
4117 inline auto truncate(TYPE input) { return std::trunc(input); }
4118 KLANG_UNARY_ADAPTER(truncate, std::trunc)
4119
4120#undef KLANG_UNARY_MATH
4121
4122
4123 // Extend standard binary maths with direct signal overloads and function(right) flow stages.
4124#define KLANG_BINARY_MATH(function) \
4125 template<typename RIGHT, std::enable_if_t<std::is_arithmetic_v<RIGHT>, int> = 0> \
4126 inline detail::BinaryMath<detail::function##_operation> function(RIGHT right) { \
4127 return {float(right)}; \
4128 } \
4129 inline signal function(signal left, signal right) { \
4130 return detail::function##_operation{}(float(left), float(right)); \
4131 } \
4132 template<typename RIGHT, std::enable_if_t<std::is_arithmetic_v<RIGHT>, int> = 0> \
4133 inline signal function(signal left, RIGHT right) { \
4134 return detail::function##_operation{}(float(left), float(right)); \
4135 } \
4136 template<typename LEFT, std::enable_if_t<std::is_arithmetic_v<LEFT>, int> = 0> \
4137 inline signal function(LEFT left, signal right) { \
4138 return detail::function##_operation{}(float(left), float(right)); \
4139 } \
4140 KLANG_CONTROL_BINARY_MATH(function)
4141
4142 // Keep ordinary scalar calls visible after adding the Klang overloads below.
4143 using std::pow;
4144 using std::atan2;
4145 using std::hypot;
4146 using std::fmod;
4147 using std::remainder;
4148 using std::copysign;
4149 using std::fdim;
4150 using std::clamp;
4151
4152 // Extend standard ternary maths with direct signal overloads and function(middle,right) flow stages.
4153#define KLANG_TERNARY_MATH(function) \
4154 template<typename MIDDLE, typename RIGHT, \
4155 std::enable_if_t<std::is_arithmetic_v<MIDDLE> && std::is_arithmetic_v<RIGHT>, int> = 0> \
4156 inline detail::TernaryMath<detail::function##_operation> function(MIDDLE middle, RIGHT right) { \
4157 return {float(middle), float(right)}; \
4158 } \
4159 inline signal function(signal left, signal middle, signal right) { \
4160 return detail::function##_operation{}(float(left), float(middle), float(right)); \
4161 } \
4162 template<typename MIDDLE, typename RIGHT, \
4163 std::enable_if_t<std::is_arithmetic_v<MIDDLE> && std::is_arithmetic_v<RIGHT>, int> = 0> \
4164 inline signal function(signal left, MIDDLE middle, RIGHT right) { \
4165 return detail::function##_operation{}(float(left), float(middle), float(right)); \
4166 } \
4167 KLANG_CONTROL_TERNARY_MATH(function)
4168
4169 KLANG_BINARY_MATH(min)
4170 KLANG_BINARY_MATH(max)
4171 KLANG_MIXED_ARITHMETIC_MATH(min)
4172 KLANG_MIXED_ARITHMETIC_MATH(max)
4173 KLANG_BINARY_MATH(pow)
4174 KLANG_BINARY_MATH(atan2)
4175 KLANG_BINARY_MATH(hypot)
4176 KLANG_BINARY_MATH(fmod)
4177 KLANG_BINARY_MATH(remainder)
4178 KLANG_BINARY_MATH(copysign)
4179 KLANG_BINARY_MATH(fdim)
4180 KLANG_TERNARY_MATH(clamp)
4181
4182 /// Alias clamp as clip for signal-flow terminology.
4183 template<typename... ARGS>
4184 inline auto clip(ARGS&&... args) -> decltype(clamp(std::forward<ARGS>(args)...)) {
4185 return clamp(std::forward<ARGS>(args)...);
4186 }
4187
4188
4189 KLANG_BINARY_MATH(mod)
4190
4191#undef KLANG_MIXED_ARITHMETIC_MATH
4192#undef KLANG_CONTROL_BINARY_MATH
4193#undef KLANG_CONTROL_TERNARY_MATH
4194#undef KLANG_BINARY_MATH
4195#undef KLANG_TERNARY_MATH
4196
4197 /// Stateless square and cube functions preserve Klang signals in audio expressions.
4198 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
4199 inline TYPE sqr(TYPE input) { return input * input; }
4200 template<typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>, int> = 0>
4201 inline TYPE cube(TYPE input) { return input * input * input; }
4202
4203 KLANG_UNARY_ADAPTER(sqr, klang::sqr)
4204 KLANG_UNARY_ADAPTER(cube, klang::cube)
4205
4206#undef KLANG_UNARY_ADAPTER
4207
4208 /// Debug text output
4209 struct Console : public Text<16384> {
4210 static std::mutex _lock;
4211 THREAD_LOCAL static Text<16384> last;
4212 int length = 0;
4213
4214 void clear() {
4215 length = 0;
4216 string[0] = 0;
4217 }
4218
4219 Console& operator=(const char* in) {
4220 std::lock_guard<std::mutex> lock(_lock);
4221 length = std::min(capacity(), (int)strlen(in));
4222 memcpy(string, in, length);
4223 string[length] = 0;
4224 return *this;
4225 }
4226
4227 Console& operator=(const Console& in) {
4228 std::lock_guard<std::mutex> lock(_lock);
4229 length = std::min(capacity(), in.length);
4230 memcpy(string, in.string, length);
4231 string[length] = 0;
4232 return *this;
4233 }
4234
4235 Console& operator+=(const char* in) {
4236 std::lock_guard<std::mutex> lock(_lock);
4237 const int len = std::max(0, std::min(capacity() - length, (int)strlen(in)));
4238 memcpy(&string[length], in, len);
4239 length += len;
4240 string[length] = 0;
4241 memcpy(&last, in, len);
4242 last.string[len] = 0;
4243 return *this;
4244 }
4245
4246 bool hasText() const {
4247 return length != 0;
4248 }
4249
4250 int getText(char* buffer) {
4251 //if (!length) return 0;
4252 std::lock_guard<std::mutex> lock(_lock);
4253 const int _length = length;
4254 memcpy(buffer, string, length);
4255 buffer[length] = 0; // null terminator
4256 clear();
4257 return _length;
4258 }
4259 };
4260
4261 inline THREAD_LOCAL Text<16384> Console::last;
4262
4263#if HAS_KLANG_DEBUG
4264#define PROFILE(func, ...) debug.print("%-16s = %fns\n", #func "(" #__VA_ARGS__ ")", debug.profile(1000, func, __VA_ARGS__));
4265#else
4266#define PROFILE(func, ...) ((void)0);
4267#endif
4268
4269 /// The Klang debug interface
4270 struct Debug : Input {
4271
4272 /// Audio buffer for debug output
4273 struct Buffer : private buffer {
4274 using buffer::clear;
4275 using buffer::rewind;
4276#if HAS_KLANG_DEBUG
4277 using buffer::operator++;
4278#else
4279 // Keep direct cursor calls valid without advancing beyond storage.
4280 signal& operator++(int) { return *ptr; }
4281#endif
4282 using buffer::operator signal&;
4283
4284 Buffer() : buffer(16384) {}
4285
4286 enum Content {
4287 Empty = 0,
4288 Notes = 1,
4289 Effect = 2,
4290 Synth = 3,
4291 } content = Empty;
4292
4293 /* void attach(float* buffer, int size) {
4294 Debug::buffer = new klang::buffer(buffer, size);
4295 }
4296
4297 void detach() {
4298 klang::buffer* tmp = buffer;
4299 buffer = nullptr;
4300 delete tmp;
4301 }*/
4302
4303 bool active = false;
4304 int used = 0;
4305
4306 const float* get() {
4307#if HAS_KLANG_DEBUG
4308 if (active) {
4309 active = false;
4310 return data();
4311 }
4312 else {
4313 return nullptr;
4314 }
4315#else
4316 return nullptr;
4317#endif
4318 }
4319
4320 Buffer& operator+=(const signal in) {
4321#if HAS_KLANG_DEBUG
4322 active = true;
4323 buffer::operator+=(in);
4324 return *this;
4325#else
4326 return *this;
4327#endif
4328 }
4329
4330 template<typename TYPE>
4331 Buffer& operator+=(TYPE& in) {
4332#if HAS_KLANG_DEBUG
4333 active = true;
4334 buffer::operator+=(in);
4335 return *this;
4336#else
4337 return *this;
4338#endif
4339 }
4340
4341 signal& operator>>(signal& destination) const {
4342#if HAS_KLANG_DEBUG
4343 destination << *ptr;
4344 return destination;
4345#else
4346 destination = 0;
4347 return destination;
4348#endif
4349 }
4350
4351 operator const signal& () const {
4352#if HAS_KLANG_DEBUG
4353 return *ptr;
4354#else
4355 static const signal silence = 0;
4356 return silence;
4357#endif
4358 }
4359 };
4360
4361 THREAD_LOCAL static Buffer buffer; // support multiple threads/instances
4362
4363 /// Debug console output
4364 Console console;
4365
4366 template <typename Func, typename... Args>
4367 inline static double profile(Func func, Args... args) {
4368#if HAS_KLANG_DEBUG
4369 using namespace std::chrono;
4370
4371 auto start = high_resolution_clock::now();
4372 func(args...);
4373 auto end = high_resolution_clock::now();
4374
4375 auto duration = duration_cast<nanoseconds>(end - start).count();
4376 return (double)duration;
4377#else
4378 return 0;
4379#endif
4380 }
4381
4382 template <typename Func, typename... Args>
4383 inline static double profile(int times, Func func, Args... args) {
4384#if HAS_KLANG_DEBUG
4385 double sum = 0;
4386 while (times--) {
4387 sum += profile(func, args...);
4388 }
4389 return sum / 1000000.0;
4390#else
4391 return 0;
4392#endif
4393 }
4394
4395 /// @cond
4396 struct Session {
4397 Session(float*, int size, Buffer::Content content) {
4398#if HAS_KLANG_DEBUG
4399 //if (buffer) {
4400 //debug.attach(buffer, size);
4401 if (buffer.content != Buffer::Notes)
4402 buffer.clear(size);
4403 buffer.content = content;
4404 buffer.rewind();
4405 //}
4406#else
4407
4408#endif
4409 }
4410 ~Session() {
4411 //debug.detach();
4412 }
4413
4414 bool hasAudio() const {
4415#if HAS_KLANG_DEBUG
4416 return buffer.active;
4417#else
4418 return false;
4419#endif
4420 }
4421 const float* getAudio() const {
4422#if HAS_KLANG_DEBUG
4423 return buffer.get();
4424#else
4425 return nullptr;
4426#endif
4427 }
4428 };
4429 /// @endcond
4430
4431 void print(const char* format, ...) {
4432#if HAS_KLANG_DEBUG
4433 if (console.length < 10000) {
4434 THREAD_LOCAL static char string[1024] = { 0 };
4435 string[0] = 0;
4436 va_list args; // Initialize the variadic argument list
4437 va_start(args, format); // Start variadic argument processing
4438 vsnprintf(string, 1024, format, args); // Safely format the string into the buffer
4439 va_end(args); // Clean up the variadic argument list
4440 console += string;
4441 }
4442#else
4443
4444#endif
4445 }
4446
4447 void printOnce(const char* format, ...) {
4448#if HAS_KLANG_DEBUG
4449 if (console.length < 1024) {
4450 THREAD_LOCAL static char string[1024] = { 0 };
4451 string[0] = 0;
4452 va_list args; // Initialize the variadic argument list
4453 va_start(args, format); // Start variadic argument processing
4454 vsnprintf(string, 1024, format, args); // Safely format the string into the buffer
4455 va_end(args); // Clean up the variadic argument list
4456
4457 if (console.last != string)
4458 console += string;
4459 }
4460#else
4461
4462#endif
4463 }
4464
4465 bool hasText() const {
4466#if HAS_KLANG_DEBUG
4467 return console.hasText();
4468#else
4469 return false;
4470#endif
4471 }
4472
4473 int getText(char* buffer) {
4474#if HAS_KLANG_DEBUG
4475 return console.getText(buffer);
4476#else
4477 if (buffer) buffer[0] = 0;
4478 return 0;
4479#endif
4480 }
4481
4482 operator const signal& () const {
4483#if HAS_KLANG_DEBUG
4484 return buffer.operator const klang::signal & ();
4485#else
4486 return passthrough();
4487#endif
4488 }
4489
4490 using Input::input;
4491#if !HAS_KLANG_DEBUG
4492 // Keep inline debug taps transparent without touching shared Input::in.
4493 static signal& passthrough() {
4494 static thread_local signal value = 0;
4495 return value;
4496 }
4497 void input(const signal& value) override { passthrough() = value; }
4498 void operator<<(const signal& value) override { passthrough() = value; }
4499#endif
4500 void input() override {
4501#if HAS_KLANG_DEBUG
4502 buffer += in;
4503#else
4504
4505#endif
4506 }
4507 };
4508
4509 //inline static Debug::Buffer& operator>>(const signal source, Debug& debug) {
4510 // return debug.buffer += source;
4511 //}
4512
4513 //template<typename TYPE>
4514 //inline static Debug::Buffer& operator>>(TYPE& source, Debug& debug) {
4515 // return debug.buffer += source;
4516 //}
4517
4518 static Debug debug;
4519 inline THREAD_LOCAL Debug::Buffer Debug::buffer; //
4520 inline std::mutex Console::_lock;
4521
4522 /// @cond
4523 template <typename TYPE>
4524 struct Result {
4525 TYPE* y = nullptr;
4526 int i = 0;
4527 TYPE sum = 0;
4528
4529 Result(TYPE* array, int index) : y(&array[index]), i(index) {}
4530
4531 TYPE& operator[](int index) {
4532 return *(y + index);
4533 }
4534
4535 operator TYPE const () { return *y; }
4536
4537 Result& operator=(const TYPE& in) {
4538 *y = in;
4539 return *this;
4540 }
4541
4542 TYPE& operator++(int) { i++; return *++y; }
4543 };
4544 /// @endcond
4545
4546 /// Lookup table object
4547 template<typename TYPE, int SIZE>
4548 struct Table : public Array<TYPE, SIZE> {
4549 typedef Array<TYPE, SIZE> Array;
4550 typedef Result<TYPE> Result;
4551
4552 using Array::add;
4553
4554 /// Construct and fill a table from a value-returning or Result-writing callable.
4555 template<typename FUNCTION, std::enable_if_t<
4556 std::is_invocable_r_v<TYPE, FUNCTION&, TYPE> ||
4557 std::is_invocable_v<FUNCTION&, TYPE, Result&>, int> = 0>
4558 Table(FUNCTION function) {
4559 Array::count = SIZE;
4560 Result result(Array::items, 0);
4561 for (int x = 0; x < SIZE; x++)
4562 if constexpr (std::is_invocable_r_v<TYPE, FUNCTION&, TYPE>)
4563 Array::items[x] = function((TYPE)x);
4564 else {
4565 function((TYPE)x, result);
4566 result.sum += Array::items[x];
4567 if (x + 1 < SIZE) result++;
4568 }
4569 }
4570
4571 // double argument
4572 Table(TYPE(*function)(TYPE, TYPE), TYPE arg) {
4573 Array::count = SIZE;
4574 for (int x = 0; x < SIZE; x++)
4575 Array::items[x] = function(x, arg);
4576 }
4577
4578 Table(std::initializer_list<TYPE> values) {
4579 for (TYPE value : values)
4580 add(value);
4581 }
4582
4583 using Array::operator[];
4584 TYPE operator[](float index) {
4585 if (index < 0) return Array::items[0];
4586 else if (index >= (SIZE - 1)) return Array::items[SIZE - 1];
4587 else {
4588 const float x = std::floor(index);
4589 const int i = int(x);
4590 const float dx = index - x;
4591 const float dy = Array::items[i + 1] - Array::items[i];
4592 return Array::items[i] + dx * dy;
4593 }
4594 }
4595 };
4596
4597 /// Audio delay object (fixed size)
4598 template<int SIZE>
4599 struct Delay : public Modifier {
4600 using Modifier::in;
4601 using Modifier::out;
4602
4603 buffer buffer;
4604 float time = 1;
4605 int position = 0;
4606
4607 Delay() : buffer(SIZE + 1, 0) { clear(); }
4608
4609 void clear() {
4610 buffer.clear();
4611 }
4612
4613 void input() override {
4614 buffer++ = in;
4615 position++;
4616 if (position == SIZE) {
4617 buffer.rewind();
4618 position = 0;
4619 }
4620 }
4621
4622 signal tap(int delay) const {
4623 int read = (position - 1) - delay;
4624 if (read < 0)
4625 read += SIZE;
4626 return buffer[read];
4627 }
4628
4629 signal tap(float delay) const {
4630 // Calculate the read position
4631 float read = static_cast<float>(position - 1) - delay;
4632 if (read < 0.f)
4633 read += SIZE;
4634
4635 // Separate integer and fractional parts
4636 const int i = static_cast<int>(read); // Integer part
4637 const float fraction = read - i; // Fractional part
4638
4639 // Use modulo to get the next index without branching
4640 const int j = (i + 1) % SIZE; // Next index in circular buffer
4641
4642 // Linear interpolation: buffer[i] + fraction * (buffer[j] - buffer[i])
4643 return buffer[i] + fraction * (buffer[j] - buffer[i]);
4644 }
4645
4646 signal lagrange(float delay) const {
4647 // Calculate the read position
4648 float read = static_cast<float>(position - 1) - delay;
4649 if (read < 0.f)
4650 read += SIZE;
4651
4652 // Separate integer and fractional parts
4653 int i = static_cast<int>(read); // Integer part
4654 float x = read - i; // Fractional part (0 ? x < 1)
4655
4656 // Get four surrounding indices using modulo for circular buffer
4657 int i0 = (i - 1 + SIZE) % SIZE;
4658 int i1 = i; // Main sample
4659 int i2 = (i + 1) % SIZE;
4660 int i3 = (i + 2) % SIZE;
4661
4662 // Read corresponding samples
4663 float y0 = buffer[i0];
4664 float y1 = buffer[i1];
4665 float y2 = buffer[i2];
4666 float y3 = buffer[i3];
4667
4668 // Compute Lagrange interpolation (third-order)
4669 float c0 = (-x * (x - 1) * (x - 2)) / 6.0f;
4670 float c1 = ((x + 1) * (x - 1) * (x - 2)) / 2.0f;
4671 float c2 = (-x * (x + 1) * (x - 2)) / 2.0f;
4672 float c3 = (x * (x + 1) * (x - 1)) / 6.0f;
4673
4674 return c0 * y0 + c1 * y1 + c2 * y2 + c3 * y3;
4675 }
4676
4677
4678 signal tap() const {
4679 // Use modulo to get the next index without branching
4680 const int i = last.position;
4681 const int j = (i + 1) % SIZE; // Next index in circular buffer
4682
4683 // Linear interpolation: buffer[i] + fraction * (buffer[j] - buffer[i])
4684 return buffer[i] + last.fraction * (buffer[j] - buffer[i]);
4685 }
4686
4687 virtual void process() override {
4688 out = tap();
4689 last.position = (last.position + 1) % SIZE;
4690 }
4691
4692 struct Tap {
4693 int position;
4694 float fraction;
4695 } last;
4696
4697 virtual void set(param samples) override {
4698 time = samples < SIZE ? (float)samples : SIZE;
4699
4700 float read = static_cast<float>(position - 1) - time;
4701 if (read < 0.f)
4702 read += SIZE;
4703
4704 last.position = static_cast<int>(read); // Integer part
4705 last.fraction = read - last.position; // Fractional part
4706 }
4707
4708 template<typename TIME>
4709 signal operator()(TIME& delay) {
4710 if constexpr (std::is_integral_v<TIME>)
4711 return tap((int)delay);
4712 else if constexpr (std::is_floating_point_v<TIME>)
4713 return tap((float)delay);
4714 else
4715 return tap((signal)delay);
4716 }
4717
4718 template<typename TIME>
4719 signal operator()(const TIME& delay) {
4720 if constexpr (std::is_integral_v<TIME>)
4721 return tap((int)delay);
4722 else if constexpr (std::is_floating_point_v<TIME>)
4723 return tap((float)delay);
4724 else
4725 return tap((signal)delay);
4726 }
4727
4728 unsigned int max() const { return SIZE; }
4729 };
4730
4731 /// Audio delay object (resizable)
4732 template<>
4733 struct Delay<0> : public Modifier {
4734 using Modifier::in;
4735 using Modifier::out;
4736
4737 buffer* buffer;
4738 float time = 1;
4739 int position = 0;
4740 int SIZE = 0;
4741
4742 Delay() : buffer(new klang::buffer(1, 0)) { clear(); }
4743
4744 void clear() {
4745 buffer->clear();
4746 }
4747
4748 void resize(int samples) {
4749 if (samples != SIZE) {
4750 SIZE = samples;
4751 klang::buffer* new_buffer = new klang::buffer(SIZE + 1, 0);
4752 std::swap(buffer, new_buffer);
4753 delete new_buffer;
4754 }
4755 }
4756
4757 void input() override {
4758 (*buffer)++ = in;
4759 position++;
4760 if (position == SIZE) {
4761 buffer->rewind();
4762 position = 0;
4763 }
4764 }
4765
4766 signal tap(int delay) const {
4767 int read = (position - 1) - delay;
4768 if (read < 0)
4769 read += SIZE;
4770 return (*buffer)[read];
4771 }
4772
4773 signal tap(float delay) const {
4774 // Calculate the read position
4775 float read = static_cast<float>(position - 1) - delay;
4776 if (read < 0.f)
4777 read += SIZE;
4778
4779 // Separate integer and fractional parts
4780 const int i = static_cast<int>(read); // Integer part
4781 const float fraction = read - i; // Fractional part
4782
4783 // Use modulo to get the next index without branching
4784 const int j = (i + 1) % SIZE; // Next index in circular buffer
4785
4786 // Linear interpolation: buffer[i] + fraction * (buffer[j] - buffer[i])
4787 return (*buffer)[i] + fraction * ((*buffer)[j] - (*buffer)[i]);
4788 }
4789
4790 signal tap() const {
4791 // Use modulo to get the next index without branching
4792 const int i = last.position;
4793 const int j = (i + 1) % SIZE; // Next index in circular buffer
4794
4795 // Linear interpolation: buffer[i] + fraction * (buffer[j] - buffer[i])
4796 return (*buffer)[i] + last.fraction * ((*buffer)[j] - (*buffer)[i]);
4797 }
4798
4799 virtual void process() override {
4800 out = tap();
4801 last.position = (last.position + 1) % SIZE;
4802 }
4803
4804 struct Tap {
4805 int position;
4806 float fraction;
4807 } last;
4808
4809 virtual void set(param samples) override {
4810 time = samples < SIZE ? (float)samples : SIZE;
4811
4812 float read = static_cast<float>(position - 1) - time;
4813 if (read < 0.f)
4814 read += SIZE;
4815
4816 last.position = static_cast<int>(read); // Integer part
4817 last.fraction = read - last.position; // Fractional part
4818 }
4819
4820 template<typename TIME>
4821 signal operator()(TIME& delay) {
4822 if constexpr (std::is_integral_v<TIME>)
4823 return tap((int)delay);
4824 else if constexpr (std::is_floating_point_v<TIME>)
4825 return tap((float)delay);
4826 else
4827 return tap((signal)delay);
4828 }
4829
4830 template<typename TIME>
4831 signal operator()(const TIME& delay) {
4832 if constexpr (std::is_integral_v<TIME>)
4833 return tap((int)delay);
4834 else if constexpr (std::is_floating_point_v<TIME>)
4835 return tap((float)delay);
4836 else
4837 return tap((signal)delay);
4838 }
4839
4840 unsigned int max() const { return SIZE; }
4841 };
4842
4843 /// Wavetable-based oscillator
4844 class Wavetable : public Oscillator {
4845 using Oscillator::set;
4846 protected:
4847 buffer buffer;
4848 const int size;
4849 public:
4850 Wavetable(int size = 2048) : buffer(size), size(size) {}
4851
4852 template<typename TYPE>
4853 Wavetable(TYPE oscillator, int size = 2048) : buffer(size), size(size) {
4854 operator=(oscillator);
4855 }
4856
4857 signal& operator[](int index) {
4858 return buffer[index];
4859 }
4860
4861 template<typename TYPE>
4862 Wavetable& operator=(TYPE& oscillator) {
4863 oscillator.set(fs / size);
4864 for (int s = 0; s < size; s++)
4865 buffer[s] = oscillator;
4866 return *this;
4867 }
4868
4869 virtual void set(param frequency) override {
4870 Oscillator::frequency = frequency;
4871 increment = frequency * (size / fs);
4872 }
4873
4874 virtual void set(param frequency, param phase) override {
4875 position = phase * float(size);
4876 set(frequency);
4877 }
4878
4879 virtual void set(relative phase) override {
4880
4881 offset = phase * float(size);
4882 }
4883
4884 virtual void set(param frequency, relative phase) override {
4885 set(frequency);
4886 set(phase);
4887 }
4888
4889 void process() override {
4890 position += { increment, size };
4891 out = buffer[position + offset /*klang::increment(offset, size)*/];
4892 }
4893 };
4894
4895 /// Sample-based signal generator with variable-rate playback.
4896 class Sample : public Generator {
4897 using Generator::set;
4898
4899 protected:
4900 buffer buffer;
4901 int size = 0;
4902
4903 public:
4904 using Generator::operator();
4905
4906 /// Optional root pitch in Hz and recording sample rate in samples per second.
4907 struct Info {
4908 Frequency frequency = 0;
4909 SampleRate samplerate = 0;
4910 } info;
4911
4912 /// Select one-shot or looping playback.
4913 enum Mode { OneShot, Looped };
4914 Mode mode = OneShot;
4915
4916 /// Buffer assignment with optional recording metadata and playback mode.
4917 struct Binding {
4918 const klang::buffer& source;
4919 std::optional<Info> info;
4920 std::optional<Mode> mode;
4921
4922 Binding(const klang::buffer& source, Info info, std::optional<Mode> mode = std::nullopt)
4923 : source(source), info(info), mode(mode) {}
4924
4925 template<typename TYPE, std::enable_if_t<std::is_same_v<TYPE, Mode>, int> = 0>
4926 Binding(const klang::buffer& source, TYPE mode)
4927 : source(source), mode(mode) {}
4928 };
4929
4930 Sample() : buffer(nullptr, 0) {}
4931
4932 signal& operator[](int index) {
4933 return buffer[index];
4934 }
4935
4936 /// Borrow the sample storage and return to the start of the buffer.
4937 Sample& operator=(const klang::buffer& source) {
4938 size = source.size;
4939 if (size > 0) buffer.attach(source, size);
4940 reset();
4941 return *this;
4942 }
4943
4944 /// Change the mode without moving the playback position.
4945 Sample& operator=(Mode mode) {
4946 this->mode = mode;
4947 return *this;
4948 }
4949
4950 Sample& operator=(const Binding& binding) {
4951 if (binding.info) info = *binding.info;
4952 if (binding.mode) mode = *binding.mode;
4953 return *this = binding.source;
4954 }
4955
4956 /// Set the playback speed, with one representing the original rate.
4957 void set(param rate) override {
4958 if (finite(rate.value)) this->rate = rate.value;
4959 }
4960
4961 /// Set playback speed from a target frequency and the available metadata.
4962 template<typename TYPE, std::enable_if_t<std::is_same_v<TYPE, Frequency>, int> = 0>
4963 void set(TYPE frequency) {
4964 const float root = info.frequency.value;
4965 const float recorded = info.samplerate.f;
4966 const float reference = positive(root) ? root : positive(recorded) ? recorded : 0;
4967 if (reference > 0 && finite(frequency.value))
4968 rate = double(frequency.value) / reference;
4969 }
4970
4971 Sample& operator()(Frequency frequency) {
4972 set(frequency);
4973 return *this;
4974 }
4975
4976 /// Set playback speed and seek to a time in seconds.
4977 void set(param rate, param time) override {
4978 set(rate);
4979 if (finite(time.value)) position = double(time.value) * sourceRate();
4980 }
4981
4982 /// Set a read offset in seconds.
4983 void set(relative time) override {
4984 if (finite(time.value)) offset = double(time.value) * sourceRate();
4985 }
4986
4987 void set(param rate, relative time) override {
4988 set(rate);
4989 set(time);
4990 }
4991
4992 /// Rewind the playback position.
4993 void reset() { position = 0; }
4994
4995 void process() override {
4996 const bool looped = mode == Looped;
4997 double read = position + offset;
4998 if (size == 0 || (!looped && (read < 0 || read >= size))) {
4999 out = 0;
5000 return;
5001 }
5002 if (looped) read = wrap(read);
5003 const int index = int(read);
5004 const int next = index + 1 < size ? index + 1 : (looped ? 0 : index);
5005 const double fraction = read - index;
5006 out = buffer[index] * (1 - fraction) + buffer[next] * fraction;
5007 const float host = fs.f;
5008 const float recorded = info.samplerate.f;
5009 const double step = positive(recorded) && positive(host) ? rate * recorded / host : rate;
5010 position += step;
5011 if (looped) position = wrap(position);
5012 }
5013
5014 private:
5015 double rate = 1, position = 0, offset = 0;
5016
5017 static bool finite(float value) {
5018 std::uint32_t bits;
5019 std::memcpy(&bits, &value, sizeof(bits));
5020 return (bits & 0x7f800000u) != 0x7f800000u;
5021 }
5022
5023 static bool positive(float value) { return finite(value) && value > 0; }
5024
5025 float sourceRate() const {
5026 if (positive(info.samplerate.f)) return info.samplerate.f;
5027 return positive(fs.f) ? fs.f : 0;
5028 }
5029
5030 double wrap(double index) const {
5031 if (index >= 0 && index < size) return index;
5032 index = std::fmod(index, double(size));
5033 if (index < 0) index += size;
5034 return index < size ? index : 0;
5035 }
5036 };
5037 inline constexpr Sample::Mode OneShot = Sample::OneShot;
5038 inline constexpr Sample::Mode Looped = Sample::Looped;
5039
5040 /// Envelope object
5041 class Envelope : public Generator {
5042 using Generator::set;
5043
5044 public:
5045
5046 struct Follower;
5047
5048 /// Abstract envelope ramp type
5049 struct Ramp : public Generator {
5050 float target;
5051 float rate;
5052 bool active = false;
5053 public:
5054
5055 // Create a null ramp (full signal)
5056 Ramp(float value = 1.f) {
5057 setValue(value);
5058 }
5059
5060 // Create a ramp from start to target over time (in seconds)
5061 Ramp(float start, float target, float time) {
5062 setValue(start);
5063 setTarget(target);
5064 setTime(time);
5065 }
5066
5067 virtual ~Ramp() {}
5068
5069 // Is ramp currently processing (ramping)?
5070 bool isActive() const {
5071 return active;
5072 }
5073
5074 // Set a new target (retains rate)
5075 virtual void setTarget(float target) {
5076 Ramp::target = target;
5077 active = (out != target);
5078 }
5079
5080 // Immediately jump to value (disables ramp)
5081 virtual void setValue(float value) {
5082 out = value;
5083 Ramp::target = value;
5084 active = false;
5085 }
5086
5087 // Set rate of change (per sample)
5088 virtual void setRate(float rate) { Ramp::rate = rate; }
5089
5090 // Set rate of change (by duration)
5091 virtual void setTime(float time) { Ramp::rate = time ? 1.f / (time * fs) : 0; }
5092
5093 // Return the current output and advanced the ramp
5094 virtual signal operator++(int) = 0;
5095
5096 void process() override { /* do nothing -> only process on ++ */ }
5097 };
5098
5099 /// Linear envelope ramp (default)
5100 struct Linear : public Ramp {
5101
5102 // Return the current output and process the next
5103 signal operator++(int) override {
5104 const signal output = out;
5105
5106 if (active) {
5107 if (target > out) {
5108 out += rate;
5109 if (out >= target) {
5110 out = target;
5111 active = false;
5112 }
5113 }
5114 else {
5115 out -= rate;
5116 if (out <= target) {
5117 out = target;
5118 active = false;
5119 }
5120 }
5121 }
5122
5123 return output;
5124 }
5125 };
5126
5127 /// Envelope stage
5128 enum Stage { Sustain, Release, Off };
5129 /// Envelope mode
5130 enum Mode { Time, Rate };
5131
5132 /// Envelope point (x,y)
5133 struct Point {
5134 float x, y;
5135
5136 Point() : x(0), y(0) {}
5137
5138 template<typename T1, typename T2>
5139 Point(T1 x, T2 y) : x(float(x)), y(float(y)) {}
5140 };
5141
5142 /// @cond
5143 // Linked-list of points (for inline initialisation)
5144 struct Points : public Point {
5145 Points(float x, float y) {
5146 Point::x = x;
5147 Point::y = y;
5148 next = NULL;
5149 }
5150 ~Points() {
5151 delete next;
5152 }
5153
5154 Points& operator()(float x, float y) {
5155 last().next = new Points(x, y);
5156 return *this;
5157 }
5158
5159 Points& last() {
5160 return next ? next->last() : *this;
5161 }
5162
5163 int count() const {
5164 return next ? 1 + next->count() : 1;
5165 }
5166
5167 Points* next;
5168 };
5169 /// @endcond
5170
5171 /// Envelope loop
5172 struct Loop {
5173 Loop(int from = -1, int to = -1) : start(from), end(to) {}
5174
5175 void set(int from, int to) { start = from; end = to; }
5176 void reset() { start = end = -1; }
5177
5178 bool isActive() const { return start != -1 && end != -1; }
5179
5180 int start;
5181 int end;
5182 };
5183
5184 // Default Envelope (full signal)
5185 Envelope() : ramp(new Linear()) { set(Points(0.f, 1.f)); }
5186
5187 // Creates a new envelope from a list of points, e.g. Envelope env = Envelope::Points(0,1)(1,0);
5188 Envelope(const Points& points) : ramp(new Linear()) { set(points); }
5189
5190 // Creates a new envelope from a list of points, e.g. Envelope env = { { 0,1 }, { 1,0 } };
5191 Envelope(std::initializer_list<Point> points) : ramp(new Linear()) { set(points); }
5192
5193 // Creates a copy of an envelope from another envelope
5194 Envelope(const Envelope& in) : ramp(new Linear()) { set(in.points); }
5195
5196 virtual ~Envelope() {}
5197
5198 // Checks if the envelope is at a specified stage (Sustain, Release, Off)
5199 bool operator==(Stage stage) const { return Envelope::stage == stage; }
5200 bool operator!=(Stage stage) const { return Envelope::stage != stage; }
5201
5202 //operator float() const { return out; }
5203
5204 // assign points (without recreating envelope)
5205 Envelope& operator=(std::initializer_list<Point> points) {
5206 set(points);
5207 return *this;
5208 }
5209
5210 // Sets the envelope based on an array of points
5211 void set(const std::vector<Point>& points) {
5212 Envelope::points = points;
5213 initialise();
5214 }
5215
5216 // Sets the envelope from a list of points, e.g. env.set( Envelope::Points(0,1)(1,0) );
5217 void set(const Points& point) {
5218 points.clear();
5219
5220 const Points* pPoint = &point;
5221 while (pPoint) {
5222 points.push_back(*pPoint);
5223 pPoint = pPoint->next;
5224 }
5225
5226 initialise();
5227 }
5228
5229 // Converts envelope points based on relative time to absolute time
5230 void sequence() {
5231 float time = 0.f;
5232 for (Point& point : points) {
5233 const float delta = point.x;
5234 time += delta + 0.00001f;
5235 point.x = time;
5236 }
5237 initialise();
5238 }
5239
5240 // Sets an envelope loop between two points
5241 void setLoop(int startPoint, int endPoint) {
5242 if (startPoint >= 0 && endPoint < points.size())
5243 loop.set(startPoint, endPoint);
5244 }
5245
5246 // Retrieve value at time (in seconds)
5247 signal at(param time) const {
5248 if (points.empty()) return 0;
5249 Point last = { 0, points[0].y };
5250 for (const Point& point : points) {
5251 if (point.x >= time) {
5252 const float dx = point.x - last.x;
5253 const float dy = point.y - last.y;
5254 const float x = time - last.x;
5255 return dx == 0 ? last.y : (last.y + x * dy / dx);
5256 }
5257 last = point;
5258 }
5259 return points.back().y;
5260 }
5261
5262 // Resets the envelope loop
5263 void resetLoop() {
5264 loop.reset();
5265 if (stage == Sustain && (point + 1) < points.size())
5266 setTarget(points[point + 1], points[point].x);
5267 }
5268
5269 // Sets the current stage of the envelope
5270 void setStage(Stage stage) { this->stage = stage; }
5271
5272 // Returns the current stage of the envelope
5273 const Stage getStage() const { return stage; }
5274
5275 // Returns the total length of the envelope (ignoring loops)
5276 float getLength() const { return points.size() ? points[points.size() - 1].x : 0.f; }
5277
5278 // Trigger the release of the envelope
5279 virtual void release(float time, float level = 0.f) {
5280 stage = Release;
5281 setTarget({ time, level }, 0);
5282 //ramp->setTime(time);
5283 //ramp->setTarget(0.f);
5284 }
5285
5286 // Returns true if the envelope has finished (is off)
5287 bool finished() const {
5288 return getStage() == Stage::Off;
5289 }
5290
5291 // Initialise a new envelope and clear any previous loop.
5292 void initialise() {
5293 loop.reset();
5294 restart();
5295 }
5296
5297 /// Restart from the first point, preserving the configured loop.
5298 void restart() {
5299 point = 0;
5300 time = 0;
5301 timeInc = 1.0f / fs;
5302 stage = Sustain;
5303 if (points.size()) {
5304 out = points[0].y;
5305 ramp->setValue(points[0].y);
5306 if (points.size() > 1)
5307 setTarget(points[1], points[0].x);
5308 }
5309 else {
5310 out = 1.0f;
5311 ramp->setValue(1.0f);
5312 }
5313 }
5314
5315 // Scales the envelope duration to specified length
5316 void resize(float length) {
5317 const float old_length = getLength();
5318 if (old_length == 0.0)
5319 return;
5320
5321 const float multiplier = length / (fs * old_length);
5322 std::vector<Point>::iterator point = points.begin();
5323 while (point != points.end()) {
5324 point->x *= multiplier;
5325 point++;
5326 }
5327
5328 initialise();
5329 }
5330
5331 // Set the current envelope target
5332 void setTarget(const Point& point, float time = 0.0) {
5333 (this->*setTargetFunction)(point, time);
5334 }
5335
5336 // Returns the output of the envelope and advances the envelope (for backwards compatibility)
5337 signal& operator++(int) {
5338 this->process();
5339 return out;
5340 }
5341
5342 void process() {
5343 out = (*ramp)++;
5344
5345 switch (stage) {
5346 case Sustain:
5347 time += timeInc;
5348 if (!ramp->isActive()) { // envelop segment end reached
5349 if (loop.isActive() && (point + 1) >= loop.end) {
5350 point = loop.start;
5351 ramp->setValue(points[point].y);
5352 if (loop.start != loop.end)
5353 setTarget(points[point + 1], points[point].x);
5354 }
5355 else if ((point + 1) < points.size()) {
5356 if (mode() == Rate || time >= points[point + 1].x) { // reached target point
5357 point++;
5358 ramp->setValue(points[point].y); // make sure exact value is set
5359
5360 if ((point + 1) < points.size()) // new target point?
5361 setTarget(points[point + 1], points[point].x);
5362 }
5363 }
5364 else {
5365 stage = Off;
5366 }
5367 } break;
5368 case Release:
5369 if (!ramp->isActive()) //if(out == 0.0)
5370 stage = Off;
5371 break;
5372 case Off:
5373 break;
5374 }
5375 }
5376
5377 // Retrieve a specified envelope point (read-only)
5378 const Point& operator[](int point) const {
5379 return points[point];
5380 }
5381
5382 // Set the Ramp class (default: Envelope::Linear)
5383 void set(Ramp* ramp) {
5384 Envelope::ramp = std::shared_ptr<Ramp>(ramp);
5385 initialise();
5386 }
5387
5388 void setMode(Mode mode) {
5389 if (mode == Time)
5390 setTargetFunction = &Envelope::setTargetTime;
5391 else
5392 setTargetFunction = &Envelope::setTargetRate;
5393 }
5394
5395 Mode mode() const { return setTargetFunction == &Envelope::setTargetTime ? Time : Rate; }
5396
5397 protected:
5398
5399 void (Envelope::* setTargetFunction)(const Point& point, float time) = &Envelope::setTargetTime;
5400
5401 void setTargetTime(const Point& point, float time = 0.0) {
5402 this->time = time;
5403 ramp->setTarget(point.y);
5404 ramp->setRate(abs(point.y - ramp->out) / ((point.x - time) * fs));
5405 }
5406
5407 void setTargetRate(const Point& point, float rate = 0.0) {
5408 this->time = 0;
5409 if (point.x == 0) {
5410 ramp->setValue(point.y);
5411 }
5412 else {
5413 ramp->setTarget(point.y);
5414 ramp->setRate(point.x);
5415 }
5416 }
5417
5418 std::vector<Point> points;
5420
5422 float time, timeInc;
5424
5425 std::shared_ptr<Ramp> ramp;
5426 };
5427
5428 /// Attack-Decay-Sustain-Release Envelope
5429 struct ADSR : public Envelope {
5430 private:
5431 using Envelope::Follower;
5432 public:
5433 param A, D, S, R;
5434
5435 enum Mode { Time, Rate } mode = Time;
5436
5437 ADSR() { set(0.5, 0.5, 1, 0.5); }
5438
5439 void set(param attack, param decay, param sustain, param release) override {
5440 A = attack;
5441 D = decay + 0.005f;
5442 S = sustain;
5443 R = release + 0.005f;
5444
5445 points.resize(3);
5446 points[0] = { 0, 0 };
5447 points[1] = { A, 1 };
5448 points[2] = { A + D, S };
5449
5450 initialise();
5451 setLoop(2, 2);
5452 }
5453
5454 void release(float time = 0.f, float level = 0.f) override {
5455 Envelope::release(time ? time : float(R), level);
5456 }
5457
5458 bool operator==(Envelope::Stage stage) const {
5459 return getStage() == stage;
5460 }
5461 };
5462
5463 /// FM operator
5464 template<class OSCILLATOR>
5465 struct Operator : public OSCILLATOR, public Input {
5467 Amplitude amp = 1.f;
5468
5469 Operator& operator()(param f) { OSCILLATOR::set(f); return *this; }
5470 Operator& operator()(param f, relative phase) { OSCILLATOR::set(f, phase); return *this; }
5471 Operator& operator()(relative phase) { OSCILLATOR::set(phase); return *this; }
5472
5473 virtual Operator& operator=(const Envelope::Points& points) {
5474 env = points;
5475 return *this;
5476 }
5477
5478 virtual Operator& operator=(const Envelope& points) {
5479 env = points;
5480 return *this;
5481 }
5482
5484 Operator::amp = amp;
5485 return *this;
5486 }
5487
5488 virtual void process() override {
5489 OSCILLATOR::set(+in);
5490 OSCILLATOR::process();
5491 OSCILLATOR::out *= env++ * amp;
5492 }
5493
5494 inline Operator& operator>>(Operator& carrier) {
5495 carrier << *this;
5496 return carrier;
5497 }
5498 };
5499
5500 template<class OSCILLATOR>
5501 inline const signal& operator>>(klang::signal modulator, Operator<OSCILLATOR>& carrier) {
5502 carrier << modulator;
5503 return carrier;
5504 }
5505
5506 /// Base class for UI / MIDI controll
5507 struct Controller {
5508 protected:
5509 virtual event control(int index, float value) {};
5510 virtual event preset(int index) {};
5511 virtual event midi(int status, int byte1, int byte2) {};
5512 public:
5513 virtual void onControl(int index, float value) { this->control(index, value); };
5514 virtual void onPreset(int index) { this->preset(index); };
5515 virtual void onMIDI(int status, int byte1, int byte2) { this->midi(status, byte1, byte2); }
5516 };
5517
5518 /// Base class for mini-plugin
5519 struct Plugin : public Controller {
5520 virtual ~Plugin() {}
5521
5522 template<typename DERIVED, typename... ARGS>
5523 static DERIVED* Create(ARGS&&... args) {
5524 static_assert(std::is_base_of_v<Plugin, DERIVED>);
5525 DERIVED* p = new DERIVED();
5526 p->controls.set(std::forward<ARGS>(args)...);
5527 return p;
5528 }
5529
5532 };
5533
5534 /// Effect mini-plugin (mono)
5535 struct Effect : public Plugin, public Modifier {
5536 virtual ~Effect() {}
5537
5538 virtual void prepare() {};
5539 virtual void process() { out = in; }
5540 virtual void process(buffer buffer) {
5541 this->prepare();
5542 while (!buffer.finished()) {
5543 input(buffer);
5544 this->process();
5545 buffer++ = out;
5546#if HAS_KLANG_DEBUG
5547 debug.buffer++;
5548#endif
5549 }
5550 }
5551 };
5552
5553 /// Sound mini-plugin (mono). Input is available through `in`, but is silent
5554 /// unless a model explicitly routes it to `out` or `debug`.
5555 struct Sound : Effect {
5556 using Effect::process;
5557 void process() override { out = 0; }
5558 };
5559
5560 /// Base class for synthesiser notes
5561 template<class SYNTH>
5562 class NoteBase : public Controller {
5563 SYNTH* synth;
5564
5565 class Controls {
5566 klang::Controls* controls = nullptr;
5567 public:
5568 Controls& operator=(klang::Controls& controls) { Controls::controls = &controls; return *this; }
5569 //signal& operator[](int index) { return controls->operator[](index).operator signal & (); }
5570 //const signal& operator[](int index) const { return controls->operator[](index).operator const signal & (); }
5571 Control& operator[](int index) { return controls->operator[](index); }
5572 const Control& operator[](int index) const { return controls->operator[](index); }
5573 unsigned int size() { return controls ? controls->size() : 0; }
5574 };
5575
5576 protected:
5577 virtual event on(Pitch p, Velocity v) {}
5578 virtual event off(Velocity v = 0) { stage = Off; }
5579
5580 //SYNTH* getSynth() { return synth; }
5581 auto getSynth() { return static_cast<std::remove_pointer_t<decltype(synth)>*>(synth); }
5582 public:
5585 Controls controls;
5586
5587 NoteBase() : synth(nullptr) {}
5588 virtual ~NoteBase() {}
5589
5590 void attach(SYNTH* synth) {
5591 NoteBase::synth = synth;
5592 controls = synth->controls;
5593 init();
5594 }
5595
5596 virtual void init() {}
5597
5598 virtual void start(Pitch p, Velocity v) {
5599 stage = Onset;
5600 pitch = p;
5601 velocity = v;
5602 on(pitch, velocity);
5603 stage = Sustain;
5604 }
5605
5606 virtual bool release(Velocity v = 0) {
5607 if (stage == Off)
5608 return true;
5609
5610 if (stage != Release) {
5611 stage = Release;
5612 off(v);
5613 }
5614
5615 return stage == Off;
5616 }
5617
5618 virtual bool stop(Velocity v = 0) {
5619 stage = Off;
5620 return true;
5621 }
5622
5623 bool finished() const { return stage == Off; }
5624
5625 enum Stage { Onset, Sustain, Release, Off } stage = Off;
5626
5627 virtual void controlChange(int controller, int value) { midi(0xB0, controller, value); };
5628 };
5629
5630 struct Synth;
5631
5632 /// Synthesiser note (mono)
5633 struct Note : public NoteBase<Synth>, public Generator {
5634 virtual void prepare() {}
5635 virtual void process() override = 0;
5636 virtual bool process(buffer buffer) {
5637 this->prepare();
5638 while (!buffer.finished()) {
5639 this->process();
5640 buffer++ += out;
5641#if HAS_KLANG_DEBUG
5642 debug.buffer++;
5643#endif
5644 }
5645 return !finished();
5646 }
5647 virtual bool process(buffer* buffer) {
5648 return this->process(buffer[0]);
5649 }
5650 };
5651
5652 /// Synthesiser note array
5653 template<class SYNTH, class NOTE = Note>
5654 struct Notes : Array<NOTE*, 128> {
5655 SYNTH* synth;
5657 using Array::items;
5658 using Array::count;
5659
5660 Notes(SYNTH* synth) : synth(synth) {
5661 for (int n = 0; n < 128; n++)
5662 items[n] = nullptr;
5663 }
5664 virtual ~Notes();
5665
5666 template<class TYPE>
5667 void add(int count) {
5668 for (int n = 0; n < count; n++) {
5669 TYPE* note = new TYPE();
5670 note->attach(synth);
5671 Array::add(note);
5672 }
5673 }
5674
5675 // returns index of a 'free' note (stealing oldest, if required)
5676 unsigned int noteOns = 0; // number of NoteOn events processed
5677 unsigned int noteStart[128] = { 0 }; // track age of notes (for note stealing)
5678
5679 int assign() {
5680 // favour unused voices
5681 for (unsigned int i = 0; i < count; i++) {
5682 if (items[i]->stage == NOTE::Off) {
5683 noteStart[i] = noteOns++;
5684 return i;
5685 }
5686 }
5687
5688 // no free notes => steal oldest released note?
5689 int oldest = -1;
5690 unsigned int oldest_start = 0;
5691 for (unsigned int i = 0; i < count; i++) {
5692 if (items[i]->stage == NOTE::Release) {
5693 if (oldest == -1 || noteStart[i] < oldest_start) {
5694 oldest = i;
5695 oldest_start = noteStart[i];
5696 }
5697 }
5698 }
5699 if (oldest != -1) {
5700 noteStart[oldest] = noteOns++;
5701 return oldest;
5702 }
5703
5704 // no available released notes => steal oldest playing note
5705 oldest = -1;
5706 oldest_start = 0;
5707 for (unsigned int i = 0; i < count; i++) {
5708 if (oldest == -1 || noteStart[i] < oldest_start) {
5709 oldest = i;
5710 oldest_start = noteStart[i];
5711 }
5712 }
5713 noteStart[oldest] = noteOns++;
5714 return oldest;
5715 }
5716 };
5717
5718 /// Synthesiser object (mono)
5719 struct Synth : public Effect {
5720 typedef Note Note;
5721
5723
5724 Synth() : notes(this) {}
5725 virtual ~Synth() {}
5726
5727 //virtual void presetLoaded(int preset) { }
5728 //virtual void optionChanged(int param, int item) { }
5729 //virtual void buttonPressed(int param) { };
5730
5731 int indexOf(Note* note) const {
5732 int index = 0;
5733 for (const auto* n : notes.items) {
5734 if (note == n)
5735 return index;
5736 index++;
5737 }
5738 return -1; // not found
5739 }
5740
5741 // pass to synth and notes
5742 virtual event onControl(int index, float value) override {
5743 this->control(index, value);
5744 for (unsigned int n = 0; n < notes.count; n++)
5745 if (notes[n]->stage != Note::Off)
5746 notes[n]->onControl(index, value);
5747 };
5748
5749 // pass to synth and notes
5750 virtual event onMIDI(int status, int byte1, int byte2) override {
5751 this->midi(status, byte1, byte2);
5752 for (unsigned int n = 0; n < notes.count; n++)
5753 if (notes[n]->stage != Note::Off)
5754 notes[n]->onMIDI(status, byte1, byte2);
5755 }
5756
5757 // pass to synth and notes
5758 virtual event onPreset(int index) override {
5759 this->preset(index);
5760 for (unsigned int n = 0; n < notes.count; n++)
5761 if (notes[n]->stage != Note::Off)
5762 notes[n]->onPreset(index);
5763 };
5764
5765 // assign and start note
5766 virtual event noteOn(int pitch, float velocity) {
5767 const int n = notes.assign();
5768 if (n != -1)
5769 notes[n]->start((float)pitch, velocity);
5770 }
5771
5772 // trigger note off (release)
5773 virtual event noteOff(int pitch, float velocity) {
5774 for (unsigned int n = 0; n < notes.count; n++)
5775 if (notes[n]->pitch == pitch && notes[n]->stage == Note::Sustain)
5776 notes[n]->release(velocity);
5777 }
5778
5779 virtual event allNotesOff(float velocity = 0.f) {
5780 for (unsigned int n = 0; n < notes.count; n++)
5781 if (notes[n]->stage != Note::Off)
5782 notes[n]->release(velocity);
5783 }
5784
5785 // post processing (see Effect::process)
5786 virtual void process() override { out = in; }
5787 virtual void process(buffer buffer) override { Effect::process(buffer); }
5788
5789 virtual bool playing() const {
5790 for (unsigned int n = 0; n < notes.count; n++)
5791 if (notes[n]->stage != Note::Off)
5792 return true;
5793 return false;
5794 }
5795
5796 virtual void process(float* buffer, int length, float* parameters = nullptr) {
5797 klang::buffer mono(buffer, length);
5798
5799 // sync parameters
5800 if (parameters) {
5801 for (unsigned int c = 0; c < controls.size(); c++)
5802 controls[c].set(parameters[c]);
5803 }
5804
5805 // generate note audio
5806 for (unsigned int n = 0; n < notes.count; n++) {
5807 Note* note = notes[n];
5808 if (note->stage != Note::Off) {
5809 if (!note->process(mono))
5810 note->stop();
5811 }
5812 }
5813
5814 // apply post processing
5815 this->process(mono);
5816
5817 // sync update (changed by process())
5818 if (parameters) {
5819 for (unsigned int c = 0; c < controls.size(); c++)
5820 parameters[c] = controls[c].value;
5821 }
5822 }
5823 };
5824
5825 template<class SYNTH, class NOTE>
5827 for (unsigned int n = 0; n < count; n++) {
5828 NOTE* tmp = items[n];
5829 items[n] = nullptr;
5830 delete tmp;
5831 }
5832 }
5833
5834 namespace Mono { using namespace klang; }
5835 namespace mono { using namespace klang; }
5836
5837 /// Objects supporting stereo audio functionality.
5838 namespace Stereo {
5839 /// Stereo audio signal
5841
5842 /// Stereo sample frame
5843 struct frame {
5846
5847 frame(mono::signal& left, mono::signal& right) : l(left), r(right) {}
5848 frame(signal& signal) : l(signal.l), r(signal.r) {}
5849
5850 frame& operator+=(const frame& x) { l += x.l; r += x.r; return *this; }
5851 frame& operator-=(const frame& x) { l -= x.l; r -= x.r; return *this; }
5852 frame& operator*=(const frame& x) { l *= x.l; r *= x.r; return *this; }
5853 frame& operator/=(const frame& x) { l /= x.l; r /= x.r; return *this; }
5854
5855 frame& operator+=(const signal x) { l += x.l; r += x.r; return *this; }
5856 frame& operator-=(const signal x) { l -= x.l; r -= x.r; return *this; }
5857 frame& operator*=(const signal x) { l *= x.l; r *= x.r; return *this; }
5858 frame& operator/=(const signal x) { l /= x.l; r /= x.r; return *this; }
5859
5860 frame& operator+=(const mono::signal x) { l += x; r += x; return *this; }
5861 frame& operator-=(const mono::signal x) { l -= x; r -= x; return *this; }
5862 frame& operator*=(const mono::signal x) { l *= x; r *= x; return *this; }
5863 frame& operator/=(const mono::signal x) { l /= x; r /= x; return *this; }
5864
5865 frame& operator+=(float x) { l += x; r += x; return *this; }
5866 frame& operator-=(float x) { l -= x; r -= x; return *this; }
5867 frame& operator*=(float x) { l *= x; r *= x; return *this; }
5868 frame& operator/=(float x) { l /= x; r /= x; return *this; }
5869
5870 frame& operator+=(double x) { l += (float)x; r += (float)x; return *this; }
5871 frame& operator-=(double x) { l -= (float)x; r -= (float)x; return *this; }
5872 frame& operator*=(double x) { l *= (float)x; r *= (float)x; return *this; }
5873 frame& operator/=(double x) { l /= (float)x; r /= (float)x; return *this; }
5874
5875 frame& operator+=(int x) { l += (float)x; r += (float)x; return *this; }
5876 frame& operator-=(int x) { l -= (float)x; r -= (float)x; return *this; }
5877 frame& operator*=(int x) { l *= (float)x; r *= (float)x; return *this; }
5878 frame& operator/=(int x) { l /= (float)x; r /= (float)x; return *this; }
5879
5880 signal operator+(const signal x) const { return { l + x.l, r + x.r }; }
5881 signal operator-(const signal x) const { return { l - x.l, r - x.r }; }
5882 signal operator*(const signal x) const { return { l * x.l, r * x.r }; }
5883 signal operator/(const signal x) const { return { l / x.l, r / x.r }; }
5884
5885 signal operator+(const mono::signal x) const { return { l + x, r + x }; }
5886 signal operator-(const mono::signal x) const { return { l - x, r - x }; }
5887 signal operator*(const mono::signal x) const { return { l * x, r * x }; }
5888 signal operator/(const mono::signal x) const { return { l / x, r / x }; }
5889
5890 signal operator+(float x) const { return { l + x, r + x }; }
5891 signal operator-(float x) const { return { l - x, r - x }; }
5892 signal operator*(float x) const { return { l * x, r * x }; }
5893 signal operator/(float x) const { return { l / x, r / x }; }
5894
5895 signal operator+(double x) const { return { l + (float)x, r + (float)x }; }
5896 signal operator-(double x) const { return { l - (float)x, r - (float)x }; }
5897 signal operator*(double x) const { return { l * (float)x, r * (float)x }; }
5898 signal operator/(double x) const { return { l / (float)x, r / (float)x }; }
5899
5900 signal operator+(int x) const { return { l + (float)x, r + (float)x }; }
5901 signal operator-(int x) const { return { l - (float)x, r - (float)x }; }
5902 signal operator*(int x) const { return { l * (float)x, r * (float)x }; }
5903 signal operator/(int x) const { return { l / (float)x, r / (float)x }; }
5904
5906 l = signal.l;
5907 r = signal.r;
5908 return *this;
5909 }
5910
5912 return (l + r) * 0.5f;
5913 }
5914 };
5915
5916 /// Audio input object (stereo)
5917 struct Input : Generic::Input<signal> { virtual ~Input() {} };
5918 /// Audio output object (stereo)
5919 struct Output : Generic::Output<signal> { virtual ~Output() {} };
5920 /// Signal generator object (stereo output)
5921 struct Generator : Generic::Generator<signal> { virtual ~Generator() {} };
5922 /// Signal modifier object (stereo, input-output)
5923 struct Modifier : Generic::Modifier<signal> { virtual ~Modifier() {} };
5924 /// Audio oscillator object (stereo, output)
5925 struct Oscillator : Generic::Oscillator<signal> { virtual ~Oscillator() {} };
5926
5927 //inline Modifier& operator>>(signal input, Modifier& modifier) {
5928 // modifier << input;
5929 // return modifier;
5930 //}
5931
5932 /// Stereo audio buffer
5933 // interleaved access to non-interleaved stereo buffers
5934 struct buffer {
5937
5938 buffer(const buffer& buffer) : left(buffer.left), right(buffer.right) { rewind(); }
5939 buffer(mono::buffer& left, mono::buffer& right) : left(left), right(right) { rewind(); }
5940
5941 operator const signal() const { return { left, right }; }
5942 operator frame () { return { left, right }; }
5943 bool finished() const { return left.finished() && right.finished(); }
5944 frame operator++(int) { return { left++, right++ }; }
5945
5947 return { left = in.l, right = in.r };
5948 }
5949
5951 left = in.left;
5952 right = in.right;
5953 return *this;
5954 }
5955
5957 left += in.l;
5958 right += in.r;
5959 return *this;
5960 }
5961
5962 buffer& operator=(const frame& in) { left = in.l; right = in.r; return *this; }
5963 buffer& operator+=(const frame& in) { left += in.l; right += in.r; return *this; }
5964 buffer& operator*=(const frame& in) { left *= in.l; right *= in.r; return *this; }
5965
5966 buffer& operator=(const mono::signal in) { left = in; right = in; return *this; }
5967 buffer& operator+=(const mono::signal in) { left += in; right += in; return *this; }
5968 buffer& operator*=(const mono::signal in) { left *= in; right *= in; return *this; }
5969
5970 frame operator[](int index) {
5971 return { left[index], right[index] };
5972 }
5973
5974 signal operator[](int index) const {
5975 return { left[index], right[index] };
5976 }
5977
5978 mono::buffer& channel(int index) {
5979 return index == 1 ? right : left;
5980 }
5981
5982 void clear() {
5983 left.clear();
5984 right.clear();
5985 }
5986
5987 void clear(int size) {
5988 left.clear(size);
5989 right.clear(size);
5990 }
5991
5992 void rewind() {
5993 left.rewind();
5994 right.rewind();
5995 }
5996 };
5997
5998 namespace interleaved {
6000 }
6001
6002 /// Stereo audio object adapter
6003 template<class TYPE>
6004 struct Bank : klang::Bank<TYPE, 2> {};
6005
6006 /// Audio delay object (stereo)
6007 template<int SIZE>
6008 struct Delay : Bank<klang::Delay<SIZE>> {
6009 using Bank<klang::Delay<SIZE>>::items;
6010 using Bank<klang::Delay<SIZE>>::in;
6011 using Bank<klang::Delay<SIZE>>::out;
6012
6013 void clear() {
6014 items[0].clear();
6015 items[1].clear();
6016 }
6017
6019 Delay<SIZE>() : l(items[0]), r(items[1]) {}
6020
6021 signal tap(int delay) const {
6022 int read = (items[0].position - 1) - delay;
6023 if (read < 0)
6024 read += SIZE;
6025 return { items[0].buffer[read], items[1].buffer[read] };
6026 }
6027
6028 signal tap(float delay) const {
6029 float read = (float)(items[0].position - 1) - delay;
6030 if (read < 0.f)
6031 read += SIZE;
6032
6033 const float f = floor(read);
6034 delay = read - f;
6035
6036 const int i = (int)read;
6037 const int j = (i == (SIZE - 1)) ? 0 : (i + 1);
6038
6039 return { items[0].buffer[i] * (1.f - delay) + items[0].buffer[j] * delay,
6040 items[1].buffer[i] * (1.f - delay) + items[1].buffer[j] * delay };
6041 }
6042
6043 virtual void process() override {
6044 out = tap(items[0].time);
6045 }
6046
6047 template<typename TIME>
6048 signal operator()(const TIME& delay) {
6049 if constexpr (std::is_integral_v<TIME>)
6050 return tap((int)delay);
6051 else if constexpr (std::is_floating_point_v<TIME>)
6052 return tap((float)delay);
6053 else if constexpr (std::is_same_v<TIME, signal>) // stereo signal (use for l/r delay times)
6054 return { items[0].tap(delay.l), items[1].tap(delay.r) };
6055 else
6056 return tap((klang::signal)delay); // else treat as single signal
6057 }
6058
6059 unsigned int max() const { return SIZE; }
6060 };
6061
6062 /// Stereo effect mini-plugin
6063 struct Effect : public Plugin, public Modifier {
6064 virtual ~Effect() {}
6065
6066 virtual void prepare() {};
6067 virtual void process() { out = in; };
6069 this->prepare();
6070 while (!buffer.finished()) {
6071 input(buffer);
6072 this->process();
6073 buffer++ = out;
6074#if HAS_KLANG_DEBUG
6075 debug.buffer++;
6076#endif
6077 }
6078 }
6079 /// Process interleaved host frames; inherited by the current Stereo::Sound.
6081 this->prepare();
6082 while (!buffer.finished()) {
6083 input(buffer);
6084 this->process();
6085 buffer++ = out;
6086#if HAS_KLANG_DEBUG
6087 debug.buffer++;
6088#endif
6089 }
6090 }
6091
6092 };
6093
6094 /// Sound mini-plugin (stereo). Input is available through `in`, but is
6095 /// silent unless a model explicitly routes it to `out` or `debug`.
6096 struct Sound : Effect {
6097 using Effect::process;
6098 void process() override { out = 0; }
6099 };
6100
6101 struct Synth;
6102
6103 /// Base class for stereo synthesiser note
6104 struct Note : public NoteBase<Synth>, public Generator {
6105 //virtual signal output() { return 0; };
6106
6107 virtual void prepare() {}
6108 virtual void process() override = 0;
6110 this->prepare();
6111 while (!buffer.finished()) {
6112 this->process();
6113 buffer++ += out;
6114 }
6115 return !finished();
6116 }
6117 virtual bool process(mono::buffer* buffers) {
6118 buffer buffer = { buffers[0], buffers[1] };
6119 return this->process(buffer);
6120 }
6121 };
6122
6123 namespace Mono {
6124 struct Note : public Stereo::Note, public klang::Mono::Generator {
6125 using klang::Mono::Generator::out;
6126
6127 virtual void prepare() override {}
6128 virtual void process() override = 0;
6129 virtual bool process(Stereo::buffer buffer) override {
6130 this->prepare();
6131 while (!buffer.finished()) {
6132 this->process();
6133 buffer.left += out;
6134 buffer.right += out;
6135 buffer++;
6136 }
6137 return !finished();
6138 }
6139 };
6140 }
6141
6142 /// Synthesier mini-plugin (stereo)
6143 struct Synth : public Effect {
6145
6146 struct Mono { typedef Stereo::Mono::Note Note; };
6147
6148 /// Synthesiser note array (stereo)
6149 struct Notes : klang::Notes<Synth, Note> {
6150 using klang::Notes<Synth, Note>::Notes;
6151 } notes;
6152
6153 Synth() : notes(this) {}
6154 virtual ~Synth() {}
6155
6156 //virtual void presetLoaded(int preset) { }
6157 //virtual void optionChanged(int param, int item) { }
6158 //virtual void buttonPressed(int param) { };
6159
6160 int indexOf(Note* note) const {
6161 int index = 0;
6162 for (const auto* n : notes.items) {
6163 if (note == n)
6164 return index;
6165 index++;
6166 }
6167 return -1; // not found
6168 }
6169
6170 // pass to synth and notes
6171 virtual event onControl(int index, float value) override {
6172 this->control(index, value);
6173 for (unsigned int n = 0; n < notes.count; n++)
6174 if (notes[n]->stage != Note::Off)
6175 notes[n]->onControl(index, value);
6176 };
6177
6178 // pass to synth and notes
6179 virtual event onMIDI(int status, int byte1, int byte2) override {
6180 this->midi(status, byte1, byte2);
6181 for (unsigned int n = 0; n < notes.count; n++)
6182 if (notes[n]->stage != Note::Off)
6183 notes[n]->onMIDI(status, byte1, byte2);
6184 }
6185
6186 // pass to synth and notes
6187 virtual event onPreset(int index) override {
6188 this->preset(index);
6189 for (unsigned int n = 0; n < notes.count; n++)
6190 if (notes[n]->stage != Note::Off)
6191 notes[n]->onPreset(index);
6192 };
6193
6194 // assign and start note
6195 virtual event noteOn(int pitch, float velocity) {
6196 const int n = notes.assign();
6197 if (n != -1)
6198 notes[n]->start((float)pitch, velocity);
6199 }
6200
6201 // trigger note off (release)
6202 virtual event noteOff(int pitch, float velocity) {
6203 for (unsigned int n = 0; n < notes.count; n++)
6204 if (notes[n]->pitch == pitch && notes[n]->stage == Note::Sustain)
6205 notes[n]->release(velocity);
6206 }
6207
6208 virtual event allNotesOff(float velocity = 0.f) {
6209 for (unsigned int n = 0; n < notes.count; n++)
6210 if (notes[n]->stage != Note::Off)
6211 notes[n]->release(velocity);
6212 }
6213
6214 // post processing (see Effect::process)
6215 virtual void process() override { out = in; }
6216 virtual void process(buffer buffer) override { Effect::process(buffer); }
6217
6218 virtual bool playing() const {
6219 for (unsigned int n = 0; n < notes.count; n++)
6220 if (notes[n]->stage != Note::Off)
6221 return true;
6222 return false;
6223 }
6224
6225 virtual void process(float** buffers, int length, float* parameters = nullptr) {
6226 klang::buffer left(buffers[0], length);
6227 klang::buffer right(buffers[1], length);
6228 klang::Stereo::buffer buffer(left, right);
6229
6230 // sync parameters
6231 if (parameters) {
6232 for (unsigned int c = 0; c < controls.size(); c++)
6233 controls[c].set(parameters[c]);
6234 }
6235
6236 // generate note audio
6237 for (unsigned int n = 0; n < notes.count; n++) {
6238 Note* note = notes[n];
6239 if (note->stage != Note::Off) {
6240 if (!note->process(buffer))
6241 note->stop();
6242 }
6243 }
6244
6245 // apply post processing
6246 this->process(buffer);
6247
6248 // sync update (changed by process())
6249 if (parameters) {
6250 for (unsigned int c = 0; c < controls.size(); c++)
6251 parameters[c] = controls[c].value;
6252 }
6253 }
6254 };
6255 }
6256
6257 /// @cond
6258 namespace stereo {
6259 using namespace Stereo;
6260 }
6261 /// @endcond
6262
6263 /// Feed audio source to destination (with source processing)
6264 template<typename SOURCE, typename DESTINATION, class = decltype(
6265 detail::flow_destination<SOURCE&, DESTINATION>(std::bool_constant<
6268 inline DESTINATION& operator>>(SOURCE& source, DESTINATION& destination) {
6270 destination.input(source); // input to destination (enables overriding of <<)
6272 destination.input(source); // input to destination (enables overriding of <<)
6273 else
6274 destination << source; // copy to destination
6275 return destination;
6276 }
6277
6278 /// Feed audio source to destination (no source processing)
6279 template<typename SOURCE, typename DESTINATION, class = decltype(
6280 detail::flow_destination<const SOURCE&, DESTINATION>(std::bool_constant<
6283 inline DESTINATION& operator>>(const SOURCE& source, DESTINATION& destination) {
6285 destination.input(source); // input to destination (enables overriding of <<)
6287 destination.input(source); // input to destination (enables overriding of <<)
6288 else
6289 destination << source; // copy to destination
6290 return destination;
6291 }
6292
6293 /** Fast scalar approximations. Angles use radians unless a `p` suffix
6294 * identifies an unsigned 32-bit phase covering one complete turn.
6295 * Sine uses the retained V2/Farbrausch range reduction and Robin Green
6296 * odd polynomial. Cosine reuses that polynomial with direct quadrant
6297 * reduction, avoiding an added pi/2 before the existing modulo step.
6298 */
6299 namespace fast {
6300 constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
6301
6302 namespace detail {
6303 inline float sin(float x) {
6304 const float x2 = x * x;
6305 return (((-0.00018542f * x2 + 0.0083143f) * x2 - 0.16666f) * x2 + 1.0f) * x;
6306 }
6307 }
6308
6309 /// Approximate sine of a finite angle in radians.
6310 inline float sin(float x) {
6311 x = fast_mod2pi(x);
6312 if (x > 3 / 2.f * pi)
6313 x -= twoPi;
6314 else if (x > pi / 2)
6315 x = pi - x;
6316 return detail::sin(x);
6317 }
6318
6319 /// Approximate cosine of a finite angle in radians.
6320 inline float cos(float x) {
6321 x = fast_mod2pi(x);
6322 x = x < pi ? pi / 2.f - x : x - 3.f / 2.f * pi;
6323 return detail::sin(x);
6324 }
6325
6326 /// Approximate sine from an unsigned 32-bit phase covering one turn.
6327 inline float sinp(unsigned int phase) {
6328 float x = fast_modp(phase);
6329 if (x > 3.f / 2.f * pi)
6330 x -= twoPi;
6331 else if (x > pi / 2.f)
6332 x = pi - x;
6333 return detail::sin(x);
6334 }
6335
6336 /// Approximate cosine from an unsigned 32-bit phase covering one turn.
6337 inline float cosp(unsigned int phase) {
6338 float x = fast_modp(phase);
6339 x = x < pi ? pi / 2.f - x : x - 3.f / 2.f * pi;
6340 return detail::sin(x);
6341 }
6342 }
6343
6344 /// Common audio generators / oscillators.
6345 namespace Generators {
6346 using namespace klang;
6347
6348 /// Simple oscillators
6349 namespace Basic {
6350 /// Sine wave oscillator
6351 struct Sine : public Oscillator {
6352 void process() {
6353 out = sin(position.wrapped(offset));
6354 position += increment;
6355 }
6356 };
6357
6358 /// Saw wave oscillator (aliased)
6359 struct Saw : public Oscillator {
6360 void process() {
6361 out = position.wrapped(offset) * pi.inv - 1.f;
6362 position += increment;
6363 }
6364 };
6365
6366 /// Aliased 0-to-1 ramp; frequency in Hz, absolute phase in radians, like Basic::Saw.
6367 struct Phasor : Saw {
6368 void process() override {
6369 Saw::process();
6370 out = out * 0.5f + 0.5f;
6371 }
6372 };
6373
6374 /// Triangle wave oscillator (aliased)
6375 struct Triangle : public Oscillator {
6376 void process() {
6377 out = abs(2.f * position.wrapped(offset) * pi.inv - 2) - 1.f;
6378 position += increment;
6379 }
6380 };
6381
6382 /// Square wave oscillator (aliased)
6383 struct Square : public Oscillator {
6384 void process() {
6385 out = position.wrapped(offset) > pi ? 1.f : -1.f;
6386 position += increment;
6387 }
6388 };
6389
6390 /// Pulse wave oscillator (aliased)
6391 struct Pulse : public Oscillator {
6392 param duty = 0.5f;
6393
6394 using Oscillator::set;
6395 void set(param frequency, param phase, param duty) {
6396 set(frequency, phase);
6397 Pulse::duty = duty;
6398 }
6399
6400 void process() {
6401 out = position.wrapped(offset) > (duty * pi) ? 1.f : -1.f;
6402 position += increment;
6403 }
6404 };
6405
6406 /// White noise generator
6407 struct Noise : public Generator {
6408 void process() {
6409 out = rand() * 2.f / (const float)RAND_MAX - 1.f;
6410 }
6411 };
6412 };
6413
6414 /// Fast oscillators and phase helpers.
6415 namespace Fast {
6416 constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
6417 constexpr float twoPiInv = float(1.0 / twoPi);
6418
6419 /// Signed phase step stored modulo one turn (2^32 ticks).
6420 struct Increment {
6421 signed int amount = 0;
6422 void reset() { amount = 0; }
6423
6424 void set(Frequency hz) {
6425 double cycles = fs > 0 && std::isfinite(hz.value) ? double(hz.value) / fs : 0;
6426 if (cycles <= -1 || cycles >= 1)
6427 cycles = std::fmod(cycles, 1.0);
6428 const unsigned int bits = static_cast<unsigned int>(
6429 static_cast<long long>(cycles * 4294967296.0));
6430 std::memcpy(&amount, &bits, sizeof(amount));
6431 }
6432
6433 // Signed principal step in cycles; phase addition uses the wrapping bits.
6434 operator float() const { return float(double(amount) / 4294967296.0); }
6435 Increment operator+(const Increment& other) const {
6436 Increment result;
6437 const unsigned int bits = static_cast<unsigned int>(amount) + static_cast<unsigned int>(other.amount);
6438 std::memcpy(&result.amount, &bits, sizeof(bits));
6439 return result;
6440 }
6441 };
6442
6443 /// Wrapping oscillator phase; setters take radians, conversion gives cycles.
6444#pragma float_control(precise, on, push)
6445 struct Phase {
6446 unsigned int position = 0;
6447
6448 Phase& operator=(klang::Phase phase) {
6449 double cycles = std::isfinite(phase.value) ? double(phase.value) / twoPi : 0;
6450 cycles -= std::floor(cycles);
6451 position = cycles < 1 ? static_cast<unsigned int>(cycles * 4294967296.0) : 0;
6452 return *this;
6453 }
6454
6455 // Full counter precision for transition integration, including very low Hz.
6456 double cycles() const { return double(position) / 4294967296.0; }
6457 operator float() const {
6458 const unsigned int bits = (position >> 9) | 0x3f800000;
6459 float value;
6460 std::memcpy(&value, &bits, sizeof(value));
6461 return value - 1.f;
6462 }
6463
6464 float operator+(const Phase& offset) const {
6465 unsigned int phase = position + offset.position + 0x40000000;
6466 if (phase & 0x80000000)
6467 phase = ~phase;
6468 const unsigned int bits = (phase >> 8) | 0x3f800000;
6469 float value;
6470 std::memcpy(&value, &bits, sizeof(value));
6471 return value * pi - 1.5f * pi;
6472 }
6473 float radians() const { return float(cycles() * twoPi); }
6474 Phase& operator+=(const Increment step) {
6475 position += static_cast<unsigned int>(step.amount);
6476 return *this;
6477 }
6478 };
6479#pragma float_control(pop)
6480
6481 /// Sine wave oscillator (band-limited, optimised)
6482 struct Sine : public Oscillator {
6483 Sine() { set(frequency); }
6484 void reset() override {
6485 Sine::position = Oscillator::position = 0;
6486 Sine::offset = Oscillator::offset = 0;
6487 set(Oscillator::frequency, 0.f);
6488 }
6489
6490 void set(param frequency) override {
6491 if (frequency != Oscillator::frequency || sampleRate != double(fs)) {
6492 sampleRate = fs;
6493 Oscillator::frequency = frequency;
6494 increment.set(frequency);
6495 }
6496 }
6497
6498 void set(param frequency, param phase) override { // set frequency and phase
6499 Sine::position = Oscillator::position = phase;
6500 Sine::offset = Oscillator::offset = 0;
6501 set(frequency);
6502 }
6503
6504 void set(param frequency, relative phase) override { // set frequency and phase
6505 set(frequency);
6506 set(phase);
6507 }
6508
6509 void set(relative phase) override { // set frequency and phase
6510 Sine::offset = Oscillator::offset = phase * twoPi;
6511 }
6512
6513 void process() override {
6514 out = klang::fast::sinp(position.position + offset.position);
6515 position += increment;
6516 }
6517
6518 protected:
6519 double sampleRate = 0;
6520 Fast::Increment increment;
6521 Fast::Phase position, offset;
6522 };
6523
6524 /// Aliased 0-to-1 ramp using an integer wrapping phase.
6526 Phasor() { set(frequency); }
6527
6528 void reset() override {
6529 Phasor::position = Oscillator::position = 0;
6530 }
6531
6532 void set(param frequency) override {
6533 if (frequency != Oscillator::frequency || sampleRate != double(fs)) {
6534 sampleRate = fs;
6535 Oscillator::frequency = frequency;
6536 increment.set(frequency);
6537 }
6538 }
6539
6540 void set(param frequency, param phase) override {
6541 Phasor::position = Oscillator::position = phase;
6542 set(frequency);
6543 }
6544
6545 void set(param frequency, relative phase) override {
6546 set(frequency);
6547 set(phase);
6548 }
6549
6550 void set(relative phase) override {
6551 Phasor::offset = Oscillator::offset = phase * twoPi;
6552 }
6553
6554 void process() override {
6555 Fast::Phase phase = position;
6556 phase.position += offset.position;
6557 out = float(phase);
6558 position += increment;
6559 }
6560
6561 protected:
6562 double sampleRate = 0;
6563 Fast::Increment increment;
6564 Fast::Phase position, offset;
6565 };
6566
6567 /// White noise generator (optimised)
6568 struct Noise : public Generator {
6569 static constexpr unsigned int bias = 0b1000011100000000000000000000000;
6570 /// @cond
6571 union { unsigned int i; float f; };
6572 /// @endcond
6573 void process() {
6574 i = ((rand() & 0b111111111111111UL) << 1) | bias;
6575 out = f - 257.f;
6576 }
6577 };
6578 };
6579
6580 /// Sample-averaged oscillator waveforms.
6581 namespace OSM {
6582 /** V2 oscillator state machine, with float arithmetic in the sample loop.
6583 * Based on Farbrausch V2 (Tammo Hinrichs; C++ port Fabian Giesen).
6584 * Averages the interval ending at the current phase, then advances.
6585 * Frequency: abs(Hz) < sample rate; phase: radians; duty: [0,1].
6586 * Zero Hz holds the point value. Unsupported/invalid Hz holds phase.
6587 * Box averaging reduces aliasing; it is not an ideal band-limit.
6588 * Negative Hz reflects phase in set(); both directions use the forward state machine.
6589 * See V2-SOURCE-REVIEW.md and OSM-STATUS.md for provenance and limits.
6590 */
6591#if defined(_MSC_VER)
6592#define KLANG_OSM_INLINE __forceinline
6593#elif defined(__clang__) || defined(__GNUC__)
6594#define KLANG_OSM_INLINE inline __attribute__((always_inline))
6595#else
6596#define KLANG_OSM_INLINE inline
6597#endif
6598 struct StateMachine {
6599 using Waveform = float(StateMachine::*)();
6600 const Waveform waveform;
6601 KLANG_OSM_INLINE StateMachine(Waveform waveform) : waveform(waveform) {}
6602
6603 // Transition bits: wrap:previous_up:current_up; "up" means phase < breakpoint.
6604 // Internal phase always travels forwards, including for negative Hz.
6605 // Codes 001/110 are retained for comparison but cannot occur here.
6606 // The stored state contains only the two history bits; tick() adds wrap.
6607 enum State { Down = 0, ReversePeak = 1, UpDown = 2, Up = 3,
6608 DownUpDown = 4, DownUp = 5, ReverseWrap = 6, UpDownUp = 7 };
6609 static constexpr double turn = 4294967296.0;
6610 static constexpr float tickScale = 1.f / 4294967296.f;
6611 Fast::Increment increment;
6612 Fast::Phase offset, phaseOffset;
6613 unsigned long long breakpoint = 0, threshold = 0;
6614 // Exact breakpoint is integer + fraction. Reflected phase has that same
6615 // fraction; forward phase is integer. Cache corrections in cycle units.
6616 float fraction = 0, phaseFraction = 0, peakFraction = 0;
6617 State state = Down;
6618 bool reverse = false;
6619 param frequency = 0;
6620 float sampleRate = 0;
6621 double stepScale = 0;
6622 float col = 0, fallingWidth = 1, f = 0, inverseStep = 0;
6623 float rising = 0, falling = 1;
6624 float upSlope = 0, downSlope = 2 * tickScale;
6625 float upBias = -1, downBias = -1;
6626 // Triangle/saw polarity is folded into coefficients; pulse keeps +1.
6627 float amplitude = 1;
6628 float gain = 1, peak = 1, high = 1, low = -1;
6629
6630 KLANG_OSM_INLINE void sync() {
6631 state = (offset.position - static_cast<unsigned int>(increment.amount)) < threshold ? Up : Down;
6632 }
6633 KLANG_OSM_INLINE void coefficients() {
6634 threshold = breakpoint + (!reverse && fraction > 0);
6635 phaseFraction = reverse ? fraction * tickScale : 0;
6636 peakFraction = reverse ? 0 : fraction * tickScale;
6637 upSlope = 2 * tickScale * rising;
6638 downSlope = 2 * tickScale * falling;
6639 upBias = (2 * phaseFraction - f) * rising - amplitude;
6640 downBias = (f - 2 * phaseFraction) * falling - amplitude;
6641 peak = amplitude;
6642 high = 1;
6643 low = -1;
6644 if (gain != 1) {
6645 upSlope *= gain;
6646 downSlope *= gain;
6647 upBias *= gain;
6648 downBias *= gain;
6649 peak *= gain;
6650 const float mean = (1 - gain) * (2 * col - 1);
6651 high = mean + gain;
6652 low = mean - gain;
6653 }
6654 sync();
6655 }
6656 // Only called outside the ordinary sub-cycle frequency range. fmod preserves
6657 // residual phase even when the number of complete turns exceeds double's integers.
6658 unsigned int wideStep(unsigned int bits);
6659 KLANG_OSM_INLINE void set(param hz) {
6660 if (frequency != hz || sampleRate != fs.f) {
6661 frequency = hz;
6662 if (sampleRate != fs.f) {
6663 sampleRate = fs.f;
6664 stepScale = sampleRate > 0 ? turn / sampleRate : 0;
6665 }
6666 const float magnitude = std::fabs(hz.value);
6667 unsigned int ticks;
6668 gain = 1;
6669 if (magnitude < sampleRate) {
6670 ticks = static_cast<unsigned int>(magnitude * stepScale);
6671 f = float(ticks) * tickScale;
6672 inverseStep = f > 0 ? 1.f / f : 0;
6673 } else {
6674 std::memcpy(&ticks, &hz.value, sizeof(ticks));
6675 ticks = wideStep(ticks);
6676 }
6677 // A negative frequency that rounds to zero keeps the point-value convention.
6678 const bool negative = hz < 0 && (ticks != 0 || gain != 1);
6679 // Reflect q = breakpoint - p only when the quantised direction changes.
6680 if (reverse != negative) {
6681 reverse = negative;
6682 offset.position = static_cast<unsigned int>(breakpoint) - offset.position;
6683 if (waveform == &StateMachine::saw) {
6684 amplitude = -amplitude;
6685 rising = -rising;
6686 falling = -falling;
6687 }
6688 }
6689 std::memcpy(&increment.amount, &ticks, sizeof(ticks));
6690 coefficients();
6691 }
6692 }
6693 KLANG_OSM_INLINE void set(param hz, param phase) {
6694 set(hz);
6695 offset = phase;
6696 if (reverse) offset.position = static_cast<unsigned int>(breakpoint) - offset.position;
6697 phaseOffset = 0;
6698 sync();
6699 }
6700 KLANG_OSM_INLINE void set(param hz, param phase, param duty) {
6701 set(hz, phase);
6702 setDuty(duty);
6703 }
6704 KLANG_OSM_INLINE void setDuty(param duty) {
6705 const double width = std::isfinite(duty.value) ? std::clamp(double(duty.value), 0.0, 1.0) : 0.5;
6706 const double ticks = width * turn;
6707 const auto whole = static_cast<unsigned long long>(ticks);
6708 setBreakpoint(whole, float(ticks - whole));
6709 }
6710 // Counter-space breakpoint also represents the exact duty=1 endpoint.
6711 KLANG_OSM_INLINE void setBreakpoint(unsigned long long ticks, float remainder = 0) {
6712 if (reverse) offset.position += static_cast<unsigned int>(ticks - breakpoint);
6713 breakpoint = ticks;
6714 fraction = remainder;
6715 col = (float(breakpoint) + fraction) * tickScale;
6716 fallingWidth = (float(4294967296ull - breakpoint) - fraction) * tickScale;
6717 rising = col > 0 ? amplitude / col : 0;
6718 falling = fallingWidth > 0 ? amplitude / fallingWidth : 0;
6719 coefficients();
6720 }
6721 KLANG_OSM_INLINE void setOffset(param radians) {
6722 const unsigned int previous = phaseOffset.position;
6723 phaseOffset = radians;
6724 const unsigned int delta = phaseOffset.position - previous;
6725 offset.position += reverse ? 0u - delta : delta;
6726 sync();
6727 }
6728 KLANG_OSM_INLINE void reset() {
6729 offset = phaseOffset;
6730 if (reverse) offset.position = static_cast<unsigned int>(breakpoint) - offset.position;
6731 sync();
6732 }
6733 KLANG_OSM_INLINE State tick() {
6734 state = State(((state << 1) | (offset.position < threshold)) & 3);
6735 // Internal phase always advances, so the original forward carry test suffices.
6736 const bool carry = (offset.position < static_cast<unsigned int>(increment.amount));
6737 const State transition = State(state | (carry ? 4 : 0));
6738 offset.position += static_cast<unsigned int>(increment.amount);
6739 return transition;
6740 }
6741 KLANG_OSM_INLINE float output() { return (this->*waveform)(); }
6742
6743 KLANG_OSM_INLINE float saw() {
6744 const unsigned int end = offset.position;
6745 switch (tick()) {
6746 case Up:
6747 return float(end) * upSlope + upBias;
6748 case Down:
6749 return (float(0xffffffffu - end) + 1.f) * downSlope + downBias;
6750 // Apply fractional corrections only at edges; ordinary samples use cached biases.
6751 case UpDown: {
6752 const float after = (float(end - static_cast<unsigned int>(breakpoint)) * tickScale - peakFraction);
6753 const float before = (float(static_cast<unsigned int>(increment.amount) - (end - static_cast<unsigned int>(breakpoint))) * tickScale + peakFraction);
6754 return peak - inverseStep * (before * before * rising + after * after * falling);
6755 }
6756 case DownUp: {
6757 const float after = (float(end) * tickScale + phaseFraction);
6758 const float before = (float(static_cast<unsigned int>(increment.amount) - end) * tickScale - phaseFraction);
6759 return -peak + inverseStep * (before * before * falling + after * after * rising);
6760 }
6761 case UpDownUp: {
6762 const unsigned int forwardEnd = end;
6763 return -(1 - f) * inverseStep * rising * (2 * (float(forwardEnd) * tickScale + phaseFraction) - f + fallingWidth);
6764 }
6765 case DownUpDown: {
6766 const unsigned int forwardEnd = end;
6767 return (1 - f) * inverseStep * falling * (2 * (float(forwardEnd) * tickScale + phaseFraction) - f - col);
6768 }
6769 default:
6770 return 0;
6771 }
6772 }
6773 KLANG_OSM_INLINE float pulse() {
6774 const unsigned int end = offset.position;
6775 switch (tick()) {
6776 case Up:
6777 return high;
6778 case Down:
6779 return low;
6780 case UpDown:
6781 return high - 2 * inverseStep * ((float(end - static_cast<unsigned int>(breakpoint)) * tickScale - peakFraction));
6782 case DownUp:
6783 return 2 * inverseStep * ((float(end) * tickScale + phaseFraction)) + low;
6784 case UpDownUp:
6785 return high - 2 * inverseStep * fallingWidth;
6786 case DownUpDown:
6787 return 2 * inverseStep * col + low;
6788 default:
6789 return 0;
6790 }
6791 }
6792 };
6793
6794 // Keep exceptional-input handling precise while the ordinary setter/sample path
6795 // retains the host's fast-math settings. Integer argument bits also avoid Clang's
6796 // no-infinity assumptions on a floating parameter declared in fast-math scope.
6797 #pragma float_control(precise, on, push)
6798 #if defined(_MSC_VER)
6799 __declspec(noinline)
6800 #elif defined(__GNUC__)
6801 __attribute__((noinline))
6802 #endif
6803 inline unsigned int StateMachine::wideStep(unsigned int bits) {
6804 if ((bits & 0x7f800000u) == 0x7f800000u || sampleRate <= 0) {
6805 f = inverseStep = 0;
6806 gain = 1;
6807 return 0;
6808 }
6809 float hz;
6810 std::memcpy(&hz, &bits, sizeof(hz));
6811 const double magnitude = std::fabs(double(hz));
6812 const double whole = std::floor(magnitude / sampleRate);
6813 const unsigned int ticks = static_cast<unsigned int>(
6814 (std::fmod(magnitude, double(sampleRate)) / sampleRate) * turn);
6815 const double fraction = double(ticks) * tickScale;
6816 const double width = whole + fraction;
6817 f = float(ticks) * tickScale;
6818 inverseStep = float(1 / width);
6819 gain = float(fraction / width);
6820 return ticks;
6821 }
6822 #pragma float_control(pop)
6823 /// @cond
6824 struct Osm : public Oscillator {
6825 const float _Duty;
6826 KLANG_OSM_INLINE Osm(StateMachine::Waveform waveform, float duty = 0.f) : _Duty(duty), osm(waveform) {
6827 osm.setDuty(duty);
6828 osm.set(frequency);
6829 }
6830 using Oscillator::set;
6831 KLANG_OSM_INLINE void set(param hz) override {
6832 if (frequency != hz || osm.sampleRate != fs.f) {
6833 Oscillator::frequency = hz;
6834 osm.set(hz);
6835 }
6836 }
6837 KLANG_OSM_INLINE void set(param hz, param phase) override {
6838 Oscillator::frequency = hz;
6839 Oscillator::position = phase;
6840 Oscillator::offset = 0;
6841 osm.set(hz, phase);
6842 }
6843 KLANG_OSM_INLINE void set(param hz, param phase, param duty) override {
6844 set(hz, phase);
6845 setDuty(duty);
6846 }
6847 KLANG_OSM_INLINE void set(param hz, relative phase) override {
6848 set(hz);
6849 set(phase);
6850 }
6851 KLANG_OSM_INLINE void set(relative phase) override {
6852 Oscillator::offset = phase * Fast::twoPi;
6853 osm.setOffset(Oscillator::offset);
6854 }
6855 KLANG_OSM_INLINE void setDuty(param duty) { osm.setDuty(duty); }
6856 KLANG_OSM_INLINE void reset() override {
6857 Oscillator::position = 0;
6858 osm.reset();
6859 }
6860 KLANG_OSM_INLINE void process() override { out = osm.output(); }
6861
6862 protected:
6863 StateMachine osm;
6864 };
6865 /// @endcond
6866
6867 /// Descending sawtooth.
6868 struct Saw : public Osm {
6869 KLANG_OSM_INLINE Saw() : Osm(&StateMachine::saw, 0.f) {}
6870 KLANG_OSM_INLINE void process() override { out = osm.saw(); }
6871 };
6872 /// Triangle wave with equal rising and falling half-cycles.
6873 struct Triangle : public Osm {
6874 KLANG_OSM_INLINE Triangle() : Osm(&StateMachine::saw, 0.5f) {}
6875 KLANG_OSM_INLINE void process() override { out = osm.saw(); }
6876 };
6877 /// Square wave with 50% high duty.
6878 struct Square : public Osm {
6879 KLANG_OSM_INLINE Square() : Osm(&StateMachine::pulse, 0.5f) {}
6880 KLANG_OSM_INLINE void process() override { out = osm.pulse(); }
6881 };
6882 /// Pulse wave with adjustable duty cycle.
6883 struct Pulse : public Osm {
6884 KLANG_OSM_INLINE Pulse() : Osm(&StateMachine::pulse, 0.5f) {}
6885 KLANG_OSM_INLINE void process() override { out = osm.pulse(); }
6886 };
6887
6888#undef KLANG_OSM_INLINE
6889 };
6890
6891 /// Polynomial antialiasing with an integer phase accumulator.
6892 namespace PolyBLEP {
6893
6894#if defined(_MSC_VER)
6895#define KLANG_BLEP_INLINE __forceinline
6896#define KLANG_BLEP_COLD __declspec(noinline)
6897#elif defined(__clang__) || defined(__GNUC__)
6898#define KLANG_BLEP_INLINE inline __attribute__((always_inline))
6899#define KLANG_BLEP_COLD __attribute__((noinline))
6900#else
6901#define KLANG_BLEP_INLINE inline
6902#define KLANG_BLEP_COLD
6903#endif
6904 /// @cond
6905 template<bool PULSE>
6906 struct Polynomial : public Oscillator {
6907 const float _Duty;
6908 using Oscillator::set;
6909
6910 KLANG_BLEP_INLINE explicit Polynomial(float duty) : _Duty(duty) {
6911 setDuty(duty);
6912 set(frequency);
6913 }
6914
6915 KLANG_BLEP_INLINE void set(param hz) override {
6916 const unsigned int request = bits(hz.value);
6917 if (bits(frequency.value) == request && sampleRate == fs.f) return;
6918 frequency = hz;
6919 if (sampleRate != fs.f) {
6920 sampleRate = fs.f;
6921 ticksPerHz = finite(bits(sampleRate)) && sampleRate > 0 ? turn / sampleRate : 0;
6922 }
6923 const float magnitude = finite(request) ? std::fabs(hz.value) : 0;
6924 const bool audible = magnitude < sampleRate * .5f;
6925 const double ticks = magnitude < sampleRate ? magnitude * ticksPerHz
6926 : ticksPerHz > 0 ? std::fmod(double(magnitude), double(sampleRate)) * ticksPerHz : 0;
6927 const auto advance = static_cast<unsigned int>(ticks < turn ? ticks : 0);
6928 width = audible ? advance : 0;
6929 inverseWidth = width ? 1.f / float(width) : 0;
6930 increment = request >> 31 ? 0u - advance : advance;
6931 // Bring the remaining harmonics to zero before the fundamental reaches Nyquist.
6932 gain = audible ? std::clamp((.5f - float(width) * tickScale) * 20.f, 0.f, 1.f)
6933 : ticksPerHz > 0 ? 0.f : 1.f;
6934 }
6935
6936 KLANG_BLEP_INLINE void set(param hz, param phase) override {
6937 set(hz);
6938 Oscillator::position = phase;
6939 Oscillator::offset = 0;
6940 position = phase;
6941 offset.position = 0;
6942 }
6943
6944 KLANG_BLEP_INLINE void set(param hz, param phase, param duty) override {
6945 set(hz, phase);
6946 setDuty(duty);
6947 }
6948
6949 KLANG_BLEP_INLINE void set(param hz, relative phase) override {
6950 set(hz);
6951 set(phase);
6952 }
6953
6954 KLANG_BLEP_INLINE void set(relative phase) override {
6955 Oscillator::offset = phase * Fast::twoPi;
6956 offset = Oscillator::offset;
6957 }
6958
6959 KLANG_BLEP_INLINE void setDuty(param duty) {
6960 dutyCycle = finite(bits(duty.value)) ? std::clamp(duty.value, 0.f, 1.f) : .5f;
6961 const auto ticks = static_cast<unsigned long long>(double(dutyCycle) * turn);
6962 breakpoint = static_cast<unsigned int>(ticks);
6963 if constexpr (PULSE) {
6964 low = dutyCycle == 1 ? 1.f : -1.f;
6965 narrowDuty = dutyCycle > 0 && dutyCycle < 1.f / 16384;
6966 }
6967 else {
6968 narrowDuty = (dutyCycle > 0 && dutyCycle < 1.f / 16384)
6969 || (dutyCycle < 1 && dutyCycle > 1.f - 1.f / 16384);
6970 rising = dutyCycle > 0 ? 2.f / dutyCycle : 0;
6971 falling = dutyCycle < 1 ? 2.f / (1 - dutyCycle) : 0;
6972 }
6973 }
6974
6975 KLANG_BLEP_INLINE void reset() override {
6976 Oscillator::position = 0;
6977 position.position = 0;
6978 }
6979
6980 KLANG_BLEP_INLINE void process() override {
6981 const unsigned int phase = position.position + offset.position;
6982 position.position += increment;
6983 const float mean = PULSE ? 2 * dutyCycle - 1 : 0;
6984 if (gain == 0) {
6985 out = mean;
6986 return;
6987 }
6988 float wave;
6989 if (narrowDuty) wave = integrate(phase);
6990 else if constexpr (PULSE) {
6991 wave = (phase < breakpoint ? 1.f : low) + step(phase) - step(phase - breakpoint);
6992 }
6993 else if (!breakpoint) {
6994 const float saw = 1.f - 2 * (float(phase) * tickScale) + step(phase);
6995 wave = dutyCycle == 0 ? saw : -saw;
6996 }
6997 else {
6998 wave = phase < breakpoint
6999 ? float(phase) * tickScale * rising - 1
7000 : float(0u - phase) * tickScale * falling - 1;
7001 // Integrate the step correction at each slope discontinuity.
7002 wave += (rising + falling) * (float(width) * (tickScale / 6))
7003 * (corner(phase) - corner(phase - breakpoint));
7004 }
7005 out = gain == 1 ? wave : mean + gain * (wave - mean);
7006 }
7007
7008 private:
7009 static constexpr double turn = 4294967296.0;
7010 static constexpr float tickScale = 1.f / 4294967296.f;
7011 Fast::Phase position, offset;
7012 unsigned int increment = 0, width = 0, breakpoint = 0;
7013 float inverseWidth = 0, dutyCycle = 0, rising = 0, falling = 0, low = -1, sampleRate = 0;
7014 double ticksPerHz = 0;
7015 float gain = 1;
7016 bool narrowDuty = false;
7017
7018 static KLANG_BLEP_INLINE unsigned int bits(float value) {
7019 unsigned int result;
7020 std::memcpy(&result, &value, sizeof(result));
7021 return result;
7022 }
7023
7024 static KLANG_BLEP_INLINE bool finite(unsigned int bits) {
7025 return (bits & 0x7f800000u) != 0x7f800000u;
7026 }
7027
7028 static KLANG_BLEP_INLINE std::int32_t signedDistance(unsigned int distance) {
7029 std::int32_t result;
7030 std::memcpy(&result, &distance, sizeof(result));
7031 return result;
7032 }
7033
7034 KLANG_BLEP_INLINE float step(unsigned int distance) const {
7035 if (distance + width >= 2u * width) return 0;
7036 const auto ticks = signedDistance(distance);
7037 const float x = 1.f - std::fabs(float(ticks)) * inverseWidth;
7038 return ticks < 0 ? x * x : -x * x;
7039 }
7040
7041 KLANG_BLEP_INLINE float corner(unsigned int distance) const {
7042 if (distance + width >= 2u * width) return 0;
7043 const float x = 1.f - std::fabs(float(signedDistance(distance))) * inverseWidth;
7044 return x * x * x;
7045 }
7046
7047 // Integrate close edges without subtracting large, nearly equal corrections.
7048 KLANG_BLEP_COLD float integrate(unsigned int phase) const {
7049 const double center = double(phase) / turn;
7050 const double duty = dutyCycle;
7051 const double radius = double(width) / turn;
7052 if (!width) {
7053 if constexpr (PULSE) return center < duty ? 1.f : -1.f;
7054 else return float(center < duty
7055 ? 2 * center / duty - 1 : 2 * (1 - center) / (1 - duty) - 1);
7056 }
7057 double sum = 0;
7058 const auto segment = [&](double start, double length, double from, double to) {
7059 const double end = start + length;
7060 for (int side : {-1, 1}) {
7061 const double a = std::max(start, side < 0 ? -radius : 0.);
7062 const double b = std::min(end, side < 0 ? 0. : radius);
7063 if (a >= b) continue;
7064 const double ka = 1 - std::fabs(a) / radius, kb = 1 - std::fabs(b) / radius;
7065 const double va = from + (to - from) * ((a - start) / length);
7066 const double vb = from + (to - from) * ((b - start) / length);
7067 sum += (b - a) / (6 * radius) * (va * (2 * ka + kb) + vb * (ka + 2 * kb));
7068 }
7069 };
7070 for (int cycle : {-1, 0, 1}) {
7071 const double start = cycle - center;
7072 if constexpr (PULSE) {
7073 segment(start, duty, 1, 1);
7074 segment(start + duty, 1 - duty, -1, -1);
7075 }
7076 else {
7077 segment(start, duty, -1, 1);
7078 segment(start + duty, 1 - duty, 1, -1);
7079 }
7080 }
7081 return float(sum);
7082 }
7083 };
7084 /// @endcond
7085
7086 /// Descending saw with polynomial correction at the wrap.
7087 struct Saw : public Polynomial<false> {
7088 KLANG_BLEP_INLINE Saw() : Polynomial(0.f) {}
7089 };
7090
7091 /// Triangle with polynomial correction at the slope changes.
7092 struct Triangle : public Polynomial<false> {
7093 KLANG_BLEP_INLINE Triangle() : Polynomial(.5f) {}
7094 };
7095
7096 /// Square wave with 50% high duty and polynomial edge correction.
7097 struct Square : public Polynomial<true> {
7098 KLANG_BLEP_INLINE Square() : Polynomial(.5f) {}
7099 };
7100
7101 /// Pulse with adjustable duty and polynomial edge correction.
7102 struct Pulse : public Polynomial<true> {
7103 KLANG_BLEP_INLINE Pulse() : Polynomial(.5f) {}
7104 };
7105
7106#undef KLANG_BLEP_COLD
7107#undef KLANG_BLEP_INLINE
7108 };
7109
7110
7111 /// Wavetable-based oscillators
7112 namespace Wavetables {
7113 /// Sine wave oscillator (wavetable)
7114 struct Sine : public Wavetable {
7115 Sine() : Wavetable(Basic::Sine()) {}
7116 };
7117
7118 /// Saw wave oscillator (wavetable)
7119 struct Saw : public Wavetable {
7120 Saw() : Wavetable(Basic::Saw()) {}
7121 };
7122 }
7123 };
7124
7125 /// @cond
7126 namespace detail {
7127 enum class Response { LowPass, HighPass, BandPass, BandReject };
7128
7129 // Transform a first- or second-order analogue prototype into digital sections.
7130 template<int FAMILY, int ORDER, Response SHAPE>
7131 struct PrototypeFilter : Modifier {
7132 static_assert(ORDER == 1 || ORDER == 2, "Supported prototype orders are 1 and 2");
7133 static constexpr bool band = SHAPE == Response::BandPass || SHAPE == Response::BandReject;
7134 static constexpr int count = band ? ORDER : 1;
7135 static constexpr float defaultRipple = FAMILY == 1 ? 1 : FAMILY == 2 ? 40 : 0;
7136
7137 /// Set the edge frequency in Hz for a low-pass or high-pass response.
7138 void set(param edge) override {
7139 if constexpr (!band) configure(edge, 0, defaultRipple);
7140 }
7141
7142 /// Set the cutoff and ripple in dB, or the two band edges in Hz.
7143 void set(param first, param second) override {
7144 if constexpr (band) configure(first, second, defaultRipple);
7145 else configure(first, 0, second);
7146 }
7147
7148 /// Set the two band edges in Hz and the ripple or attenuation in dB.
7149 void set(param lower, param upper, param ripple) override {
7150 if constexpr (band) configure(lower, upper, ripple);
7151 }
7152
7153 void reset() {
7154 for (auto& section : sections) section.z1 = section.z2 = 0;
7155 in = out = 0;
7156 }
7157
7158 void process() override {
7159 double sample = float(in);
7160 for (auto& section : sections) {
7161 const double next = section.b0 * sample + section.z1;
7162 section.z1 = section.b1 * sample - section.a1 * next + section.z2;
7163 section.z2 = section.b2 * sample - section.a2 * next;
7164 sample = next;
7165 }
7166 out = sample;
7167 }
7168
7169 private:
7170 using Complex = std::complex<double>;
7171
7172 struct Section {
7173 double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0;
7174 double z1 = 0, z2 = 0;
7175 };
7176
7177 Section sections[count];
7178 float lowerHz = 0, upperHz = 0, rippleDb = 0, sampleRate = 0;
7179
7180 static bool finite(float value) {
7181 std::uint32_t bits;
7182 std::memcpy(&bits, &value, sizeof(bits));
7183 return (bits & 0x7f800000u) != 0x7f800000u;
7184 }
7185
7186 static Complex digital(Complex value) { return (1.0 + value) / (1.0 - value); }
7187
7188 static std::array<Complex, 2> bandRoots(Complex value, double center, double width) {
7189 const Complex half = value * (width * .5);
7190 const Complex root = std::sqrt(half * half - center * center);
7191 return { half + root, half - root };
7192 }
7193
7194 static Section coefficients(Complex pole, Complex otherPole, Complex zero, Complex otherZero) {
7195 return { 1, -(zero + otherZero).real(), (zero * otherZero).real(),
7196 -(pole + otherPole).real(), (pole * otherPole).real() };
7197 }
7198
7199 void configure(float lower, float upper, float ripple) {
7200 const float rate = fs;
7201 if (lower == lowerHz && upper == upperHz && ripple == rippleDb && rate == sampleRate)
7202 return;
7203 if (!finite(lower) || !finite(upper) || !finite(ripple) || !finite(rate)
7204 || lower <= 0 || lower >= rate * .5f
7205 || (band && (upper <= lower || upper >= rate * .5f)))
7206 return;
7207 if constexpr (FAMILY != 0)
7208 if (ripple <= 0 || ripple > 120) return;
7209
7210 const double diagonal = 1 / root2.d;
7211 Complex pole(-diagonal, diagonal);
7212 if constexpr (ORDER == 1) pole = -1;
7213 double passGain = 1;
7214 if constexpr (FAMILY != 0) {
7215 const double epsilon = std::sqrt(std::expm1(double(ripple) * std::log(10.0) / 10));
7216 const double stretch = std::asinh(FAMILY == 1 ? 1 / epsilon : epsilon) / 2;
7217 pole = Complex(-std::sinh(stretch), std::cosh(stretch)) * diagonal;
7218 if constexpr (FAMILY == 1) passGain = std::pow(10.0, -double(ripple) / 20);
7219 else pole = 1.0 / pole;
7220 }
7221
7222 const double edge = std::tan(pi.d * lower / rate);
7223 const Complex prototypeZero(0, root2.d);
7224 Section next[count];
7225 Complex point(1);
7226 if constexpr (!band) {
7227 const bool high = SHAPE == Response::HighPass;
7228 const Complex p = digital(high ? edge / pole : edge * pole);
7229 Complex z = high ? 1.0 : -1.0;
7230 if constexpr (FAMILY == 2)
7231 z = digital(high ? edge / prototypeZero : edge * prototypeZero);
7232 next[0] = coefficients(p, ORDER == 1 ? Complex{} : std::conj(p),
7233 z, ORDER == 1 ? Complex{} : std::conj(z));
7234 if (high) point = -1;
7235 }
7236 else {
7237 const bool reject = SHAPE == Response::BandReject;
7238 const double high = std::tan(pi.d * upper / rate);
7239 const double center = std::sqrt(edge * high);
7240 const double width = high - edge;
7241 const auto poles = bandRoots(reject ? 1.0 / pole : pole, center, width);
7242 const auto zeros = bandRoots(reject ? 1.0 / prototypeZero : prototypeZero, center, width);
7243 for (int i = 0; i < count; i++) {
7244 const Complex p = digital(poles[i]);
7245 const Complex other = ORDER == 1 ? digital(poles[1]) : std::conj(p);
7246 Complex z = reject ? digital(Complex(0, center)) : Complex(1);
7247 Complex second = reject ? std::conj(z) : Complex(-1);
7248 if constexpr (FAMILY == 2) {
7249 z = digital(zeros[i]);
7250 second = std::conj(z);
7251 }
7252 next[i] = coefficients(p, other, z, second);
7253 }
7254 if (!reject) point = digital(Complex(0, center));
7255 }
7256
7257 // Normalise each section at the pass-band reference frequency.
7258 const Complex delay = 1.0 / point;
7259 const Complex delay2 = delay * delay;
7260 for (auto& section : next) {
7261 if (std::abs(section.a2) >= 1 || 1 + section.a1 + section.a2 <= 0
7262 || 1 - section.a1 + section.a2 <= 0) return;
7263 const double gain = std::abs(1.0 + section.a1 * delay + section.a2 * delay2)
7264 / std::abs(section.b0 + section.b1 * delay + section.b2 * delay2);
7265 if (!(gain > 0) || !(gain <= std::numeric_limits<double>::max())) return;
7266 section.b0 *= gain;
7267 section.b1 *= gain;
7268 section.b2 *= gain;
7269 }
7270 next[0].b0 *= passGain;
7271 next[0].b1 *= passGain;
7272 next[0].b2 *= passGain;
7273 for (int i = 0; i < count; i++) {
7274 next[i].z1 = sections[i].z1;
7275 next[i].z2 = sections[i].z2;
7276 sections[i] = next[i];
7277 }
7278 lowerHz = lower;
7279 upperHz = upper;
7280 rippleDb = ripple;
7281 sampleRate = rate;
7282 }
7283 };
7284 }
7285 /// @endcond
7286
7287
7288 /// Common audio filters.
7289 namespace Filters {
7290
7291 /// Simple DC filter / blocker
7292 struct DCF : public Modifier {
7293 float r = 0.995f; // Decay factor (adjustable)
7294 float z = 0; // Filter state (last input)
7295
7296 void set(param r) override { this->r = r; }
7297
7298 void process() override {
7299 out = in - z + r * out;
7300 z = in;
7301 }
7302 };
7303
7304 /// IIR filter for specified order
7305 template<int ORDER>
7306 struct IIR : public Modifier {
7307 virtual ~IIR() {}
7308
7309 float a[ORDER] = { }; // Feedback coefficients (a1, a2, ..., aN)
7310 float y[ORDER] = { }; // Previous outputs (y[n-1], y[n-2], ..., y[n-N])
7311
7312 template <typename... Coeffs>
7313 void set(Coeffs... coeffs) {
7314 static_assert(sizeof...(coeffs) == ORDER, "Incorrect number of coefficients.");
7315 _set<0>(coeffs...);
7316 }
7317
7318 void process() {
7319 out = in;
7320 for (size_t i = 0; i < ORDER; ++i)
7321 out -= a[i] * y[i];
7322
7323 for (size_t i = ORDER - 1; i > 0; --i)
7324 y[i] = y[i - 1];
7325 y[0] = out;
7326 }
7327
7328 protected:
7329 // Helper function to unpack variadic arguments into a[]
7330 template <size_t index, typename First, typename... Rest>
7331 void _set(First first, Rest... rest) {
7332 a[index] = first;
7333 if constexpr (index + 1 < ORDER)
7334 _set<index + 1>(rest...);
7335 }
7336 };
7337
7338 // optimised first-order IIR
7339 template <>
7340 struct IIR<1> : public Modifier {
7341 virtual ~IIR() {}
7342
7343 float a = 1, b = 0; // Feedback coefficients (a1, a2)
7344
7345 void set(param coeff) {
7346 a = coeff;
7347 b = 1.f - a;
7348 }
7349
7350 void process() {
7351 out = in * a + out * b;
7352 }
7353
7354 /// Compute the phase offset in seconds at a given frequency
7355 float phase(float f) const {
7356 float omega = 2.0f * pi.f * f / fs.f;
7357 float cos_w = cosf(omega);
7358 float sin_w = sinf(omega);
7359
7360 return atan2(b * sin_w, 1.f - b * cos_w) / (2.0f * pi.f * f); // Convert to seconds
7361 }
7362
7363 /// Compute the group delay in samples at a given frequency
7364 float delay(float f) const {
7365 const float omega = 2.0f * pi.f * f / fs.f;
7366 const float cos_w = cosf(omega);
7367 return (1.f - a * a) / (1.f - 2.f * a * cos_w + a * a);
7368 }
7369 };
7370
7371 /// Single-pole (one-pole, one-zero) First Order Filters
7372 namespace OnePole
7373 {
7374 /// Abstract filter class
7375 struct Filter : Modifier {
7376 virtual ~Filter() {}
7377
7378 float f = 0; // cutoff f
7379 //float shelf = 1; // shelving gain
7380
7381 float /*a0 = 1*/ a1 = 0, b0 = 1, b1 = 0; //coefficients
7382
7383 float exp0 = 0;
7384 //float tan0 = 0;
7385 float z = 0; // filter state
7386
7387 void reset() {
7388 a1 = 0;
7389 b0 = 1;
7390 b1 = 0;
7391 f = 0;
7392 z = 0;
7393 }
7394
7395 void set(param f) {
7396 if (Filter::f != f) {
7397 Filter::f = f;
7398 init();
7399 }
7400 }
7401
7402 virtual void init() = 0;
7403
7404 void process() {
7405 out = b0 * in + b1 * z + a1 * out + DENORMALISE;
7406 z = in;
7407 }
7408 };
7409
7410 /// Low-pass filter (LPF)
7411 struct LPF : Filter {
7412 virtual ~LPF() {}
7413
7414 void init() {
7415 const float exp0 = expf(-f * fs.w);
7416 b0 = 1 - exp0;
7417 a1 = exp0;
7418 }
7419
7420 void process() {
7421 out = b0 * in + a1 * out + DENORMALISE;
7422 }
7423
7424 /// Compute the phase delay in seconds at a given frequency
7425 float phase(float f) const {
7426 float omega = 2.0f * pi.f * f / fs.f;
7427 float cos_w = cosf(omega);
7428 float sin_w = sinf(omega);
7429
7430 float real = b0 - a1 * cos_w;
7431 float imag = -a1 * sin_w;
7432
7433 float phaseRadians = atan2f(imag, real);
7434 return phaseRadians / (2.0f * pi.f * f); // Convert to seconds
7435 }
7436 };
7437
7438 /// High-pass filter (HPF)
7439 struct HPF : Filter {
7440 virtual ~HPF() {}
7441
7442 void init() {
7443 const float exp0 = expf(-f * fs.w);
7444 b0 = 0.5f * (1.f + exp0);
7445 b1 = -b0;
7446 a1 = exp0;
7447 }
7448 };
7449 };
7450
7451 /// Transposed Direct Form II Biquadratic Filter
7452 namespace Biquad {
7453
7454 /// Abstract filter class
7456 {
7457 virtual ~Filter() {}
7458
7459 float f = 0; // cutoff/centre f
7460 float Q = 0; // Q (resonance)
7461
7462 float /*a0 = 1*/ a1 = 0, a2 = 0, b0 = 1, b1 = 0, b2 = 0; // coefficients
7463
7464 float a = 0; // alpha
7465 float cos0 = 1; // cos(omega)
7466 float sin0 = 0; // sin(omega)
7467 float z[2] = { 0 }; // filter state
7468
7469 /// Reset filter state
7470 void reset() {
7471 f = 0;
7472 Q = 0;
7473 b0 = 1;
7474 a1 = a2 = b1 = b2 = 0;
7475 a = 0;
7476 z[0] = z[1] = 0;
7477 }
7478
7479 /// Set the filter cutoff (default Q)
7480 void set(param f) { this->set(f, root2.inv); }
7481
7482 /// Set the filter cutoff and bandwidth
7483 void set(param f, relative bw) {
7484 if (bw > 0)
7485 this->set(f, param(f / bw));
7486 }
7487
7488 /// Set the filter cutoff and Q
7489 void set(param f, param Q) {
7490 if (Q < 0) // treat negative Q as bandwidth
7491 Q = f / -Q;
7492
7493 if (Filter::f != f || Filter::Q != Q) {
7494 Filter::f = f;
7495 Filter::Q = Q;
7496
7497 const float w = f * fs.w;
7498 cos0 = cosf(w);
7499 sin0 = sinf(w);
7500
7501 if (Q < 0.5) Q = 0.5;
7502 a = sin0 / (2.f * Q);
7503 this->init();
7504 }
7505 }
7506
7507 virtual void init() = 0;
7508
7509 /// Apply the biquad filter (Transposed Direct Form II)
7510 void process() noexcept {
7511 const float z0 = z[0];
7512 const float z1 = z[1];
7513 const float y = b0 * in + z0;
7514 z[0] = b1 * in - a1 * y + z1;
7515 z[1] = b2 * in - a2 * y;
7516 out = y;
7517 }
7518
7519 /// Return the phase offset for the specified frequency (in seconds)
7520 float phase(float f) const
7521 {
7522 float omega = 2.0f * pi.f * f / fs.f;
7523 float cos_w = std::cos(omega);
7524 float sin_w = std::sin(omega);
7525
7526 float real = b0 + b1 * cos_w + b2 * cos(2 * omega);// -(a1 * cos_w + a2 * cos(2 * omega));
7527 float imag = b1 * sin_w + b2 * sin(2 * omega);// -(a1 * sin_w + a2 * sin(2 * omega));
7528 float phaseRadians = std::atan2(-imag, real);
7529
7530 real = 1 + (a1 * cos_w + a2 * cos(2 * omega));
7531 imag = (a1 * sin_w + a2 * sin(2 * omega));
7532
7533 phaseRadians -= std::atan2(-imag, real);
7534 return phaseRadians / (2.0f * pi.f * f); // Convert to seconds
7535 }
7536
7537 /// Return the group delay for the specified frequency (in samples)
7538 float delay(float f) const
7539 {
7540 float omega = 2.0f * pi.f * f / fs.f;
7541 float cos_w = std::cos(omega);
7542 float sin_w = std::sin(omega);
7543
7544 // Compute transfer function components
7545 float R = b0 + b1 * cos_w + b2 * cos(2 * omega) - (a1 * cos_w + a2 * cos(2 * omega));
7546 float I = b1 * sin_w + b2 * sin(2 * omega) - (a1 * sin_w + a2 * sin(2 * omega));
7547
7548 // Compute phase response
7549 //float phaseRadians = std::atan2(I, R);
7550
7551 // Compute the derivative of phase (group delay)
7552 float dR_dOmega = -b1 * sin_w - 2 * b2 * sin(2 * omega) + a1 * sin_w + 2 * a2 * sin(2 * omega);
7553 float dI_dOmega = b1 * cos_w + 2 * b2 * cos(2 * omega) - a1 * cos_w - 2 * a2 * cos(2 * omega);
7554
7555 return (R * dI_dOmega - I * dR_dOmega) / (R * R + I * I);
7556 }
7557 };
7558
7559 /// Low-pass filter (LPF)
7560 struct LPF : Filter {
7561 virtual ~LPF() {}
7562
7563 void init() override {
7564 constant a0 = { 1.f + a };
7565 a1 = a0.inv * (-2.f * cos0);
7566 a2 = a0.inv * (1.f - a);
7567
7568 b2 = b0 = a0.inv * (1.f - cos0) * 0.5f;
7569 b1 = a0.inv * (1.f - cos0);
7570 }
7571 };
7572
7573 typedef LPF HCF; ///< High-cut filter (HCF)
7574 typedef LPF HRF; ///< High-reject filter (HRF)
7575
7576 /// High-pass filter (HPF)
7577 struct HPF : Filter {
7578 virtual ~HPF() {}
7579
7580 void init() {
7581 constant a0 = { 1.f + a };
7582 a1 = a0.inv * (-2.f * cos0);
7583 a2 = a0.inv * (1.f - a);
7584
7585 b2 = b0 = a0.inv * (1.f + cos0) * 0.5f;
7586 b1 = a0.inv * -(1.f + cos0);
7587 }
7588 };
7589
7590 typedef HPF LCF; ///< Low-cut filter (LCF)
7591 typedef HPF LRF; ///< Low-reject filter (LRF)
7592
7593 /// Band-pass filter (BPF)
7594 struct BPF : Filter {
7595
7596 enum Gain {
7597 ConstantSkirtGain, ///< Constant Skirt Gain
7598 ConstantPeakGain ///< Constant Peak Gain
7600
7601 /// Set the constant gain mode.
7603 init_gain = gain == ConstantSkirtGain ? &BPF::init_skirt : &BPF::init_peak;
7604 init();
7605 return *this;
7606 }
7607
7608 using Init = void(BPF::*)(void); ///< @internal
7609 Init init_gain = &BPF::init_peak; ///< @internal
7610 void init() { (this->*init_gain)(); } ///< @internal
7611
7612 /// @internal
7613 void init_skirt() {
7614 // constant skirt gain
7615 constant a0 = { 1.f + a };
7616 a1 = a0.inv * (-2.f * cos0);
7617 a2 = a0.inv * (1.f - a);
7618
7619 b0 = a0.inv * sin0 * 0.5f;
7620 b1 = 0;
7621 b2 = -b0;
7622 }
7623
7624 /// @internal
7625 void init_peak() {
7626 // constant peak gain
7627 constant a0 = { 1.f + a };
7628 a1 = a0.inv * (-2.f * cos0);
7629 a2 = a0.inv * (1.f - a);
7630
7631 b0 = a0.inv * a;
7632 b1 = 0;
7633 b2 = a0.inv * -a;
7634 }
7635 };
7636
7637 /// Band-Reject Filter (BRF)
7638 struct BRF : Filter {
7639 void init() {
7640 constant a0 = { 1.f + a };
7641 b1 = a1 = a0.inv * (-2.f * cos0);
7642 a2 = a0.inv * (1.f - a);
7643 b0 = b2 = a0.inv;
7644 }
7645 };
7646
7647 typedef BRF BSF; ///< Band-stop filter (BSF)
7648
7649 /// All-pass filter (APF)
7650 struct APF : Filter {
7651 param r = 1.f;
7652
7653 /// Set the filter cutoff (default r)
7654 void set(param f) { this->set(f, 1.f); }
7655
7656 /// Set the pole frequency and radius (r)
7657 void set(param f, param r) {
7658 if (Filter::f != f || a != r) {
7659 Filter::f = f;
7660 a = r;
7661
7662 const float w = f * fs.w;
7663 cos0 = cosf(w);
7664 sin0 = sinf(w);
7665
7666 init();
7667 }
7668 }
7669
7670 void init() {
7671 float omega = 2.0f * pi * f / fs;
7672 float cos0 = cos(omega);
7673
7674 b0 = a2 = a * a;
7675 b1 = a1 = (-2.f * a * cos0);
7676 b2 = 1.f;
7677 }
7678 };
7679 }
7680 // }
7681
7682 /// Butterworth filters with a maximally flat passband.
7683 namespace Butterworth {
7684 /// Low-pass filter (LPF).
7685 template<int ORDER>
7687 virtual ~LPF() {}
7688 };
7689
7690 template<>
7691 struct LPF<1> : OnePole::Filter {
7692 virtual ~LPF() {}
7693
7694 void init() {
7695 const float c = 1.f / tanf(pi * f * fs.inv);
7696 constant a0 = { 1.f + c };
7697 b0 = a0.inv; // b0 == b1
7698 a1 = (1.f - c) * a0.inv; // = (1-c) / a0
7699 }
7700 void process() {
7701 out = b0 * (in + z) - a1 * out;// +DENORMALISE;
7702 z = in;
7703 }
7704 };
7705
7706 template<>
7707 struct LPF<2> : Biquad::Filter {
7708 void init() {
7709 constant a0 = { 1.f + a };
7710 b0 = a0.inv * ((1.f - cos0) / 2.f);
7711 b1 = a0.inv * (1.f - cos0);
7712 b2 = a0.inv * ((1.f - cos0) / 2.f);
7713 a1 = a0.inv * ( - 2.f * cos0);
7714 a2 = a0.inv * (1.f - a);
7715 }
7716 };
7717
7718 /// High-pass Butterworth filter for prototype order 1 or 2.
7719 template<int ORDER>
7720 struct HPF : detail::PrototypeFilter<0, ORDER, detail::Response::HighPass> {};
7721
7722 /// Band-pass Butterworth filter for prototype order 1 or 2.
7723 template<int ORDER>
7724 struct BPF : detail::PrototypeFilter<0, ORDER, detail::Response::BandPass> {};
7725
7726 /// Band-reject Butterworth filter for prototype order 1 or 2.
7727 template<int ORDER>
7728 struct BRF : detail::PrototypeFilter<0, ORDER, detail::Response::BandReject> {};
7729 };
7730
7731 /// Chebyshev filters selected by type, with a second-order low-pass prototype.
7732 template<int TYPE>
7733 struct Chebyshev {
7734 static_assert(TYPE == 1 || TYPE == 2, "Chebyshev type must be 1 or 2");
7735
7736 /// Low-pass Chebyshev response.
7737 struct LPF : detail::PrototypeFilter<TYPE, 2, detail::Response::LowPass> {};
7738
7739 /// High-pass Chebyshev response.
7740 struct HPF : detail::PrototypeFilter<TYPE, 2, detail::Response::HighPass> {};
7741
7742 /// Band-pass Chebyshev response.
7743 struct BPF : detail::PrototypeFilter<TYPE, 2, detail::Response::BandPass> {};
7744
7745 /// Band-reject Chebyshev response.
7746 struct BRF : detail::PrototypeFilter<TYPE, 2, detail::Response::BandReject> {};
7747 };
7748 }
7749
7750 /// Common audio modifiers.
7751 namespace Modifiers {
7752 /// Modal resonator
7753 struct Modal : public Modifier {
7754 float a1 = 0, a2 = 0;
7755 float y1 = 0, y2 = 0;
7756
7757 float gain = 0.05f;
7758
7759 // initialise the resonator
7760 void set(param f, param decay, param gain) {
7761 set(f, decay);
7762 this->gain = std::clamp(gain.value * 0.05f, -0.05f, 0.05f);
7763 }
7764
7765 void set(param f, param decay) {
7766 gain = 0.05f;
7767
7768 constexpr float min_d = 1e-6f; // Prevents underflow
7769 constexpr float max_d = 0.9999f; // Ensures stability
7770
7771 const float w = f.value * fs.w;
7772 const float d = std::clamp(std::exp(-pi / (decay * fs)), min_d, max_d);
7773
7774 a1 = 2.f * d * std::clamp(std::cos(w), -0.9999f, 0.9999f);
7775 a2 = -d * d;
7776
7777 y2 = 0;
7778 y1 = 0;
7779 in = 0;
7780 out = 0;
7781 }
7782
7783 void input() {
7784 in *= gain;
7785 }
7786
7787 void process() {
7788 out = in + a1 * y1 + a2 * y2;
7789 y2 = y1;
7790 y1 = out;
7791 in = 0;
7792 }
7793 };
7794 };
7795
7796 /// Envelope follower (Peak / RMS)
7798
7799 /// Attack / Release IIR Filter (~Butterworth when attack == release)
7800 struct AR : Modifier {
7801 param attack = 0;
7802 param release = 0;
7803
7804 param A = 1, R = 1;
7805
7806 void set(param attack, param release) {
7807 if (AR::attack != attack || AR::release != release) {
7808 AR::attack = attack;
7809 AR::release = release;
7810 A = 1.f - (attack == 0.f ? 0.f : expf(-1.0f / (fs * attack)));
7811 R = 1.f - (release == 0.f ? 0.f : expf(-1.0f / (fs * release)));
7812 }
7813 }
7814
7815 void process() {
7816 const float smoothing = in > out ? A : R;
7817 (out + smoothing * (in - out)) >> out;
7818 }
7819 } ar;
7820
7821 // Peak / RMS Envelope Follower (default; filter-based)
7822 Follower() { set(0.01f, 0.1f); }
7823 void set(param attack, param release) {
7824 ar.set(attack, release);
7825 }
7826
7828 _process = (mode == RMS) ? &Follower::rms : &Follower::peak;
7829 return *this;
7830 }
7831
7832 using Process = void(Follower::*)();
7833 Process _process = &Follower::rms;
7834
7835 void process() { (this->*_process)(); }
7836
7837 void peak() { abs(in) >> ar >> out; }
7838 void rms() { (in * in) >> ar >> sqrt >> out; }
7839
7840 /// Window-based envelope follower
7841 template<int WINDOW>
7843 {
7846 double sum = 0; // NB: must be 64-bit to avoid rounding errors
7847 static constexpr constant window = { WINDOW };
7848
7849 Window() : buffer(WINDOW, 0) {
7850 set(0.01f, 0.1f);
7851 }
7852
7853 void set(param attack, param release) {
7854 ar.set(attack, release);
7855 }
7856
7858 _process = (mode == RMS) ? &Window::rms : &Window::mean;
7859 return *this;
7860 }
7861
7862 using Process = void(Window::*)();
7863 Process _process = &Window::rms;
7864
7865 void process() { (this->*_process)(); }
7866
7867 void mean() {
7868 sum -= double(buffer);
7869 abs(in) >> buffer;
7870 sum += double(buffer++);
7871 if (buffer.finished())
7872 buffer.rewind();
7873 sum* window.inv >> ar >> out;
7874 }
7875 void rms() {
7876 sum -= double(buffer);
7877 (in * in) >> buffer;
7878 sum += double(buffer++);
7879 if (buffer.finished())
7880 buffer.rewind();
7881 signal(sum * window.inv) >> sqrt >> ar >> out;
7882 }
7883 };
7884 };
7885
7886 struct File {
7887#if defined(_MSC_VER) && !defined(__clang__)
7888#define packed __pragma(pack(push,1)) struct __pragma(pack(pop))
7889#else
7890#define packed struct __attribute__((packed))
7891#endif
7892 struct Format {
7893 unsigned int channels = 0;
7894 unsigned int samplerate = 0;
7895 unsigned int bitrate = 0;
7896 };
7897
7898 packed Chunk{
7899 struct ID {
7900 char id[4] = { 0 };
7901 ID() = default;
7902 ID(const char* id) : id{ id[0], id[1], id[2], id[3] } {}
7903 bool operator==(const ID& id) const {
7904 return memcmp(ID::id, id.id, 4) == 0;
7905 }
7906 bool operator==(const char* const id) const {
7907 return memcmp(ID::id, id, 4) == 0;
7908 }
7909 } id;
7910 unsigned int size = 0;
7911
7912 Chunk() = default;
7913 Chunk(ID id, unsigned int size = 0) : id(id), size(size) {}
7914 };
7915
7916 packed Header : Chunk{
7917 ID format;
7918
7919 Header() = default;
7920 Header(ID id, ID format, unsigned int size = 0) : Chunk(id, size), format(format) {}
7921
7922 bool isWAV() const { return id == "RIFF" && format == "WAVE"; }
7923 bool isAIFF() const { return id == "FORM" && format == "AIFF"; }
7924 };
7925
7926 packed WAV{
7927 Memory memory;
7928
7929 packed Header : File::Header {
7930 Header() : File::Header("RIFF", "WAVE") {}
7931 } *header = nullptr;
7932
7933 packed Format : Chunk {
7934 unsigned short AudioFormat;
7935 unsigned short NumChannels;
7936 unsigned int SampleRate;
7937 unsigned int ByteRate;
7938 unsigned short BlockAlign;
7939 unsigned short BitsPerSample;
7940
7941 Format() : Chunk("fmt ", sizeof(Format)) {}
7942
7943 operator File::Format() const { return { NumChannels, SampleRate, BitsPerSample }; }
7944 } *format = nullptr;
7945
7946 packed Data : Chunk {
7947 unsigned char data[1] = { 0 };
7948
7949 Data() : Chunk("data") {}
7950 } *data = nullptr;
7951
7952 // use internal memory
7953 bool load(const char* path) {
7954 memory.load(path);
7955 return load();
7956 }
7957
7958 // use external memory
7959 bool load(Memory& memory) {
7960 WAV::memory = &memory;
7961 return load();
7962 }
7963
7964 bool load() {
7965 if (!memory.ptr)
7966 return false;
7967 memory.rewind();
7968
7969 // header
7970 header = (Header*)memory.ptr;
7971 if (!header->isWAV())
7972 return false;
7973 memory.skip(sizeof(Header));
7974
7975 // other chunks
7976 while (!memory.finished()) {
7977 const Chunk chunk = memory;
7978 memory.rewind(sizeof(Chunk));
7979 if (chunk.id == "fmt ")
7980 format = (Format*)memory.ptr;
7981 else if (chunk.id == "data") {
7982 if (memory.ptr + chunk.size > memory.end)
7983 return false; // corrupt
7984 data = (Data*)memory.ptr;
7985 }
7986 memory.skip(sizeof(Chunk) + chunk.size);
7987 }
7988 return true;
7989 }
7990
7991 template<typename TYPE, int STEP = 1>
7992 inline static void decode(float* buffer, const TYPE* data, int length) {
7993 if constexpr (std::is_floating_point<TYPE>::value) {
7994 while (length--) {
7995 *buffer++ = *data;
7996 data += STEP;
7997 }
7998 } else {
7999 constexpr unsigned int twoComp = 1U << (sizeof(TYPE) * 8 - 1);
8000 if constexpr (std::numeric_limits<TYPE>::is_signed) {
8001 constexpr float scale = 1.f / twoComp;
8002 while (length--) {
8003 *buffer++ = static_cast<float>(*data) * scale;
8004 data += STEP;
8005 }
8006 } else {
8007 constexpr float scale = 1.f / ((twoComp << 1) - 1);
8008 while (length--) {
8009 *buffer++ = (static_cast<float>(*data) - twoComp) * scale;
8010 data += STEP;
8011 }
8012 }
8013 }
8014 }
8015
8017 if (!header || !format || !data)
8018 return false;
8019
8020 buffer.resize(data->size / format->BlockAlign);
8021 if (format->AudioFormat == 1) { // PCM (integer)
8022 if (format->BitsPerSample == 8)
8023 decode<unsigned char>(buffer.data(), (unsigned char*)data->data, buffer.size); // 8-bit (unsigned)
8024 else if(format->BitsPerSample == 16)
8025 decode<signed short>(buffer.data(), (signed short*)data->data, buffer.size); // 16-bit (signed)
8026 else if(format->BitsPerSample == 32)
8027 decode<signed int>(buffer.data(), (signed int*)data->data, buffer.size); // 32-bit (signed)
8028 } else if (format->AudioFormat == 3) {
8029 if(format->BitsPerSample == 32)
8030 decode<float>(buffer.data(), (float*)data->data, buffer.size); // 32-bit (float)
8031 }
8032 return true;
8033 }
8034 };
8035
8036 //struct AIFF {
8037 // struct Binary Extended {
8038 // unsigned short exponent; // 15-bit exponent + sign bit
8039 // unsigned long long mantissa; // 64-bit mantissa
8040 //
8041 // operator double() const {
8042 // uint16_t exp = (exponent >> 8) | (exponent << 8); // Swap bytes (big-endian to host)
8043 // const bool sign = exp & 0x8000; // Extract sign bit
8044 // exp &= 0x7FFF; // Remove sign bit
8045 //
8046 // uint64_t mant = __builtin_bswap64(mantissa); // Convert mantissa (big-endian to host)
8047 // if (exp == 0 && mant == 0) return 0.0; // Handle zero case
8048 //
8049 // double fraction = static_cast<double>(mant) / (1ULL << 63); // normalize mantissa (hidden bit)
8050 // return (sign ? -fraction : fraction) * std::pow(2.0, exp - 16383);
8051 // }
8052 // };
8053 //
8054 // struct Binary Header : File::Header {
8055 // Header() : File::Header("FORM", "AIFF") {}
8056 // };
8057 //
8058 // struct Binary Format : Chunk {
8059 // unsigned short numChannels;
8060 // unsigned int numSamplesFrames;
8061 // unsigned short sampleSize;
8062 // Extended sampleRate;
8063 //
8064 // Format() : Chunk("COMM ", sizeof(Format)) { }
8065 //
8066 // operator File::Format() const { return { numChannels, sampleRate, sampleSize }; }
8067 // };
8068 //};
8069 };
8070
8071 namespace basic {
8072 using namespace klang;
8073
8074 using namespace Generators::Basic;
8075 using namespace Modifiers;
8076 using namespace Filters;
8077 using namespace Filters::Biquad;
8078 };
8079
8080 namespace optimised {
8081 using namespace klang;
8082
8083 using namespace Generators::Fast;
8084 using namespace Generators::OSM;
8085 using namespace Modifiers;
8086 using namespace Filters;
8087 using namespace Filters::Biquad;
8088 };
8089
8090 namespace minimal {
8091 using namespace klang;
8092 };
8093
8094 //using namespace optimised;
8095};
8096
8097#if defined(KLANG_WARNING_SCOPE)
8098#pragma warning(pop)
8099#undef KLANG_WARNING_SCOPE
8100#endif
8101
8102//using namespace klang;
Envelope object.
Definition klang.h:5041
std::shared_ptr< Ramp > ramp
Definition klang.h:5425
Stage
Envelope stage.
Definition klang.h:5128
std::vector< Point > points
Definition klang.h:5418
Base class for synthesiser notes.
Definition klang.h:5562
enum klang::NoteBase::Stage stage
virtual event on(Pitch p, Velocity v)
Definition klang.h:5577
virtual bool stop(Velocity v=0)
Definition klang.h:5618
virtual void init()
Definition klang.h:5596
bool finished() const
Definition klang.h:5623
void attach(SYNTH *synth)
Definition klang.h:5590
Controls controls
Definition klang.h:5585
virtual ~NoteBase()
Definition klang.h:5588
virtual void controlChange(int controller, int value)
Definition klang.h:5627
virtual void start(Pitch p, Velocity v)
Definition klang.h:5598
Velocity velocity
Definition klang.h:5584
virtual event off(Velocity v=0)
Definition klang.h:5578
virtual bool release(Velocity v=0)
Definition klang.h:5606
auto getSynth()
Definition klang.h:5581
Wavetable-based oscillator.
Definition klang.h:4844
Audio buffer (mono)
Definition klang.h:2610
float * data()
Definition klang.h:2762
constexpr unsigned int capacity(unsigned int n)
Definition klang.h:2612
signal operator[](float offset)
Definition klang.h:2700
signal & operator*=(const signal &in)
Definition klang.h:2747
virtual ~buffer()
Definition klang.h:2654
const bool owned
Definition klang.h:2625
signal & operator[](int offset)
Definition klang.h:2692
buffer(float *buffer, int size)
Definition klang.h:2633
const signal & operator[](int index) const
Definition klang.h:2714
int offset() const
Definition klang.h:2681
buffer(const buffer &buf)
Definition klang.h:2650
signal signal
Definition klang.h:2630
float * samples
Definition klang.h:2626
signal * ptr
Definition klang.h:2627
buffer & operator=(const buffer &in)
Definition klang.h:2752
float level() const
Definition klang.h:2765
signal * end
Definition klang.h:2628
signal & operator=(const signal &in)
Definition klang.h:2738
signal & operator[](unsigned int offset)
Definition klang.h:2696
const int size
Definition klang.h:2631
void clear(int size)
Definition klang.h:2677
signal operator[](float offset) const
Definition klang.h:2704
float rms() const
Definition klang.h:2772
signal & operator+=(const signal &in)
Definition klang.h:2742
bool finished() const
Definition klang.h:2730
buffer & operator<<(const signal &in)
Definition klang.h:2757
buffer(int size=1, float initial=0)
Definition klang.h:2644
void rewind(int offset=0)
Definition klang.h:2665
void set(float value=0)
Definition klang.h:2685
const float * data() const
Definition klang.h:2763
const unsigned int mask
Definition klang.h:2624
signal & operator++(int)
Definition klang.h:2734
void attach(const buffer &buffer, int size=0)
Definition klang.h:2659
buffer(float *buffer, int size, float initial)
Definition klang.h:2638
void clear()
Definition klang.h:2673
const signal & operator[](int index) const
Definition klang.h:2905
buffer & operator<<(const signal &value)
Definition klang.h:2927
signal & operator[](int index)
Definition klang.h:2902
signal operator[](float offset)
Definition klang.h:2914
signal & operator+=(const signal &value)
Definition klang.h:2920
buffer(const buffer &other)
Definition klang.h:2882
void set(float value=0)
Definition klang.h:2898
buffer(int size=1, float initial=0)
Definition klang.h:2875
void rewind(int offset=0)
Definition klang.h:2887
signal & operator*=(const signal &value)
Definition klang.h:2921
buffer(float *samples, int size)
Definition klang.h:2868
buffer & operator=(const buffer &other)
Definition klang.h:2922
signal & operator=(const signal &value)
Definition klang.h:2919
void clear(int count)
Definition klang.h:2894
const float * data() const
Definition klang.h:2929
bool finished() const
Definition klang.h:2917
buffer(float *samples, int size, float initial)
Definition klang.h:2872
signals< CHANNELS > signal
Definition klang.h:2844
signal operator[](float offset) const
Definition klang.h:2908
signal & operator++(int)
Definition klang.h:2918
signal operator[](float offset)
Definition klang.h:2805
void clear(int size)
Definition klang.h:2800
bool finished() const
Definition klang.h:2811
void set(float value=0)
Definition klang.h:2802
const float * data() const
Definition klang.h:2826
float level() const
Definition klang.h:2828
buffer(int size=1, float initial=0.f)
Definition klang.h:2786
buffer(const klang::buffer &buffer)
Definition klang.h:2787
signal operator[](float offset) const
Definition klang.h:2806
void resize(int size)
Definition klang.h:2793
void rewind(int offset=0)
Definition klang.h:2798
signal & operator[](int offset)
Definition klang.h:2803
const signal & operator[](int index) const
Definition klang.h:2807
int offset() const
Definition klang.h:2801
variable::buffer & operator=(const klang::buffer &in)
Definition klang.h:2817
variable::buffer & operator=(const variable::buffer &in)
Definition klang.h:2821
float rms() const
Definition klang.h:2829
signal & operator[](unsigned int offset)
Definition klang.h:2804
signal & operator++(int)
Definition klang.h:2812
Chebyshev filters selected by type, with a second-order low-pass prototype.
Definition klang.h:7733
constexpr float twoPiInv
Definition klang.h:6417
std::enable_if_t<(std::is_arithmetic_v< SCALAR >||(std::is_same_v< std::decay_t< SCALAR >, OutputSignal< OBJECT > > && !std::is_lvalue_reference_v< SCALAR >)) &&!std::is_const_v< OBJECT > && std::is_base_of_v< Output< OutputSignal< OBJECT > >, OBJECT > && !std::is_convertible_v< OBJECT &, float >, OutputSignal< OBJECT > > ScalarOutput
Definition klang.h:3002
SIGNAL operator+(float other, Output< SIGNAL > &output)
Definition klang.h:2994
std::decay_t< decltype(std::declval< OBJECT & >().out)> OutputSignal
Definition klang.h:3001
SIGNAL operator*(float other, Output< SIGNAL > &output)
Definition klang.h:2995
Function() -> Function< signal, Args... >
SIGNAL operator/(float other, Output< SIGNAL > &output)
Definition klang.h:2997
SIGNAL operator-(float other, Output< SIGNAL > &output)
Definition klang.h:2996
float cosp(unsigned int phase)
Approximate cosine from an unsigned 32-bit phase covering one turn.
Definition klang.h:6337
constexpr float twoPi
Definition klang.h:6300
float sinp(unsigned int phase)
Approximate sine from an unsigned 32-bit phase covering one turn.
Definition klang.h:6327
float cos(float x)
Approximate cosine of a finite angle in radians.
Definition klang.h:6320
Definition klang.h:134
static TYPE random(const TYPE min, const TYPE max)
Generates a random number between min and max. Use an integer types for whole numbers.
Definition klang.h:297
float fast_mod(float x, float y)
Definition klang.h:1532
Values values
Definition klang.h:2558
static Control Toggle(const char *name, bool initial=false, Control::Size size=Automatic)
Definition klang.h:1972
static THREAD_LOCAL GraphPtr graph
Definition klang.h:3829
float fast_mod2pi(float x)
Definition klang.h:1552
static Control PitchBend(Control::Size size=Automatic)
Definition klang.h:2009
constexpr constant ln2
The natural logorithm of 2 (and it's inverse).
Definition klang.h:290
constexpr constant pi
The mathematical constant, pi (and it's inverse).
Definition klang.h:287
const Control::Options NoOptions
Definition klang.h:1915
signals< CHANNELS > operator/(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel divided into x.
Definition klang.h:1452
Mode
Klang mode identifiers (e.g. averages, level following)
Definition klang.h:149
@ Peak
Definition klang.h:149
@ RMS
Definition klang.h:149
@ Mean
Definition klang.h:149
double fast_modi(double x)
Definition klang.h:1571
struct klang::Version version
static Control Meter(const char *name, float min=0.f, float max=1.f, float initial=0.f, Control::Size size=Automatic)
Definition klang.h:2004
static Control Dial(const char *name, float min=0.f, float max=1.f, float initial=0.f, Control::Size size=Automatic)
Definition klang.h:1962
float truncate(float input)
Alias for trunc, including signal-flow use.
Definition klang.h:4115
signal & operator>>(TYPE input, signal &destination)
Stream a built-in arithmetic value into a signal, narrowing at the signal boundary.
Definition klang.h:1257
typename std::conditional_t< std::is_integral_v< BASE >, float, BASE > power_t
Definition klang.h:212
float(float) UnaryFunction
A stateless unary C/C++ function that maps one float sample to another.
Definition klang.h:1268
static Control Button(const char *name, Control::Size size=Automatic)
Definition klang.h:1967
static Control Menu(const char *name, const Options... options)
Definition klang.h:1983
constexpr bool is_literal
Definition klang.h:183
constexpr bool are_scalars(Head &&head, Tail &&... tail)
Definition klang.h:192
signals< CHANNELS > operator-(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel subtracted from x.
Definition klang.h:1448
const Control::Size Automatic
Definition klang.h:1914
static Debug debug
Definition klang.h:4518
static Control ModWheel(Control::Size size=Automatic)
Definition klang.h:2014
klang::dB fs
signals< CHANNELS > operator*(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel scaled by x.
Definition klang.h:1450
float fast_modp(unsigned int x)
Definition klang.h:1558
Array< float, 128 > Values
Definition klang.h:2553
constexpr BASE poweri(BASE base)
Definition klang.h:198
auto mod(LEFT left, RIGHT right)
Return the C++ remainder for integers and the floating-point remainder otherwise.
Definition klang.h:3881
unsigned char byte
Definition klang.h:135
signals< CHANNELS > operator+(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel offset by x.
Definition klang.h:1446
constexpr power_t< BASE, EXP > power(BASE base, EXP exp)
Raise base to the power exp.
Definition klang.h:216
float fast_mod1(float x)
Definition klang.h:1542
Caption name
Definition klang.h:2557
constexpr constant root2
The square root of 2 (and it's inverse).
Definition klang.h:293
Text< 32 > Caption
A short Text object used to label controls.
Definition klang.h:1116
void event
A function that handles an event.
Definition klang.h:303
static Control Slider(const char *name, float min=0.f, float max=1.f, float initial=0.f, Control::Size size=Automatic)
Definition klang.h:1977
constexpr bool is_derived_from()
Definition klang.h:187
Factory preset.
Definition klang.h:2556
Attack-Decay-Sustain-Release Envelope.
Definition klang.h:5429
bool operator==(Envelope::Stage stage) const
Definition klang.h:5458
void release(float time=0.f, float level=0.f) override
Definition klang.h:5454
param A
Definition klang.h:5433
void set(param attack, param decay, param sustain, param release) override
Definition klang.h:5439
Control parameter (linear amplitude)
Definition klang.h:1774
static THREAD_LOCAL Conversion dB
Definition klang.h:1795
Amplitude(const dB &db)
Definition klang.h:1779
Amplitude(float a=1.f)
Definition klang.h:1778
const Amplitude * operator->() const
Definition klang.h:1790
Variable-sized array, pre-allocated to a max. capacity.
Definition klang.h:307
unsigned int size() const
The current number of items in the array.
Definition klang.h:315
Array(std::initializer_list< TYPE > init_list)
Construct an array given the specified values.
Definition klang.h:375
float max() const
Find the maximum value in the array.
Definition klang.h:334
TYPE items[CAPACITY]
Definition klang.h:309
Array()=default
Construct an empty array.
void add(const TYPE &item)
Add the specified item to the end of the array.
Definition klang.h:318
float mean() const
Find the mean average of values in the array.
Definition klang.h:343
unsigned int count
Definition klang.h:308
void normalise(float target=1.f, int mode=Peak)
Normalises values in the array to the specified target, based on peak, mean, or RMS value;.
Definition klang.h:359
float rms() const
Find the root mean squared (RMS) average of values in the array.
Definition klang.h:351
void clear()
Clear the array contents. Only resets the item count, without wiping memory.
Definition klang.h:331
const TYPE & operator[](int index) const
Returns a read-only reference to the array item at the given index.
Definition klang.h:372
static int capacity()
The maximum capacity of the array.
Definition klang.h:312
TYPE * add()
Add a blank item to the end of the array, returning a pointer that allows the item to be modified.
Definition klang.h:324
TYPE & operator[](int index)
Returns a reference to the array item at the given index.
Definition klang.h:369
A parallel bank of multiple audio objects.
Definition klang.h:3694
void set(Args... args)
Definition klang.h:3705
signal sum() const
Return the sum of the cached parallel outputs.
Definition klang.h:3721
TYPE & operator[](int index)
Definition klang.h:3701
void process() override
Definition klang.h:3715
const TYPE & operator[](int index) const
Definition klang.h:3702
signal & operator>>(signal &destination)
Process every item once and route their summed output to mono.
Definition klang.h:3727
signal mono() const
Return the Bank's default mono reduction: the sum of its parallel outputs.
Definition klang.h:3724
void input() override
Definition klang.h:3710
Control::Size size
Definition klang.h:1838
bool contains(unsigned int c) const
Definition klang.h:1842
Control size.
Definition klang.h:1821
bool isRelative() const
Definition klang.h:1832
Size(int x=-1, int y=-1, int width=-1, int height=-1)
Definition klang.h:1822
bool isAuto() const
Definition klang.h:1831
Construction-time entry: temporary controls are owned; mutable lvalues are borrowed.
Definition klang.h:2022
Control * reference
Definition klang.h:2025
ControlEntry(Control &&control)
Definition klang.h:2028
Controls * collection
Definition klang.h:2026
Kind
Definition klang.h:2023
@ Owned
Definition klang.h:2023
@ Reference
Definition klang.h:2023
@ Collection
Definition klang.h:2023
enum klang::ControlEntry::Kind kind
Control owned
Definition klang.h:2024
ControlEntry(Controls &controls)
Definition klang.h:2031
ControlEntry(Control &control)
Definition klang.h:2030
ControlEntry(const Control &control)
Definition klang.h:2029
ControlEntry(Controls &&)=delete
UI control / parameter.
Definition klang.h:1806
float range() const
Definition klang.h:1868
Caption name
Definition klang.h:1847
float normalise(float value) const
Definition klang.h:1869
Options options
Definition klang.h:1855
float operator+(TYPE &x) const
Definition klang.h:1904
signal value
Definition klang.h:1857
signal operator*(const Control &x) const
Definition klang.h:1900
Array< Caption, 128 > Options
Definition klang.h:1845
Control & operator=(TYPE input)
Definition klang.h:1881
Control & operator*=(float x)
Definition klang.h:1890
Control & operator=(TYPE &&input)
Definition klang.h:1884
Control & operator-=(float x)
Definition klang.h:1891
void setNormalised(float norm)
Definition klang.h:1871
float operator*(TYPE &x) const
Definition klang.h:1905
Control & operator<<(const signal &input)
Definition klang.h:1909
Control & operator+=(float x)
Definition klang.h:1889
float operator/(TYPE &x) const
Definition klang.h:1907
signal smooth()
Definition klang.h:1866
signal operator-(const Control &x) const
Definition klang.h:1901
signal operator+(const Control &x) const
Definition klang.h:1899
Control & set(float x)
Definition klang.h:1875
float operator-(TYPE &x) const
Definition klang.h:1906
Control & operator<<(TYPE input)
Definition klang.h:1911
Control & operator/=(float x)
Definition klang.h:1892
float initial
Definition klang.h:1852
float normalised() const
Definition klang.h:1870
signal operator/(const Control &x) const
Definition klang.h:1902
signal smoothed
Definition klang.h:1858
Mapped UI control.
Definition klang.h:1932
ControlMap(Control &control)
Definition klang.h:1936
ControlMap & operator=(TYPE input)
Definition klang.h:1947
signal smooth()
Definition klang.h:1943
Control & operator<<(const signal &input)
Definition klang.h:1953
Control * control
Definition klang.h:1933
ControlMap & operator=(TYPE &&input)
Definition klang.h:1951
Control & operator<<(TYPE input)
Definition klang.h:1955
ControlMap & operator=(Control &mapped)
Definition klang.h:1945
Base class for UI / MIDI controll.
Definition klang.h:5507
virtual void onMIDI(int status, int byte1, int byte2)
Definition klang.h:5515
virtual void onPreset(int index)
Definition klang.h:5514
virtual void onControl(int index, float value)
Definition klang.h:5513
virtual event midi(int status, int byte1, int byte2)
Definition klang.h:5511
virtual event control(int index, float value)
Definition klang.h:5509
virtual event preset(int index)
Definition klang.h:5510
Controls(const Controls &other)
Definition klang.h:2318
int scopeSize(int index) const
Definition klang.h:2493
float rms() const
Definition klang.h:2457
void bindAlias(int index, int canonicalIndex)
Reconstruct an earlier canonical slot when a proxy flattens aliases.
Definition klang.h:2529
bool isInput(int index) const
Definition klang.h:2494
const Control * snapshot()
Refresh only the legacy contiguous metadata/value snapshot before raw ABI export.
Definition klang.h:2544
bool hasReferences() const
Definition klang.h:2502
void operator+=(const Control &control)
Definition klang.h:2398
int scopeStart(int index) const
Definition klang.h:2492
void group(const char *name, unsigned int start, unsigned int length, Control::Size size=Automatic)
Definition klang.h:2473
void clear()
Definition klang.h:2343
bool changed()
Definition klang.h:2439
void operator+=(Controls &controls)
Definition klang.h:2400
float mean() const
Definition klang.h:2452
Array< Control::Group, 10 > groups
Definition klang.h:2081
Control & operator[](int index)
Resolve one actual control; ordinary owned collections take the direct path.
Definition klang.h:2329
const char * scope(int index) const
Definition klang.h:2491
Controls & operator=(Source &&source) &
Definition klang.h:2360
Controls & operator=(const Controls &) &&=delete
void normalise(float target=1, int mode=Peak)
Definition klang.h:2462
Control * add()
Definition klang.h:2402
bool inGroup(int index) const
Definition klang.h:2429
Controls & operator=(std::initializer_list< klang::Group > declaration)
Definition klang.h:2369
const Control * snapshot() const
Definition klang.h:2549
Controls(Controls &&other)
Definition klang.h:2319
const char * key(int index) const
Stable declaration key for metadata/retention; never a pointer or a default value.
Definition klang.h:2490
void add(const Control &control)
Definition klang.h:2401
void markInput(int index, bool state=true)
Definition klang.h:2495
void add(const char *name, Control::Type type, std::initializer_list< const char * > options, Control::Size size=Automatic)
Definition klang.h:2417
float max() const
Definition klang.h:2447
void add(const char *name, Control::Type type=Control::ROTARY, float min=0.f, float max=1.f, float initial=0.f, Control::Size size=Automatic)
Definition klang.h:2408
const Control & operator[](int index) const
Definition klang.h:2336
const Control::Group * getGroup(int index) const
Definition klang.h:2434
void operator+=(Control &control)
Definition klang.h:2397
void operator+=(Control &&control)
Definition klang.h:2399
void set(Args... args)
Definition klang.h:2480
void setMetadata(int index, const char *identity, const char *block, int start, int length, bool gameInput)
Preserve original identities when a proxy reconstructs a flat schema.
Definition klang.h:2505
float value[128]
Definition klang.h:2080
static THREAD_LOCAL Buffer buffer
Definition klang.h:4361
Audio delay object (fixed size)
Definition klang.h:4599
Effect mini-plugin (mono)
Definition klang.h:5535
virtual void prepare()
Definition klang.h:5538
virtual void process(buffer buffer)
Definition klang.h:5540
virtual void process()
Definition klang.h:5539
virtual ~Effect()
Definition klang.h:5536
Attack / Release IIR Filter (~Butterworth when attack == release)
Definition klang.h:7800
void set(param attack, param release)
Definition klang.h:7806
Window-based envelope follower.
Definition klang.h:7843
Window & operator=(klang::Mode mode)
Definition klang.h:7857
void set(param attack, param release)
Definition klang.h:7853
void(Window::*)() Process
Definition klang.h:7862
Envelope follower (Peak / RMS)
Definition klang.h:7797
void set(param attack, param release)
Definition klang.h:7823
Follower & operator=(klang::Mode mode)
Definition klang.h:7827
void(Follower::*)() Process
Definition klang.h:7832
Envelope loop.
Definition klang.h:5172
bool isWAV() const
Definition klang.h:7922
unsigned int ByteRate
Definition klang.h:7937
bool load()
Definition klang.h:7964
packed Format
Definition klang.h:7934
Chunk(ID id, unsigned int size=0)
Definition klang.h:7913
unsigned short NumChannels
Definition klang.h:7935
packed Data
Definition klang.h:7947
unsigned int SampleRate
Definition klang.h:7936
bool isAIFF() const
Definition klang.h:7923
unsigned short BlockAlign
Definition klang.h:7938
bool load(Memory &memory)
Definition klang.h:7959
packed Header
Definition klang.h:7917
bool load(const char *path)
Definition klang.h:7953
static void decode(float *buffer, const TYPE *data, int length)
Definition klang.h:7992
bool operator>>(variable::buffer &buffer)
Definition klang.h:8016
Header(ID id, ID format, unsigned int size=0)
Definition klang.h:7920
unsigned short BitsPerSample
Definition klang.h:7939
Header()=default
Chunk()=default
All-pass filter (APF)
Definition klang.h:7650
void set(param f, param r)
Set the pole frequency and radius (r)
Definition klang.h:7657
void set(param f)
Set the filter cutoff (default r)
Definition klang.h:7654
Band-pass filter (BPF)
Definition klang.h:7594
BPF & operator=(Gain gain)
Set the constant gain mode.
Definition klang.h:7602
void(BPF::*)(void) Init
Definition klang.h:7608
@ ConstantSkirtGain
Constant Skirt Gain.
Definition klang.h:7597
Band-Reject Filter (BRF)
Definition klang.h:7638
Abstract filter class.
Definition klang.h:7456
void process() noexcept
Apply the biquad filter (Transposed Direct Form II)
Definition klang.h:7510
void set(param f, relative bw)
Set the filter cutoff and bandwidth.
Definition klang.h:7483
float phase(float f) const
Return the phase offset for the specified frequency (in seconds)
Definition klang.h:7520
void set(param f, param Q)
Set the filter cutoff and Q.
Definition klang.h:7489
float delay(float f) const
Return the group delay for the specified frequency (in samples)
Definition klang.h:7538
void reset()
Reset filter state.
Definition klang.h:7470
void set(param f)
Set the filter cutoff (default Q)
Definition klang.h:7480
High-pass filter (HPF)
Definition klang.h:7577
Low-pass filter (LPF)
Definition klang.h:7560
void init() override
Definition klang.h:7563
Band-pass Butterworth filter for prototype order 1 or 2.
Definition klang.h:7724
Band-reject Butterworth filter for prototype order 1 or 2.
Definition klang.h:7728
High-pass Butterworth filter for prototype order 1 or 2.
Definition klang.h:7720
Low-pass filter (LPF).
Definition klang.h:7686
Band-pass Chebyshev response.
Definition klang.h:7743
Band-reject Chebyshev response.
Definition klang.h:7746
High-pass Chebyshev response.
Definition klang.h:7740
Low-pass Chebyshev response.
Definition klang.h:7737
Simple DC filter / blocker.
Definition klang.h:7292
void process() override
Definition klang.h:7298
void set(param r) override
Definition klang.h:7296
float phase(float f) const
Compute the phase offset in seconds at a given frequency.
Definition klang.h:7355
float delay(float f) const
Compute the group delay in samples at a given frequency.
Definition klang.h:7364
void set(param coeff)
Definition klang.h:7345
IIR filter for specified order.
Definition klang.h:7306
void set(Coeffs... coeffs)
Definition klang.h:7313
void _set(First first, Rest... rest)
Definition klang.h:7331
virtual ~IIR()
Definition klang.h:7307
Abstract filter class.
Definition klang.h:7375
High-pass filter (HPF)
Definition klang.h:7439
Low-pass filter (LPF)
Definition klang.h:7411
float phase(float f) const
Compute the phase delay in seconds at a given frequency.
Definition klang.h:7425
Control parameter (frequency)
Definition klang.h:1723
static THREAD_LOCAL Conversion Pitch
Definition klang.h:1734
const Frequency * operator->() const
Convert a positive frequency in Hz to MIDI pitch.
Definition klang.h:1729
Frequency(float f=1000.f)
Definition klang.h:1726
Applies a function to a signal (input-output)
Definition klang.h:3735
Function(std::function< float(Args...)> function)
Definition klang.h:3743
Signal generator object (mono)
Definition klang.h:3680
White noise generator.
Definition klang.h:6407
Aliased 0-to-1 ramp; frequency in Hz, absolute phase in radians, like Basic::Saw.
Definition klang.h:6367
Pulse wave oscillator (aliased)
Definition klang.h:6391
void set(param frequency, param phase, param duty)
Definition klang.h:6395
Saw wave oscillator (aliased)
Definition klang.h:6359
Sine wave oscillator.
Definition klang.h:6351
Square wave oscillator (aliased)
Definition klang.h:6383
Triangle wave oscillator (aliased)
Definition klang.h:6375
White noise generator (optimised)
Definition klang.h:6568
Aliased 0-to-1 ramp using an integer wrapping phase.
Definition klang.h:6525
void set(param frequency) override
Definition klang.h:6532
void set(param frequency, relative phase) override
Definition klang.h:6545
Fast::Increment increment
Definition klang.h:6563
void set(param frequency, param phase) override
Definition klang.h:6540
void set(relative phase) override
Definition klang.h:6550
Sine wave oscillator (band-limited, optimised)
Definition klang.h:6482
void process() override
Definition klang.h:6513
Fast::Increment increment
Definition klang.h:6520
void set(relative phase) override
Definition klang.h:6509
void reset() override
Definition klang.h:6484
void set(param frequency, param phase) override
Definition klang.h:6498
void set(param frequency) override
Definition klang.h:6490
void set(param frequency, relative phase) override
Definition klang.h:6504
Pulse wave with adjustable duty cycle.
Definition klang.h:6883
KLANG_OSM_INLINE void process() override
Definition klang.h:6885
KLANG_OSM_INLINE Pulse()
Definition klang.h:6884
Descending sawtooth.
Definition klang.h:6868
KLANG_OSM_INLINE Saw()
Definition klang.h:6869
KLANG_OSM_INLINE void process() override
Definition klang.h:6870
Square wave with 50% high duty.
Definition klang.h:6878
KLANG_OSM_INLINE Square()
Definition klang.h:6879
KLANG_OSM_INLINE void process() override
Definition klang.h:6880
Triangle wave with equal rising and falling half-cycles.
Definition klang.h:6873
KLANG_OSM_INLINE Triangle()
Definition klang.h:6874
KLANG_OSM_INLINE void process() override
Definition klang.h:6875
Pulse with adjustable duty and polynomial edge correction.
Definition klang.h:7102
KLANG_BLEP_INLINE Pulse()
Definition klang.h:7103
Descending saw with polynomial correction at the wrap.
Definition klang.h:7087
KLANG_BLEP_INLINE Saw()
Definition klang.h:7088
Square wave with 50% high duty and polynomial edge correction.
Definition klang.h:7097
KLANG_BLEP_INLINE Square()
Definition klang.h:7098
Triangle with polynomial correction at the slope changes.
Definition klang.h:7092
Saw wave oscillator (wavetable)
Definition klang.h:7119
Sine wave oscillator (wavetable)
Definition klang.h:7114
Applies a function to a signal (input-output)
Definition klang.h:3125
Function< SIGNAL, Args... > & operator()(const FuncArgs &... args)
Definition klang.h:3214
klang::GraphPtr & operator>>(klang::GraphPtr &graph)
Definition klang.h:3832
virtual void process() override
Definition klang.h:3298
unsigned int args() const
Definition klang.h:3176
Function(FunctionPtr function)
Definition klang.h:3190
const First & first(const First &first, Rest...) const
Definition klang.h:3210
std::tuple< Args... > inputs
Definition klang.h:3178
const float operator()(const FuncArgs &... args) const
Definition klang.h:3247
static constexpr unsigned int ARGS
Definition klang.h:3175
void input() override
Definition klang.h:3200
klang::Graph & operator>>(klang::Graph &graph)
Definition klang.h:3849
Function< SIGNAL, Args... > & with(FuncArgs... args)
Definition klang.h:3282
std::function< float(Args...)> function
Definition klang.h:3173
First & first(First &first, Rest...)
Definition klang.h:3206
Function(FunctionPtr function, OtherArgs... args)
Definition klang.h:3195
std::tuple< Rest... > tail(const std::tuple< First, Rest... > &t) const
Definition klang.h:3182
signal evaluate() const
Definition klang.h:3289
Signal generator object (output only)
Definition klang.h:3045
Output< SIGNAL > & operator()(params &&... p)
Definition klang.h:3050
Graph axes (x/y)
Definition klang.h:3446
bool contains(const Point &pt) const
Definition klang.h:3450
double range() const
Definition klang.h:3422
void from(const Series &series, double Point::*axis)
Definition klang.h:3426
bool contains(double value) const
Definition klang.h:3423
Series * find(void *function)
Definition klang.h:3476
Series & operator>>(Series &series)
void input() override
Definition klang.h:3413
void plot(const Generic::Function< SIGNAL, Args... > &f, const Axis &x_axis)
Definition klang.h:3362
bool operator==(const Series &in) const
Definition klang.h:3395
bool operator!=(const Series &in) const
Definition klang.h:3403
void plot(RETURN(*f)(ARG), const Axis &x_axis)
Definition klang.h:3379
A line graph plotter.
Definition klang.h:3328
void setDirty(bool dirty)
Definition klang.h:3617
Graph & operator=(TYPE(*function)(TYPE))
Plot the given function of x.
Definition klang.h:3568
Graph & operator+=(TYPE y)
Add a data point (incrementing x)
Definition klang.h:3562
Graph & operator()(double min, double max)
Definition klang.h:3484
Graph & operator<<(const TYPE &in)
Definition klang.h:3592
void truncate(unsigned int count)
Definition klang.h:3619
Graph & operator=(std::initializer_list< Point > values)
Plot the given data points.
Definition klang.h:3574
size_t capacity() const
Definition klang.h:3331
void add(const Point pt)
Add a data point.
Definition klang.h:3558
Graph & operator<<(TYPE &in)
Definition klang.h:3591
void plot(FUNCTION f, VALUES... values)
Plot the given function for x plus additional arguments.
Definition klang.h:3541
Graph::Series & operator[](int index)
Definition klang.h:3490
const Graph::Series & operator[](int index) const
Definition klang.h:3495
void getAxes(Axes &axes) const
Definition klang.h:3598
Graph & operator<<(Function< Args... > &function)
Plot the given function for x plus additional arguments.
Definition klang.h:3586
void plot(Generic::Function< SIGNAL, Args... > &function)
Plot the given Function.
Definition klang.h:3513
const Data & getData() const
Definition klang.h:3615
Graph & operator+=(const Point pt)
Add a data point.
Definition klang.h:3564
const Axes & getAxes() const
Definition klang.h:3595
Graph & operator+=(std::initializer_list< Point > values)
Plot the given data points.
Definition klang.h:3579
bool isDirty() const
Definition klang.h:3616
void add(TYPE y)
Add a data point (incrementing x)
Definition klang.h:3556
void plot(TYPE(*function)(TYPE))
Plot the given function of x.
Definition klang.h:3527
Graph & operator()(double x_min, double x_max, double y_min, double y_max)
Definition klang.h:3499
Audio input object.
Definition klang.h:2942
virtual const SIGNAL & input() const
Definition klang.h:2947
virtual void operator<<(const SIGNAL &source)
Definition klang.h:2950
virtual void input(const SIGNAL &source)
Definition klang.h:2951
virtual void input()
Definition klang.h:2955
Signal modifier object (input-output)
Definition klang.h:3083
Modifier< SIGNAL > & operator()(params &&... p)
Definition klang.h:3098
virtual void process() override
Definition klang.h:3094
Audio oscillator object (output)
Definition klang.h:3642
virtual void set(param frequency, relative phase)
Definition klang.h:3664
virtual void set(param frequency)
Definition klang.h:3654
virtual void set(relative phase)
Definition klang.h:3669
virtual void reset()
Definition klang.h:3651
virtual void set(param frequency, param phase)
Definition klang.h:3659
Audio output object.
Definition klang.h:2960
SIGNAL operator+(TYPE &other)
Definition klang.h:2976
SIGNAL operator/(TYPE &other)
Definition klang.h:2979
virtual const SIGNAL & output() const
Definition klang.h:2964
SIGNAL operator*(TYPE &other)
Definition klang.h:2977
virtual void process()=0
SIGNAL operator-(TYPE &other)
Definition klang.h:2978
A line graph plotter.
Definition klang.h:3749
Graph & operator<<(Function< Args... > &function)
Plot the given function for x plus additional arguments.
Definition klang.h:3754
Optional presentation grouping, independent of value ownership.
Definition klang.h:2036
Group(const char *name, std::initializer_list< ControlEntry > controls)
Definition klang.h:2041
Control::Size size
Definition klang.h:2038
std::vector< ControlEntry > controls
Definition klang.h:2039
const char * name
Definition klang.h:2037
Group(const char *name, Entries &&... entries)
Definition klang.h:2056
Group(Entries &&... entries)
Definition klang.h:2059
Group(const char *name, Control::Size size, std::initializer_list< ControlEntry > controls)
Definition klang.h:2043
Group(Control::Size size, Entries &&... entries)
Definition klang.h:2065
Group(const char *name, Control::Size size, List &&list)
Definition klang.h:2052
Group(const char *name, List &&list)
Definition klang.h:2048
Group(const char *name, Control::Size size, Entries &&... entries)
Definition klang.h:2062
Audio input object (mono)
Definition klang.h:3676
Matrix processor.
Definition klang.h:1580
float operator()(int col, int row) const
Definition klang.h:1587
const float * operator[](int col) const
Definition klang.h:1584
float * operator[](int col)
Definition klang.h:1583
float & operator()(int col, int row)
Definition klang.h:1586
void attach(unsigned char *data, size_t size, bool own=false)
Definition klang.h:406
unsigned char Byte
Definition klang.h:386
Memory & operator+=(const Memory &memory)
Definition klang.h:558
bool create(size_t size)
Definition klang.h:421
Memory & operator=(const Memory &memory)
Definition klang.h:542
bool load(const char *path)
Definition klang.h:476
bool finished() const
Definition klang.h:464
bool operator==(const TYPE &value) const
Definition klang.h:535
Pointer end
Definition klang.h:389
Pointer ptr
Definition klang.h:389
void rewind()
Definition klang.h:439
void free()
Definition klang.h:454
Pointer start
Definition klang.h:389
FILE * file()
Definition klang.h:469
void skip(int bytes)
Definition klang.h:449
bool get(TYPE &value)
Definition klang.h:498
void detach()
Definition klang.h:414
Byte * Pointer
Definition klang.h:387
Memory(size_t size)
Definition klang.h:397
size_t size
Definition klang.h:390
void rewind(int bytes)
Definition klang.h:444
bool owned
Definition klang.h:391
Memory & operator=(Memory *memory)
Definition klang.h:551
bool add(const TYPE &value)
Definition klang.h:518
void clear()
Definition klang.h:434
Memory & operator+=(const TYPE &value)
Definition klang.h:528
Signal modifier object (mono input-output)
Definition klang.h:3682
Modal resonator.
Definition klang.h:7753
void set(param f, param decay)
Definition klang.h:7765
void set(param f, param decay, param gain)
Definition klang.h:7760
Synthesiser note (mono)
Definition klang.h:5633
virtual bool process(buffer buffer)
Definition klang.h:5636
virtual void process() override=0
virtual void prepare()
Definition klang.h:5634
virtual bool process(buffer *buffer)
Definition klang.h:5647
Synthesiser note array.
Definition klang.h:5654
int assign()
Definition klang.h:5679
Array< NOTE *, 128 > Array
Definition klang.h:5656
virtual ~Notes()
Definition klang.h:5826
void add(int count)
Definition klang.h:5667
Notes(SYNTH *synth)
Definition klang.h:5660
SYNTH * synth
Definition klang.h:5655
FM operator.
Definition klang.h:5465
Envelope env
Definition klang.h:5466
Operator & operator*(signal amp)
Definition klang.h:5483
Operator & operator>>(Operator &carrier)
Definition klang.h:5494
Operator & operator()(param f, relative phase)
Definition klang.h:5470
virtual Operator & operator=(const Envelope &points)
Definition klang.h:5478
virtual Operator & operator=(const Envelope::Points &points)
Definition klang.h:5473
Operator & operator()(relative phase)
Definition klang.h:5471
virtual void process() override
Definition klang.h:5488
Operator & operator()(param f)
Definition klang.h:5469
Audio oscillator object (mono output)
Definition klang.h:3684
Audio output object (mono)
Definition klang.h:3678
Control parameter (phase)
Definition klang.h:1647
Phase operator+(const increment &step) const
Definition klang.h:1678
param & operator+=(float step)
Definition klang.h:1664
Phase operator%(float modulus)
Definition klang.h:1682
float wrapped(float offset=0) const
Return this phase plus an optional offset, wrapped to one turn.
Definition klang.h:1662
static float wrap(float phase, float cycle=2 *pi)
Wrap a finite phase to [0, cycle); invalid values become zero.
Definition klang.h:1653
param & operator+=(const increment &step)
Definition klang.h:1671
Control parameter (pitch)
Definition klang.h:1690
Pitch operator-(TYPE in)
Definition klang.h:1713
Pitch operator/(TYPE in)
Definition klang.h:1715
const Pitch * operator->()
Definition klang.h:1705
Pitch operator*(TYPE in)
Definition klang.h:1714
Pitch operator+(TYPE in)
Definition klang.h:1712
static THREAD_LOCAL Conversion Frequency
Definition klang.h:1710
const char * text() const
Definition klang.h:1698
Base class for mini-plugin.
Definition klang.h:5519
virtual ~Plugin()
Definition klang.h:5520
static DERIVED * Create(ARGS &&... args)
Definition klang.h:5523
Presets presets
Definition klang.h:5531
Controls controls
Definition klang.h:5530
Factory presets.
Definition klang.h:2582
void operator+=(const Preset &preset)
Definition klang.h:2583
void operator=(const Presets &presets)
Definition klang.h:2587
void add(const char *name, const Values... values)
Definition klang.h:2598
void operator=(std::initializer_list< Preset > presets)
Definition klang.h:2592
Sample rate constants.
Definition klang.h:1743
SampleRate(float sr)
Definition klang.h:1751
float w
angular frequency (omega)
Definition klang.h:1748
float nyquist
nyquist frequency (f / 2)
Definition klang.h:1749
int i
sample rate (integer)
Definition klang.h:1745
float f
sample rate (float)
Definition klang.h:1744
double d
sample rate (double)
Definition klang.h:1746
float inv
1 / sample rate (inverse)
Definition klang.h:1747
void process() override
Definition klang.h:5557
Stereo audio object adapter.
Definition klang.h:6004
Audio delay object (stereo)
Definition klang.h:6008
signal operator()(const TIME &delay)
Definition klang.h:6048
unsigned int max() const
Definition klang.h:6059
signal tap(float delay) const
Definition klang.h:6028
virtual void process() override
Definition klang.h:6043
signal tap(int delay) const
Definition klang.h:6021
Stereo effect mini-plugin.
Definition klang.h:6063
virtual void prepare()
Definition klang.h:6066
virtual ~Effect()
Definition klang.h:6064
virtual void process(interleaved::buffer buffer)
Process interleaved host frames; inherited by the current Stereo::Sound.
Definition klang.h:6080
virtual void process(Stereo::buffer buffer)
Definition klang.h:6068
virtual void process()
Definition klang.h:6067
Signal generator object (stereo output)
Definition klang.h:5921
Audio input object (stereo)
Definition klang.h:5917
virtual ~Input()
Definition klang.h:5917
Signal modifier object (stereo, input-output)
Definition klang.h:5923
virtual void prepare() override
Definition klang.h:6127
virtual void process() override=0
virtual bool process(Stereo::buffer buffer) override
Definition klang.h:6129
Base class for stereo synthesiser note.
Definition klang.h:6104
virtual bool process(Stereo::buffer buffer)
Definition klang.h:6109
virtual void process() override=0
virtual bool process(mono::buffer *buffers)
Definition klang.h:6117
virtual void prepare()
Definition klang.h:6107
Audio oscillator object (stereo, output)
Definition klang.h:5925
Audio output object (stereo)
Definition klang.h:5919
virtual ~Output()
Definition klang.h:5919
void process() override
Definition klang.h:6098
Synthesiser note array (stereo)
Definition klang.h:6149
Synthesier mini-plugin (stereo)
Definition klang.h:6143
Stereo::Mono::Note Note
Definition klang.h:6146
int indexOf(Note *note) const
Definition klang.h:6160
virtual event onMIDI(int status, int byte1, int byte2) override
Definition klang.h:6179
Stereo::Note Note
Definition klang.h:6144
virtual event onControl(int index, float value) override
Definition klang.h:6171
virtual event allNotesOff(float velocity=0.f)
Definition klang.h:6208
virtual event noteOn(int pitch, float velocity)
Definition klang.h:6195
virtual event noteOff(int pitch, float velocity)
Definition klang.h:6202
virtual void process(float **buffers, int length, float *parameters=nullptr)
Definition klang.h:6225
virtual void process(buffer buffer) override
Definition klang.h:6216
virtual event onPreset(int index) override
Definition klang.h:6187
virtual void process() override
Definition klang.h:6215
virtual ~Synth()
Definition klang.h:6154
virtual bool playing() const
Definition klang.h:6218
Stereo audio buffer.
Definition klang.h:5934
buffer & operator=(const buffer &in)
Definition klang.h:5950
buffer(mono::buffer &left, mono::buffer &right)
Definition klang.h:5939
buffer & operator=(const mono::signal in)
Definition klang.h:5966
bool finished() const
Definition klang.h:5943
void clear(int size)
Definition klang.h:5987
buffer & operator*=(const frame &in)
Definition klang.h:5964
frame operator=(const signal &in)
Definition klang.h:5946
frame operator[](int index)
Definition klang.h:5970
buffer & operator=(const frame &in)
Definition klang.h:5962
buffer & operator+=(const frame &in)
Definition klang.h:5963
Stereo::signal signal
Definition klang.h:5935
signal operator[](int index) const
Definition klang.h:5974
buffer(const buffer &buffer)
Definition klang.h:5938
mono::buffer & left
Definition klang.h:5936
mono::buffer & right
Definition klang.h:5936
buffer & operator*=(const mono::signal in)
Definition klang.h:5968
buffer & operator+=(const mono::signal in)
Definition klang.h:5967
frame operator++(int)
Definition klang.h:5944
mono::buffer & channel(int index)
Definition klang.h:5978
buffer & operator+=(const signal &in)
Definition klang.h:5956
Stereo sample frame.
Definition klang.h:5843
frame & operator*=(float x)
Definition klang.h:5867
signal operator*(const mono::signal x) const
Definition klang.h:5887
frame & operator+=(const mono::signal x)
Definition klang.h:5860
frame & operator-=(int x)
Definition klang.h:5876
signal operator*(int x) const
Definition klang.h:5902
signal operator-(double x) const
Definition klang.h:5896
frame & operator/=(int x)
Definition klang.h:5878
signal operator*(const signal x) const
Definition klang.h:5882
signal operator+(const mono::signal x) const
Definition klang.h:5885
signal operator+(float x) const
Definition klang.h:5890
signal operator-(float x) const
Definition klang.h:5891
frame & operator+=(double x)
Definition klang.h:5870
frame & operator*=(const signal x)
Definition klang.h:5857
signal operator-(const mono::signal x) const
Definition klang.h:5886
signal operator/(double x) const
Definition klang.h:5898
frame & operator+=(const frame &x)
Definition klang.h:5850
frame & operator*=(const mono::signal x)
Definition klang.h:5862
frame & operator*=(int x)
Definition klang.h:5877
signal operator-(const signal x) const
Definition klang.h:5881
frame & operator-=(double x)
Definition klang.h:5871
signal operator-(int x) const
Definition klang.h:5901
frame & operator/=(const frame &x)
Definition klang.h:5853
frame & operator-=(const mono::signal x)
Definition klang.h:5861
frame & operator*=(const frame &x)
Definition klang.h:5852
frame & operator=(const signal &signal)
Definition klang.h:5905
frame & operator-=(const frame &x)
Definition klang.h:5851
signal operator/(int x) const
Definition klang.h:5903
mono::signal mono() const
Definition klang.h:5911
frame & operator*=(double x)
Definition klang.h:5872
signal operator+(int x) const
Definition klang.h:5900
signal operator/(const mono::signal x) const
Definition klang.h:5888
mono::signal & l
Definition klang.h:5844
frame & operator+=(int x)
Definition klang.h:5875
signal operator*(double x) const
Definition klang.h:5897
signal operator+(double x) const
Definition klang.h:5895
frame & operator/=(const mono::signal x)
Definition klang.h:5863
frame & operator+=(const signal x)
Definition klang.h:5855
signal operator+(const signal x) const
Definition klang.h:5880
frame & operator/=(const signal x)
Definition klang.h:5858
frame & operator+=(float x)
Definition klang.h:5865
mono::signal & r
Definition klang.h:5845
frame & operator/=(float x)
Definition klang.h:5868
signal operator*(float x) const
Definition klang.h:5892
signal operator/(float x) const
Definition klang.h:5893
frame(mono::signal &left, mono::signal &right)
Definition klang.h:5847
frame & operator/=(double x)
Definition klang.h:5873
frame & operator-=(float x)
Definition klang.h:5866
frame & operator-=(const signal x)
Definition klang.h:5856
signal operator/(const signal x) const
Definition klang.h:5883
frame(signal &signal)
Definition klang.h:5848
Synthesiser object (mono)
Definition klang.h:5719
virtual event allNotesOff(float velocity=0.f)
Definition klang.h:5779
Notes< Synth, Note > notes
Definition klang.h:5722
int indexOf(Note *note) const
Definition klang.h:5731
virtual event onMIDI(int status, int byte1, int byte2) override
Definition klang.h:5750
virtual event onPreset(int index) override
Definition klang.h:5758
Note Note
Definition klang.h:5720
virtual ~Synth()
Definition klang.h:5725
virtual event noteOff(int pitch, float velocity)
Definition klang.h:5773
virtual void process() override
Definition klang.h:5786
virtual void process(buffer buffer) override
Definition klang.h:5787
virtual bool playing() const
Definition klang.h:5789
virtual event noteOn(int pitch, float velocity)
Definition klang.h:5766
virtual void process(float *buffer, int length, float *parameters=nullptr)
Definition klang.h:5796
virtual event onControl(int index, float value) override
Definition klang.h:5742
String of characters representing text.
Definition klang.h:1078
static Text from(const char *in)
Create a new Text object from a C-string.
Definition klang.h:1092
int capacity() const
Maximum size of the string.
Definition klang.h:1083
bool operator==(const char *in) const
Returns true if Text matches the given C-string.
Definition klang.h:1105
char string[SIZE+1]
The character buffer.
Definition klang.h:1080
const char * c_str() const
Return constant C-string.
Definition klang.h:1089
bool operator!=(const char *in) const
Returns true if Text does not matches the given C-string.
Definition klang.h:1110
void operator=(const char *in)
Assign C-String to Text object.
Definition klang.h:1099
Klang language version (major.minor.build.debug)
Definition klang.h:138
unsigned char build
Definition klang.h:139
bool below(unsigned char M, unsigned char m, unsigned char b) const
Definition klang.h:144
unsigned char extra
Definition klang.h:139
bool isDebug() const
Definition klang.h:140
bool atLeast(unsigned char M, unsigned char m, unsigned char b) const
Definition klang.h:141
unsigned char minor
Definition klang.h:139
unsigned char major
Definition klang.h:139
Constant scalar (pre-converted to double, float and int).
Definition klang.h:154
float operator^(int x) const
Definition klang.h:170
const float inv
Inverse of constant.
Definition klang.h:164
const double d
Constant as double.
Definition klang.h:161
const float f
Constant as float.
Definition klang.h:162
float operator^(double x) const
Definition klang.h:171
float operator^(float x) const
Constant raised to the power, x.
Definition klang.h:169
constexpr constant(double value) noexcept
Create a constant from the given value.
Definition klang.h:157
const int i
Constant as integer.
Definition klang.h:163
Control parameter (idecibels)
Definition klang.h:1759
static THREAD_LOCAL Conversion Amplitude
Definition klang.h:1770
const dB * operator->() const
Definition klang.h:1765
dB(float gain=0.f)
Definition klang.h:1763
A phase or wavetable increment.
Definition klang.h:1468
increment(float amount, const float size=2 *pi)
Create a phase increment (default to radians).
Definition klang.h:1473
float amount
The current phase.
Definition klang.h:1469
increment(float amount, double size)
Create a phase increment.
Definition klang.h:1477
increment & operator=(float in)
Set current phase.
Definition klang.h:1480
increment(float amount, int size)
Create a phase increment (wavetable size).
Definition klang.h:1475
const float size
The length of a a full cycle (e.g. 2 pi or wavetable size)
Definition klang.h:1470
A signal used as a control parameter.
Definition klang.h:1486
param(const float initial=0.f)
Definition klang.h:1488
param(SOURCE &&source)
Definition klang.h:1496
param(const signal &in)
Definition klang.h:1489
param & operator+=(const increment &increment)
Definition klang.h:1499
param(constant in)
Definition klang.h:1487
param(signal &in)
Definition klang.h:1490
A signal used as an offset relative to another signal.
Definition klang.h:1248
A mono audio signal (equivalent to a float).
Definition klang.h:1123
signal & operator*=(const signal &x)
Multiply (modulate) signal by another signal.
Definition klang.h:1160
signal operator^(int x) const
Return a copy of the signal raised to the power of x.
Definition klang.h:1223
signal & operator=(Output &in)
Assign processed output of in to signal.
Definition klang.h:3866
signal(const double initial)
Create signal from a 64-bit double.
Definition klang.h:1133
relative operator+() const
Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
Definition klang.h:1251
signal operator*(double x) const
Return a copy of the signal scaled by x.
Definition klang.h:1205
signal operator^(double x) const
Return a copy of the signal raised to the power of x.
Definition klang.h:1221
const signal & operator<<(const signal &input)
Feedback operator (prevents further processing of returned value).
Definition klang.h:1139
signal operator*(float x) const
Multiply (modulate) two signals.
Definition klang.h:1196
bool isDenormal() const
Check if the signal contains a denormal value.
Definition klang.h:1229
signal operator^(float x) const
Return a copy of the signal raised to the power of x.
Definition klang.h:1219
signal & operator-=(float x)
Subtract the specified amount from the signal.
Definition klang.h:1167
signal & operator/=(double x)
Divide signal by the specified amount.
Definition klang.h:1180
signal & operator>>(signal &destination) const
Stream operator (feedforward; allows further processing)
Definition klang.h:1145
signal & operator+=(const signal &x)
Add (mix) another signal to the signal.
Definition klang.h:1156
signal & operator+=(float x)
Add the specified amount to the signal.
Definition klang.h:1165
signal operator-(double x) const
Return a copy of the signal offset by -x.
Definition klang.h:1203
signal & operator-=(double x)
Subtract the specified amount from the signal.
Definition klang.h:1176
float value
Definition klang.h:1124
int channels() const
Returns the number of channels (1 = mono).
Definition klang.h:1235
signal & operator/=(int x)
Divide signal by the specified amount.
Definition klang.h:1189
signal & operator-=(int x)
Subtract the specified amount from the signal.
Definition klang.h:1185
signal operator-(float x) const
Subtract one signal from another.
Definition klang.h:1194
signal operator*(int x) const
Return a copy of the signal scaled by x.
Definition klang.h:1214
relative relative() const
Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
Definition klang.h:1253
signal & operator+=(double x)
Add the specified amount to the signal.
Definition klang.h:1174
signal & operator+=(int x)
Add the specified amount to the signal.
Definition klang.h:1183
signal(const float initial=0.f)
Create signal from a 32-bit float..
Definition klang.h:1130
signal operator/(int x) const
Return a copy of the signal divided by x.
Definition klang.h:1216
signal & operator+=(Output &in)
Adds processed output of in to signal.
Definition klang.h:3872
signal operator+(float x) const
Add two signals together.
Definition klang.h:1192
signal & operator*=(double x)
Multiply signal by the specified amount.
Definition klang.h:1178
signal & operator-=(const signal &x)
Subtract another signal from the signal.
Definition klang.h:1158
signal & operator/=(float x)
Divide signal by the specified amount.
Definition klang.h:1171
signal operator+(double x) const
Return a copy of the signal offset by x.
Definition klang.h:1201
signal operator/(float x) const
Divide one signal by another.
Definition klang.h:1198
signal & operator*=(int x)
Multiply signal by the specified amount.
Definition klang.h:1187
signal operator-(int x) const
Return a copy of the signal offset by -x.
Definition klang.h:1212
signal(constant initial)
Create signal from a constant.
Definition klang.h:1127
signal(const int value)
Create signal from an 32-bit signed integer.
Definition klang.h:1136
signal operator/(double x) const
Return a copy of the signal divided by.
Definition klang.h:1207
signal & operator/=(const signal &x)
Divide signal by another signal.
Definition klang.h:1162
signal operator+(int x) const
Return a copy of the signal offset by x.
Definition klang.h:1210
signal & operator*=(float x)
Multiply signal by the specified amount.
Definition klang.h:1169
A multi-channel audio signal (e.g. stereo).
Definition klang.h:1278
klang::signal sum() const
Return the sum of all channels.
Definition klang.h:1353
signals operator-(float x) const
Return a copy of the signal with each channel offset by -x.
Definition klang.h:1420
const signal & operator[](int index) const
Return a read-only reference to the signal at the specified index (0 = left, 1 = right).
Definition klang.h:1369
signals operator/(double x) const
Return a copy of the signal with each channel divided by x.
Definition klang.h:1433
signals operator-(const signal x) const
Return a copy of the multi-channel signal, subtracting a mono signal from each channel.
Definition klang.h:1411
signals operator+(float x) const
Return a copy of the signal with each channel offset by x.
Definition klang.h:1418
signals(TYPE &initial)
Evaluate a mono Klang object once and broadcast its signal to every channel.
Definition klang.h:1346
signals(Args... initial)
Create a multi-channel signal with the given channel values.
Definition klang.h:1312
signals operator*(const signals x) const
Multiply (modulate) two multi-channel signals.
Definition klang.h:1399
signals(float initial=0.f)
Create a multi-channel signal by broadcasting the given value.
Definition klang.h:1292
signals operator+(const signals x) const
Add two multi-channel signals together.
Definition klang.h:1395
signals operator/(const signals x) const
Divide one multi-channel signal by another.
Definition klang.h:1401
signals operator*(double x) const
Return a copy of the signal with each channel scaled by x.
Definition klang.h:1431
signals & operator>>(signals &destination) const
Stream operator (feedforward; allows further processing).
Definition klang.h:1380
signals operator+(double x) const
Return a copy of the signal with each channel offset by x.
Definition klang.h:1427
signals(const klang::signal &initial)
Create a multi-channel signal by broadcasting the given signal.
Definition klang.h:1298
signals operator*(const signal x) const
Return a copy of the multi-channel signal, multiplying (modulating) each channel by a mono signal.
Definition klang.h:1413
signals operator/(float x) const
Return a copy of the signal with each channel divided by x.
Definition klang.h:1424
signals operator*(float x) const
Return a copy of the signal with each channel scaled by x.
Definition klang.h:1422
signals(int left, int right)
Create a multi-channel signal with the first two channel values; remaining channels are zero.
Definition klang.h:1305
signals operator-(int x) const
Return a copy of the signal with each channel offset by -x.
Definition klang.h:1438
signals & operator+=(const signals x)
Add (mix) another signal to the signal.
Definition klang.h:1386
signals(double left, double right)
Create a multi-channel signal with the first two channel values; remaining channels are zero.
Definition klang.h:1303
signals & operator/=(const signals x)
Divide signal by another signal.
Definition klang.h:1392
signals & operator*=(const signals x)
Multiply (modulate) signal by another signal.
Definition klang.h:1390
int channels() const
Returns the number of channels in the signal.
Definition klang.h:1372
signals operator/(int x) const
Return a copy of the signal with each channel divided by x.
Definition klang.h:1442
signals(float left, float right)
Create a multi-channel signal with the first two channel values; remaining channels are zero.
Definition klang.h:1301
signals operator-(double x) const
Return a copy of the signal with each channel offset by -x.
Definition klang.h:1429
klang::signal mono() const
Return the default mono downmix: the arithmetic mean of all channels.
Definition klang.h:1364
signals operator-(const signals x) const
Subtract one multi-channel signal from another.
Definition klang.h:1397
signals & operator-=(const signals x)
Subtract another signal from the signal.
Definition klang.h:1388
signals operator+(const signal x) const
Return a copy of the multi-channel signal, adding a mono signal to each channel.
Definition klang.h:1409
signals(double initial)
Create a multi-channel signal by broadcasting the given value.
Definition klang.h:1294
klang::signal average() const
Return the arithmetic mean of all channels.
Definition klang.h:1361
signals operator/(const signal x) const
Return a copy of the multi-channel signal, dividing each channel by a mono signal.
Definition klang.h:1415
signals operator+(int x) const
Return a copy of the signal with each channel offset by x.
Definition klang.h:1436
signals operator*(int x) const
Return a copy of the signal with each channel scaled by x.
Definition klang.h:1440
const signals & operator<<(const signals &input)
Feedback operator (prevents further processing of returned value).
Definition klang.h:1375
signals(int initial)
Create a multi-channel signal by broadcasting the given value.
Definition klang.h:1296
signal & operator[](int index)
Return a reference to the signal at the specified index (0 = left, 1 = right).
Definition klang.h:1367
signals(Args &... initial)
Create a multi-channel signal with the given channel values.
Definition klang.h:1309