1#define KLANG_CONTROL_REFERENCES 1
18#ifndef _CRT_SECURE_NO_WARNINGS
19#define _CRT_SECURE_NO_WARNINGS
25#if defined(__WAJIC__) && !defined(_LIBCPP_HAS_NO_LOCALIZATION)
26#pragma push_macro("_LIBCPP_HAS_NO_LOCALIZATION")
27#define _LIBCPP_HAS_NO_LOCALIZATION
29#pragma pop_macro("_LIBCPP_HAS_NO_LOCALIZATION")
63#if defined(_MSC_VER) && !KLANG_STRICT
65#pragma warning(disable: 4587 4263 4264 4996)
66#define KLANG_WARNING_SCOPE 1
71#ifndef HAS_KLANG_DEBUG
72#if defined(KLANG) && KLANG
73#define HAS_KLANG_DEBUG 1
75#define HAS_KLANG_DEBUG 0
83static inline float _sqrt(
float x) {
return __builtin_sqrtf(x); }
84static inline float _abs(
float x) {
return __builtin_fabsf(x); }
90#elif defined(__APPLE__)
97#elif defined(_MSC_VER)
98#define THREAD_LOCAL thread_local
105#define THREAD_LOCAL thread_local
112#if defined(DEBUG) || defined(_DEBUG)
119#define GRAPH_SIZE 44100
122#define GRAPH_SERIES 4
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");
141 bool atLeast(
unsigned char M,
unsigned char m,
unsigned char b)
const {
144 bool below(
unsigned char M,
unsigned char m,
unsigned char b)
const {
return !
atLeast(M, m, b); }
146 static constexpr version = { 0, 7, 15, KLANG_DEBUG };
151#define DENORMALISE 1.175494e-38f
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)) {
166 constexpr operator float() const noexcept {
return f; }
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)); }
174#define CONSTANT constexpr constant
176#if __cplusplus == 201703L
178 template <
typename T>
179 inline constexpr bool is_literal = std::is_literal_type_v<T>;
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>;
186 template<
typename Base,
typename Derived>
188 return std::is_base_of_v<Base, Derived>;
191 template<
typename Head,
typename... 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)...));
197 template <
typename BASE,
int EXP>
198 inline constexpr BASE
poweri(BASE base) {
200 constexpr bool negative = EXP < 0;
201 int exp = negative ? -EXP : EXP;
208 return negative ? 1 / result : result;
211 template <
typename BASE,
typename EXP>
212 using power_t =
typename std::conditional_t<std::is_integral_v<BASE>, float, BASE>;
215 template <
typename BASE,
typename EXP, std::enable_if_t < is_literal<EXP>,
bool>>
217 if constexpr (std::is_integral_v<EXP>) {
219 case 0:
return (BASE)1;
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);
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);
243 return (BASE)std::pow(base, exp);;
247 template <
typename BASE,
typename EXP>
249 if constexpr (std::is_integral_v<BASE>) {
250 return power(
float(base), exp);
252 else if constexpr (std::is_integral_v<EXP>) {
254 case 0:
return (BASE)1;
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);
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);
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;
287 constexpr constant pi = { 3.1415926535897932384626433832795 };
296 template<
typename TYPE>
297 inline static TYPE
random(
const TYPE min,
const TYPE max) {
return rand() * ((max - min) / (TYPE)RAND_MAX) + min; }
300 inline static void random(
const unsigned int seed) { srand(seed); }
306 template<
typename TYPE,
int CAPACITY>
318 void add(
const TYPE& item) {
319 if (
count < CAPACITY)
325 if (
count < CAPACITY)
336 for (
unsigned int i = 0; i <
count; i++)
337 if (abs(
items[i]) > max)
345 for (
unsigned int i = 0; i <
count; i++)
346 sum += abs(
items[i]);
353 for (
unsigned int i = 0; i <
count; i++)
355 return sqrt(sum /
count);
363 const float scale = current == 0.f ? 0.f : target / current;
364 for (
int i = 0; i <
count; i++)
375 Array(std::initializer_list<TYPE> init_list) {
376 count = std::min(
static_cast<unsigned int>(init_list.size()),
static_cast<unsigned int>(CAPACITY));
406 void attach(
unsigned char* data,
size_t size,
bool own =
false) {
470 FILE* f = fopen(
"/dev/null",
"wt");
471 if (!f) f = fopen(
"nul",
"wt");
477 FILE* f = fopen(path,
"rb");
478 if (!f)
return false;
481 fseek(f, 0, SEEK_END);
482 size_t length = ftell(f);
483 fseek(f, 0, SEEK_SET);
490 fread(
start, 1, length, f);
497 template<
typename TYPE>
499 if (
ptr +
sizeof(TYPE) >
end) {
509 template<
typename TYPE>
517 template<
typename TYPE>
518 bool add(
const TYPE& value) {
519 if (
ptr +
sizeof(TYPE) >
end)
527 template<
typename TYPE>
534 template<
typename TYPE>
536 if (
ptr +
sizeof(TYPE) >
end)
538 return value == *(TYPE*)
ptr;
1080 char string[SIZE + 1] = { 0 };
1086 operator const char* ()
const {
return string; }
1100 memcpy(
string, in, SIZE);
1106 return strcmp(
string, in) == 0;
1225 operator const float()
const {
return value; }
1230 const unsigned int bits = *(
const unsigned int*)&
value;
1231 return !(bits & 0x7F800000) && (bits & 0x007FFFFF);
1244 static_assert(
sizeof(signal) ==
sizeof(float),
"signal != float");
1245 IS_SIMPLE_TYPE(signal)
1256 template<
typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>,
int> = 0>
1258 destination << signal(static_cast<float>(input));
1263 destination <<
signal(input.
f);
1272 return function(
float(input));
1277 template<
int CHANNELS = 2>
1279 static_assert(CHANNELS > 0,
"signals requires at least one channel");
1280#if !defined(__GNUC__) || defined(__clang__)
1292 signals(
float initial = 0.f) {
for (
int channel = 0; channel < CHANNELS; channel++) value[channel] = initial; }
1298 signals(
const klang::signal& initial) {
for (
int channel = 0; channel < CHANNELS; channel++) value[channel] = initial; }
1308 template <
typename... Args,
typename = std::enable_if_t<
sizeof...(Args) == CHANNELS && (std::is_convertible_v<Args, signal> && ...)>>
1309 signals(Args&... initial) : value{ initial... } {}
1311 template <
typename... Args,
typename = std::enable_if_t<
sizeof...(Args) == CHANNELS && (std::is_scalar_v<Args> && ...)>>
1319 signals(
float initial = 0.f) {
for (
int v = 0; v < CHANNELS; v++) value[v] = initial; }
1321 signals(
double initial) : signals((float)initial) {}
1323 signals(
int initial) : signals((float)initial) {}
1325 signals(
const klang::signal& initial) {
for (
int v = 0; v < CHANNELS; v++) value[v] = initial; }
1328 signals(
float left,
float right) { l = left; r = right;
for (
int v = 2; v < CHANNELS; v++) value[v] = 0.f; }
1330 signals(
double left,
double right) : signals((float)left, (float)right) {}
1332 signals(
int left,
int right) : signals((float)left, (float)right) {}
1335 template <
typename... Args,
typename = std::enable_if_t<
sizeof...(Args) == CHANNELS && (std::is_convertible_v<Args, signal> && ...)>>
1336 signals(Args&... initial) : value{ initial... } {}
1338 template <
typename... Args,
typename = std::enable_if_t<
sizeof...(Args) == CHANNELS && (std::is_scalar_v<Args> && ...)>>
1339 signals(Args... initial) : value{ initial... } {}
1341 signals& operator=(
const signals& input) {
for (
int v = 0; v < CHANNELS; v++) value[v] = input[v];
return *
this; }
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>
1348 for (
int channel = 0; channel < CHANNELS; channel++)
1349 value[channel] = mono;
1355 for (
int channel = 0; channel < CHANNELS; channel++)
1356 result += value[channel];
1376 return this->operator=(input);
1381 destination = *
this;
1454 for (
int c = 0; c < CHANNELS; c++)
1456 return std::move(s);
1461 struct Conversion :
public signal {
1462 using signal::signal;
1473 increment(
float amount,
const float size = 2 * pi) : amount(amount), size(size) {}
1475 increment(
float amount,
int size) : amount(amount), size((float)size) {}
1477 increment(
float amount,
double size) : amount(amount), size((float)size) {}
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>
1497 :
signal(static_cast<const
signal&>(std::forward<SOURCE>(source))) {}
1508 static_assert(
sizeof(param) ==
sizeof(float),
"param != float");
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()) {
1524 for (param p : params)
1525 parameters[index++] = p;
1528 param& operator[](
int index) {
return parameters[index]; }
1533 const unsigned int i = (((
unsigned int)(x * (float(UINT_MAX) + 1.f) / y)) >> 9) | 0x3f800000;
1534 return (*(
const float*)&i - 1.f) * 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;
1543 const unsigned int i = ((
unsigned int)(x * (float(UINT_MAX) + 1.f)) >> 9) | 0x3f800000;
1544 return *(
const float*)&i - 1.f;
1548 const unsigned long long i = (((
unsigned long long)(x * (double(ULLONG_MAX) + 1.0))) >> 12ULL) | 0x7FF0000000000000ULL;
1549 return (*(
const double*)&i - 1.0);
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;
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;
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;
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;
1581 float v[4][4] = { 0 };
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] };
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] };
1607 template<
typename TYPE,
typename _TYPE>
1609 static constexpr TYPE twoPi = TYPE(2.0 * 3.1415926535897932384626433832795);
1616 phase(TYPE phase = 0) {
1617 if constexpr (std::is_same<TYPE, double>()) {
1618 constexpr TYPE FUINTMAX = TYPE(ULLONG_MAX + 1.0) / twoPi;
1622 else if constexpr (std::is_same<TYPE, float>()) {
1623 constexpr TYPE FUINTMAX = TYPE(UINT_MAX + 1.0) /
twoPi;
1630 operator TYPE()
const {
1631 const _TYPE phase = (i >> 12ULL) | 0x3FF0000000000000ULL;
1632 return (*(
const TYPE*)&phase - TYPE(1.0)) *
twoPi;
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;
1662 float wrapped(
float offset = 0)
const {
return wrap(value + offset); }
1666 if (value < 0 || value >= (2 *
pi))
1667 value = wrap(value);
1673 if (value < 0 || value >= step.
size)
1674 value = wrap(value, step.
size);
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);
1718 THREAD_LOCAL
inline Conversion Pitch::Frequency;
1730 Pitch = 69.0 + 12.0 * std::log2(
double(value) / 440.0);
1737 THREAD_LOCAL
inline Conversion Frequency::Pitch;
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) {}
1753 operator float() {
return f; }
1791 dB = 20.f * log10f(value);
1795 THREAD_LOCAL
static Conversion
dB;
1798 THREAD_LOCAL
inline Conversion dB::Amplitude;
1799 THREAD_LOCAL
inline Conversion Amplitude::dB;
1822 Size(
int x = -1,
int y = -1,
int width = -1,
int height = -1)
1823 : x(x), y(y), width(width), height(height) {
1831 bool isAuto()
const {
return x == -1 && y == -1 && width == -1 && height == -1; }
1839 unsigned int start = 0;
1840 unsigned int length = 0;
1842 bool contains(
unsigned int c)
const {
return c >= start && c < (start + length); }
1862 operator param()
const {
return value; }
1863 operator float()
const {
return value.
value; }
1865 static constexpr float smoothing = 0.999f;
1866 signal smooth() {
return smoothed = smoothed * smoothing + (1.f - smoothing) * value; }
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); }
1876 value = std::clamp(x, min, max);
1880 template<
typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>,
int> = 0>
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>
1885 const signal sample = std::forward<TYPE>(input);
1910 template<
typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>,
int> = 0>
1926 for (
int c = 0; c < CHANNELS; c++)
1927 s[c] = x.
value / y[c];
1928 return std::move(s);
1942 operator float()
const {
return control->
value; }
1946 template<
typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>,
int> = 0>
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>
1954 template<
typename TYPE, std::enable_if_t<std::is_arithmetic_v<TYPE>,
int> = 0>
1982 template<
typename... Options>
1986 const char* strings[] = { options... };
1987 int nbValues =
sizeof...(options);
1988 for (
int p = 0; p < nbValues; p++)
1993 template<
typename... Options>
1997 const char* strings[] = { options... };
1998 int nbValues =
sizeof...(options);
1999 for (
int p = 0; p < nbValues; p++)
2047 template<
class List, std::enable_if_t<std::is_same_v<std::decay_t<List>, std::initializer_list<Control>>,
int> = 0>
2049 for (
const auto& control : list)
controls.emplace_back(control);
2051 template<
class List, std::enable_if_t<std::is_same_v<std::decay_t<List>, std::initializer_list<Control>>,
int> = 0>
2053 for (
const auto& control : list)
controls.emplace_back(control);
2055 template<
class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...),
int> = 0>
2058 template<
class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...),
int> = 0>
2061 template<
class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...),
int> = 0>
2064 template<
class... Entries, std::enable_if_t<(std::is_constructible_v<ControlEntry, Entries&&> && ...),
int> = 0>
2084 [[noreturn]]
static void invalid(
const char* message) {
2085#if defined(__cpp_exceptions) || defined(_CPPUNWIND)
2086 throw std::logic_error(message);
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>();
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) {}
2105 Control* target =
nullptr;
2106 std::shared_ptr<Lifetime> lifetime;
2110 unsigned int start = 0, length = 0;
2113 bool borrowed =
false;
2115 unsigned int scopeIndex[128] {};
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;
2124 struct Entry {
Controls* owner; Control* first;
const Construction* creator; };
2126 std::vector<Entry> collections;
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()) {
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");
2144 auto* owner = entry.owner;
2145 for (
unsigned int i = 0; i < owner->count; ++i)
2146 if (&owner->items[i] == &control) {
2148 return { { &control, owner->token() }, owner, i };
2152 return { { &control, {} },
nullptr, 0 };
2155 void mutableSchema()
const {
2156 if (lifetime && lifetime.use_count() > 1)
2157 invalid(
"Cannot change a Controls schema while it is referenced");
2159 std::shared_ptr<Lifetime> token()
const {
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;
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;
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);
2182 std::string childIdentity(
const Controls& child,
char kind)
const {
2183 if (child.lifetime->creator != lifetime->creator || child.lifetime->birth <= lifetime->birth)
2185 return std::string(1, kind) + std::to_string(child.lifetime->birth - lifetime->birth);
2187 void room(
unsigned int entries)
const {
2188 if (entries > 128 -
count) invalid(
"Controls capacity exceeded");
2190 bool owns(
const Control* control)
const {
2191 for (
const auto& item :
items)
if (&item == control)
return true;
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;
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);
2207 scopes[index] = { name,
count, length };
2210 void appendOwned(
const Control& control) {
2213 aliases[
count] = {};
2214 input[
count] =
false;
2215 scopeIndex[
count] = 0;
2216 sourceKeys[
count].clear();
2218 metadataDirty =
true;
2220 void appendReference(Control& control) {
2222 if (owns(&control)) invalid(
"A Controls collection cannot reference its own storage");
2223 Origin origin = capture(control, input[
count]);
2224 std::string identity;
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();
2231 identity = std::string(
"control/") + control.name.c_str();
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]);
2242 if (ambiguous) identity.clear();
2244 const auto scope = newScope(1, identity);
2245 pin(origin.alias.lifetime);
2247 aliases[
count] = std::move(origin.alias);
2251 borrowed = metadataDirty =
true;
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");
2262 aliases[
count].target = ⌖
2263 aliases[
count].lifetime = controls.token();
2264 input[
count] = controls.isInput(i);
2266 const char* localKey = controls.key(i);
2267 sourceKeys[
count] = localKey[0] ? scopes[
scope].name +
"/" + localKey :
"";
2270 borrowed = metadataDirty =
true;
2272 void append(
const ControlEntry& entry) {
2275 else appendOwned(entry.owned);
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())) {
2284 if (!sourceKeys[i].empty()) {
2285 keys[i] = sourceKeys[i];
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();
2292 unsigned int duplicate = 0;
2293 for (
unsigned int j = 0; j < i; ++j)
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;
2300 keys[i] = path +
"/" + std::to_string(duplicate);
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;
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() });
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());
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;
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;
2347 for (
auto& alias : aliases) alias = {};
2348 lifetime->dependencies.clear();
2349 for (
auto& flag : input) flag =
false;
2350 for (
auto& index : scopeIndex) index = 0;
2353 metadataDirty =
true;
2359 template<
class Source, std::enable_if_t<std::is_same_v<std::decay_t<Source>, Controls>,
int> = 0>
2362 if (
this == &other)
return *
this;
2364 for (
unsigned int i = 0; i < other.
count; ++i) appendOwned(other[i]);
2366 for (
unsigned int i = 0; i <
count; ++i) input[i] = other.
isInput(i);
2371 unsigned int entries = 0, headings = 0;
2372 for (
const auto&
group : declaration) {
2373 for (
const auto& entry :
group.controls) {
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;
2381 invalid(
"A Controls collection cannot reference its own storage");
2387 if (entries > 128 || headings > 10) invalid(
"Controls declaration capacity exceeded");
2389 for (
const auto&
group : declaration) {
2390 const auto start =
count;
2391 for (
const auto& entry :
group.controls) append(entry);
2394 metadataDirty =
true;
2401 void add(
const Control& control) { mutableSchema(); appendOwned(control); }
2404 if (
count == 128)
return nullptr;
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);
2421 if (options.size() > 128) invalid(
"Control options capacity exceeded");
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);
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; }
2449 for (
unsigned int i = 0; i <
count; ++i) result = std::max(result, std::abs(
float((*
this)[i])));
2454 for (
unsigned int i = 0; i <
count; ++i) result += std::abs(
float((*
this)[i]));
2455 return result /
count;
2459 for (
unsigned int i = 0; i <
count; ++i) {
const float sample = (*this)[i]; result += sample * sample; }
2460 return std::sqrt(result /
count);
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;
2476 invalid(
"Invalid Controls group");
2478 metadataDirty =
true;
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]);
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]; }
2496 if (index < 0 || index >=
static_cast<int>(
count))
return;
2498 const Control* target = &(*this)[index];
2499 for (
unsigned int i = 0; i <
count; ++i)
2500 if (&(*
this)[i] == target) input[i] = state;
2505 void setMetadata(
int index,
const char* identity,
const char* block,
int start,
int length,
bool gameInput) {
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") {
2516 if (
scope == scopeCount) {
2517 if (scopeCount == 129) invalid(
"Controls scope capacity exceeded");
2520 scopes[
scope] = { scopeName,
static_cast<unsigned int>(start),
static_cast<unsigned int>(length) };
2522 scopeIndex[index] =
scope;
2523 sourceKeys[index] = identity;
2525 metadataDirty =
true;
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 };
2539 markInput(canonicalIndex, input[canonicalIndex]);
2540 metadataDirty =
true;
2545 for (
unsigned int i = 0; i <
count; ++i)
2546 if (aliases[i].target)
items[i] = (*this)[i];
2588 for (
int p = 0; p < 128 && presets[p].name[0]; p++)
2589 operator+=(presets[p]);
2593 for (
auto preset : presets)
2597 template<
typename...
Values>
2601 const float preset[] = { values... };
2602 int nbValues =
sizeof...(values);
2603 for (
int p = 0; p < nbValues; p++)
2624 const unsigned int mask = 0xFFFFFFFF;
2667 _controlfp_s(
nullptr, _DN_FLUSH, _MCW_DN);
2688 else for (
int s = 0; s <
size; s++)
2705 const float f = floorf(
offset);
2706 const float frac =
offset - f;
2708 const int i = (int)
offset;
2709 const int j = (i == (
size - 1)) ? 0 : (i + 1);
2726 explicit operator double()
const {
2767 for (
int s = 0; s <
size; s++)
2774 for (
int s = 0; s <
size; s++)
2780 namespace variable {
2782 std::unique_ptr<klang::buffer> ptr;
2794 if (
size != ptr->size)
2802 void set(
float value = 0) { ptr->set(value); }
2809 operator const signal& ()
const {
return ptr->operator
const signal & (); }
2810 explicit operator double()
const {
return ptr->operator double(); }
2822 resize(in.
size); *ptr = *in.ptr;
return *
this;
2825 float*
data() {
return ptr->data(); }
2826 const float*
data()
const {
return ptr->data(); }
2828 float level()
const {
return ptr->level(); }
2829 float rms()
const {
return ptr->rms(); }
2833 namespace interleaved {
2841 template<
int CHANNELS = 2>
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));
2851 static unsigned int capacity(
unsigned int size) {
2852 if (
size == 0)
return 1;
2861 const unsigned int mask = 0xFFFFFFFF;
2862 const bool owned =
false;
2869 assert(
size >= 0 && (samples ||
size == 0));
2876 : mask(capacity(
size) - 1), owned(true),
2883 : mask(other.mask), samples(other.samples),
size(other.
size) {
rewind(); }
2885 if (owned)
delete[]
reinterpret_cast<signal*
>(samples);
2889 ptr = samples ?
reinterpret_cast<signal*
>(samples) +
offset :
nullptr;
2890 end = samples ?
reinterpret_cast<signal*
>(samples) +
size :
nullptr;
2892 int offset()
const {
return samples ? int(ptr -
reinterpret_cast<signal*
>(samples)) : 0; }
2896 if (count > 0 &&
size > 0) std::memset(samples, 0,
sizeof(
signal) * std::min(count,
size));
2899 if (value == 0)
clear();
2900 else for (
size_t i = 0; i < size_t(
size) * CHANNELS; ++i) samples[i] = value;
2903 return reinterpret_cast<signal*
>(samples)[
static_cast<unsigned int>(index) & mask];
2906 return reinterpret_cast<const signal*
>(samples)[
static_cast<unsigned int>(index) & mask];
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;
2916 operator const signal& ()
const {
return *ptr; }
2924 std::memmove(samples, other.samples, std::min(
size, other.
size) *
sizeof(
signal));
2929 const float*
data()
const {
return samples; }
2941 template<
typename SIGNAL>
2947 virtual const SIGNAL&
input()
const {
return in; }
2959 template<
typename SIGNAL>
2967 template<
typename TYPE,
class =
decltype(
2968 std::declval<TYPE&>() = std::declval<SIGNAL&>())>
2969 TYPE&
operator>>(TYPE& destination) { this->
process();
return destination =
out; }
2972 virtual operator const SIGNAL& () { this->
process();
return out; }
2973 virtual operator const SIGNAL& ()
const {
return out; }
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); }
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> ||
3005 !std::is_lvalue_reference_v<SCALAR>)) && !std::is_const_v<OBJECT> &&
3006 std::is_base_of_v<Output<OutputSignal<OBJECT>>, OBJECT> &&
3009 template<
typename OBJECT,
typename SCALAR>
3011 if constexpr (std::is_arithmetic_v<SCALAR>)
3016 template<
typename OBJECT,
typename SCALAR>
3018 if constexpr (std::is_arithmetic_v<SCALAR>)
3023 template<
typename OBJECT,
typename SCALAR>
3025 if constexpr (std::is_arithmetic_v<SCALAR>)
3030 template<
typename OBJECT,
typename SCALAR>
3032 if constexpr (std::is_arithmetic_v<SCALAR>)
3044 template<
typename SIGNAL>
3049 template<
typename... params>
3051 set(std::forward<params>(p)...);
return *
this;
3054 using Output<SIGNAL>::operator>>;
3056 operator const SIGNAL& ()
override { this->
process();
return out; }
3057 operator const SIGNAL& ()
const override {
return out; }
3062 virtual void set(
param) {};
3064 virtual void set(param, param) {};
3065 virtual void set(param, relative) {};
3066 virtual void set(param, param, param) {};
3067 virtual void set(param, param, relative) {};
3068 virtual void set(param, param, param, param) {};
3069 virtual void set(param, param, param, relative) {};
3070 virtual void set(param, param, param, param, param) {};
3071 virtual void set(param, param, param, param, relative) {};
3072 virtual void set(param, param, param, param, param, param) {};
3073 virtual void set(param, param, param, param, param, relative) {};
3074 virtual void set(param, param, param, param, param, param, param) {};
3075 virtual void set(param, param, param, param, param, param, relative) {};
3076 virtual void set(param, param, param, param, param, param, param, param) {};
3077 virtual void set(param, param, param, param, param, param, param, relative) {};
3082 template<
typename SIGNAL>
3090 operator const SIGNAL& ()
override { this->
process();
return out; }
3091 operator const SIGNAL& ()
const override {
return out; }
3097 template<
typename... params>
3099 set(std::forward<params>(p)...);
return *
this;
3104 virtual void set(
param) {};
3106 virtual void set(param, param) {};
3107 virtual void set(param, relative) {};
3108 virtual void set(param, param, param) {};
3109 virtual void set(param, param, relative) {};
3110 virtual void set(param, param, param, param) {};
3111 virtual void set(param, param, param, relative) {};
3112 virtual void set(param, param, param, param, param) {};
3113 virtual void set(param, param, param, param, relative) {};
3114 virtual void set(param, param, param, param, param, param) {};
3115 virtual void set(param, param, param, param, param, relative) {};
3116 virtual void set(param, param, param, param, param, param, param) {};
3117 virtual void set(param, param, param, param, param, param, relative) {};
3118 virtual void set(param, param, param, param, param, param, param, param) {};
3119 virtual void set(param, param, param, param, param, param, param, relative) {};
3124 template<
typename SIGNAL,
typename... Args>
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);
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));
3169 operator void* () {
return this; }
3170 uint64_t hash()
const {
return hash_tuple(
tail(
inputs)); }
3175 static constexpr unsigned int ARGS =
sizeof...(Args);
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);
3186 template<
typename FunctionPtr>
3189 template<
typename FunctionPtr>
3194 template<
typename FunctionPtr,
typename... OtherArgs>
3205 template <
typename First,
typename... Rest>
3209 template <
typename First,
typename... Rest>
3213 template<
typename... FuncArgs>
3224 if constexpr (
ARGS ==
sizeof...(FuncArgs)) {
3231 else if constexpr (
sizeof...(FuncArgs) == (
ARGS - 1)) {
3238 static_assert(
sizeof...(FuncArgs) < (
ARGS - 1),
"Insufficient arguments: can only omit first argument");
3246 template<
typename... FuncArgs>
3252 if constexpr (ARGS > 1 &&
sizeof...(FuncArgs) == 1) {
3256 else if constexpr (
ARGS ==
sizeof...(FuncArgs)) {
3260 else if constexpr (
sizeof...(FuncArgs) == (
ARGS - 1)) {
3270 if constexpr (
ARGS > 1)
3281 template<
typename... FuncArgs>
3283 static_assert(
sizeof...(FuncArgs) == (
ARGS - 1),
"with() arguments must have all but first argument.");
3292 if constexpr (
ARGS > 1)
3312 template <
typename... Args>
3315 template <
typename... Args>
3322 SIGNAL y = (SIGNAL)func;
3323 return (SIGNAL)x / y;
3338 bool valid()
const {
return !::isnan(
x) && !::isinf(
x) && !::isnan(
y); }
3361 template<
typename SIGNAL,
typename... Args>
3363 constexpr int size = SIZE > 1024 ? 1024 : SIZE;
3370 const double dx = x_axis.
range() /
size;
3371 for (
int i = 0; i <=
size; i++) {
3372 x = x_axis.
min + i * dx;
3378 template<
typename RETURN,
typename ARG>
3380 constexpr int size = SIZE > 1024 ? 1024 : SIZE;
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) });
3396 if (
count !=
in.count)
return false;
3397 for (
unsigned int i = 0; i <
count; i++)
3420 double min = 0, max = 0;
3423 bool contains(
double value)
const {
return value >= min && value <=
max; }
3427 if (!series.
count)
return;
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;
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;
3456 for (
int s = 0; s < GRAPH_SERIES; s++)
3462 bool isActive()
const {
3465 for (
int s = 0; s < GRAPH_SERIES; s++)
3477 for (
int s = 0; s < GRAPH_SERIES; s++)
3478 if (this->
operator[](s).function == function)
3512 template<
typename SIGNAL,
typename... Args>
3526 template<
typename TYPE>
3540 template<
typename FUNCTION,
typename... VALUES>
3541 void plot(FUNCTION f, VALUES... values) {
3542 thread_local static Function fun(f);
3555 template<
typename TYPE>
3561 template<
typename TYPE>
3567 template<
typename TYPE>
3580 for (
const auto& value : values)
3601 for (
int s = 0; s < GRAPH_SERIES; s++)
3608 for (
int s = 0; s < GRAPH_SERIES; s++)
3623 for (
int s = 0; s < GRAPH_SERIES; s++)
3624 if (count <
data[s].count)
3641 template<
typename SIGNAL>
3655 Oscillator::frequency = frequency;
3670 offset = phase * (2 *
pi);
3687 template <
typename TYPE,
typename SIGNAL>
3693 template<
typename TYPE,
int COUNT>
3694 struct Bank :
public GeneratorOrModifier<TYPE, signals<COUNT>> {
3704 template<
typename... Args>
3706 for (
int n = 0; n < COUNT; n++)
3707 items[n].set(args...);
3711 for (
int n = 0; n < COUNT; n++)
3716 for (
int n = 0; n < COUNT; n++)
3729 return destination = mono();
3734 template<
typename... Args>
3762 std::unique_ptr<Graph> ptr;
3765 if (ptr.get() ==
nullptr)
3766 ptr = std::make_unique<Graph>();
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(); }
3773 void clear() { init(); ptr->clear(); }
3774 bool isActive()
const {
return ptr ? ptr->isActive() :
false; }
3776 Graph& operator()(
double min,
double max) { init();
return (Graph&)ptr->operator()(min, max); }
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; }
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); }
3783 operator Graph::Series& () { init();
return ptr->operator Graph::Series & (); }
3785 template<
typename SIGNAL,
typename... Args>
3786 void plot(Generic::Function<SIGNAL, Args...>& function) { init(); ((Graph*)(ptr.get()))->plot(function); }
3788 template<
typename TYPE>
3789 void plot(TYPE(*function)(TYPE)) { init(); ((Graph*)(ptr.get()))->plot(function); }
3791 template<
typename FUNCTION,
typename... VALUES>
3792 void plot(FUNCTION f, VALUES... values) { init(); ((Graph*)(ptr.get()))->plot(f, values...); }
3794 template<
typename TYPE>
void add(TYPE y) { init(); ptr->add(y); }
3795 void add(
const Graph::Point pt) { init(); ptr->add(pt); }
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); }
3800 template<
typename TYPE> Graph& operator=(TYPE(*function)(TYPE)) { init();
return (Graph&)ptr->operator=(function); }
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); }
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; }
3807 template<
typename TYPE> Graph& operator<<(
const TYPE& in) { add(in);
return *
this; }
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); }
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); }
3816 void truncate(
unsigned int count) { init(); ptr->truncate(count); }
3823 template <
typename... Args>
3831 template<
typename SIGNAL,
typename... Args>
3838 graph->plot(
static_cast<float(*)(
float)
>(function));
3842 template<
typename TYPE>
3844 graph->plot(function);
3848 template<
typename SIGNAL,
typename... Args>
3855 graph.plot(
static_cast<float(*)(
float)
>(function));
3859 template<
typename TYPE>
3861 graph.plot(function);
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;
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));
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>;
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> ||
3907 template<
class... Values>
3908 inline constexpr bool are_math_values_v = (is_math_value_v<Values> && ...);
3910 template<
class... Values>
3911 inline constexpr bool has_control_v = (is_control_v<Values> || ...);
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); }
3917 template<
class TARGET,
class VALUE,
class =
void>
3918 struct has_native_template_inlet : std::false_type {};
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 {};
3925 template<class TARGET>
3926 using param_inlet_result = decltype(std::declval<TARGET&>().operator<<(std::declval<param>()));
3928 template<class TARGET, class = void>
3929 struct has_param_inlet : std::false_type {};
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 {};
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>>;
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)); \
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)); \
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)
3970 #undef KLANG_BINARY_OPERATION
3971 #undef KLANG_TERNARY_OPERATION
3974 template<class OPERATION>
3980 template<class OPERATION>
3981 struct TernaryMath {
3982 float middle, right;
3985 template<class OPERATION>
3986 inline signal operator>>(signal left, const BinaryMath<OPERATION>& stage) {
3987 return OPERATION{}(float(left), stage.right);
3990 template<class OPERATION>
3991 inline signal operator>>(signal left, const TernaryMath<OPERATION>& stage) {
3992 return OPERATION{}(float(left), stage.middle, stage.right);
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));
4003 template<class SOURCE, class DESTINATION>
4004 auto flow_destination(std::true_type)
4005 -> decltype(std::declval<DESTINATION&>().input(std::declval<SOURCE>()));
4007 template<class SOURCE, class DESTINATION>
4008 auto flow_destination(std::false_type)
4009 -> decltype(std::declval<DESTINATION&>() << std::declval<SOURCE>());
4012using detail::operator<<;
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)); \
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)}; \
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)); \
4036 inline signal function(const Control& left, const Control& right) { \
4037 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4038 detail::numeric_snapshot(right)); \
4040 inline signal function(const ControlMap& left, const ControlMap& right) { \
4041 return detail::function##_operation{}(detail::numeric_snapshot(left), \
4042 detail::numeric_snapshot(right)); \
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)); \
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)}; \
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)); \
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)); \
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)); \
4081#define KLANG_UNARY_MATH(function) \
4082 using std::function; \
4083 KLANG_UNARY_ADAPTER(function, std::function)
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)
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)
4120#undef KLANG_UNARY_MATH
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)}; \
4129 inline signal function(signal left, signal right) { \
4130 return detail::function##_operation{}(float(left), float(right)); \
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)); \
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)); \
4140 KLANG_CONTROL_BINARY_MATH(function)
4147 using std::remainder;
4148 using std::copysign;
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)}; \
4159 inline signal function(signal left, signal middle, signal right) { \
4160 return detail::function##_operation{}(float(left), float(middle), float(right)); \
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)); \
4167 KLANG_CONTROL_TERNARY_MATH(function)
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)
4183 template<typename... ARGS>
4184 inline auto clip(ARGS&&... args) -> decltype(clamp(std::forward<ARGS>(args)...)) {
4185 return clamp(std::forward<ARGS>(args)...);
4189 KLANG_BINARY_MATH(mod)
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
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; }
4203 KLANG_UNARY_ADAPTER(sqr, klang::sqr)
4204 KLANG_UNARY_ADAPTER(cube, klang::cube)
4206#undef KLANG_UNARY_ADAPTER
4209 struct Console : public Text<16384> {
4210 static std::mutex _lock;
4211 THREAD_LOCAL static Text<16384> last;
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);
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);
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);
4241 memcpy(&last, in, len);
4242 last.string[len] = 0;
4246 bool hasText() const {
4250 int getText(char* buffer) {
4252 std::lock_guard<std::mutex> lock(_lock);
4253 const int _length = length;
4254 memcpy(buffer, string, length);
4261 inline THREAD_LOCAL Text<16384> Console::last;
4264#define PROFILE(func, ...) debug.print("%-16s = %fns\n", #func "(" #__VA_ARGS__ ")", debug.profile(1000, func, __VA_ARGS__));
4266#define PROFILE(func, ...) ((void)0);
4270 struct Debug : Input {
4273 struct Buffer : private buffer {
4274 using buffer::clear;
4275 using buffer::rewind;
4277 using buffer::operator++;
4280 signal& operator++(int) { return *ptr; }
4282 using buffer::operator signal&;
4284 Buffer() : buffer(16384) {}
4303 bool active = false;
4306 const float* get() {
4320 Buffer& operator+=(const signal in) {
4323 buffer::operator+=(in);
4330 template<typename TYPE>
4331 Buffer& operator+=(TYPE& in) {
4334 buffer::operator+=(in);
4341 signal& operator>>(signal& destination) const {
4343 destination << *ptr;
4351 operator const signal& () const {
4355 static const signal silence = 0;
4361 THREAD_LOCAL static Buffer buffer;
4366 template <typename Func, typename... Args>
4367 inline static double profile(Func func, Args... args) {
4369 using namespace std::chrono;
4371 auto start = high_resolution_clock::now();
4373 auto end = high_resolution_clock::now();
4375 auto duration = duration_cast<nanoseconds>(end - start).count();
4376 return (double)duration;
4382 template <typename Func, typename... Args>
4383 inline static double profile(int times, Func func, Args... args) {
4387 sum += profile(func, args...);
4389 return sum / 1000000.0;
4397 Session(float*, int size, Buffer::Content content) {
4401 if (buffer.content != Buffer::Notes)
4403 buffer.content = content;
4414 bool hasAudio() const {
4416 return buffer.active;
4421 const float* getAudio() const {
4423 return buffer.get();
4431 void print(const char* format, ...) {
4433 if (console.length < 10000) {
4434 THREAD_LOCAL static char string[1024] = { 0 };
4437 va_start(args, format);
4438 vsnprintf(string, 1024, format, args);
4447 void printOnce(const char* format, ...) {
4449 if (console.length < 1024) {
4450 THREAD_LOCAL static char string[1024] = { 0 };
4453 va_start(args, format);
4454 vsnprintf(string, 1024, format, args);
4457 if (console.last != string)
4465 bool hasText() const {
4467 return console.hasText();
4473 int getText(char* buffer) {
4475 return console.getText(buffer);
4477 if (buffer) buffer[0] = 0;
4482 operator const signal& () const {
4484 return buffer.operator const klang::signal & ();
4486 return passthrough();
4493 static signal& passthrough() {
4494 static thread_local signal value = 0;
4497 void input(const signal& value) override { passthrough() = value; }
4498 void operator<<(const signal& value) override { passthrough() = value; }
4500 void input() override {
4519 inline THREAD_LOCAL Debug::Buffer Debug::buffer;
4520 inline std::mutex Console::_lock;
4523 template <typename TYPE>
4529 Result(TYPE* array, int index) : y(&array[index]), i(index) {}
4531 TYPE& operator[](int index) {
4532 return *(y + index);
4535 operator TYPE const () { return *y; }
4537 Result& operator=(const TYPE& in) {
4542 TYPE& operator++(int) { i++; return *++y; }
4547 template<typename TYPE, int SIZE>
4548 struct Table : public Array<TYPE, SIZE> {
4549 typedef Array<TYPE, SIZE> Array;
4550 typedef Result<TYPE> Result;
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);
4565 function((TYPE)x, result);
4566 result.sum += Array::items[x];
4567 if (x + 1 < SIZE) result++;
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);
4578 Table(std::initializer_list<TYPE> values) {
4579 for (TYPE value : values)
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];
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;
4599 struct Delay : public Modifier {
4601 using Modifier::out;
4607 Delay() : buffer(SIZE + 1, 0) { clear(); }
4613 void input() override {
4616 if (position == SIZE) {
4622 signal tap(int delay) const {
4623 int read = (position - 1) - delay;
4626 return buffer[read];
4629 signal tap(float delay) const {
4631 float read = static_cast<float>(position - 1) - delay;
4636 const int i = static_cast<int>(read);
4637 const float fraction = read - i;
4640 const int j = (i + 1) % SIZE;
4643 return buffer[i] + fraction * (buffer[j] - buffer[i]);
4646 signal lagrange(float delay) const {
4648 float read = static_cast<float>(position - 1) - delay;
4653 int i = static_cast<int>(read);
4657 int i0 = (i - 1 + SIZE) % SIZE;
4659 int i2 = (i + 1) % SIZE;
4660 int i3 = (i + 2) % SIZE;
4663 float y0 = buffer[i0];
4664 float y1 = buffer[i1];
4665 float y2 = buffer[i2];
4666 float y3 = buffer[i3];
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;
4674 return c0 * y0 + c1 * y1 + c2 * y2 + c3 * y3;
4678 signal tap() const {
4680 const int i = last.position;
4681 const int j = (i + 1) % SIZE;
4684 return buffer[i] + last.fraction * (buffer[j] - buffer[i]);
4687 virtual void process() override {
4689 last.position = (last.position + 1) % SIZE;
4697 virtual void set(param samples) override {
4698 time = samples < SIZE ? (float)samples : SIZE;
4700 float read = static_cast<float>(position - 1) - time;
4704 last.position = static_cast<int>(read);
4705 last.fraction = read - last.position;
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);
4715 return tap((signal)delay);
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);
4725 return tap((signal)delay);
4728 unsigned int max() const { return SIZE; }
4733 struct Delay<0> : public Modifier {
4735 using Modifier::out;
4742 Delay() : buffer(new klang::buffer(1, 0)) { clear(); }
4748 void resize(int samples) {
4749 if (samples != SIZE) {
4751 klang::buffer* new_buffer = new klang::buffer(SIZE + 1, 0);
4752 std::swap(buffer, new_buffer);
4757 void input() override {
4760 if (position == SIZE) {
4766 signal tap(int delay) const {
4767 int read = (position - 1) - delay;
4770 return (*buffer)[read];
4773 signal tap(float delay) const {
4775 float read = static_cast<float>(position - 1) - delay;
4780 const int i = static_cast<int>(read);
4781 const float fraction = read - i;
4784 const int j = (i + 1) % SIZE;
4787 return (*buffer)[i] + fraction * ((*buffer)[j] - (*buffer)[i]);
4790 signal tap() const {
4792 const int i = last.position;
4793 const int j = (i + 1) % SIZE;
4796 return (*buffer)[i] + last.fraction * ((*buffer)[j] - (*buffer)[i]);
4799 virtual void process() override {
4801 last.position = (last.position + 1) % SIZE;
4809 virtual void set(param samples) override {
4810 time = samples < SIZE ? (float)samples : SIZE;
4812 float read = static_cast<float>(position - 1) - time;
4816 last.position = static_cast<int>(read);
4817 last.fraction = read - last.position;
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);
4827 return tap((signal)delay);
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);
4837 return tap((signal)delay);
4840 unsigned int max() const { return SIZE; }
4844 class Wavetable : public Oscillator {
4845 using Oscillator::set;
4850 Wavetable(int size = 2048) : buffer(size), size(size) {}
4852 template<typename TYPE>
4853 Wavetable(TYPE oscillator, int size = 2048) : buffer(size), size(size) {
4854 operator=(oscillator);
4857 signal& operator[](int index) {
4858 return buffer[index];
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;
4869 virtual void set(param frequency) override {
4870 Oscillator::frequency = frequency;
4871 increment = frequency * (size / fs);
4874 virtual void set(param frequency, param phase) override {
4875 position = phase * float(size);
4879 virtual void set(relative phase) override {
4881 offset = phase * float(size);
4884 virtual void set(param frequency, relative phase) override {
4889 void process() override {
4890 position += { increment, size };
4891 out = buffer[position + offset ];
4896 class Sample : public Generator {
4897 using Generator::set;
4904 using Generator::operator();
4908 Frequency frequency = 0;
4909 SampleRate samplerate = 0;
4913 enum Mode { OneShot, Looped };
4914 Mode mode = OneShot;
4918 const klang::buffer& source;
4919 std::optional<Info> info;
4920 std::optional<Mode> mode;
4922 Binding(const klang::buffer& source, Info info, std::optional<Mode> mode = std::nullopt)
4923 : source(source), info(info), mode(mode) {}
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) {}
4930 Sample() : buffer(nullptr, 0) {}
4932 signal& operator[](int index) {
4933 return buffer[index];
4937 Sample& operator=(const klang::buffer& source) {
4939 if (size > 0) buffer.attach(source, size);
4945 Sample& operator=(Mode mode) {
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;
4957 void set(param rate) override {
4958 if (finite(rate.value)) this->rate = rate.value;
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;
4971 Sample& operator()(Frequency frequency) {
4977 void set(param rate, param time) override {
4979 if (finite(time.value)) position = double(time.value) * sourceRate();
4983 void set(relative time) override {
4984 if (finite(time.value)) offset = double(time.value) * sourceRate();
4987 void set(param rate, relative time) override {
4993 void reset() { position = 0; }
4995 void process() override {
4996 const bool looped = mode == Looped;
4997 double read = position + offset;
4998 if (size == 0 || (!looped && (read < 0 || read >= size))) {
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;
5011 if (looped) position = wrap(position);
5015 double rate = 1, position = 0, offset = 0;
5017 static bool finite(float value) {
5019 std::memcpy(&bits, &value, sizeof(bits));
5020 return (bits & 0x7f800000u) != 0x7f800000u;
5023 static bool positive(float value) { return finite(value) && value > 0; }
5025 float sourceRate() const {
5026 if (positive(info.samplerate.f)) return info.samplerate.f;
5027 return positive(fs.f) ? fs.f : 0;
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;
5037 inline constexpr Sample::Mode OneShot = Sample::OneShot;
5038 inline constexpr Sample::Mode Looped = Sample::Looped;
5041 class Envelope : public Generator {
5042 using Generator::set;
5049 struct Ramp : public Generator {
5052 bool active = false;
5056 Ramp(float value = 1.f) {
5061 Ramp(float start, float target, float time) {
5070 bool isActive() const {
5075 virtual void setTarget(float target) {
5076 Ramp::target = target;
5077 active = (out != target);
5081 virtual void setValue(float value) {
5083 Ramp::target = value;
5088 virtual void setRate(float rate) { Ramp::rate = rate; }
5091 virtual void setTime(float time) { Ramp::rate = time ? 1.f / (time * fs) : 0; }
5094 virtual signal operator++(int) = 0;
5096 void process() override { }
5100 struct Linear : public Ramp {
5103 signal operator++(int) override {
5104 const signal output = out;
5109 if (out >= target) {
5116 if (out <= target) {
5128 enum Stage { Sustain, Release, Off };
5130 enum Mode { Time, Rate };
5136 Point() : x(0), y(0) {}
5138 template<typename T1, typename T2>
5139 Point(T1 x, T2 y) : x(float(x)), y(float(y)) {}
5144 struct Points : public Point {
5145 Points(float x, float y) {
5154 Points& operator()(float x, float y) {
5155 last().next = new Points(x, y);
5160 return next ? next->last() : *this;
5164 return next ? 1 + next->count() : 1;
5173 Loop(int from = -1, int to = -1) : start(from), end(to) {}
5175 void set(int from, int to) { start = from; end = to; }
5176 void reset() { start = end = -1; }
5178 bool isActive() const { return start != -1 && end != -1; }
5185 Envelope() : ramp(new Linear()) { set(Points(0.f, 1.f)); }
5188 Envelope(const Points& points) : ramp(new Linear()) { set(points); }
5191 Envelope(std::initializer_list<Point> points) : ramp(new Linear()) { set(points); }
5194 Envelope(const Envelope& in) : ramp(new Linear()) { set(in.points); }
5196 virtual ~Envelope() {}
5199 bool operator==(Stage stage) const { return Envelope::stage == stage; }
5200 bool operator!=(Stage stage) const { return Envelope::stage != stage; }
5205 Envelope& operator=(std::initializer_list<Point> points) {
5211 void set(const std::vector<Point>& points) {
5212 Envelope::points = points;
5217 void set(const Points& point) {
5220 const Points* pPoint = &point;
5222 points.push_back(*pPoint);
5223 pPoint = pPoint->next;
5232 for (Point& point : points) {
5233 const float delta = point.x;
5234 time += delta + 0.00001f;
5241 void setLoop(int startPoint, int endPoint) {
5242 if (startPoint >= 0 && endPoint < points.size())
5243 loop.set(startPoint, endPoint);
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);
5259 return points.back().y;
5265 if (stage == Sustain && (point + 1) < points.size())
5266 setTarget(points[point + 1], points[point].x);
5270 void setStage(Stage stage) { this->stage = stage; }
5273 const Stage getStage() const { return stage; }
5276 float getLength() const { return points.size() ? points[points.size() - 1].x : 0.f; }
5279 virtual void release(float time, float level = 0.f) {
5281 setTarget({ time, level }, 0);
5287 bool finished() const {
5288 return getStage() == Stage::Off;
5301 timeInc = 1.0f / fs;
5303 if (points.size()) {
5305 ramp->setValue(points[0].y);
5306 if (points.size() > 1)
5307 setTarget(points[1], points[0].x);
5311 ramp->setValue(1.0f);
5316 void resize(float length) {
5317 const float old_length = getLength();
5318 if (old_length == 0.0)
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;
5332 void setTarget(const Point& point, float time = 0.0) {
5333 (this->*setTargetFunction)(point, time);
5337 signal& operator++(int) {
5348 if (!ramp->isActive()) {
5349 if (loop.isActive() && (point + 1) >= loop.end) {
5351 ramp->setValue(points[point].y);
5352 if (loop.start != loop.end)
5353 setTarget(points[point + 1], points[point].x);
5355 else if ((point + 1) < points.size()) {
5356 if (mode() == Rate || time >= points[point + 1].x) {
5358 ramp->setValue(points[point].y);
5360 if ((point + 1) < points.size())
5361 setTarget(points[point + 1], points[point].x);
5369 if (!ramp->isActive())
5378 const Point& operator[](int point) const {
5379 return points[point];
5383 void set(Ramp* ramp) {
5384 Envelope::ramp = std::shared_ptr<Ramp>(ramp);
5388 void setMode(Mode mode) {
5390 setTargetFunction = &Envelope::setTargetTime;
5392 setTargetFunction = &Envelope::setTargetRate;
5395 Mode mode() const { return setTargetFunction == &Envelope::setTargetTime ? Time : Rate; }
5399 void (Envelope::* setTargetFunction)(const Point& point, float time) = &Envelope::setTargetTime;
5401 void setTargetTime(const Point& point, float time = 0.0) {
5403 ramp->setTarget(point.y);
5404 ramp->setRate(abs(point.y - ramp->out) / ((point.x - time) * fs));
5407 void setTargetRate(const Point& point, float rate = 0.0) {
5410 ramp->setValue(point.y);
5413 ramp->setTarget(point.y);
5414 ramp->setRate(point.x);
5435 enum Mode { Time, Rate } mode = Time;
5443 R = release + 0.005f;
5446 points[0] = { 0, 0 };
5447 points[1] = { A, 1 };
5448 points[2] = { A + D, S };
5454 void release(
float time = 0.f,
float level = 0.f)
override {
5455 Envelope::release(time ? time :
float(R), level);
5459 return getStage() == stage;
5464 template<
class OSCILLATOR>
5484 Operator::amp = amp;
5489 OSCILLATOR::set(+in);
5490 OSCILLATOR::process();
5491 OSCILLATOR::out *= env++ * amp;
5500 template<
class OSCILLATOR>
5502 carrier << modulator;
5511 virtual event midi(
int status,
int byte1,
int byte2) {};
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); }
5522 template<
typename DERIVED,
typename... ARGS>
5524 static_assert(std::is_base_of_v<Plugin, DERIVED>);
5525 DERIVED* p =
new DERIVED();
5526 p->controls.set(std::forward<ARGS>(args)...);
5556 using Effect::process;
5561 template<
class SYNTH>
5568 Controls& operator=(
klang::Controls& controls) { Controls::controls = &controls;
return *
this; }
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; }
5581 auto getSynth() {
return static_cast<std::remove_pointer_t<decltype(synth)
>*>(synth); }
5591 NoteBase::synth = synth;
5592 controls = synth->controls;
5602 on(pitch, velocity);
5610 if (stage != Release) {
5615 return stage == Off;
5625 enum Stage { Onset, Sustain, Release, Off } stage = Off;
5627 virtual void controlChange(
int controller,
int value) { midi(0xB0, controller, value); };
5648 return this->process(
buffer[0]);
5653 template<
class SYNTH,
class NOTE = Note>
5661 for (
int n = 0; n < 128; n++)
5666 template<
class TYPE>
5668 for (
int n = 0; n < count; n++) {
5669 TYPE* note =
new TYPE();
5670 note->attach(synth);
5676 unsigned int noteOns = 0;
5677 unsigned int noteStart[128] = { 0 };
5681 for (
unsigned int i = 0; i < count; i++) {
5682 if (items[i]->stage == NOTE::Off) {
5683 noteStart[i] = noteOns++;
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) {
5695 oldest_start = noteStart[i];
5700 noteStart[oldest] = noteOns++;
5707 for (
unsigned int i = 0; i < count; i++) {
5708 if (oldest == -1 || noteStart[i] < oldest_start) {
5710 oldest_start = noteStart[i];
5713 noteStart[oldest] = noteOns++;
5733 for (
const auto* n : notes.
items) {
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);
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);
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);
5766 virtual event noteOn(
int pitch,
float velocity) {
5767 const int n = notes.
assign();
5769 notes[n]->start((
float)pitch, velocity);
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);
5780 for (
unsigned int n = 0; n < notes.
count; n++)
5781 if (notes[n]->stage != Note::Off)
5782 notes[n]->release(velocity);
5790 for (
unsigned int n = 0; n < notes.
count; n++)
5791 if (notes[n]->stage != Note::Off)
5801 for (
unsigned int c = 0; c < controls.size(); c++)
5802 controls[c].set(parameters[c]);
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))
5815 this->process(mono);
5819 for (
unsigned int c = 0; c < controls.size(); c++)
5820 parameters[c] = controls[c].value;
5825 template<
class SYNTH,
class NOTE>
5827 for (
unsigned int n = 0; n < count; n++) {
5828 NOTE* tmp = items[n];
5834 namespace Mono {
using namespace klang; }
5835 namespace mono {
using namespace klang; }
5912 return (l + r) * 0.5f;
5941 operator const signal()
const {
return { left, right }; }
5942 operator frame () {
return { left, right }; }
5947 return { left = in.l, right = in.r };
5971 return { left[index], right[index] };
5975 return { left[index], right[index] };
5979 return index == 1 ? right : left;
5998 namespace interleaved {
6003 template<
class TYPE>
6022 int read = (items[0].position - 1) - delay;
6025 return { items[0].buffer[read], items[1].buffer[read] };
6029 float read = (float)(items[0].position - 1) - delay;
6033 const float f = floor(read);
6036 const int i = (int)read;
6037 const int j = (i == (SIZE - 1)) ? 0 : (i + 1);
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 };
6044 out = tap(items[0].time);
6047 template<
typename TIME>
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>)
6054 return { items[0].tap(delay.l), items[1].tap(delay.r) };
6059 unsigned int max()
const {
return SIZE; }
6097 using Effect::process;
6119 return this->process(
buffer);
6125 using klang::Mono::Generator::out;
6162 for (
const auto* n : notes.items) {
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);
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);
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);
6195 virtual event noteOn(
int pitch,
float velocity) {
6196 const int n = notes.assign();
6198 notes[n]->start((
float)pitch, velocity);
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);
6209 for (
unsigned int n = 0; n < notes.count; n++)
6210 if (notes[n]->stage != Note::Off)
6211 notes[n]->release(velocity);
6219 for (
unsigned int n = 0; n < notes.count; n++)
6220 if (notes[n]->stage != Note::Off)
6225 virtual void process(
float** buffers,
int length,
float* parameters =
nullptr) {
6232 for (
unsigned int c = 0; c < controls.size(); c++)
6233 controls[c].set(parameters[c]);
6237 for (
unsigned int n = 0; n < notes.count; n++) {
6238 Note* note = notes[n];
6239 if (note->
stage != Note::Off) {
6250 for (
unsigned int c = 0; c < controls.size(); c++)
6251 parameters[c] = controls[c].value;
6259 using namespace Stereo;
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);
6272 destination.input(source);
6274 destination << source;
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);
6287 destination.input(source);
6289 destination << source;
6300 constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
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;
6310 inline float sin(
float x) {
6312 if (x > 3 / 2.f *
pi)
6314 else if (x >
pi / 2)
6316 return detail::sin(x);
6322 x = x <
pi ?
pi / 2.f - x : x - 3.f / 2.f *
pi;
6323 return detail::sin(x);
6327 inline float sinp(
unsigned int phase) {
6329 if (x > 3.f / 2.f *
pi)
6331 else if (x >
pi / 2.f)
6333 return detail::sin(x);
6337 inline float cosp(
unsigned int phase) {
6339 x = x <
pi ?
pi / 2.f - x : x - 3.f / 2.f *
pi;
6340 return detail::sin(x);
6345 namespace Generators {
6346 using namespace klang;
6353 out = sin(position.wrapped(offset));
6361 out = position.wrapped(offset) *
pi.
inv - 1.f;
6370 out = out * 0.5f + 0.5f;
6377 out = abs(2.f * position.wrapped(offset) *
pi.
inv - 2) - 1.f;
6385 out = position.wrapped(offset) >
pi ? 1.f : -1.f;
6394 using Oscillator::set;
6396 set(frequency, phase);
6401 out = position.wrapped(offset) > (duty *
pi) ? 1.f : -1.f;
6409 out = rand() * 2.f / (
const float)RAND_MAX - 1.f;
6416 constexpr float twoPi = float(2.0 * 3.1415926535897932384626433832795);
6421 signed int amount = 0;
6422 void reset() { amount = 0; }
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));
6434 operator float()
const {
return float(
double(amount) / 4294967296.0); }
6435 Increment operator+(
const Increment& other)
const {
6437 const unsigned int bits =
static_cast<unsigned int>(amount) +
static_cast<unsigned int>(other.amount);
6438 std::memcpy(&result.amount, &bits,
sizeof(bits));
6444#pragma float_control(precise, on, push)
6446 unsigned int position = 0;
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;
6456 double cycles()
const {
return double(position) / 4294967296.0; }
6457 operator float()
const {
6458 const unsigned int bits = (position >> 9) | 0x3f800000;
6460 std::memcpy(&value, &bits,
sizeof(value));
6465 unsigned int phase = position + offset.position + 0x40000000;
6466 if (phase & 0x80000000)
6468 const unsigned int bits = (phase >> 8) | 0x3f800000;
6470 std::memcpy(&value, &bits,
sizeof(value));
6471 return value *
pi - 1.5f *
pi;
6473 float radians()
const {
return float(cycles() * twoPi); }
6474 Phase& operator+=(
const Increment step) {
6475 position +=
static_cast<unsigned int>(step.amount);
6479#pragma float_control(pop)
6485 Sine::position = Oscillator::position = 0;
6486 Sine::offset = Oscillator::offset = 0;
6487 set(Oscillator::frequency, 0.f);
6491 if (frequency != Oscillator::frequency || sampleRate !=
double(
fs)) {
6493 Oscillator::frequency = frequency;
6499 Sine::position = Oscillator::position = phase;
6500 Sine::offset = Oscillator::offset = 0;
6510 Sine::offset = Oscillator::offset = phase * twoPi;
6519 double sampleRate = 0;
6529 Phasor::position = Oscillator::position = 0;
6533 if (frequency != Oscillator::frequency || sampleRate !=
double(
fs)) {
6535 Oscillator::frequency = frequency;
6541 Phasor::position = Oscillator::position = phase;
6551 Phasor::offset = Oscillator::offset = phase * twoPi;
6555 Fast::Phase phase = position;
6556 phase.position += offset.position;
6562 double sampleRate = 0;
6569 static constexpr unsigned int bias = 0b1000011100000000000000000000000;
6571 union {
unsigned int i;
float f; };
6574 i = ((rand() & 0b111111111111111UL) << 1) | bias;
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))
6596#define KLANG_OSM_INLINE inline
6598 struct StateMachine {
6599 using Waveform = float(StateMachine::*)();
6600 const Waveform waveform;
6601 KLANG_OSM_INLINE StateMachine(Waveform waveform) : waveform(waveform) {}
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;
6612 Fast::Phase offset, phaseOffset;
6613 unsigned long long breakpoint = 0, threshold = 0;
6616 float fraction = 0, phaseFraction = 0, peakFraction = 0;
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;
6627 float amplitude = 1;
6628 float gain = 1, peak = 1, high = 1, low = -1;
6630 KLANG_OSM_INLINE
void sync() {
6631 state = (offset.position -
static_cast<unsigned int>(
increment.
amount)) < threshold ? Up : Down;
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;
6650 const float mean = (1 - gain) * (2 * col - 1);
6658 unsigned int wideStep(
unsigned int bits);
6659 KLANG_OSM_INLINE
void set(
param hz) {
6660 if (frequency != hz || sampleRate !=
fs.f) {
6662 if (sampleRate !=
fs.f) {
6664 stepScale = sampleRate > 0 ? turn / sampleRate : 0;
6666 const float magnitude = std::fabs(hz.
value);
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;
6674 std::memcpy(&ticks, &hz.
value,
sizeof(ticks));
6675 ticks = wideStep(ticks);
6678 const bool negative = hz < 0 && (ticks != 0 || gain != 1);
6680 if (reverse != negative) {
6682 offset.position =
static_cast<unsigned int>(breakpoint) - offset.position;
6683 if (waveform == &StateMachine::saw) {
6684 amplitude = -amplitude;
6693 KLANG_OSM_INLINE
void set(
param hz,
param phase) {
6696 if (reverse) offset.position =
static_cast<unsigned int>(breakpoint) - offset.position;
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));
6711 KLANG_OSM_INLINE
void setBreakpoint(
unsigned long long ticks,
float remainder = 0) {
6712 if (reverse) offset.position +=
static_cast<unsigned int>(ticks - breakpoint);
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;
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;
6728 KLANG_OSM_INLINE
void reset() {
6729 offset = phaseOffset;
6730 if (reverse) offset.position =
static_cast<unsigned int>(breakpoint) - offset.position;
6733 KLANG_OSM_INLINE State tick() {
6734 state = State(((state << 1) | (offset.position < threshold)) & 3);
6736 const bool carry = (offset.position <
static_cast<unsigned int>(
increment.
amount));
6737 const State transition = State(state | (carry ? 4 : 0));
6741 KLANG_OSM_INLINE
float output() {
return (this->*waveform)(); }
6743 KLANG_OSM_INLINE
float saw() {
6744 const unsigned int end = offset.position;
6747 return float(end) * upSlope + upBias;
6749 return (
float(0xffffffffu - end) + 1.f) * downSlope + downBias;
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);
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);
6762 const unsigned int forwardEnd = end;
6763 return -(1 - f) * inverseStep * rising * (2 * (
float(forwardEnd) * tickScale + phaseFraction) - f + fallingWidth);
6766 const unsigned int forwardEnd = end;
6767 return (1 - f) * inverseStep * falling * (2 * (float(forwardEnd) * tickScale + phaseFraction) - f - col);
6773 KLANG_OSM_INLINE
float pulse() {
6774 const unsigned int end = offset.position;
6781 return high - 2 * inverseStep * ((float(end -
static_cast<unsigned int>(breakpoint)) * tickScale - peakFraction));
6783 return 2 * inverseStep * ((float(end) * tickScale + phaseFraction)) + low;
6785 return high - 2 * inverseStep * fallingWidth;
6787 return 2 * inverseStep * col + low;
6797 #pragma float_control(precise, on, push)
6798 #if defined(_MSC_VER)
6799 __declspec(noinline)
6800 #elif defined(__GNUC__)
6801 __attribute__((noinline))
6803 inline unsigned int StateMachine::wideStep(
unsigned int bits) {
6804 if ((bits & 0x7f800000u) == 0x7f800000u || sampleRate <= 0) {
6805 f = inverseStep = 0;
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);
6822 #pragma float_control(pop)
6826 KLANG_OSM_INLINE Osm(StateMachine::Waveform waveform,
float duty = 0.f) : _Duty(duty), osm(waveform) {
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;
6837 KLANG_OSM_INLINE
void set(
param hz,
param phase)
override {
6838 Oscillator::frequency = hz;
6839 Oscillator::position = phase;
6840 Oscillator::offset = 0;
6843 KLANG_OSM_INLINE
void set(
param hz,
param phase,
param duty)
override {
6847 KLANG_OSM_INLINE
void set(
param hz,
relative phase)
override {
6851 KLANG_OSM_INLINE
void set(
relative phase)
override {
6852 Oscillator::offset = phase * Fast::twoPi;
6853 osm.setOffset(Oscillator::offset);
6855 KLANG_OSM_INLINE
void setDuty(
param duty) { osm.setDuty(duty); }
6856 KLANG_OSM_INLINE
void reset()
override {
6857 Oscillator::position = 0;
6860 KLANG_OSM_INLINE
void process()
override { out = osm.output(); }
6869 KLANG_OSM_INLINE
Saw() : Osm(&StateMachine::saw, 0.f) {}
6870 KLANG_OSM_INLINE
void process()
override { out = osm.saw(); }
6874 KLANG_OSM_INLINE
Triangle() : Osm(&StateMachine::saw, 0.5f) {}
6875 KLANG_OSM_INLINE
void process()
override { out = osm.saw(); }
6879 KLANG_OSM_INLINE
Square() : Osm(&StateMachine::pulse, 0.5f) {}
6880 KLANG_OSM_INLINE
void process()
override { out = osm.pulse(); }
6884 KLANG_OSM_INLINE
Pulse() : Osm(&StateMachine::pulse, 0.5f) {}
6885 KLANG_OSM_INLINE
void process()
override { out = osm.pulse(); }
6888#undef KLANG_OSM_INLINE
6892 namespace PolyBLEP {
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))
6901#define KLANG_BLEP_INLINE inline
6902#define KLANG_BLEP_COLD
6905 template<
bool PULSE>
6908 using Oscillator::set;
6910 KLANG_BLEP_INLINE
explicit Polynomial(
float duty) : _Duty(duty) {
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;
6919 if (sampleRate !=
fs.f) {
6921 ticksPerHz = finite(bits(sampleRate)) && sampleRate > 0 ? turn / sampleRate : 0;
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;
6932 gain = audible ? std::clamp((.5f -
float(width) * tickScale) * 20.f, 0.f, 1.f)
6933 : ticksPerHz > 0 ? 0.f : 1.f;
6936 KLANG_BLEP_INLINE
void set(
param hz,
param phase)
override {
6938 Oscillator::position = phase;
6939 Oscillator::offset = 0;
6941 offset.position = 0;
6944 KLANG_BLEP_INLINE
void set(
param hz,
param phase,
param duty)
override {
6949 KLANG_BLEP_INLINE
void set(
param hz,
relative phase)
override {
6954 KLANG_BLEP_INLINE
void set(
relative phase)
override {
6955 Oscillator::offset = phase * Fast::twoPi;
6956 offset = Oscillator::offset;
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;
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;
6975 KLANG_BLEP_INLINE
void reset()
override {
6976 Oscillator::position = 0;
6977 position.position = 0;
6980 KLANG_BLEP_INLINE
void process()
override {
6981 const unsigned int phase = position.position + offset.position;
6983 const float mean = PULSE ? 2 * dutyCycle - 1 : 0;
6989 if (narrowDuty) wave = integrate(phase);
6990 else if constexpr (PULSE) {
6991 wave = (phase < breakpoint ? 1.f : low) + step(phase) - step(phase - breakpoint);
6993 else if (!breakpoint) {
6994 const float saw = 1.f - 2 * (float(phase) * tickScale) + step(phase);
6995 wave = dutyCycle == 0 ? saw : -saw;
6998 wave = phase < breakpoint
6999 ? float(phase) * tickScale * rising - 1
7000 : float(0u - phase) * tickScale * falling - 1;
7002 wave += (rising + falling) * (
float(width) * (tickScale / 6))
7003 * (corner(phase) - corner(phase - breakpoint));
7005 out = gain == 1 ? wave : mean + gain * (wave - mean);
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;
7016 bool narrowDuty =
false;
7018 static KLANG_BLEP_INLINE
unsigned int bits(
float value) {
7019 unsigned int result;
7020 std::memcpy(&result, &value,
sizeof(result));
7024 static KLANG_BLEP_INLINE
bool finite(
unsigned int bits) {
7025 return (bits & 0x7f800000u) != 0x7f800000u;
7028 static KLANG_BLEP_INLINE std::int32_t signedDistance(
unsigned int distance) {
7029 std::int32_t result;
7030 std::memcpy(&result, &distance,
sizeof(result));
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;
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;
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;
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);
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));
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);
7077 segment(start, duty, -1, 1);
7078 segment(start + duty, 1 - duty, 1, -1);
7087 struct Saw :
public Polynomial<false> {
7088 KLANG_BLEP_INLINE
Saw() : Polynomial(0.f) {}
7098 KLANG_BLEP_INLINE
Square() : Polynomial(.5f) {}
7102 struct Pulse :
public Polynomial<true> {
7103 KLANG_BLEP_INLINE
Pulse() : Polynomial(.5f) {}
7106#undef KLANG_BLEP_COLD
7107#undef KLANG_BLEP_INLINE
7112 namespace Wavetables {
7127 enum class Response { LowPass, HighPass, BandPass, BandReject };
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;
7138 void set(
param edge)
override {
7139 if constexpr (!band) configure(edge, 0, defaultRipple);
7143 void set(
param first,
param second)
override {
7144 if constexpr (band) configure(first, second, defaultRipple);
7145 else configure(first, 0, second);
7150 if constexpr (band) configure(lower, upper, ripple);
7154 for (
auto& section : sections) section.z1 = section.z2 = 0;
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;
7170 using Complex = std::complex<double>;
7173 double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0;
7174 double z1 = 0, z2 = 0;
7177 Section sections[count];
7178 float lowerHz = 0, upperHz = 0, rippleDb = 0, sampleRate = 0;
7180 static bool finite(
float value) {
7182 std::memcpy(&bits, &value,
sizeof(bits));
7183 return (bits & 0x7f800000u) != 0x7f800000u;
7186 static Complex digital(Complex value) {
return (1.0 + value) / (1.0 - value); }
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 };
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() };
7199 void configure(
float lower,
float upper,
float ripple) {
7200 const float rate =
fs;
7201 if (lower == lowerHz && upper == upperHz && ripple == rippleDb && rate == sampleRate)
7203 if (!finite(lower) || !finite(upper) || !finite(ripple) || !finite(rate)
7204 || lower <= 0 || lower >= rate * .5f
7205 || (band && (upper <= lower || upper >= rate * .5f)))
7207 if constexpr (FAMILY != 0)
7208 if (ripple <= 0 || ripple > 120)
return;
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;
7222 const double edge = std::tan(
pi.
d * lower / rate);
7223 const Complex prototypeZero(0,
root2.
d);
7224 Section next[count];
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;
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);
7252 next[i] = coefficients(p, other, z, second);
7254 if (!reject) point = digital(Complex(0, center));
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;
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];
7299 out = in - z + r * out;
7309 float a[ORDER] = { };
7310 float y[ORDER] = { };
7312 template <
typename... Coeffs>
7314 static_assert(
sizeof...(coeffs) == ORDER,
"Incorrect number of coefficients.");
7320 for (
size_t i = 0; i < ORDER; ++i)
7323 for (
size_t i = ORDER - 1; i > 0; --i)
7330 template <
size_t index,
typename First,
typename... Rest>
7331 void _set(First first, Rest... rest) {
7333 if constexpr (index + 1 < ORDER)
7334 _set<index + 1>(rest...);
7351 out = in * a + out * b;
7356 float omega = 2.0f *
pi.
f * f /
fs.f;
7357 float cos_w = cosf(omega);
7358 float sin_w = sinf(omega);
7360 return atan2(b * sin_w, 1.f - b * cos_w) / (2.0f *
pi.
f * f);
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);
7381 float a1 = 0, b0 = 1, b1 = 0;
7396 if (Filter::f != f) {
7405 out = b0 * in + b1 * z + a1 * out + DENORMALISE;
7415 const float exp0 = expf(-f *
fs.w);
7421 out = b0 * in + a1 * out + DENORMALISE;
7426 float omega = 2.0f *
pi.
f * f /
fs.f;
7427 float cos_w = cosf(omega);
7428 float sin_w = sinf(omega);
7430 float real = b0 - a1 * cos_w;
7431 float imag = -a1 * sin_w;
7433 float phaseRadians = atan2f(imag, real);
7434 return phaseRadians / (2.0f *
pi.
f * f);
7443 const float exp0 = expf(-f *
fs.w);
7444 b0 = 0.5f * (1.f + exp0);
7462 float a1 = 0, a2 = 0, b0 = 1, b1 = 0, b2 = 0;
7474 a1 = a2 = b1 = b2 = 0;
7485 this->set(f,
param(f / bw));
7493 if (Filter::f != f || Filter::Q != Q) {
7497 const float w = f *
fs.w;
7501 if (Q < 0.5) Q = 0.5;
7502 a = sin0 / (2.f * Q);
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;
7522 float omega = 2.0f *
pi.
f * f /
fs.f;
7523 float cos_w = std::cos(omega);
7524 float sin_w = std::sin(omega);
7526 float real = b0 + b1 * cos_w + b2 * cos(2 * omega);
7527 float imag = b1 * sin_w + b2 * sin(2 * omega);
7528 float phaseRadians = std::atan2(-imag, real);
7530 real = 1 + (a1 * cos_w + a2 * cos(2 * omega));
7531 imag = (a1 * sin_w + a2 * sin(2 * omega));
7533 phaseRadians -= std::atan2(-imag, real);
7534 return phaseRadians / (2.0f *
pi.
f * f);
7540 float omega = 2.0f *
pi.
f * f /
fs.f;
7541 float cos_w = std::cos(omega);
7542 float sin_w = std::sin(omega);
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));
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);
7555 return (R * dI_dOmega - I * dR_dOmega) / (R * R + I * I);
7565 a1 = a0.
inv * (-2.f * cos0);
7566 a2 = a0.
inv * (1.f - a);
7568 b2 = b0 = a0.
inv * (1.f - cos0) * 0.5f;
7569 b1 = a0.
inv * (1.f - cos0);
7582 a1 = a0.
inv * (-2.f * cos0);
7583 a2 = a0.
inv * (1.f - a);
7585 b2 = b0 = a0.
inv * (1.f + cos0) * 0.5f;
7586 b1 = a0.
inv * -(1.f + cos0);
7603 init_gain = gain == ConstantSkirtGain ? &BPF::init_skirt : &BPF::init_peak;
7610 void init() { (this->*init_gain)(); }
7616 a1 = a0.
inv * (-2.f * cos0);
7617 a2 = a0.
inv * (1.f - a);
7619 b0 = a0.
inv * sin0 * 0.5f;
7628 a1 = a0.
inv * (-2.f * cos0);
7629 a2 = a0.
inv * (1.f - a);
7641 b1 = a1 = a0.
inv * (-2.f * cos0);
7642 a2 = a0.
inv * (1.f - a);
7658 if (Filter::f != f || a != r) {
7662 const float w = f *
fs.w;
7671 float omega = 2.0f *
pi * f /
fs;
7672 float cos0 = cos(omega);
7675 b1 = a1 = (-2.f * a * cos0);
7683 namespace Butterworth {
7695 const float c = 1.f / tanf(
pi * f *
fs.inv);
7698 a1 = (1.f - c) * a0.
inv;
7701 out = b0 * (in + z) - a1 * out;
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);
7720 struct HPF : detail::PrototypeFilter<0, ORDER, detail::Response::HighPass> {};
7724 struct BPF : detail::PrototypeFilter<0, ORDER, detail::Response::BandPass> {};
7728 struct BRF : detail::PrototypeFilter<0, ORDER, detail::Response::BandReject> {};
7734 static_assert(TYPE == 1 || TYPE == 2,
"Chebyshev type must be 1 or 2");
7737 struct LPF : detail::PrototypeFilter<TYPE, 2, detail::Response::LowPass> {};
7740 struct HPF : detail::PrototypeFilter<TYPE, 2, detail::Response::HighPass> {};
7743 struct BPF : detail::PrototypeFilter<TYPE, 2, detail::Response::BandPass> {};
7746 struct BRF : detail::PrototypeFilter<TYPE, 2, detail::Response::BandReject> {};
7751 namespace Modifiers {
7754 float a1 = 0, a2 = 0;
7755 float y1 = 0, y2 = 0;
7762 this->gain = std::clamp(gain.
value * 0.05f, -0.05f, 0.05f);
7768 constexpr float min_d = 1e-6f;
7769 constexpr float max_d = 0.9999f;
7771 const float w = f.value *
fs.w;
7772 const float d = std::clamp(std::exp(-
pi / (decay *
fs)), min_d, max_d);
7774 a1 = 2.f * d * std::clamp(std::cos(w), -0.9999f, 0.9999f);
7788 out = in + a1 * y1 + a2 * y2;
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)));
7816 const float smoothing = in > out ? A : R;
7817 (out + smoothing * (in - out)) >> out;
7824 ar.set(attack, release);
7828 _process = (mode ==
RMS) ? &Follower::rms : &Follower::peak;
7837 void peak() { abs(in) >> ar >> out; }
7838 void rms() { (in * in) >> ar >> sqrt >> out; }
7841 template<
int WINDOW>
7854 ar.
set(attack, release);
7858 _process = (mode ==
RMS) ? &Window::rms : &Window::mean;
7873 sum* window.
inv >> ar >> out;
7881 signal(sum * window.
inv) >> sqrt >> ar >> out;
7887#if defined(_MSC_VER) && !defined(__clang__)
7888#define packed __pragma(pack(push,1)) struct __pragma(pack(pop))
7890#define packed struct __attribute__((packed))
7893 unsigned int channels = 0;
7894 unsigned int samplerate = 0;
7895 unsigned int bitrate = 0;
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;
7906 bool operator==(
const char*
const id)
const {
7907 return memcmp(ID::id,
id, 4) == 0;
7910 unsigned int size = 0;
7913 Chunk(ID
id,
unsigned int size = 0) : id(id), size(size) {}
7920 Header(ID
id, ID format,
unsigned int size = 0) : Chunk(id, size), format(format) {}
7922 bool isWAV()
const {
return id ==
"RIFF" && format ==
"WAVE"; }
7923 bool isAIFF()
const {
return id ==
"FORM" && format ==
"AIFF"; }
7929 packed Header : File::Header {
7930 Header() :
File::Header(
"RIFF",
"WAVE") {}
7931 } *header =
nullptr;
7934 unsigned short AudioFormat;
7944 } *format =
nullptr;
7947 unsigned char data[1] = { 0 };
7960 WAV::memory = &memory;
7970 header = (Header*)memory.
ptr;
7971 if (!header->isWAV())
7973 memory.
skip(
sizeof(Header));
7977 const Chunk chunk = memory;
7978 memory.
rewind(
sizeof(Chunk));
7979 if (chunk.id ==
"fmt ")
7981 else if (chunk.id ==
"data") {
7982 if (memory.
ptr + chunk.size > memory.
end)
7984 data = (Data*)memory.
ptr;
7986 memory.
skip(
sizeof(Chunk) + chunk.size);
7991 template<
typename TYPE,
int STEP = 1>
7993 if constexpr (std::is_floating_point<TYPE>::value) {
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;
8003 *
buffer++ =
static_cast<float>(*data) * scale;
8007 constexpr float scale = 1.f / ((twoComp << 1) - 1);
8009 *
buffer++ = (
static_cast<float>(*data) - twoComp) * scale;
8017 if (!header || !format || !data)
8020 buffer.resize(data->size / format->BlockAlign);
8021 if (format->AudioFormat == 1) {
8022 if (format->BitsPerSample == 8)
8024 else if(format->BitsPerSample == 16)
8026 else if(format->BitsPerSample == 32)
8028 }
else if (format->AudioFormat == 3) {
8029 if(format->BitsPerSample == 32)
8072 using namespace klang;
8074 using namespace Generators::Basic;
8075 using namespace Modifiers;
8076 using namespace Filters;
8077 using namespace Filters::Biquad;
8080 namespace optimised {
8081 using namespace klang;
8083 using namespace Generators::Fast;
8084 using namespace Generators::OSM;
8085 using namespace Modifiers;
8086 using namespace Filters;
8087 using namespace Filters::Biquad;
8091 using namespace klang;
8097#if defined(KLANG_WARNING_SCOPE)
8099#undef KLANG_WARNING_SCOPE
std::shared_ptr< Ramp > ramp
std::vector< Point > points
Base class for synthesiser notes.
enum klang::NoteBase::Stage stage
virtual event on(Pitch p, Velocity v)
virtual bool stop(Velocity v=0)
void attach(SYNTH *synth)
virtual void controlChange(int controller, int value)
virtual void start(Pitch p, Velocity v)
virtual event off(Velocity v=0)
virtual bool release(Velocity v=0)
Wavetable-based oscillator.
constexpr unsigned int capacity(unsigned int n)
signal operator[](float offset)
signal & operator*=(const signal &in)
signal & operator[](int offset)
buffer(float *buffer, int size)
const signal & operator[](int index) const
buffer(const buffer &buf)
buffer & operator=(const buffer &in)
signal & operator=(const signal &in)
signal & operator[](unsigned int offset)
signal operator[](float offset) const
signal & operator+=(const signal &in)
buffer & operator<<(const signal &in)
buffer(int size=1, float initial=0)
void rewind(int offset=0)
const float * data() const
void attach(const buffer &buffer, int size=0)
buffer(float *buffer, int size, float initial)
const signal & operator[](int index) const
buffer & operator<<(const signal &value)
signal & operator[](int index)
signal operator[](float offset)
signal & operator+=(const signal &value)
buffer(const buffer &other)
buffer(int size=1, float initial=0)
void rewind(int offset=0)
signal & operator*=(const signal &value)
buffer(float *samples, int size)
buffer & operator=(const buffer &other)
signal & operator=(const signal &value)
const float * data() const
buffer(float *samples, int size, float initial)
signals< CHANNELS > signal
signal operator[](float offset) const
signal operator[](float offset)
const float * data() const
buffer(int size=1, float initial=0.f)
buffer(const klang::buffer &buffer)
signal operator[](float offset) const
void rewind(int offset=0)
signal & operator[](int offset)
const signal & operator[](int index) const
variable::buffer & operator=(const klang::buffer &in)
variable::buffer & operator=(const variable::buffer &in)
signal & operator[](unsigned int offset)
Chebyshev filters selected by type, with a second-order low-pass prototype.
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
SIGNAL operator+(float other, Output< SIGNAL > &output)
std::decay_t< decltype(std::declval< OBJECT & >().out)> OutputSignal
SIGNAL operator*(float other, Output< SIGNAL > &output)
Function() -> Function< signal, Args... >
SIGNAL operator/(float other, Output< SIGNAL > &output)
SIGNAL operator-(float other, Output< SIGNAL > &output)
float cosp(unsigned int phase)
Approximate cosine from an unsigned 32-bit phase covering one turn.
float sinp(unsigned int phase)
Approximate sine from an unsigned 32-bit phase covering one turn.
float cos(float x)
Approximate cosine of a finite angle in radians.
static TYPE random(const TYPE min, const TYPE max)
Generates a random number between min and max. Use an integer types for whole numbers.
float fast_mod(float x, float y)
static Control Toggle(const char *name, bool initial=false, Control::Size size=Automatic)
static THREAD_LOCAL GraphPtr graph
float fast_mod2pi(float x)
static Control PitchBend(Control::Size size=Automatic)
constexpr constant ln2
The natural logorithm of 2 (and it's inverse).
constexpr constant pi
The mathematical constant, pi (and it's inverse).
const Control::Options NoOptions
signals< CHANNELS > operator/(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel divided into x.
Mode
Klang mode identifiers (e.g. averages, level following)
double fast_modi(double x)
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)
static Control Dial(const char *name, float min=0.f, float max=1.f, float initial=0.f, Control::Size size=Automatic)
float truncate(float input)
Alias for trunc, including signal-flow use.
signal & operator>>(TYPE input, signal &destination)
Stream a built-in arithmetic value into a signal, narrowing at the signal boundary.
typename std::conditional_t< std::is_integral_v< BASE >, float, BASE > power_t
float(float) UnaryFunction
A stateless unary C/C++ function that maps one float sample to another.
static Control Button(const char *name, Control::Size size=Automatic)
static Control Menu(const char *name, const Options... options)
constexpr bool is_literal
constexpr bool are_scalars(Head &&head, Tail &&... tail)
signals< CHANNELS > operator-(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel subtracted from x.
const Control::Size Automatic
static Control ModWheel(Control::Size size=Automatic)
signals< CHANNELS > operator*(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel scaled by x.
float fast_modp(unsigned int x)
Array< float, 128 > Values
constexpr BASE poweri(BASE base)
auto mod(LEFT left, RIGHT right)
Return the C++ remainder for integers and the floating-point remainder otherwise.
signals< CHANNELS > operator+(float x, const signals< CHANNELS > &y)
Return a copy of the signal with each channel offset by x.
constexpr power_t< BASE, EXP > power(BASE base, EXP exp)
Raise base to the power exp.
constexpr constant root2
The square root of 2 (and it's inverse).
Text< 32 > Caption
A short Text object used to label controls.
void event
A function that handles an event.
static Control Slider(const char *name, float min=0.f, float max=1.f, float initial=0.f, Control::Size size=Automatic)
constexpr bool is_derived_from()
Attack-Decay-Sustain-Release Envelope.
bool operator==(Envelope::Stage stage) const
void release(float time=0.f, float level=0.f) override
void set(param attack, param decay, param sustain, param release) override
Control parameter (linear amplitude)
static THREAD_LOCAL Conversion dB
const Amplitude * operator->() const
Variable-sized array, pre-allocated to a max. capacity.
unsigned int size() const
The current number of items in the array.
Array(std::initializer_list< TYPE > init_list)
Construct an array given the specified values.
float max() const
Find the maximum value in the array.
Array()=default
Construct an empty array.
void add(const TYPE &item)
Add the specified item to the end of the array.
float mean() const
Find the mean average of values in the array.
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;.
float rms() const
Find the root mean squared (RMS) average of values in the array.
void clear()
Clear the array contents. Only resets the item count, without wiping memory.
const TYPE & operator[](int index) const
Returns a read-only reference to the array item at the given index.
static int capacity()
The maximum capacity of the array.
TYPE * add()
Add a blank item to the end of the array, returning a pointer that allows the item to be modified.
TYPE & operator[](int index)
Returns a reference to the array item at the given index.
A parallel bank of multiple audio objects.
signal sum() const
Return the sum of the cached parallel outputs.
TYPE & operator[](int index)
const TYPE & operator[](int index) const
signal & operator>>(signal &destination)
Process every item once and route their summed output to mono.
signal mono() const
Return the Bank's default mono reduction: the sum of its parallel outputs.
bool contains(unsigned int c) const
Size(int x=-1, int y=-1, int width=-1, int height=-1)
Construction-time entry: temporary controls are owned; mutable lvalues are borrowed.
ControlEntry(Control &&control)
enum klang::ControlEntry::Kind kind
ControlEntry(Controls &controls)
ControlEntry(Control &control)
ControlEntry(const Control &control)
ControlEntry(Controls &&)=delete
float normalise(float value) const
float operator+(TYPE &x) const
signal operator*(const Control &x) const
Array< Caption, 128 > Options
Control & operator=(TYPE input)
Control & operator*=(float x)
Control & operator=(TYPE &&input)
Control & operator-=(float x)
void setNormalised(float norm)
float operator*(TYPE &x) const
Control & operator<<(const signal &input)
Control & operator+=(float x)
float operator/(TYPE &x) const
signal operator-(const Control &x) const
signal operator+(const Control &x) const
float operator-(TYPE &x) const
Control & operator<<(TYPE input)
Control & operator/=(float x)
signal operator/(const Control &x) const
ControlMap(Control &control)
ControlMap & operator=(TYPE input)
Control & operator<<(const signal &input)
ControlMap & operator=(TYPE &&input)
Control & operator<<(TYPE input)
ControlMap & operator=(Control &mapped)
Base class for UI / MIDI controll.
virtual void onMIDI(int status, int byte1, int byte2)
virtual void onPreset(int index)
virtual void onControl(int index, float value)
virtual event midi(int status, int byte1, int byte2)
virtual event control(int index, float value)
virtual event preset(int index)
Controls(const Controls &other)
int scopeSize(int index) const
void bindAlias(int index, int canonicalIndex)
Reconstruct an earlier canonical slot when a proxy flattens aliases.
bool isInput(int index) const
const Control * snapshot()
Refresh only the legacy contiguous metadata/value snapshot before raw ABI export.
bool hasReferences() const
void operator+=(const Control &control)
int scopeStart(int index) const
void group(const char *name, unsigned int start, unsigned int length, Control::Size size=Automatic)
void operator+=(Controls &controls)
Array< Control::Group, 10 > groups
Control & operator[](int index)
Resolve one actual control; ordinary owned collections take the direct path.
const char * scope(int index) const
Controls & operator=(Source &&source) &
Controls & operator=(const Controls &) &&=delete
void normalise(float target=1, int mode=Peak)
bool inGroup(int index) const
Controls & operator=(std::initializer_list< klang::Group > declaration)
const Control * snapshot() const
Controls(Controls &&other)
const char * key(int index) const
Stable declaration key for metadata/retention; never a pointer or a default value.
void add(const Control &control)
void markInput(int index, bool state=true)
void add(const char *name, Control::Type type, std::initializer_list< const char * > options, Control::Size size=Automatic)
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)
const Control & operator[](int index) const
const Control::Group * getGroup(int index) const
void operator+=(Control &control)
void operator+=(Control &&control)
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.
static THREAD_LOCAL Buffer buffer
Audio delay object (fixed size)
Effect mini-plugin (mono)
virtual void process(buffer buffer)
Attack / Release IIR Filter (~Butterworth when attack == release)
void set(param attack, param release)
Window-based envelope follower.
Window & operator=(klang::Mode mode)
void set(param attack, param release)
void(Window::*)() Process
Envelope follower (Peak / RMS)
void set(param attack, param release)
Follower & operator=(klang::Mode mode)
void(Follower::*)() Process
Chunk(ID id, unsigned int size=0)
unsigned short NumChannels
unsigned short BlockAlign
bool load(Memory &memory)
bool load(const char *path)
static void decode(float *buffer, const TYPE *data, int length)
bool operator>>(variable::buffer &buffer)
Header(ID id, ID format, unsigned int size=0)
unsigned short BitsPerSample
void set(param f, param r)
Set the pole frequency and radius (r)
void set(param f)
Set the filter cutoff (default r)
BPF & operator=(Gain gain)
Set the constant gain mode.
@ ConstantSkirtGain
Constant Skirt Gain.
void process() noexcept
Apply the biquad filter (Transposed Direct Form II)
void set(param f, relative bw)
Set the filter cutoff and bandwidth.
float phase(float f) const
Return the phase offset for the specified frequency (in seconds)
void set(param f, param Q)
Set the filter cutoff and Q.
float delay(float f) const
Return the group delay for the specified frequency (in samples)
void reset()
Reset filter state.
void set(param f)
Set the filter cutoff (default Q)
Band-pass Butterworth filter for prototype order 1 or 2.
Band-reject Butterworth filter for prototype order 1 or 2.
High-pass Butterworth filter for prototype order 1 or 2.
Band-pass Chebyshev response.
Band-reject Chebyshev response.
High-pass Chebyshev response.
Low-pass Chebyshev response.
Simple DC filter / blocker.
void set(param r) override
float phase(float f) const
Compute the phase offset in seconds at a given frequency.
float delay(float f) const
Compute the group delay in samples at a given frequency.
IIR filter for specified order.
void set(Coeffs... coeffs)
void _set(First first, Rest... rest)
float phase(float f) const
Compute the phase delay in seconds at a given frequency.
Control parameter (frequency)
static THREAD_LOCAL Conversion Pitch
const Frequency * operator->() const
Convert a positive frequency in Hz to MIDI pitch.
Frequency(float f=1000.f)
Applies a function to a signal (input-output)
Function(std::function< float(Args...)> function)
Signal generator object (mono)
Aliased 0-to-1 ramp; frequency in Hz, absolute phase in radians, like Basic::Saw.
Pulse wave oscillator (aliased)
void set(param frequency, param phase, param duty)
Saw wave oscillator (aliased)
Square wave oscillator (aliased)
Triangle wave oscillator (aliased)
White noise generator (optimised)
Aliased 0-to-1 ramp using an integer wrapping phase.
void set(param frequency) override
void set(param frequency, relative phase) override
Fast::Increment increment
void set(param frequency, param phase) override
void set(relative phase) override
Sine wave oscillator (band-limited, optimised)
Fast::Increment increment
void set(relative phase) override
void set(param frequency, param phase) override
void set(param frequency) override
void set(param frequency, relative phase) override
Pulse wave with adjustable duty cycle.
KLANG_OSM_INLINE void process() override
KLANG_OSM_INLINE void process() override
Square wave with 50% high duty.
KLANG_OSM_INLINE Square()
KLANG_OSM_INLINE void process() override
Triangle wave with equal rising and falling half-cycles.
KLANG_OSM_INLINE Triangle()
KLANG_OSM_INLINE void process() override
Pulse with adjustable duty and polynomial edge correction.
KLANG_BLEP_INLINE Pulse()
Descending saw with polynomial correction at the wrap.
Square wave with 50% high duty and polynomial edge correction.
KLANG_BLEP_INLINE Square()
Triangle with polynomial correction at the slope changes.
KLANG_BLEP_INLINE Triangle()
Saw wave oscillator (wavetable)
Sine wave oscillator (wavetable)
Applies a function to a signal (input-output)
Function< SIGNAL, Args... > & operator()(const FuncArgs &... args)
klang::GraphPtr & operator>>(klang::GraphPtr &graph)
virtual void process() override
unsigned int args() const
Function(FunctionPtr function)
const First & first(const First &first, Rest...) const
std::tuple< Args... > inputs
const float operator()(const FuncArgs &... args) const
static constexpr unsigned int ARGS
klang::Graph & operator>>(klang::Graph &graph)
Function< SIGNAL, Args... > & with(FuncArgs... args)
std::function< float(Args...)> function
First & first(First &first, Rest...)
Function(FunctionPtr function, OtherArgs... args)
std::tuple< Rest... > tail(const std::tuple< First, Rest... > &t) const
Signal generator object (output only)
Output< SIGNAL > & operator()(params &&... p)
bool contains(const Point &pt) const
void from(const Series &series, double Point::*axis)
bool contains(double value) const
Series * find(void *function)
Series & operator>>(Series &series)
void plot(const Generic::Function< SIGNAL, Args... > &f, const Axis &x_axis)
bool operator==(const Series &in) const
bool operator!=(const Series &in) const
void plot(RETURN(*f)(ARG), const Axis &x_axis)
void setDirty(bool dirty)
Graph & operator=(TYPE(*function)(TYPE))
Plot the given function of x.
Graph & operator+=(TYPE y)
Add a data point (incrementing x)
Graph & operator()(double min, double max)
Graph & operator<<(const TYPE &in)
void truncate(unsigned int count)
Graph & operator=(std::initializer_list< Point > values)
Plot the given data points.
void add(const Point pt)
Add a data point.
Graph & operator<<(TYPE &in)
void plot(FUNCTION f, VALUES... values)
Plot the given function for x plus additional arguments.
Graph::Series & operator[](int index)
const Graph::Series & operator[](int index) const
void getAxes(Axes &axes) const
Graph & operator<<(Function< Args... > &function)
Plot the given function for x plus additional arguments.
void plot(Generic::Function< SIGNAL, Args... > &function)
Plot the given Function.
const Data & getData() const
Graph & operator+=(const Point pt)
Add a data point.
const Axes & getAxes() const
Graph & operator+=(std::initializer_list< Point > values)
Plot the given data points.
void add(TYPE y)
Add a data point (incrementing x)
void plot(TYPE(*function)(TYPE))
Plot the given function of x.
Graph & operator()(double x_min, double x_max, double y_min, double y_max)
Signal modifier object (input-output)
Modifier< SIGNAL > & operator()(params &&... p)
virtual void process() override
Audio oscillator object (output)
virtual void set(param frequency, relative phase)
virtual void set(param frequency)
virtual void set(relative phase)
virtual void set(param frequency, param phase)
SIGNAL operator+(TYPE &other)
SIGNAL operator/(TYPE &other)
virtual const SIGNAL & output() const
SIGNAL operator*(TYPE &other)
SIGNAL operator-(TYPE &other)
Graph & operator<<(Function< Args... > &function)
Plot the given function for x plus additional arguments.
Optional presentation grouping, independent of value ownership.
Group(const char *name, std::initializer_list< ControlEntry > controls)
std::vector< ControlEntry > controls
Group(const char *name, Entries &&... entries)
Group(Entries &&... entries)
Group(const char *name, Control::Size size, std::initializer_list< ControlEntry > controls)
Group(Control::Size size, Entries &&... entries)
Group(const char *name, Control::Size size, List &&list)
Group(const char *name, List &&list)
Group(const char *name, Control::Size size, Entries &&... entries)
float operator()(int col, int row) const
const float * operator[](int col) const
float * operator[](int col)
float & operator()(int col, int row)
void attach(unsigned char *data, size_t size, bool own=false)
Memory & operator+=(const Memory &memory)
Memory & operator=(const Memory &memory)
bool load(const char *path)
bool operator==(const TYPE &value) const
Memory & operator=(Memory *memory)
bool add(const TYPE &value)
Memory & operator+=(const TYPE &value)
Signal modifier object (mono input-output)
void set(param f, param decay)
void set(param f, param decay, param gain)
virtual bool process(buffer buffer)
virtual void process() override=0
virtual bool process(buffer *buffer)
Array< NOTE *, 128 > Array
Operator & operator*(signal amp)
Operator & operator>>(Operator &carrier)
Operator & operator()(param f, relative phase)
virtual Operator & operator=(const Envelope &points)
virtual Operator & operator=(const Envelope::Points &points)
Operator & operator()(relative phase)
virtual void process() override
Operator & operator()(param f)
Audio oscillator object (mono output)
Audio output object (mono)
Control parameter (phase)
Phase operator+(const increment &step) const
param & operator+=(float step)
Phase operator%(float modulus)
float wrapped(float offset=0) const
Return this phase plus an optional offset, wrapped to one turn.
static float wrap(float phase, float cycle=2 *pi)
Wrap a finite phase to [0, cycle); invalid values become zero.
param & operator+=(const increment &step)
Control parameter (pitch)
const Pitch * operator->()
static THREAD_LOCAL Conversion Frequency
const char * text() const
Base class for mini-plugin.
static DERIVED * Create(ARGS &&... args)
void operator+=(const Preset &preset)
void operator=(const Presets &presets)
void add(const char *name, const Values... values)
void operator=(std::initializer_list< Preset > presets)
float w
angular frequency (omega)
float nyquist
nyquist frequency (f / 2)
int i
sample rate (integer)
float f
sample rate (float)
double d
sample rate (double)
float inv
1 / sample rate (inverse)
Stereo audio object adapter.
Audio delay object (stereo)
signal operator()(const TIME &delay)
signal tap(float delay) const
virtual void process() override
signal tap(int delay) const
Stereo effect mini-plugin.
virtual void process(interleaved::buffer buffer)
Process interleaved host frames; inherited by the current Stereo::Sound.
virtual void process(Stereo::buffer buffer)
Signal generator object (stereo output)
Signal modifier object (stereo, input-output)
virtual void prepare() override
virtual void process() override=0
virtual bool process(Stereo::buffer buffer) override
Base class for stereo synthesiser note.
virtual bool process(Stereo::buffer buffer)
virtual void process() override=0
virtual bool process(mono::buffer *buffers)
Audio oscillator object (stereo, output)
Audio output object (stereo)
Synthesiser note array (stereo)
Synthesier mini-plugin (stereo)
int indexOf(Note *note) const
virtual event onMIDI(int status, int byte1, int byte2) override
virtual event onControl(int index, float value) override
virtual event allNotesOff(float velocity=0.f)
virtual event noteOn(int pitch, float velocity)
virtual event noteOff(int pitch, float velocity)
virtual void process(float **buffers, int length, float *parameters=nullptr)
virtual void process(buffer buffer) override
virtual event onPreset(int index) override
virtual void process() override
virtual bool playing() const
buffer & operator=(const buffer &in)
buffer(mono::buffer &left, mono::buffer &right)
buffer & operator=(const mono::signal in)
buffer & operator*=(const frame &in)
frame operator=(const signal &in)
frame operator[](int index)
buffer & operator=(const frame &in)
buffer & operator+=(const frame &in)
signal operator[](int index) const
buffer(const buffer &buffer)
buffer & operator*=(const mono::signal in)
buffer & operator+=(const mono::signal in)
mono::buffer & channel(int index)
buffer & operator+=(const signal &in)
frame & operator*=(float x)
signal operator*(const mono::signal x) const
frame & operator+=(const mono::signal x)
frame & operator-=(int x)
signal operator*(int x) const
signal operator-(double x) const
frame & operator/=(int x)
signal operator*(const signal x) const
signal operator+(const mono::signal x) const
signal operator+(float x) const
signal operator-(float x) const
frame & operator+=(double x)
frame & operator*=(const signal x)
signal operator-(const mono::signal x) const
signal operator/(double x) const
frame & operator+=(const frame &x)
frame & operator*=(const mono::signal x)
frame & operator*=(int x)
signal operator-(const signal x) const
frame & operator-=(double x)
signal operator-(int x) const
frame & operator/=(const frame &x)
frame & operator-=(const mono::signal x)
frame & operator*=(const frame &x)
frame & operator=(const signal &signal)
frame & operator-=(const frame &x)
signal operator/(int x) const
mono::signal mono() const
frame & operator*=(double x)
signal operator+(int x) const
signal operator/(const mono::signal x) const
frame & operator+=(int x)
signal operator*(double x) const
signal operator+(double x) const
frame & operator/=(const mono::signal x)
frame & operator+=(const signal x)
signal operator+(const signal x) const
frame & operator/=(const signal x)
frame & operator+=(float x)
frame & operator/=(float x)
signal operator*(float x) const
signal operator/(float x) const
frame(mono::signal &left, mono::signal &right)
frame & operator/=(double x)
frame & operator-=(float x)
frame & operator-=(const signal x)
signal operator/(const signal x) const
Synthesiser object (mono)
virtual event allNotesOff(float velocity=0.f)
Notes< Synth, Note > notes
int indexOf(Note *note) const
virtual event onMIDI(int status, int byte1, int byte2) override
virtual event onPreset(int index) override
virtual event noteOff(int pitch, float velocity)
virtual void process() override
virtual void process(buffer buffer) override
virtual bool playing() const
virtual event noteOn(int pitch, float velocity)
virtual void process(float *buffer, int length, float *parameters=nullptr)
virtual event onControl(int index, float value) override
String of characters representing text.
static Text from(const char *in)
Create a new Text object from a C-string.
int capacity() const
Maximum size of the string.
bool operator==(const char *in) const
Returns true if Text matches the given C-string.
char string[SIZE+1]
The character buffer.
const char * c_str() const
Return constant C-string.
bool operator!=(const char *in) const
Returns true if Text does not matches the given C-string.
void operator=(const char *in)
Assign C-String to Text object.
Klang language version (major.minor.build.debug)
bool below(unsigned char M, unsigned char m, unsigned char b) const
bool atLeast(unsigned char M, unsigned char m, unsigned char b) const
Constant scalar (pre-converted to double, float and int).
float operator^(int x) const
const float inv
Inverse of constant.
const double d
Constant as double.
const float f
Constant as float.
float operator^(double x) const
float operator^(float x) const
Constant raised to the power, x.
constexpr constant(double value) noexcept
Create a constant from the given value.
const int i
Constant as integer.
Control parameter (idecibels)
static THREAD_LOCAL Conversion Amplitude
const dB * operator->() const
A phase or wavetable increment.
increment(float amount, const float size=2 *pi)
Create a phase increment (default to radians).
float amount
The current phase.
increment(float amount, double size)
Create a phase increment.
increment & operator=(float in)
Set current phase.
increment(float amount, int size)
Create a phase increment (wavetable size).
const float size
The length of a a full cycle (e.g. 2 pi or wavetable size)
A signal used as a control parameter.
param(const float initial=0.f)
param & operator+=(const increment &increment)
A signal used as an offset relative to another signal.
A mono audio signal (equivalent to a float).
signal & operator*=(const signal &x)
Multiply (modulate) signal by another signal.
signal operator^(int x) const
Return a copy of the signal raised to the power of x.
signal & operator=(Output &in)
Assign processed output of in to signal.
signal(const double initial)
Create signal from a 64-bit double.
relative operator+() const
Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
signal operator*(double x) const
Return a copy of the signal scaled by x.
signal operator^(double x) const
Return a copy of the signal raised to the power of x.
const signal & operator<<(const signal &input)
Feedback operator (prevents further processing of returned value).
signal operator*(float x) const
Multiply (modulate) two signals.
bool isDenormal() const
Check if the signal contains a denormal value.
signal operator^(float x) const
Return a copy of the signal raised to the power of x.
signal & operator-=(float x)
Subtract the specified amount from the signal.
signal & operator/=(double x)
Divide signal by the specified amount.
signal & operator>>(signal &destination) const
Stream operator (feedforward; allows further processing)
signal & operator+=(const signal &x)
Add (mix) another signal to the signal.
signal & operator+=(float x)
Add the specified amount to the signal.
signal operator-(double x) const
Return a copy of the signal offset by -x.
signal & operator-=(double x)
Subtract the specified amount from the signal.
int channels() const
Returns the number of channels (1 = mono).
signal & operator/=(int x)
Divide signal by the specified amount.
signal & operator-=(int x)
Subtract the specified amount from the signal.
signal operator-(float x) const
Subtract one signal from another.
signal operator*(int x) const
Return a copy of the signal scaled by x.
relative relative() const
Returns a copy of the signal to treat as a relative offset (e.g. for phase modulation).
signal & operator+=(double x)
Add the specified amount to the signal.
signal & operator+=(int x)
Add the specified amount to the signal.
signal(const float initial=0.f)
Create signal from a 32-bit float..
signal operator/(int x) const
Return a copy of the signal divided by x.
signal & operator+=(Output &in)
Adds processed output of in to signal.
signal operator+(float x) const
Add two signals together.
signal & operator*=(double x)
Multiply signal by the specified amount.
signal & operator-=(const signal &x)
Subtract another signal from the signal.
signal & operator/=(float x)
Divide signal by the specified amount.
signal operator+(double x) const
Return a copy of the signal offset by x.
signal operator/(float x) const
Divide one signal by another.
signal & operator*=(int x)
Multiply signal by the specified amount.
signal operator-(int x) const
Return a copy of the signal offset by -x.
signal(constant initial)
Create signal from a constant.
signal(const int value)
Create signal from an 32-bit signed integer.
signal operator/(double x) const
Return a copy of the signal divided by.
signal & operator/=(const signal &x)
Divide signal by another signal.
signal operator+(int x) const
Return a copy of the signal offset by x.
signal & operator*=(float x)
Multiply signal by the specified amount.
A multi-channel audio signal (e.g. stereo).
klang::signal sum() const
Return the sum of all channels.
signals operator-(float x) const
Return a copy of the signal with each channel offset by -x.
const signal & operator[](int index) const
Return a read-only reference to the signal at the specified index (0 = left, 1 = right).
signals operator/(double x) const
Return a copy of the signal with each channel divided by x.
signals operator-(const signal x) const
Return a copy of the multi-channel signal, subtracting a mono signal from each channel.
signals operator+(float x) const
Return a copy of the signal with each channel offset by x.
signals(TYPE &initial)
Evaluate a mono Klang object once and broadcast its signal to every channel.
signals(Args... initial)
Create a multi-channel signal with the given channel values.
signals operator*(const signals x) const
Multiply (modulate) two multi-channel signals.
signals(float initial=0.f)
Create a multi-channel signal by broadcasting the given value.
signals operator+(const signals x) const
Add two multi-channel signals together.
signals operator/(const signals x) const
Divide one multi-channel signal by another.
signals operator*(double x) const
Return a copy of the signal with each channel scaled by x.
signals & operator>>(signals &destination) const
Stream operator (feedforward; allows further processing).
signals operator+(double x) const
Return a copy of the signal with each channel offset by x.
signals(const klang::signal &initial)
Create a multi-channel signal by broadcasting the given signal.
signals operator*(const signal x) const
Return a copy of the multi-channel signal, multiplying (modulating) each channel by a mono signal.
signals operator/(float x) const
Return a copy of the signal with each channel divided by x.
signals operator*(float x) const
Return a copy of the signal with each channel scaled by x.
signals(int left, int right)
Create a multi-channel signal with the first two channel values; remaining channels are zero.
signals operator-(int x) const
Return a copy of the signal with each channel offset by -x.
signals & operator+=(const signals x)
Add (mix) another signal to the signal.
signals(double left, double right)
Create a multi-channel signal with the first two channel values; remaining channels are zero.
signals & operator/=(const signals x)
Divide signal by another signal.
signals & operator*=(const signals x)
Multiply (modulate) signal by another signal.
int channels() const
Returns the number of channels in the signal.
signals operator/(int x) const
Return a copy of the signal with each channel divided by x.
signals(float left, float right)
Create a multi-channel signal with the first two channel values; remaining channels are zero.
signals operator-(double x) const
Return a copy of the signal with each channel offset by -x.
klang::signal mono() const
Return the default mono downmix: the arithmetic mean of all channels.
signals operator-(const signals x) const
Subtract one multi-channel signal from another.
signals & operator-=(const signals x)
Subtract another signal from the signal.
signals operator+(const signal x) const
Return a copy of the multi-channel signal, adding a mono signal to each channel.
signals(double initial)
Create a multi-channel signal by broadcasting the given value.
klang::signal average() const
Return the arithmetic mean of all channels.
signals operator/(const signal x) const
Return a copy of the multi-channel signal, dividing each channel by a mono signal.
signals operator+(int x) const
Return a copy of the signal with each channel offset by x.
signals operator*(int x) const
Return a copy of the signal with each channel scaled by x.
const signals & operator<<(const signals &input)
Feedback operator (prevents further processing of returned value).
signals(int initial)
Create a multi-channel signal by broadcasting the given value.
signal & operator[](int index)
Return a reference to the signal at the specified index (0 = left, 1 = right).
signals(Args &... initial)
Create a multi-channel signal with the given channel values.