DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DSParkPlugin.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
62// <windows.h> without NOMINMAX defines function-like min/max macros that
63// break every std::min/std::max and numeric_limits<T>::max() below. Park
64// them for the length of this header and restore them at its end.
65#pragma push_macro("min")
66#pragma push_macro("max")
67#undef min
68#undef max
69
70#include "../Core/AudioSpec.h"
71#include "../Core/AudioBuffer.h"
72#include "../Core/DenormalGuard.h"
73
74#include <algorithm>
75#include <array>
76#include <atomic>
77#include <bit>
78#include <concepts>
79#include <cstdint>
80#include <cstdio>
81#include <cstdlib>
82#include <cstring>
83#include <limits>
84#include <type_traits>
85#include <vector>
86
87namespace dspark::plugin {
88
89// -- Descriptor ---------------------------------------------------------------
90
100enum class Category
101{
102 Fx,
104};
105
115{
116 const char* name = "DSPark Plugin";
117 const char* vendor = "DSPark";
118 const char* url = "";
119 const char* email = "";
120 const char* productId = "com.dspark.plugin";
121 const char* version = "1.0.0";
123};
124
125// -- Parameters ---------------------------------------------------------------
126
135struct Param
136{
137 const char* id = "";
138 const char* name = "";
139 float minValue = 0.0f;
140 float maxValue = 1.0f;
141 float defValue = 0.0f;
142 const char* unit = "";
143 int steps = 0;
144 const char* const* labels = nullptr;
145 bool perVoice = false;
146};
147
149constexpr Param param(const char* id, const char* name,
150 float minValue, float maxValue, float defValue,
151 const char* unit) noexcept
152{
153 return Param { id, name, minValue, maxValue, defValue, unit, 0 };
154}
155
157constexpr Param toggle(const char* id, const char* name, bool defaultOn) noexcept
158{
159 return Param { id, name, 0.0f, 1.0f, defaultOn ? 1.0f : 0.0f, "", 1 };
160}
161
167constexpr Param stepped(const char* id, const char* name,
168 float minValue, float maxValue, float defValue,
169 int steps, const char* unit = "") noexcept
170{
171 return Param { id, name, minValue, maxValue, defValue, unit,
172 steps > 1 ? steps : 1, nullptr };
173}
174
185template <size_t N>
186constexpr Param choice(const char* id, const char* name,
187 const char* const (&labels)[N], int defaultIndex = 0) noexcept
188{
189 static_assert(N >= 2, "a choice needs at least two labels");
190 const int def = defaultIndex < 0 ? 0
191 : (defaultIndex > static_cast<int>(N) - 1 ? static_cast<int>(N) - 1
192 : defaultIndex);
193 return Param { id, name, 0.0f, static_cast<float>(N - 1), static_cast<float>(def),
194 "", static_cast<int>(N - 1), labels };
195}
196
209constexpr Param perVoice(Param p) noexcept
210{
211 p.perVoice = true;
212 return p;
213}
214
216constexpr bool isToggle(const Param& p) noexcept
217{
218 return p.steps == 1 && p.labels == nullptr;
219}
220
222template <typename... Ps>
223constexpr std::array<Param, sizeof...(Ps)> params(Ps... ps) noexcept
224{
225 return { ps... };
226}
227
228// -- Normalisation ------------------------------------------------------------
229
231constexpr double toNormalized(const Param& p, double plain) noexcept
232{
233 const double range = static_cast<double>(p.maxValue) - p.minValue;
234 if (range <= 0.0) return 0.0;
235 const double n = (plain - p.minValue) / range;
236 // Written so a NaN (a host's text-to-value on garbage, say) lands on 0
237 // rather than passing through: NaN compares false against both bounds.
238 return !(n > 0.0) ? 0.0 : (n > 1.0 ? 1.0 : n);
239}
240
242constexpr double toPlain(const Param& p, double normalized) noexcept
243{
244 // Written so a NaN lands on 0 rather than passing through: NaN compares
245 // false against both bounds, and the snap below would then convert it.
246 double n = !(normalized > 0.0) ? 0.0 : (normalized > 1.0 ? 1.0 : normalized);
247 if (p.steps > 0)
248 {
249 // Snap to the nearest of steps+1 positions. n is bounded above, so the
250 // conversion is in range by construction.
251 const double scaled = n * p.steps + 0.5;
252 const double idx = static_cast<double>(static_cast<long long>(scaled));
253 n = idx / p.steps;
254 n = n < 0.0 ? 0.0 : (n > 1.0 ? 1.0 : n);
255 }
256 return p.minValue + n * (static_cast<double>(p.maxValue) - p.minValue);
257}
258
263inline int parseToggleText(const char* text) noexcept
264{
265 auto lower = [](char c) { return c >= 'A' && c <= 'Z' ? static_cast<char>(c + 32) : c; };
266 if (text == nullptr) return -1;
267 if (lower(text[0]) == 'o' && lower(text[1]) == 'n' && text[2] == '\0') return 1;
268 if (lower(text[0]) == 'o' && lower(text[1]) == 'f' && lower(text[2]) == 'f'
269 && text[3] == '\0') return 0;
270 return -1;
271}
272
274constexpr int stepIndex(const Param& p, double plain) noexcept
275{
276 if (p.steps <= 0) return 0;
277 const double scaled = toNormalized(p, plain) * p.steps + 0.5;
278 const int idx = static_cast<int>(scaled);
279 return idx < 0 ? 0 : (idx > p.steps ? p.steps : idx);
280}
281
283inline void formatValue(const Param& p, double plain, char* out, int outSize) noexcept
284{
285 if (out == nullptr || outSize <= 0) return;
286 const size_t cap = static_cast<size_t>(outSize);
287 if (p.labels != nullptr && p.steps > 0)
288 {
289 const char* label = p.labels[stepIndex(p, plain)];
290 std::snprintf(out, cap, "%s", label != nullptr ? label : "");
291 return;
292 }
293 if (isToggle(p))
294 {
295 std::snprintf(out, cap, "%s",
296 plain >= 0.5 * (p.minValue + p.maxValue) ? "On" : "Off");
297 return;
298 }
299 // Whole-number positions (a stepped 1..8, say) display without decimals.
300 bool whole = false;
301 if (p.steps > 1)
302 {
303 const double step = (static_cast<double>(p.maxValue) - p.minValue) / p.steps;
304 auto isWhole = [](double v) {
305 const double r = static_cast<double>(static_cast<long long>(v < 0.0 ? v - 0.5
306 : v + 0.5));
307 return v - r < 1e-9 && r - v < 1e-9;
308 };
309 whole = isWhole(step) && isWhole(p.minValue);
310 }
311 char number[48];
312 if (whole)
313 std::snprintf(number, sizeof(number), "%.0f", plain);
314 else
315 std::snprintf(number, sizeof(number), "%.2f", plain);
316 // "<number> <unit>", cut to the host's buffer (always terminated).
317 size_t n = 0;
318 auto put = [&](const char* text) noexcept {
319 for (; text != nullptr && *text != '\0' && n + 1 < cap; ++text) out[n++] = *text;
320 };
321 put(number);
322 if (p.unit != nullptr && p.unit[0] != '\0')
323 {
324 put(" ");
325 put(p.unit);
326 }
327 out[n] = '\0';
328}
329
337inline bool parseValue(const Param& p, const char* text, double& plain) noexcept
338{
339 if (text == nullptr) return false;
340 while (*text == ' ' || *text == '\t') ++text;
341 if (p.labels != nullptr && p.steps > 0)
342 {
343 auto lower = [](char c) {
344 return c >= 'A' && c <= 'Z' ? static_cast<char>(c + 32) : c;
345 };
346 for (int i = 0; i <= p.steps; ++i)
347 {
348 const char* label = p.labels[i];
349 if (label == nullptr) continue;
350 size_t k = 0;
351 while (label[k] != '\0' && lower(label[k]) == lower(text[k])) ++k;
352 if (label[k] == '\0' && text[k] == '\0')
353 {
354 plain = toPlain(p, static_cast<double>(i) / p.steps);
355 return true;
356 }
357 }
358 }
359 if (isToggle(p))
360 {
361 const int toggle = parseToggleText(text);
362 if (toggle >= 0)
363 {
364 plain = toggle != 0 ? p.maxValue : p.minValue;
365 return true;
366 }
367 }
368 char* end = nullptr;
369 const double v = std::strtod(text, &end);
370 if (end == text || v != v) return false; // not a number, or NaN
371 plain = toPlain(p, toNormalized(p, v)); // clamp + snap
372 return true;
373}
374
375// -- Stable hashing (parameter ids, class UIDs) -------------------------------
376
378constexpr uint32_t hash32(const char* s) noexcept
379{
380 uint32_t h = 2166136261u;
381 while (*s != '\0')
382 {
383 h ^= static_cast<uint8_t>(*s++);
384 h *= 16777619u;
385 }
386 return h;
387}
388
390constexpr uint64_t hash64(const char* s, uint64_t salt) noexcept
391{
392 uint64_t h = 14695981039346656037ull ^ salt;
393 while (*s != '\0')
394 {
395 h ^= static_cast<uint8_t>(*s++);
396 h *= 1099511628211ull;
397 }
398 return h;
399}
400
409template <typename P>
410constexpr bool paramIdsUnique() noexcept
411{
412 constexpr size_t n = P::parameters.size();
413 for (size_t i = 0; i < n; ++i)
414 {
415 const uint32_t h = hash32(P::parameters[i].id);
416 if (h == 0x5052474Du || h == 0x42595053u) return false; // 'PRGM'/'BYPS'
417 if (h == 0x45445357u || h == 0x45445348u) return false; // 'EDSW'/'EDSH'
418 if ((h & 0xFFFF0000u) == 0x4D440000u) return false; // VST3 MIDI proxies
419 for (size_t j = i + 1; j < n; ++j)
420 if (hash32(P::parameters[j].id) == h) return false;
421 }
422 return true;
423}
424
428template <typename P>
429inline constexpr auto paramIdTable = [] {
430 std::array<uint32_t, P::parameters.size()> ids {};
431 for (size_t i = 0; i < P::parameters.size(); ++i)
432 ids[i] = hash32(P::parameters[i].id);
433 return ids;
434}();
435
437template <typename P>
438constexpr int paramIndexOf(uint32_t id) noexcept
439{
440 for (size_t i = 0; i < P::parameters.size(); ++i)
441 if (paramIdTable<P>[i] == id) return static_cast<int>(i);
442 return -1;
443}
444
446template <typename P>
447constexpr size_t perVoiceParamCount() noexcept
448{
449 size_t count = 0;
450 for (size_t i = 0; i < P::parameters.size(); ++i)
451 if (P::parameters[i].perVoice) ++count;
452 return count;
453}
454
457template <typename P>
458inline constexpr auto perVoiceSlotTable = [] {
459 std::array<int, P::parameters.size()> slots {};
460 int next = 0;
461 for (size_t i = 0; i < P::parameters.size(); ++i)
462 slots[i] = P::parameters[i].perVoice ? next++ : -1;
463 return slots;
464}();
465
470constexpr std::array<uint8_t, 16> makeUid(const char* productId, uint64_t salt) noexcept
471{
472 const uint64_t a = hash64(productId, salt);
473 const uint64_t b = hash64(productId, salt ^ 0x9E3779B97F4A7C15ull);
474 std::array<uint8_t, 16> uid {};
475 for (int i = 0; i < 8; ++i)
476 {
477 uid[static_cast<size_t>(i)] = static_cast<uint8_t>(a >> (8 * i));
478 uid[static_cast<size_t>(i + 8)] = static_cast<uint8_t>(b >> (8 * i));
479 }
480 return uid;
481}
482
483// -- Capability detection -----------------------------------------------------
484
485template <typename P>
486concept HasReset = requires(P p) { p.reset(); };
487
488template <typename P>
489concept HasLatency = requires(const P p) { { p.getLatency() } -> std::convertible_to<int>; };
490
491template <typename P>
492concept HasTail = requires(const P p) { { p.getTailSeconds() } -> std::convertible_to<double>; };
493
494template <typename P>
495concept HasGetState = requires(const P p) {
496 { p.getState() } -> std::convertible_to<std::vector<uint8_t>>;
497};
498
499template <typename P>
500concept HasSetState = requires(P p, const uint8_t* d, size_t n) {
501 { p.setState(d, n) } -> std::convertible_to<bool>;
502};
503
508template <typename P>
509concept HasEditor = requires { P::hasEditor; } && P::hasEditor;
510
529template <typename P>
530concept HasSidechain = requires(P p, AudioBufferView<float> io,
531 AudioBufferView<float> sc) {
532 p.processBlock(io, sc);
533};
534
535// -- Transport (host tempo & timeline) ------------------------------------------
536
548{
549 double tempoBpm = 120.0;
550 double ppqPosition = 0.0;
551 double barStartPpq = 0.0;
554 double loopStartPpq = 0.0;
555 double loopEndPpq = 0.0;
556 bool playing = false;
557 bool recording = false;
558 bool looping = false;
559 bool tempoValid = false;
560 bool positionValid = false;
561 bool timeSigValid = false;
562 bool loopValid = false;
563
565 [[nodiscard]] double secondsPerBeat() const noexcept
566 {
567 return 60.0 / (tempoBpm > 1.0 ? tempoBpm : 120.0);
568 }
569
571 [[nodiscard]] double samplesPerBeat(double sampleRate) const noexcept
572 {
573 return secondsPerBeat() * sampleRate;
574 }
575};
576
583template <typename P>
584concept HasTransport = requires(P p, const TransportInfo& t) {
585 p.setTransport(t);
586};
587
588// -- MIDI ------------------------------------------------------------------------
589
634{
635 enum class Type : uint8_t
636 {
637 NoteOn,
638 NoteOff,
639 PitchBend,
645 };
646
648 enum class ExpressionType : uint8_t
649 {
650 Volume,
651 Pan,
652 Tuning,
653 Vibrato,
654 Expression,
655 Brightness,
656 Pressure
657 };
658
660 uint8_t channel = 0;
661 uint8_t note = 0;
662 float value = 0.0f;
663 int sampleOffset = 0;
664 bool choke = false;
666 int16_t param = -1;
667 int32_t noteId = -1;
668};
669
671constexpr uint32_t expressionBit(MidiEvent::ExpressionType type) noexcept
672{
673 return 1u << static_cast<uint32_t>(type);
674}
675
677inline constexpr uint32_t kAllNoteExpressions =
678 (1u << (static_cast<uint32_t>(MidiEvent::ExpressionType::Pressure) + 1u)) - 1u;
679
688template <typename... Types>
689constexpr uint32_t expressions(Types... types) noexcept
690{
691 return (0u | ... | expressionBit(types));
692}
693
703template <typename P>
704concept HasNoteExpressions = requires {
705 { P::noteExpressions } -> std::convertible_to<uint32_t>;
706};
707
709template <typename P>
710constexpr uint32_t noteExpressionsOf() noexcept
711{
712 if constexpr (HasNoteExpressions<P>)
713 return static_cast<uint32_t>(P::noteExpressions) & kAllNoteExpressions;
714 else
715 return kAllNoteExpressions;
716}
717
728template <typename P>
729concept HasVoiceQuery = requires(const P p, int channel, int key, int32_t noteId) {
730 { p.isVoiceActive(channel, key, noteId) } -> std::convertible_to<bool>;
731};
732
740template <typename P>
741concept HasMidi = requires(P p, const MidiEvent& e) {
742 p.handleMidiEvent(e);
743};
744
745// -- Offline rendering ------------------------------------------------------------
746
755template <typename P>
756concept HasOfflineMode = requires(P p, bool offline) {
757 p.setOfflineRendering(offline);
758};
759
760// -- Channel support ----------------------------------------------------------------
761
772{
774 StereoOnly,
775 MonoOnly
776};
777
778template <typename P>
779concept HasChannelSupport = requires {
780 { P::channels } -> std::convertible_to<ChannelSupport>;
781};
782
784template <typename P>
786{
787 if constexpr (HasChannelSupport<P>)
788 return P::channels;
789 else
791}
792
794template <typename P>
795constexpr bool supportsChannelCount(int numChannels) noexcept
796{
797 constexpr ChannelSupport s = channelSupportOf<P>();
798 if (numChannels == 1) return s != ChannelSupport::StereoOnly;
799 if (numChannels == 2) return s != ChannelSupport::MonoOnly;
800 return false;
801}
802
804template <typename P>
805constexpr int defaultChannelCount() noexcept
806{
807 return channelSupportOf<P>() == ChannelSupport::MonoOnly ? 1 : 2;
808}
809
810// -- Factory presets ----------------------------------------------------------------
811
817template <size_t NumValues>
819{
820 const char* name = "";
821 std::array<float, NumValues> values {};
822};
823
826template <typename... Vs>
827constexpr PresetDef<sizeof...(Vs)> preset(const char* name, Vs... values) noexcept
828{
829 return PresetDef<sizeof...(Vs)> { name, { static_cast<float>(values)... } };
830}
831
835template <typename First, typename... Rest>
836constexpr std::array<First, 1 + sizeof...(Rest)> presets(First first, Rest... rest) noexcept
837{
838 static_assert((std::is_same_v<First, Rest> && ...),
839 "every preset must list one value per parameter");
840 return { first, rest... };
841}
842
850template <typename P>
851concept HasFactoryPresets = requires {
852 { P::factoryPresets.size() } -> std::convertible_to<size_t>;
853 { P::factoryPresets[0].name } -> std::convertible_to<const char*>;
854 { P::factoryPresets[0].values.size() } -> std::convertible_to<size_t>;
855};
856
858template <typename P>
859constexpr int factoryPresetCountOf() noexcept
860{
861 if constexpr (HasFactoryPresets<P>)
862 {
863 static_assert(P::factoryPresets[0].values.size() == P::parameters.size(),
864 "factoryPresets must list one PLAIN value per parameter, "
865 "in parameter-table order");
866 return static_cast<int>(P::factoryPresets.size());
867 }
868 else
869 return 0;
870}
871
874template <typename P>
875constexpr double presetNormalized(int presetIndex, size_t paramIndex) noexcept
876{
877 if constexpr (HasFactoryPresets<P>)
878 return toNormalized(P::parameters[paramIndex],
879 P::factoryPresets[static_cast<size_t>(presetIndex)]
880 .values[paramIndex]);
881 else
882 {
883 (void) presetIndex;
884 (void) paramIndex;
885 return 0.0;
886 }
887}
888
889// -- Sample-accurate automation -------------------------------------------------------
890
899template <typename P>
900concept HasSampleAccurateOptOut = requires {
901 { P::sampleAccurateAutomation } -> std::convertible_to<bool>;
902};
903
904template <typename P>
905constexpr bool sampleAccurateOf() noexcept
906{
907 if constexpr (HasSampleAccurateOptOut<P>)
908 return P::sampleAccurateAutomation;
909 else
910 return true;
911}
912
915inline constexpr int kAutomationQuantum = 32;
916
922inline constexpr int kMaxBlockEvents = 256;
923
931{
934 enum class Kind : uint8_t { Param, Bypass, Midi, ParamMod };
935 int32_t offset = 0;
937 uint32_t paramId = 0;
938 double value = 0.0;
940 uint32_t order = 0;
943 int32_t targetNoteId = -1;
944 int16_t targetPort = -1;
945 int16_t targetChannel = -1;
946 int16_t targetKey = -1;
949 bool voiceValue = false;
950};
951
954inline void sortBlockEvents(BlockEvent* events, int count) noexcept
955{
956 for (int i = 1; i < count; ++i)
957 {
958 BlockEvent key = events[i];
959 int j = i - 1;
960 while (j >= 0 && (events[j].offset > key.offset
961 || (events[j].offset == key.offset && events[j].order > key.order)))
962 {
963 events[j + 1] = events[j];
964 --j;
965 }
966 events[j + 1] = key;
967 }
968}
969
990{
991public:
993 void clear() noexcept
994 {
995 count_ = 0;
996 freeCount_ = 0;
997 dropped_ = 0;
998 nextOrder_ = 0;
999 if (++generation_ == 0) // wrapped: make every stale entry unreachable
1000 {
1001 for (auto& slot : table_) slot.generation = 0;
1002 generation_ = 1;
1003 }
1004 }
1005
1007 void add(const BlockEvent& event) noexcept
1008 {
1009 BlockEvent ev = event;
1010 ev.order = nextOrder_++;
1011 // MIDI and voice events are never superseded: each one counts.
1012 const bool isPoint = ev.kind != BlockEvent::Kind::Midi;
1013 // A modulation amount and a value of one parameter are separate
1014 // points: neither supersedes the other.
1015 TableSlot* entry = isPoint ? find(ev.paramId, ev.kind) : nullptr;
1016 const bool known = entry != nullptr && entry->generation == generation_;
1017 if (count_ < kMaxBlockEvents)
1018 {
1019 const int index = count_++;
1020 events_[index] = ev;
1021 if (isPoint)
1022 {
1023 if (known) freeList_[freeCount_++] = static_cast<int16_t>(entry->index);
1024 remember(entry, ev.paramId, ev.kind, index);
1025 }
1026 return;
1027 }
1028 if (known)
1029 {
1030 events_[entry->index] = ev; // the newer point supersedes the stored one
1031 return;
1032 }
1033 if (freeCount_ > 0)
1034 {
1035 const int index = freeList_[--freeCount_];
1036 events_[index] = ev;
1037 if (isPoint) remember(entry, ev.paramId, ev.kind, index);
1038 return;
1039 }
1040 ++dropped_;
1041 }
1042
1044 void sort() noexcept { sortBlockEvents(events_.data(), count_); }
1045
1046 [[nodiscard]] int size() const noexcept { return count_; }
1047 [[nodiscard]] int dropped() const noexcept { return dropped_; }
1048 BlockEvent& operator[](int i) noexcept { return events_[static_cast<size_t>(i)]; }
1049 const BlockEvent& operator[](int i) const noexcept { return events_[static_cast<size_t>(i)]; }
1050
1051private:
1052 struct TableSlot
1053 {
1054 uint32_t key = 0;
1055 uint32_t generation = 0;
1056 int index = 0;
1058 };
1059 static constexpr int kTableSize = 2 * kMaxBlockEvents; // power of two, load <= 1/2
1060
1062 TableSlot* find(uint32_t key, BlockEvent::Kind kind) noexcept
1063 {
1064 uint32_t h = (key + static_cast<uint32_t>(kind)) * 2654435761u;
1065 for (int probe = 0; probe < kTableSize; ++probe)
1066 {
1067 TableSlot& slot = table_[(h + static_cast<uint32_t>(probe)) & (kTableSize - 1)];
1068 if (slot.generation != generation_ || (slot.key == key && slot.kind == kind))
1069 return &slot;
1070 }
1071 return nullptr; // unreachable: the table never fills past one half
1072 }
1073
1074 void remember(TableSlot* entry, uint32_t key, BlockEvent::Kind kind, int index) noexcept
1075 {
1076 if (entry == nullptr) return;
1077 entry->key = key;
1078 entry->kind = kind;
1079 entry->generation = generation_;
1080 entry->index = index;
1081 }
1082
1083 std::array<BlockEvent, kMaxBlockEvents> events_ {};
1084 std::array<TableSlot, kTableSize> table_ {};
1085 std::array<int16_t, kMaxBlockEvents> freeList_ {};
1086 int count_ = 0;
1087 int freeCount_ = 0;
1088 int dropped_ = 0;
1089 uint32_t nextOrder_ = 0;
1090 uint32_t generation_ = 1;
1091};
1092
1106template <size_t NumParams>
1108{
1109public:
1110 void mark(size_t index) noexcept
1111 {
1112 words_[index >> 5].fetch_or(1u << (index & 31u), std::memory_order_release);
1113 any_.store(true, std::memory_order_release);
1114 }
1115
1117 template <typename Apply>
1118 bool drain(Apply&& apply) noexcept
1119 {
1120 if (!any_.exchange(false, std::memory_order_acquire)) return false;
1121 bool applied = false;
1122 for (size_t w = 0; w < kWords; ++w)
1123 {
1124 uint32_t bits = words_[w].exchange(0u, std::memory_order_acquire);
1125 while (bits != 0u)
1126 {
1127 const int b = std::countr_zero(bits);
1128 bits &= bits - 1u;
1129 const size_t index = w * 32u + static_cast<size_t>(b);
1130 if (index < NumParams)
1131 {
1132 apply(static_cast<int>(index));
1133 applied = true;
1134 }
1135 }
1136 }
1137 return applied;
1138 }
1139
1140private:
1141 static constexpr size_t kWords = NumParams == 0 ? 1 : (NumParams + 31) / 32;
1142 std::array<std::atomic<uint32_t>, kWords> words_ {};
1143 std::atomic<bool> any_ { false };
1144};
1145
1157{
1158public:
1159 void clear() noexcept
1160 {
1161 for (auto& row : on_) row = {};
1162 }
1163
1164 void noteOn(int channel, int key, int32_t noteId) noexcept
1165 {
1166 if (!valid(channel, key)) return;
1167 on_[static_cast<size_t>(channel)][static_cast<size_t>(key) >> 6]
1168 |= uint64_t { 1 } << (key & 63);
1169 id_[static_cast<size_t>(channel)][static_cast<size_t>(key)] = noteId;
1170 }
1171
1172 void noteOff(int channel, int key) noexcept
1173 {
1174 if (!valid(channel, key)) return;
1175 on_[static_cast<size_t>(channel)][static_cast<size_t>(key) >> 6]
1176 &= ~(uint64_t { 1 } << (key & 63));
1177 }
1178
1181 [[nodiscard]] int32_t noteIdOf(int channel, int key) const noexcept
1182 {
1183 return valid(channel, key)
1184 ? id_[static_cast<size_t>(channel)][static_cast<size_t>(key)] : -1;
1185 }
1186
1190 template <typename Off>
1191 void releaseMatching(int channel, int key, int32_t noteId, Off&& off) noexcept
1192 {
1193 for (int c = 0; c < 16; ++c)
1194 {
1195 if (channel >= 0 && channel != c) continue;
1196 for (int k = 0; k < 128; ++k)
1197 {
1198 if (key >= 0 && key != k) continue;
1199 const uint64_t bit = uint64_t { 1 } << (k & 63);
1200 if ((on_[static_cast<size_t>(c)][static_cast<size_t>(k) >> 6] & bit) == 0)
1201 continue;
1202 if (noteId >= 0 && id_[static_cast<size_t>(c)][static_cast<size_t>(k)] >= 0
1203 && id_[static_cast<size_t>(c)][static_cast<size_t>(k)] != noteId)
1204 continue;
1205 on_[static_cast<size_t>(c)][static_cast<size_t>(k) >> 6] &= ~bit;
1206 off(c, k);
1207 }
1208 }
1209 }
1210
1211private:
1212 static constexpr bool valid(int channel, int key) noexcept
1213 {
1214 return channel >= 0 && channel < 16 && key >= 0 && key < 128;
1215 }
1216 std::array<std::array<uint64_t, 2>, 16> on_ {};
1217 std::array<std::array<int32_t, 128>, 16> id_ {};
1218};
1219
1220// -- Bypass dry path -------------------------------------------------------------
1221
1235{
1236public:
1239 void prepare(int maxLatency, int maxBlock)
1240 {
1241 const int need = (maxLatency > 0 ? maxLatency : 0) + (maxBlock > 0 ? maxBlock : 0) + 1;
1242 size_ = 1;
1243 while (size_ < need) size_ <<= 1;
1244 for (auto& b : buf_) b.assign(static_cast<size_t>(size_), 0.0f);
1245 write_ = 0;
1246 }
1247
1249 void reset() noexcept
1250 {
1251 for (auto& b : buf_) std::fill(b.begin(), b.end(), 0.0f);
1252 write_ = 0;
1253 }
1254
1256 [[nodiscard]] int capacity(int n) const noexcept { return size_ - 1 - n; }
1257
1263 void process(float* const* dry, int numChannels, int n, int latency) noexcept
1264 {
1265 if (size_ == 0 || n <= 0) return;
1266 const int mask = size_ - 1;
1267 const int cap = capacity(n);
1268 const int d = latency < 0 ? 0 : (latency > cap ? (cap > 0 ? cap : 0) : latency);
1269 for (int ch = 0; ch < numChannels && ch < 2; ++ch)
1270 {
1271 float* ring = buf_[static_cast<size_t>(ch)].data();
1272 float* x = dry[ch];
1273 for (int i = 0; i < n; ++i)
1274 {
1275 const int w = (write_ + i) & mask;
1276 ring[w] = x[i];
1277 x[i] = ring[(w - d) & mask];
1278 }
1279 }
1280 write_ = (write_ + n) & mask;
1281 }
1282
1283private:
1284 std::array<std::vector<float>, 2> buf_;
1285 int size_ = 0;
1286 int write_ = 0;
1287};
1288
1292inline constexpr int kDryDelayMinCapacity = 8192;
1293
1294// -- Editor contract (used by plugin/webview/DSParkWebViewEditor.h) -------------
1295
1298{
1299 int width = 480;
1300 int height = 320;
1301};
1302
1310{
1311 Fixed,
1312 Free,
1313 KeepAspect
1314};
1315
1318template <typename P>
1319concept HasEditorHtml = requires {
1320 { P::editorHtml() } -> std::convertible_to<const char*>;
1321};
1322
1324template <typename P>
1325concept HasEditorSize = requires {
1326 { P::editorSize.width } -> std::convertible_to<int>;
1327 { P::editorSize.height } -> std::convertible_to<int>;
1328};
1329
1331template <typename P>
1332constexpr EditorSize editorSizeOf() noexcept
1333{
1334 if constexpr (HasEditorSize<P>)
1335 return EditorSize { static_cast<int>(P::editorSize.width),
1336 static_cast<int>(P::editorSize.height) };
1337 else
1338 return EditorSize {};
1339}
1340
1343template <typename P>
1344concept HasEditorResizable = requires { P::editorResizable; } && P::editorResizable;
1345
1348template <typename P>
1349concept HasEditorResize = requires {
1350 { P::editorResize } -> std::convertible_to<EditorResize>;
1351};
1352
1354template <typename P>
1355constexpr EditorResize editorResizeOf() noexcept
1356{
1357 if constexpr (HasEditorResize<P>)
1358 return P::editorResize;
1359 else if constexpr (HasEditorResizable<P>)
1360 return EditorResize::Free;
1361 else
1362 return EditorResize::Fixed;
1363}
1364
1366inline constexpr double kEditorMinSizeFactor = 0.5;
1367inline constexpr double kEditorMaxSizeFactor = 3.0;
1368
1378inline constexpr double kEditorMaxPixels = 32767.0;
1379
1394constexpr int toBoundedInt(double value, int lo, int hi) noexcept
1395{
1396 if (!(value > static_cast<double>(lo))) return lo; // false for NaN
1397 if (value >= static_cast<double>(hi)) return hi;
1398 return static_cast<int>(value);
1399}
1400
1409template <typename P>
1410constexpr void constrainEditorSize(double& width, double& height, double scale) noexcept
1411{
1412 const EditorSize logical = editorSizeOf<P>();
1413 constexpr EditorResize mode = editorResizeOf<P>();
1414 if constexpr (mode == EditorResize::Fixed)
1415 {
1416 width = logical.width * scale;
1417 height = logical.height * scale;
1418 }
1419 else
1420 {
1421 const double minW = logical.width * scale * kEditorMinSizeFactor;
1422 const double maxW = logical.width * scale * kEditorMaxSizeFactor;
1423 const double minH = logical.height * scale * kEditorMinSizeFactor;
1424 const double maxH = logical.height * scale * kEditorMaxSizeFactor;
1425 width = width < minW ? minW : (width > maxW ? maxW : width);
1426 height = height < minH ? minH : (height > maxH ? maxH : height);
1427 if constexpr (mode == EditorResize::KeepAspect)
1428 {
1429 const double ratio = static_cast<double>(logical.width) / logical.height;
1430 double fitW = width;
1431 if (height * ratio < fitW) fitW = height * ratio; // inside-fit
1432 fitW = fitW < minW ? minW : (fitW > maxW ? maxW : fitW);
1433 width = fitW;
1434 height = fitW / ratio;
1435 }
1436 }
1437 // The policy above is expressed as multiples of a host-chosen scale, so
1438 // its own bounds move with that scale. Every caller converts these to an
1439 // integer; bound them in pixels first, and write the test so a NaN cannot
1440 // pass through it.
1441 width = !(width > 1.0) ? 1.0
1442 : (width > kEditorMaxPixels ? kEditorMaxPixels : width);
1443 height = !(height > 1.0) ? 1.0
1444 : (height > kEditorMaxPixels ? kEditorMaxPixels : height);
1445}
1446
1459template <typename P>
1461{
1462public:
1464 static constexpr bool kPersists =
1465 HasEditor<P> && editorResizeOf<P>() != EditorResize::Fixed;
1466
1468 void remember(double logicalWidth, double logicalHeight) noexcept
1469 {
1470 if constexpr (kPersists)
1471 {
1472 double w = logicalWidth;
1473 double h = logicalHeight;
1474 constrainEditorSize<P>(w, h, 1.0);
1475 const uint32_t pw = static_cast<uint32_t>(
1476 toBoundedInt(w + 0.5, 1, static_cast<int>(kEditorMaxPixels)));
1477 const uint32_t ph = static_cast<uint32_t>(
1478 toBoundedInt(h + 0.5, 1, static_cast<int>(kEditorMaxPixels)));
1479 packed_.store((pw << 16) | ph, std::memory_order_relaxed);
1480 }
1481 else
1482 {
1483 (void) logicalWidth;
1484 (void) logicalHeight;
1485 }
1486 }
1487
1489 bool remembered(EditorSize& out) const noexcept
1490 {
1491 const uint32_t p = packed_.load(std::memory_order_relaxed);
1492 if (p == 0u) return false;
1493 out.width = static_cast<int>(p >> 16);
1494 out.height = static_cast<int>(p & 0xFFFFu);
1495 return true;
1496 }
1497
1499 [[nodiscard]] EditorSize current() const noexcept
1500 {
1501 EditorSize size = editorSizeOf<P>();
1502 (void) remembered(size);
1503 return size;
1504 }
1505
1506private:
1507 std::atomic<uint32_t> packed_ { 0u };
1508};
1509
1512template <typename P>
1513concept HasEditorDebug = requires { P::editorDebug; } && P::editorDebug;
1514
1519template <typename P>
1520concept HasEditorDevFile = requires {
1521 { P::editorDevFile() } -> std::convertible_to<const char*>;
1522};
1523
1524// -- PluginBase: the whole contract, visible in one place ----------------------
1525
1562template <typename Derived>
1564{
1573 void reset() noexcept {}
1574
1583 [[nodiscard]] int getLatency() const noexcept { return 0; }
1584
1591 [[nodiscard]] double getTailSeconds() const noexcept { return 0.0; }
1592
1600 [[nodiscard]] std::vector<uint8_t> getState() const { return {}; }
1601
1603 bool setState(const uint8_t*, size_t) { return false; }
1604
1613 void setTransport(const TransportInfo&) noexcept {}
1614
1623 void setOfflineRendering(bool) noexcept {}
1624
1631 static constexpr bool hasEditor = false;
1632};
1633
1634// -- Wrapper-side state serialisation ------------------------------------------
1635//
1636// Every backend stores plugin state in ONE container format so presets stay
1637// portable across formats and tolerant across versions (same philosophy as
1638// Core/StateBlob): a magic/version header, the parameter table keyed by
1639// hash32(id) - unknown ids are skipped, missing ids keep defaults - and an
1640// optional opaque user-state section appended verbatim.
1641
1642inline constexpr uint32_t kStateMagic = 0x4453504Bu; // "DSPK"
1643inline constexpr uint32_t kStateVersion = 1u;
1644
1648inline constexpr size_t kMaxStateBytes = size_t { 1 } << 30;
1649
1652inline constexpr uint32_t kProgramStateId = 0x5052474Du;
1653
1658inline constexpr uint32_t kBypassStateId = 0x42595053u;
1659
1663inline constexpr uint32_t kEditorWidthStateId = 0x45445357u;
1664inline constexpr uint32_t kEditorHeightStateId = 0x45445348u;
1665
1672template <typename P>
1673inline std::vector<uint8_t> buildState(const P& user, const double* normalized,
1674 size_t numParams, int programIndex = -1,
1675 int bypassState = -1,
1676 const EditorSize* editorSize = nullptr)
1677{
1678 auto push32 = [](std::vector<uint8_t>& v, uint32_t x) {
1679 v.push_back(static_cast<uint8_t>(x));
1680 v.push_back(static_cast<uint8_t>(x >> 8));
1681 v.push_back(static_cast<uint8_t>(x >> 16));
1682 v.push_back(static_cast<uint8_t>(x >> 24));
1683 };
1684 auto pushValue = [&push32](std::vector<uint8_t>& v, double value) {
1685 uint64_t bits = 0;
1686 static_assert(sizeof(bits) == sizeof(value));
1687 std::memcpy(&bits, &value, sizeof(bits));
1688 push32(v, static_cast<uint32_t>(bits));
1689 push32(v, static_cast<uint32_t>(bits >> 32));
1690 };
1691 const bool withSize = editorSize != nullptr && editorSize->width > 0
1692 && editorSize->height > 0;
1693 std::vector<uint8_t> blob;
1694 push32(blob, kStateMagic);
1695 push32(blob, kStateVersion);
1696 push32(blob, static_cast<uint32_t>(numParams) + (programIndex >= 0 ? 1u : 0u)
1697 + (bypassState >= 0 ? 1u : 0u) + (withSize ? 2u : 0u));
1698 for (size_t i = 0; i < numParams; ++i)
1699 {
1700 push32(blob, hash32(P::parameters[i].id));
1701 pushValue(blob, normalized[i]);
1702 }
1703 if (programIndex >= 0)
1704 {
1705 // The active factory preset rides along as one more entry so hosts
1706 // restore the program selection with the session.
1707 push32(blob, kProgramStateId);
1708 pushValue(blob, static_cast<double>(programIndex));
1709 }
1710 if (bypassState >= 0)
1711 {
1712 push32(blob, kBypassStateId);
1713 pushValue(blob, bypassState > 0 ? 1.0 : 0.0);
1714 }
1715 if (withSize)
1716 {
1717 push32(blob, kEditorWidthStateId);
1718 pushValue(blob, static_cast<double>(editorSize->width));
1719 push32(blob, kEditorHeightStateId);
1720 pushValue(blob, static_cast<double>(editorSize->height));
1721 }
1722 if constexpr (HasGetState<P>)
1723 {
1724 const std::vector<uint8_t> userBlob = user.getState();
1725 push32(blob, static_cast<uint32_t>(userBlob.size()));
1726 blob.insert(blob.end(), userBlob.begin(), userBlob.end());
1727 }
1728 else
1729 push32(blob, 0u);
1730 return blob;
1731}
1732
1737template <typename P>
1738inline void loadDefaultNormalized(double* normalized) noexcept
1739{
1740 for (size_t i = 0; i < P::parameters.size(); ++i)
1741 normalized[i] = toNormalized(P::parameters[i], P::parameters[i].defValue);
1742}
1743
1750template <typename P>
1751inline bool applyState(P& user, const uint8_t* data, size_t size, double* normalized,
1752 int* programIndex = nullptr, int* bypassState = nullptr,
1753 EditorSize* editorSize = nullptr)
1754{
1755 auto read32 = [&](size_t& pos, uint32_t& out) {
1756 if (pos + 4 > size) return false;
1757 out = static_cast<uint32_t>(data[pos])
1758 | static_cast<uint32_t>(data[pos + 1]) << 8
1759 | static_cast<uint32_t>(data[pos + 2]) << 16
1760 | static_cast<uint32_t>(data[pos + 3]) << 24;
1761 pos += 4;
1762 return true;
1763 };
1764 size_t pos = 0;
1765 uint32_t magic = 0, version = 0, count = 0;
1766 if (!read32(pos, magic) || magic != kStateMagic) return false;
1767 if (!read32(pos, version) || version == 0) return false;
1768 if (!read32(pos, count)) return false;
1769
1770 constexpr size_t numParams = P::parameters.size();
1771 int editorWidth = 0, editorHeight = 0;
1772 for (uint32_t i = 0; i < count; ++i)
1773 {
1774 uint32_t id = 0, lo = 0, hi = 0;
1775 if (!read32(pos, id) || !read32(pos, lo) || !read32(pos, hi)) return false;
1776 const uint64_t bits = static_cast<uint64_t>(lo) | (static_cast<uint64_t>(hi) << 32);
1777 double v = 0.0;
1778 std::memcpy(&v, &bits, sizeof(v));
1779 // A corrupt blob can carry any bit pattern: a NaN would survive both
1780 // range checks below (every comparison is false) and poison the
1781 // parameter shadow, so non-finite entries keep the default instead.
1782 if (v != v) continue;
1783 if (id == kProgramStateId)
1784 {
1785 // Converting a double that does not fit an int is undefined, and a
1786 // blob out of a project file can carry any value at all, so the
1787 // range is settled BEFORE the conversion rather than after it. An
1788 // index past the end of the preset list is refused by the caller's
1789 // own bounds check, exactly as an index written by a build with a
1790 // longer list always was.
1791 if (programIndex != nullptr && v >= 0.0)
1792 {
1793 const double rounded = v + 0.5;
1794 constexpr double intLimit =
1795 static_cast<double>(std::numeric_limits<int>::max());
1796 *programIndex = rounded < intLimit
1797 ? static_cast<int>(rounded)
1798 : std::numeric_limits<int>::max();
1799 }
1800 continue;
1801 }
1802 if (id == kBypassStateId)
1803 {
1804 if (bypassState != nullptr)
1805 *bypassState = v >= 0.5 ? 1 : 0;
1806 continue;
1807 }
1808 if (id == kEditorWidthStateId || id == kEditorHeightStateId)
1809 {
1810 // Any value a project file carries: bounded before the conversion.
1811 const int px = toBoundedInt(v + 0.5, 0, static_cast<int>(kEditorMaxPixels));
1812 (id == kEditorWidthStateId ? editorWidth : editorHeight) = px;
1813 continue;
1814 }
1815 for (size_t k = 0; k < numParams; ++k)
1816 if (hash32(P::parameters[k].id) == id)
1817 {
1818 normalized[k] = v < 0.0 ? 0.0 : (v > 1.0 ? 1.0 : v);
1819 break;
1820 }
1821 // Unknown ids are skipped: forward-compatible by construction.
1822 }
1823 if (editorSize != nullptr && editorWidth > 0 && editorHeight > 0)
1824 *editorSize = EditorSize { editorWidth, editorHeight };
1825
1826 uint32_t userSize = 0;
1827 // Subtraction form: pos <= size is guaranteed after read32, and on
1828 // 32-bit size_t targets (WASM) the addition form `pos + userSize` could
1829 // wrap around and admit an out-of-bounds user section.
1830 if (read32(pos, userSize) && userSize > 0 && userSize <= size - pos)
1831 {
1832 if constexpr (HasSetState<P>)
1833 user.setState(data + pos, userSize);
1834 }
1835 return true;
1836}
1837
1838} // namespace dspark::plugin
1839
1840#pragma pop_macro("max")
1841#pragma pop_macro("min")
The notes a backend has delivered as sounding, per channel and key, with the host note id each starte...
void noteOn(int channel, int key, int32_t noteId) noexcept
void releaseMatching(int channel, int key, int32_t noteId, Off &&off) noexcept
int32_t noteIdOf(int channel, int key) const noexcept
void noteOff(int channel, int key) noexcept
The fixed-capacity, allocation-free event list one block of host events is collected into (a member o...
BlockEvent & operator[](int i) noexcept
void add(const BlockEvent &event) noexcept
const BlockEvent & operator[](int i) const noexcept
int dropped() const noexcept
The dry signal of the wrappers' soft bypass, delayed by the plugin's latency.
int capacity(int n) const noexcept
void prepare(int maxLatency, int maxBlock)
void process(float *const *dry, int numChannels, int n, int latency) noexcept
The editor size the user last left, in logical pixels, kept by each backend across editor re-opens an...
EditorSize current() const noexcept
void remember(double logicalWidth, double logicalHeight) noexcept
static constexpr bool kPersists
bool remembered(EditorSize &out) const noexcept
Parameter changes made OFF the audio thread, handed to it.
bool drain(Apply &&apply) noexcept
void mark(size_t index) noexcept
Optional static constexpr bool editorDebug = true; - enables the browser DevTools in the editor (WebV...
Optional static const char* editorDevFile() - absolute path of an HTML file to load INSTEAD of editor...
static const char* editorHtml() - the editor page (HTML/CSS/JS), usually a raw string literal....
Optional static constexpr bool editorResizable = true; - shorthand for editorResize = EditorResize::F...
Optional static constexpr EditorResize editorResize = ...; - full resize policy; takes precedence ove...
Optional static constexpr EditorSize editorSize { w, h };.
Custom-editor switch. With hasEditor = false (or absent) hosts show their generic parameter UI....
Factory-preset capability: a static constexpr auto factoryPresets table built with presets()....
MIDI capability: void handleMidiEvent(const MidiEvent&) noexcept. Its presence grows a note/event inp...
Optional note-expression declaration: static constexpr uint32_t noteExpressions = expressions(....
Render-mode capability: void setOfflineRendering(bool) noexcept. The host flips it to true for non-re...
Sample-accurate opt-out: static constexpr bool sampleAccurateAutomation = false;. By default the wrap...
Sidechain capability. Implement the two-buffer process - the same shape DSPark's own dynamics take:
Transport capability: void setTransport(const TransportInfo&) noexcept. Called on the audio thread,...
Optional voice query: bool isVoiceActive(int channel, int key, int32_t noteId) const noexcept - true ...
constexpr bool supportsChannelCount(int numChannels) noexcept
True when P accepts a bus width of numChannels (1 or 2).
constexpr std::array< Param, sizeof...(Ps)> params(Ps... ps) noexcept
Builds the parameter table (use inside static constexpr auto).
constexpr size_t perVoiceParamCount() noexcept
Number of parameters of P marked with perVoice().
constexpr double kEditorMinSizeFactor
Resize bounds: hosts may shrink to half and grow to 3x the declared size.
EditorResize
How the host may resize the editor window. Declare static constexpr EditorResize editorResize = ....
@ Fixed
The window is exactly editorSize; hosts cannot drag-resize it.
@ KeepAspect
Drag-resizable, locked to the declared width:height ratio.
@ Free
Drag-resizable between 0.5x and 3x the declared size.
constexpr bool paramIdsUnique() noexcept
Compile-time guarantee that every parameter id hashes uniquely and collides with no id the wrappers r...
constexpr ChannelSupport channelSupportOf() noexcept
The declared channel support of P (default: mono+stereo).
constexpr uint32_t kProgramStateId
Reserved entry id persisting the active factory-preset index ('PRGM'); never a user parameter....
constexpr uint32_t kEditorWidthStateId
Reserved entry ids persisting the editor size the user left ('EDSW' / 'EDSH', logical pixels; see Edi...
constexpr uint32_t kStateVersion
constexpr Param perVoice(Param p) noexcept
Marks a parameter as modulatable per voice: params(perVoice(param("cutoff", "Cutoff",...
Category
Plugin category (reflected into each format's class metadata).
@ Instrument
Audio generator (MIDI in -> audio out, no audio input).
@ Fx
Audio effect (audio in -> audio out).
constexpr double kEditorMaxPixels
Pixel ceiling for a negotiated editor size.
constexpr size_t kMaxStateBytes
Largest state a backend reads back (1 GiB). It only bounds a hostile, endless host stream: getState()...
constexpr Param stepped(const char *id, const char *name, float minValue, float maxValue, float defValue, int steps, const char *unit="") noexcept
Discrete parameter helper: steps + 1 evenly spaced positions from minValue to maxValue,...
constexpr Param toggle(const char *id, const char *name, bool defaultOn) noexcept
On/off parameter helper.
std::vector< uint8_t > buildState(const P &user, const double *normalized, size_t numParams, int programIndex=-1, int bypassState=-1, const EditorSize *editorSize=nullptr)
Serialises the plugin state: every parameter (normalized), the active factory preset (programIndex,...
constexpr int stepIndex(const Param &p, double plain) noexcept
Position index (0..steps) of a plain value of a discrete parameter.
constexpr int kDryDelayMinCapacity
Ring headroom of the bypass dry path: latencies up to this (or twice the latency at activation,...
constexpr bool sampleAccurateOf() noexcept
constexpr uint32_t expressionBit(MidiEvent::ExpressionType type) noexcept
The bit of one ExpressionType in a note-expression mask.
constexpr int paramIndexOf(uint32_t id) noexcept
Table index of the parameter whose host id is id, or -1.
constexpr uint64_t hash64(const char *s, uint64_t salt) noexcept
FNV-1a 64-bit with a salt (two runs build a 128-bit class UID).
constexpr Param param(const char *id, const char *name, float minValue, float maxValue, float defValue, const char *unit) noexcept
Continuous parameter helper.
constexpr std::array< uint8_t, 16 > makeUid(const char *productId, uint64_t salt) noexcept
Deterministic 16-byte class UID from the stable productId. Each backend salts differently so VST3/CLA...
constexpr double toNormalized(const Param &p, double plain) noexcept
Plain [min, max] -> normalized [0, 1] (steps snap on the way back).
constexpr uint32_t expressions(Types... types) noexcept
Builds a note-expression mask for the noteExpressions declaration:
constexpr double toPlain(const Param &p, double normalized) noexcept
Normalized [0, 1] -> plain [min, max], snapped for stepped params.
constexpr uint32_t noteExpressionsOf() noexcept
The note expressions P receives: its declaration, else all.
constexpr uint32_t kAllNoteExpressions
Every ExpressionType at once (the mask of a class that declares none).
int parseToggleText(const char *text) noexcept
Case-insensitive "On"/"Off" recognition - the inverse of the toggle display below....
constexpr double presetNormalized(int presetIndex, size_t paramIndex) noexcept
Normalized value of parameter paramIndex in factory preset presetIndex (bounds already validated by t...
constexpr int kAutomationQuantum
Sub-block grain: automation/event splits snap to this many frames (bounds the per-call overhead; ~0....
constexpr uint32_t hash32(const char *s) noexcept
FNV-1a 32-bit over a C string - the per-parameter host id.
constexpr Param choice(const char *id, const char *name, const char *const (&labels)[N], int defaultIndex=0) noexcept
Named-choice helper: one position per label, plain values 0..N-1 (the label index),...
constexpr EditorResize editorResizeOf() noexcept
The effective resize policy for plugin class P.
void loadDefaultNormalized(double *normalized) noexcept
Fills normalized with every parameter's DEFAULT (normalized): what a state load starts from,...
constexpr uint32_t kStateMagic
constexpr void constrainEditorSize(double &width, double &height, double scale) noexcept
Applies the resize policy of P to a size the host proposes: Fixed pins it, Free clamps each axis to t...
constexpr double kEditorMaxSizeFactor
constexpr auto perVoiceSlotTable
For every parameter of P, its position among the perVoice() parameters (table order),...
constexpr int kMaxBlockEvents
Capacity of the per-block event list. Past it the list merges rather than drops: an intermediate para...
constexpr bool isToggle(const Param &p) noexcept
True for an on/off parameter (two unnamed positions).
constexpr PresetDef< sizeof...(Vs)> preset(const char *name, Vs... values) noexcept
Builds one factory preset: preset("Warm", 6.0f, 0.8f, ...) - one PLAIN value per parameter,...
constexpr EditorSize editorSizeOf() noexcept
The declared (logical) editor size, or the 480x320 default.
constexpr int factoryPresetCountOf() noexcept
Number of factory presets of P (0 when none declared).
constexpr int defaultChannelCount() noexcept
The width every backend starts in before the host negotiates.
bool applyState(P &user, const uint8_t *data, size_t size, double *normalized, int *programIndex=nullptr, int *bypassState=nullptr, EditorSize *editorSize=nullptr)
Parses a state blob; fills normalized (defaults pre-loaded by the caller, see loadDefaultNormalized),...
void formatValue(const Param &p, double plain, char *out, int outSize) noexcept
Formats a plain value for host display ("3.5 dB", "On", "Saw", "4").
void sortBlockEvents(BlockEvent *events, int count) noexcept
Insertion sort by (offset, arrival order) - tiny N, allocation-free, audio-thread safe; equal offsets...
constexpr auto paramIdTable
The hash32 of every parameter id of P, computed at compile time (table order), so id lookups on the a...
constexpr uint32_t kEditorHeightStateId
ChannelSupport
Bus widths a plugin offers to the host. The DSPark contract is channel-agnostic by construction (prep...
@ MonoOnly
Strictly 1->1 (rare; metering/utility plugins).
@ StereoOnly
Strictly 2->2 (inherently stereo DSP).
@ MonoAndStereo
Negotiates 1->1 or 2->2 with the host (default).
constexpr uint32_t kBypassStateId
Reserved entry id persisting the host bypass ('BYPS' - the same value every backend uses as the bypas...
constexpr int toBoundedInt(double value, int lo, int hi) noexcept
A floating value from outside converted to an integer, with the range settled BEFORE the conversion.
constexpr std::array< First, 1+sizeof...(Rest)> presets(First first, Rest... rest) noexcept
Builds the factory preset table (all presets must cover the same parameter count - enforced here; mat...
bool parseValue(const Param &p, const char *text, double &plain) noexcept
Host text -> plain value, the inverse of formatValue(): a choice's label (any case),...
One timestamped in-block event, normalised across formats: a parameter point, a bypass point,...
uint32_t paramId
hash32 id (Param, ParamMod), bypass id (Bypass).
int32_t offset
Frame position within the block.
double value
Normalized value / modulation amount / bypass >= 0.5.
MidiEvent midi
Kind::Midi payload.
Static identity of a plugin. All fields are plain literals so the whole descriptor can live in a stat...
Editor window size in logical pixels (physical = logical x host scale).
One incoming MIDI-ish event, normalised across formats.
ExpressionType
The per-voice expressions of Type::NoteExpression.
@ Expression
0..1 (a generic per-note intensity).
@ Volume
Linear gain 0..4 (1 = unchanged).
@ Pan
0 left, 0.5 centre, 1 right.
@ NoteOn
note = key, value = velocity 0..1.
@ NoteExpression
One voice: expression, value (see above).
@ PolyPressure
note = key, value = pressure 0..1.
@ NoteOff
note = key, value = release velocity 0..1.
@ NoteModulation
One voice: parameters[param] heard, plain units.
@ ControlChange
note = controller number, value = 0..1.
@ ChannelPressure
value = pressure 0..1 (note unused).
@ PitchBend
value = bend -1..+1 (note unused).
float value
Velocity / CC / pressure 0..1; bend -1..+1.
ExpressionType expression
NoteExpression only.
int sampleOffset
Frames into the NEXT processBlock call.
uint8_t note
Key 0..127, or controller number for CC.
int32_t noteId
Host voice id of the note (-1: none given).
bool choke
NoteOff only: end the voice now, no release.
int16_t param
NoteModulation only: the parameter index.
One automatable parameter. Plain values run [min, max]; hosts see the normalized [0,...
const char * name
Display name.
const char *const * labels
steps+1 position names, or null.
const char * unit
Display unit ("dB", "Hz", "%", ...).
bool perVoice
Host may modulate it per voice (see perVoice()).
int steps
0 continuous, 1 toggle, N discrete.
Optional convenience base that makes EVERY contract method visible and overridable from one place - I...
void setOfflineRendering(bool) noexcept
void setTransport(const TransportInfo &) noexcept
static constexpr bool hasEditor
double getTailSeconds() const noexcept
std::vector< uint8_t > getState() const
bool setState(const uint8_t *, size_t)
- restore side. Return false on a foreign blob.
int getLatency() const noexcept
One factory preset: a name plus a PLAIN value for every parameter, in parameter-table order....
std::array< float, NumValues > values
Host transport snapshot, delivered once per audio block.
bool playing
Transport is rolling.
double secondsPerBeat() const noexcept
Seconds per quarter note at the current tempo.
double tempoBpm
Current tempo (when tempoValid).
double loopStartPpq
Cycle start (when loopValid).
double samplesPerBeat(double sampleRate) const noexcept
Samples per quarter note - the basis for tempo-synced delays/LFOs.
bool timeSigValid
Time signature came from the host.
bool tempoValid
tempoBpm came from the host.
bool positionValid
ppqPosition/barStartPpq came from the host.
double ppqPosition
Musical position of frame 0, in quarter notes.
double loopEndPpq
Cycle end (when loopValid).
double barStartPpq
Quarter-note position of the current bar start.
bool loopValid
Loop points came from the host.
int timeSigNumerator
e.g. 3 in 3/4 (when timeSigValid).
bool looping
Cycle/loop mode is engaged.
bool recording
Transport is recording.
int timeSigDenominator
e.g. 4 in 3/4 (when timeSigValid).