DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DSParkClap.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
86#define DSPARK_PLUGIN_CLAP_INCLUDED 1
87
88#include "../DSParkPlugin.h"
89
90#include "clap/clap.h"
91
92// Survive a <windows.h> included earlier without NOMINMAX (restored at the end).
93#pragma push_macro("min")
94#pragma push_macro("max")
95#undef min
96#undef max
97
98#include <algorithm>
99#include <array>
100#include <atomic>
101#include <cstdint>
102#include <cstdlib>
103#include <cstring>
104#include <new>
105#include <vector>
106
108
109inline constexpr uint32_t kBypassParamId = 0x42595053u; // matches the VST3 backend
110inline constexpr int kBypassRampSamples = 256;
111
126template <size_t NumPerVoice>
128{
129public:
130 static constexpr int kCapacity = 128;
131
133 struct Voice
134 {
135 int16_t channel = 0;
136 int16_t key = 0;
137 int32_t noteId = -1;
138 uint32_t serial = 0;
139 bool used = false;
140 bool held = false;
141 };
142
145 {
146 static constexpr size_t kSlots = NumPerVoice == 0 ? 1 : NumPerVoice;
147 std::array<double, kSlots> amount {};
148 std::array<bool, kSlots> modulated {};
150 std::array<double, kSlots> value {};
151 std::array<bool, kSlots> valued {};
152 };
153
154 void clear() noexcept
155 {
156 for (auto& voice : voices_) voice.used = false;
157 end_ = 0;
158 }
159
161 int start(int channel, int key, int32_t noteId) noexcept
162 {
163 for (int i = 0; i < kCapacity; ++i)
164 {
165 Voice& voice = voices_[static_cast<size_t>(i)];
166 if (voice.used) continue;
167 voice.channel = static_cast<int16_t>(channel);
168 voice.key = static_cast<int16_t>(key);
169 voice.noteId = noteId;
170 voice.serial = nextSerial_++;
171 voice.used = true;
172 voice.held = true;
173 if constexpr (NumPerVoice > 0)
174 {
175 // A new voice starts unmodulated (the amounts and values only
176 // count once their flag is set).
177 auto& params = params_[static_cast<size_t>(i)];
178 params.modulated.fill(false);
179 params.valued.fill(false);
180 }
181 if (i >= end_) end_ = i + 1;
182 return i;
183 }
184 return -1;
185 }
186
189 [[nodiscard]] int oldest() const noexcept
190 {
191 int best = -1;
192 bool bestHeld = true;
193 uint32_t bestAge = 0;
194 for (int i = 0; i < end_; ++i)
195 {
196 const Voice& voice = voices_[static_cast<size_t>(i)];
197 if (!voice.used) continue;
198 const uint32_t age = nextSerial_ - voice.serial; // wrap-safe
199 if (best < 0 || (bestHeld && !voice.held)
200 || (bestHeld == voice.held && age > bestAge))
201 {
202 best = i;
203 bestHeld = voice.held;
204 bestAge = age;
205 }
206 }
207 return best;
208 }
209
211 [[nodiscard]] int end() const noexcept { return end_; }
212
215 template <typename Fn>
216 void forEachMatching(int port, int channel, int key, int32_t noteId, Fn&& fn) noexcept
217 {
218 if (port > 0) return;
219 for (int i = 0; i < end_; ++i)
220 {
221 const Voice& voice = voices_[static_cast<size_t>(i)];
222 if (!voice.used
223 || (channel >= 0 && voice.channel != channel)
224 || (key >= 0 && voice.key != key)
225 || (noteId >= 0 && voice.noteId != noteId))
226 continue;
227 fn(i);
228 }
229 }
230
231 Voice& operator[](int slot) noexcept { return voices_[static_cast<size_t>(slot)]; }
232
234 VoiceParams& paramsOf(int slot) noexcept
235 {
236 return params_[NumPerVoice > 0 ? static_cast<size_t>(slot) : 0u];
237 }
238
240 void release(int slot) noexcept
241 {
242 voices_[static_cast<size_t>(slot)].used = false;
243 while (end_ > 0 && !voices_[static_cast<size_t>(end_ - 1)].used) --end_;
244 }
245
246private:
247 std::array<Voice, kCapacity> voices_ {};
248 std::array<VoiceParams, (NumPerVoice > 0 ? kCapacity : 1)> params_ {};
249 int end_ = 0; // one past the highest slot in use
250 uint32_t nextSerial_ = 0;
251};
252
253template <typename P>
254struct Plugin
255{
256 static constexpr size_t kNumParams = P::parameters.size();
257 static constexpr bool kIsInstrument =
258 P::descriptor.category == Category::Instrument;
259 static constexpr int kNumPresets = factoryPresetCountOf<P>();
260 static_assert(!(kIsInstrument && HasSidechain<P>),
261 "an Instrument has no audio inputs; remove the sidechain "
262 "processBlock or use Category::Fx");
263 static_assert(!kIsInstrument || HasMidi<P>,
264 "an Instrument needs handleMidiEvent (see HasMidi): it has "
265 "no audio input to process");
266 static_assert(paramIdsUnique<P>(),
267 "two parameter ids share a hash32 (or collide with the "
268 "reserved PRGM/BYPS/EDSW/EDSH state ids): automation and state "
269 "would cross-wire. Rename one id.");
270 static constexpr size_t kNumPerVoice = perVoiceParamCount<P>();
271 static constexpr bool kHasPerVoice = kNumPerVoice > 0;
272 static_assert(!kHasPerVoice || HasMidi<P>,
273 "a perVoice() parameter needs handleMidiEvent (see HasMidi): "
274 "only a plugin with a note input has voices to modulate");
275
276 clap_plugin_t plugin {}; // the C-facing object (plugin_data = this)
277 const clap_host_t* host = nullptr;
278 const clap_host_latency_t* hostLatency = nullptr;
279 const clap_host_params_t* hostParams = nullptr;
280 const clap_host_preset_load_t* hostPresetLoad = nullptr;
281
282 P user {};
283 double sampleRate = 48000.0;
284 uint32_t maxFrames = 0;
285 bool prepared = false;
292 std::atomic<int> cachedLatency { 0 };
293 int currentChannels = defaultChannelCount<P>(); // selected ports config
294 bool offlineRender = false; // last render-extension setting
295 std::atomic<bool> latencyDirty { false }; // audio -> main thread notify
296 int latencyAtActivate = 0; // what the host last learned in activate()
297
303 std::atomic<bool> active { false };
305 BlockEventList blockEvents; // one block of host events (audio thread)
306 ActiveNotes sounding; // for CLAP's wildcard note-off / choke
307
316 {
317 int16_t channel;
318 int16_t key;
319 int32_t noteId;
320 };
321 static constexpr int kMaxEndedVoices =
324 int endedCount = 0;
325
326 std::atomic<double> shadow[kNumParams == 0 ? 1 : kNumParams] {};
328 double modulation[kNumParams == 0 ? 1 : kNumParams] {};
329 std::atomic<bool> bypass { false };
330 std::atomic<int> currentProgram { 0 }; // last factory preset loaded
331 float bypassMix = 0.0f;
332 std::vector<float> dryL, dryR;
333 std::vector<float> silence; // stand-in sidechain when not connected
334 DryDelay dryDelay; // latency-aligned dry path of the bypass
338
339#if defined(DSPARK_PLUGIN_WEBVIEW)
340 // --- editor state + UI -> host event queue (single producer: main thread;
341 // single consumer: process() on audio or flush() on main - never both).
342 webview_ui::Editor<P> guiEditor;
343 bool guiActive = false;
344 double guiScale = 1.0;
345 int guiWidth = 0, guiHeight = 0;
346 bool guiEditActive[kNumParams == 0 ? 1 : kNumParams] {};
347 const clap_host_gui_t* hostGui = nullptr; // resize requests (state loads)
348#if defined(__linux__)
349 // GTK is driven from the host's run loop: a timer-support tick pumps it.
350 const clap_host_timer_support_t* hostTimer = nullptr;
351 clap_id guiTimerId = CLAP_INVALID_ID;
352#endif
353
354 enum : uint8_t { kUiGestureBegin = 0, kUiValue = 1, kUiGestureEnd = 2 };
355 struct UiEvent
356 {
357 uint32_t paramId;
358 uint8_t kind;
359 double value;
360 };
361 static constexpr uint32_t kUiQueueSize = 256; // power of two
362 UiEvent uiQueue[kUiQueueSize] {};
363 std::atomic<uint32_t> uiHead { 0 }, uiTail { 0 };
364#endif
365
366 explicit Plugin(const clap_host_t* h) noexcept : host(h)
367 {
368 for (size_t i = 0; i < kNumParams; ++i)
369 shadow[i].store(toNormalized(P::parameters[i], P::parameters[i].defValue),
370 std::memory_order_relaxed);
371 }
372
373 static Plugin* self(const clap_plugin_t* p) noexcept
374 {
375 return static_cast<Plugin*>(p->plugin_data);
376 }
377
381 double heardPlain(int index, double normalized) const noexcept
382 {
383 const auto& spec = P::parameters[static_cast<size_t>(index)];
384 const double value = toPlain(spec, normalized);
385 const double mod = modulation[static_cast<size_t>(index)];
386 return (mod == 0.0) ? value : toPlain(spec, toNormalized(spec, value + mod));
387 }
388
389 void applyNormalized(int index, double normalized) noexcept
390 {
391 // Host values are untrusted doubles: a NaN would pass both range
392 // clamps, poison the shadow and reach the user's setter. Ignore it.
393 if (normalized != normalized) return;
394 shadow[static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
395 user.setParameter(index, static_cast<float>(heardPlain(index, normalized)));
396 }
397
398 static int indexOfParamId(uint32_t id) noexcept
399 {
400 return paramIndexOf<P>(id);
401 }
402
410 bool applyFromUi(int index, double normalized) noexcept
411 {
412 if (normalized != normalized) return false;
413 if (active.load(std::memory_order_acquire))
414 {
415 shadow[static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
416 pending.mark(static_cast<size_t>(index));
417 return false;
418 }
419 applyNormalized(index, normalized);
420 return true;
421 }
422
423 bool drainPending() noexcept
424 {
425 return pending.drain([this](int i) {
426 user.setParameter(i, static_cast<float>(heardPlain(
427 i, shadow[static_cast<size_t>(i)].load(std::memory_order_relaxed))));
428 resendVoiceModulation(i, 0, false);
429 });
430 }
431
432 // --- per-voice events (polyphonic modulation and automation, expressions) ---
433
439 double voiceHeardPlain(int index, bool valued, double value, bool modulated,
440 double amount) const noexcept
441 {
442 const auto& spec = P::parameters[static_cast<size_t>(index)];
443 const double base = valued
444 ? value
445 : toPlain(spec, shadow[static_cast<size_t>(index)].load(std::memory_order_relaxed));
446 const double mod = modulated ? amount : modulation[static_cast<size_t>(index)];
447 return toPlain(spec, toNormalized(spec, base + mod));
448 }
449
452 template <typename Params>
453 double voiceHeardPlain(int index, int slot, const Params& params) const noexcept
454 {
455 const auto s = static_cast<size_t>(slot);
456 return voiceHeardPlain(index, params.valued[s], params.value[s],
457 params.modulated[s], params.amount[s]);
458 }
459
462 void deliverToVoice(MidiEvent midi, int channel, int key, int32_t noteId) noexcept
463 {
464 if constexpr (HasMidi<P>)
465 {
466 midi.channel = static_cast<uint8_t>(channel & 0x0F);
467 midi.note = static_cast<uint8_t>(key & 0x7F);
468 midi.noteId = noteId;
469 user.handleMidiEvent(midi);
470 }
471 else
472 {
473 (void) midi;
474 (void) channel;
475 (void) key;
476 (void) noteId;
477 }
478 }
479
486 void resendVoiceModulation(int index, int sampleOffset, bool modulationMoved) noexcept
487 {
488 if constexpr (kHasPerVoice)
489 {
490 const int slot = perVoiceSlotTable<P>[static_cast<size_t>(index)];
491 if (slot < 0) return;
492 const auto s = static_cast<size_t>(slot);
493 const auto& spec = P::parameters[static_cast<size_t>(index)];
494 // The global value and amount, read once for every voice.
495 const double globalValue =
496 toPlain(spec, shadow[static_cast<size_t>(index)].load(std::memory_order_relaxed));
497 const double globalAmount = modulation[static_cast<size_t>(index)];
498 MidiEvent midi {};
500 midi.param = static_cast<int16_t>(index);
501 midi.sampleOffset = sampleOffset;
502 for (int v = 0; v < voices.end(); ++v)
503 {
504 const auto& voice = voices[v];
505 if (!voice.used) continue;
506 const auto& params = voices.paramsOf(v);
507 const bool valued = params.valued[s];
508 const bool modulated = params.modulated[s];
509 if (modulationMoved ? (!valued || modulated) : (!modulated || valued)) continue;
510 const double base = valued ? params.value[s] : globalValue;
511 const double amount = modulated ? params.amount[s] : globalAmount;
512 midi.value = static_cast<float>(toPlain(spec, toNormalized(spec, base + amount)));
513 deliverToVoice(midi, voice.channel, voice.key, voice.noteId);
514 }
515 }
516 else
517 {
518 (void) index;
519 (void) sampleOffset;
520 (void) modulationMoved;
521 }
522 }
523
526 void endVoice(int slot) noexcept
527 {
528 if constexpr (kHasPerVoice)
529 {
530 if (endedCount < kMaxEndedVoices) // by construction (see kMaxEndedVoices)
531 {
532 const auto& voice = voices[slot];
533 endedVoices[endedCount++] = EndedVoice { voice.channel, voice.key,
534 voice.noteId };
535 }
536 }
537 voices.release(slot);
538 }
539
541 void trackVoice(const MidiEvent& midi) noexcept
542 {
543 if (midi.type == MidiEvent::Type::NoteOn)
544 {
545 // A full table retires its oldest voice (a released one first)
546 // and reports its end, as a synth that steals a voice does: the
547 // old table simply did not track the new voice, which then never
548 // received a NOTE_END, and the host kept its modulators forever.
549 if (voices.start(midi.channel, midi.note, midi.noteId) < 0)
550 if (const int victim = voices.oldest(); victim >= 0)
551 {
552 endVoice(victim);
553 (void) voices.start(midi.channel, midi.note, midi.noteId);
554 }
555 return;
556 }
557 if (midi.type != MidiEvent::Type::NoteOff) return;
558 voices.forEachMatching(-1, midi.channel, midi.note, midi.noteId, [&](int slot) {
559 // A choke ends the voice now. A release ends it when the plugin
560 // says it fell silent (isVoiceActive) - or, without that query,
561 // at the release itself.
562 if constexpr (HasVoiceQuery<P>)
563 {
564 if (!midi.choke)
565 {
566 voices[slot].held = false;
567 return;
568 }
569 }
570 endVoice(slot);
571 });
572 }
573
578 void applyVoiceEvent(const BlockEvent& ev, MidiEvent midi) noexcept
579 {
580 const bool isModulation = midi.type == MidiEvent::Type::NoteModulation;
581 const int index = midi.param;
582 const int slot = isModulation ? perVoiceSlotTable<P>[static_cast<size_t>(index)] : -1;
583 if (isModulation && slot < 0) return;
584 const auto s = static_cast<size_t>(slot < 0 ? 0 : slot);
585 bool delivered = false;
586 voices.forEachMatching(ev.targetPort, ev.targetChannel, ev.targetKey,
587 ev.targetNoteId, [&](int v) {
588 const auto& voice = voices[v];
589 if (isModulation)
590 {
591 auto& params = voices.paramsOf(v);
592 if (ev.voiceValue)
593 {
594 params.value[s] = ev.value;
595 params.valued[s] = true;
596 }
597 else
598 {
599 params.amount[s] = ev.value;
600 params.modulated[s] = true;
601 }
602 midi.value = static_cast<float>(voiceHeardPlain(index, slot, params));
603 }
604 deliverToVoice(midi, voice.channel, voice.key, voice.noteId);
605 delivered = true;
606 });
607 if (!delivered && ev.targetPort <= 0 && ev.targetChannel >= 0 && ev.targetKey >= 0)
608 {
609 if (isModulation)
610 midi.value = static_cast<float>(ev.voiceValue
611 ? voiceHeardPlain(index, true, ev.value, false, 0.0)
612 : voiceHeardPlain(index, false, 0.0, true, ev.value));
613 deliverToVoice(midi, ev.targetChannel, ev.targetKey, ev.targetNoteId);
614 }
615 }
616
619 void pollVoices() noexcept
620 {
621 if constexpr (kHasPerVoice && HasVoiceQuery<P>)
622 {
623 for (int v = voices.end() - 1; v >= 0; --v) // ending shrinks end()
624 {
625 const auto& voice = voices[v];
626 if (voice.used
627 && !static_cast<bool>(user.isVoiceActive(voice.channel, voice.key,
628 voice.noteId)))
629 endVoice(v);
630 }
631 }
632 }
633
635 void flushEndedVoices(const clap_output_events_t* out, uint32_t time) noexcept
636 {
637 if constexpr (kHasPerVoice)
638 {
639 for (int i = 0; out != nullptr && out->try_push != nullptr && i < endedCount; ++i)
640 {
641 clap_event_note_t ev {};
642 ev.header.size = sizeof(ev);
643 ev.header.time = time;
644 ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
645 ev.header.type = CLAP_EVENT_NOTE_END;
646 ev.note_id = endedVoices[i].noteId;
647 ev.port_index = 0;
648 ev.channel = endedVoices[i].channel;
649 ev.key = endedVoices[i].key;
650 ev.velocity = 0.0;
651 out->try_push(out, &ev.header);
652 }
653 }
654 else
655 {
656 (void) out;
657 (void) time;
658 }
659 endedCount = 0;
660 }
661
664 void requestParamFlush() noexcept
665 {
666 if (hostParams != nullptr && hostParams->request_flush != nullptr && host != nullptr)
667 hostParams->request_flush(host);
668 }
669
671 void applyFactoryPresetIdx(int idx) noexcept
672 {
673 if constexpr (kNumPresets > 0)
674 {
675 if (idx < 0 || idx >= kNumPresets) return;
676 bool direct = true;
677 for (size_t i = 0; i < kNumParams; ++i)
678 direct &= applyFromUi(static_cast<int>(i), presetNormalized<P>(idx, i));
679 currentProgram.store(idx, std::memory_order_relaxed);
680 if (!direct) requestParamFlush();
681 }
682 else
683 (void) idx;
684 }
685
690 void refreshLatency() noexcept
691 {
692 if constexpr (HasLatency<P>)
693 {
694 const int now = user.getLatency();
695 if (prepared && now != cachedLatency.load(std::memory_order_relaxed))
696 {
697 cachedLatency.store(now, std::memory_order_relaxed);
698 latencyDirty.store(true, std::memory_order_release);
699 if (host != nullptr && host->request_callback != nullptr)
700 host->request_callback(host);
701 }
702 }
703 }
704
708 void collectEvent(const clap_event_header_t* ev, uint32_t numSamples,
709 BlockEventList& events) noexcept
710 {
711 if (ev == nullptr || ev->space_id != CLAP_CORE_EVENT_SPACE_ID) return;
712 BlockEvent out {};
713 out.offset = static_cast<int32_t>(ev->time);
714 if (numSamples > 0 && out.offset >= static_cast<int32_t>(numSamples))
715 out.offset = static_cast<int32_t>(numSamples) - 1;
716 if (out.offset < 0) out.offset = 0;
717
718 if (ev->type == CLAP_EVENT_PARAM_VALUE)
719 {
720 const auto* pv = reinterpret_cast<const clap_event_param_value_t*>(ev);
721 // A NaN value is ignored like a NaN modulation amount: the plain
722 // -> normalized mapping sends NaN to 0, so the old code moved the
723 // parameter to its minimum.
724 if (pv->value != pv->value) return;
725 if (pv->param_id == kBypassParamId)
726 {
727 out.kind = BlockEvent::Kind::Bypass;
728 out.paramId = kBypassParamId;
729 out.value = pv->value;
730 }
731 else
732 {
733 const int idx = indexOfParamId(pv->param_id);
734 if (idx < 0) return;
735 // Per-note automation: a value addressed by note id, key or
736 // channel sets single voices of a perVoice() parameter (the
737 // parameter's own value stays as it is) and becomes one
738 // NoteModulation per matching voice when applied. The old
739 // wrapper offered none and moved the global value instead.
740 // A port-only address (one note port: every voice) and any
741 // address on another parameter keep the global meaning.
742 if (pv->note_id >= 0 || pv->key >= 0 || pv->channel >= 0)
743 {
744 if constexpr (HasMidi<P>)
745 {
746 if (P::parameters[static_cast<size_t>(idx)].perVoice)
747 {
748 out.kind = BlockEvent::Kind::Midi;
749 out.midi.type = MidiEvent::Type::NoteModulation;
750 out.midi.param = static_cast<int16_t>(idx);
751 out.value = pv->value;
752 out.voiceValue = true;
753 out.targetNoteId = pv->note_id;
754 out.targetPort = pv->port_index;
755 out.targetChannel = pv->channel;
756 out.targetKey = pv->key;
757 events.add(out);
758 return;
759 }
760 }
761 }
762 out.kind = BlockEvent::Kind::Param;
763 out.paramId = pv->param_id;
764 out.value = toNormalized(P::parameters[static_cast<size_t>(idx)],
765 pv->value);
766 }
767 }
768 else if (ev->type == CLAP_EVENT_PARAM_MOD)
769 {
770 // The global signal (every address part -1) is added to the value
771 // setParameter receives. An addressed one - per note id, key,
772 // channel or port - modulates single voices: only a perVoice()
773 // parameter declares that, and it becomes one NoteModulation per
774 // matching voice when applied. A NaN amount is ignored.
775 const auto* pm = reinterpret_cast<const clap_event_param_mod_t*>(ev);
776 if (pm->amount != pm->amount) return;
777 const int idx = indexOfParamId(pm->param_id);
778 if (idx < 0) return;
779 if (pm->note_id >= 0 || pm->key >= 0 || pm->channel >= 0 || pm->port_index >= 0)
780 {
781 if constexpr (HasMidi<P>)
782 {
783 if (!P::parameters[static_cast<size_t>(idx)].perVoice) return;
784 out.kind = BlockEvent::Kind::Midi;
785 out.midi.type = MidiEvent::Type::NoteModulation;
786 out.midi.param = static_cast<int16_t>(idx);
787 out.value = pm->amount;
788 out.targetNoteId = pm->note_id;
789 out.targetPort = pm->port_index;
790 out.targetChannel = pm->channel;
791 out.targetKey = pm->key;
792 events.add(out);
793 }
794 return;
795 }
797 out.paramId = pm->param_id;
798 out.value = pm->amount;
799 }
800 else if constexpr (HasMidi<P>)
801 {
802 out.kind = BlockEvent::Kind::Midi;
803 if (ev->type == CLAP_EVENT_NOTE_ON || ev->type == CLAP_EVENT_NOTE_OFF
804 || ev->type == CLAP_EVENT_NOTE_CHOKE)
805 {
806 const auto* note = reinterpret_cast<const clap_event_note_t*>(ev);
807 if (ev->type == CLAP_EVENT_NOTE_ON)
808 {
809 if ((note->key < 0) || (note->key > 127)) return; // no voice to start
810 const int ch = note->channel >= 0 ? (note->channel & 0x0F) : 0;
811 out.midi.type = MidiEvent::Type::NoteOn;
812 out.midi.channel = static_cast<uint8_t>(ch);
813 out.midi.note = static_cast<uint8_t>(note->key);
814 out.midi.value = static_cast<float>(note->velocity);
815 out.midi.noteId = note->note_id >= 0 ? note->note_id : -1;
816 sounding.noteOn(ch, note->key, note->note_id);
817 }
818 else
819 {
820 // NOTE_OFF and NOTE_CHOKE address notes by (channel, key,
821 // note id), each part possibly the wildcard -1. Every
822 // sounding note the address matches gets its NoteOff. A
823 // choke is a NoteOff with `choke` set: the voice must end
824 // now, without its release phase. Delivered as a plain
825 // NoteOff (the previous behaviour), a choked voice rang
826 // out its whole release; a plugin that ignores the flag
827 // still releases it.
828 const bool choke = ev->type == CLAP_EVENT_NOTE_CHOKE;
829 const float velocity = choke ? 0.0f : static_cast<float>(note->velocity);
830 out.midi.choke = choke;
831 const bool exact = note->channel >= 0 && note->key >= 0;
832 if (exact)
833 {
834 // A precise off is delivered even for a note the
835 // tracker never saw (its on may predate an overflow).
836 sounding.noteOff(note->channel & 0x0F, note->key & 0x7F);
837 out.midi.type = MidiEvent::Type::NoteOff;
838 out.midi.channel = static_cast<uint8_t>(note->channel & 0x0F);
839 out.midi.note = static_cast<uint8_t>(note->key & 0x7F);
840 out.midi.value = velocity;
841 out.midi.noteId = note->note_id >= 0 ? note->note_id : -1;
842 }
843 else
844 {
845 sounding.releaseMatching(note->channel, note->key, note->note_id,
846 [&](int c, int k) {
847 BlockEvent off = out;
849 off.midi.channel = static_cast<uint8_t>(c);
850 off.midi.note = static_cast<uint8_t>(k);
851 off.midi.value = velocity;
852 off.midi.noteId = sounding.noteIdOf(c, k);
853 events.add(off);
854 });
855 return;
856 }
857 }
858 }
859 else if (ev->type == CLAP_EVENT_NOTE_EXPRESSION)
860 {
861 // Per-voice expressions (CLAP numbers them in ExpressionType
862 // order). Resolved against the delivered voices when applied;
863 // the old code dropped every one of them.
864 const auto* ne = reinterpret_cast<const clap_event_note_expression_t*>(ev);
865 if ((ne->expression_id < CLAP_NOTE_EXPRESSION_VOLUME)
866 || (ne->expression_id > CLAP_NOTE_EXPRESSION_PRESSURE)
867 || ne->value != ne->value)
868 return;
869 const auto expression =
870 static_cast<MidiEvent::ExpressionType>(ne->expression_id);
871 // A class that declares its expressions hears only those.
872 if ((noteExpressionsOf<P>() & expressionBit(expression)) == 0u) return;
873 out.midi.type = MidiEvent::Type::NoteExpression;
874 out.midi.expression = expression;
875 out.midi.value = static_cast<float>(ne->value);
876 out.targetNoteId = ne->note_id;
877 out.targetPort = ne->port_index;
878 out.targetChannel = ne->channel;
879 out.targetKey = ne->key;
880 }
881 else if (ev->type == CLAP_EVENT_MIDI)
882 {
883 const auto* midi = reinterpret_cast<const clap_event_midi_t*>(ev);
884 const uint8_t status = midi->data[0] & 0xF0u;
885 const uint8_t channel = midi->data[0] & 0x0Fu;
886 const uint8_t d1 = midi->data[1] & 0x7Fu;
887 const uint8_t d2 = midi->data[2] & 0x7Fu;
888 out.midi.channel = channel;
889 switch (status)
890 {
891 case 0x90: // wire convention: velocity 0 means note off
892 out.midi.type = d2 > 0 ? MidiEvent::Type::NoteOn
894 out.midi.note = d1;
895 out.midi.value = static_cast<float>(d2) / 127.0f;
896 if (d2 > 0) sounding.noteOn(channel, d1, -1);
897 else sounding.noteOff(channel, d1);
898 break;
899 case 0x80:
900 out.midi.type = MidiEvent::Type::NoteOff;
901 out.midi.note = d1;
902 out.midi.value = static_cast<float>(d2) / 127.0f;
903 sounding.noteOff(channel, d1);
904 break;
905 case 0xA0:
906 out.midi.type = MidiEvent::Type::PolyPressure;
907 out.midi.note = d1;
908 out.midi.value = static_cast<float>(d2) / 127.0f;
909 break;
910 case 0xB0:
911 out.midi.type = MidiEvent::Type::ControlChange;
912 out.midi.note = d1;
913 out.midi.value = static_cast<float>(d2) / 127.0f;
914 break;
915 case 0xD0:
916 out.midi.type = MidiEvent::Type::ChannelPressure;
917 out.midi.value = static_cast<float>(d1) / 127.0f;
918 break;
919 case 0xE0:
920 out.midi.type = MidiEvent::Type::PitchBend;
921 out.midi.value = (static_cast<float>((d2 << 7) | d1) - 8192.0f)
922 / 8192.0f;
923 break;
924 default:
925 return;
926 }
927 }
928 else
929 return;
930 }
931 else
932 return;
933
934 // Past the capacity an intermediate parameter point gives way; the
935 // old code overwrote the last slot, losing every event but the final
936 // one - note-offs and final parameter values included.
937 events.add(out);
938 }
939
940 void collectEvents(const clap_input_events_t* in, uint32_t numSamples,
941 BlockEventList& events) noexcept
942 {
943 if (in == nullptr) return;
944 const uint32_t n = in->size(in);
945 for (uint32_t i = 0; i < n; ++i)
946 collectEvent(in->get(in, i), numSamples, events);
947 }
948
951 bool applyBlockEvent(const BlockEvent& ev, int blockStart) noexcept
952 {
953 switch (ev.kind)
954 {
956 bypass.store(ev.value >= 0.5, std::memory_order_relaxed);
957 return false;
959 if constexpr (HasMidi<P>)
960 {
961 MidiEvent midi = ev.midi;
962 midi.sampleOffset = ev.offset - blockStart;
963 if (midi.sampleOffset < 0) midi.sampleOffset = 0;
966 applyVoiceEvent(ev, midi);
967 else
968 {
969 user.handleMidiEvent(midi);
970 trackVoice(midi);
971 }
972 }
973 return false;
975 if (const int idx = indexOfParamId(ev.paramId); idx >= 0)
976 {
977 modulation[static_cast<size_t>(idx)] = ev.value;
978 user.setParameter(idx, static_cast<float>(heardPlain(
979 idx, shadow[static_cast<size_t>(idx)].load(std::memory_order_relaxed))));
980 const int offset = ev.offset - blockStart;
981 resendVoiceModulation(idx, offset < 0 ? 0 : offset, true);
982 return true;
983 }
984 return false;
986 default:
987 if (const int idx = indexOfParamId(ev.paramId); idx >= 0)
988 {
989 applyNormalized(idx, ev.value);
990 const int offset = ev.offset - blockStart;
991 resendVoiceModulation(idx, offset < 0 ? 0 : offset, false);
992 return true;
993 }
994 return false;
995 }
996 }
997
999 void forwardTransport(const clap_event_transport_t* t) noexcept
1000 {
1001 if constexpr (HasTransport<P>)
1002 {
1003 if (t == nullptr) return;
1004 constexpr double kBeatFactor = static_cast<double>(CLAP_BEATTIME_FACTOR);
1005 TransportInfo info {};
1006 info.playing = (t->flags & CLAP_TRANSPORT_IS_PLAYING) != 0;
1007 info.recording = (t->flags & CLAP_TRANSPORT_IS_RECORDING) != 0;
1008 info.looping = (t->flags & CLAP_TRANSPORT_IS_LOOP_ACTIVE) != 0;
1009 if ((t->flags & CLAP_TRANSPORT_HAS_TEMPO) != 0)
1010 {
1011 info.tempoBpm = t->tempo;
1012 info.tempoValid = true;
1013 }
1014 if ((t->flags & CLAP_TRANSPORT_HAS_BEATS_TIMELINE) != 0)
1015 {
1016 info.ppqPosition = static_cast<double>(t->song_pos_beats) / kBeatFactor;
1017 info.barStartPpq = static_cast<double>(t->bar_start) / kBeatFactor;
1018 info.positionValid = true;
1019 info.loopStartPpq =
1020 static_cast<double>(t->loop_start_beats) / kBeatFactor;
1021 info.loopEndPpq = static_cast<double>(t->loop_end_beats) / kBeatFactor;
1022 info.loopValid = true;
1023 }
1024 if ((t->flags & CLAP_TRANSPORT_HAS_TIME_SIGNATURE) != 0)
1025 {
1026 info.timeSigNumerator = t->tsig_num;
1027 info.timeSigDenominator = t->tsig_denom;
1028 info.timeSigValid = true;
1029 }
1030 user.setTransport(info);
1031 }
1032 else
1033 (void) t;
1034 }
1035
1036#if defined(DSPARK_PLUGIN_WEBVIEW)
1037 // --- UI -> host parameter events ---------------------------------------------
1038
1039 void pushUiEvent(uint32_t paramId, uint8_t kind, double value) noexcept
1040 {
1041 const uint32_t tail = uiTail.load(std::memory_order_relaxed);
1042 const uint32_t next = (tail + 1) & (kUiQueueSize - 1);
1043 if (next == uiHead.load(std::memory_order_acquire)) return; // full: drop
1044 uiQueue[tail] = UiEvent { paramId, kind, value };
1045 uiTail.store(next, std::memory_order_release);
1046 }
1047
1048 void requestUiFlush() noexcept
1049 {
1050 // Host schedules process()/flush(), which drains the queue below.
1051 if (hostParams != nullptr && host != nullptr)
1052 hostParams->request_flush(host);
1053 }
1054
1055 void drainUiEvents(const clap_output_events_t* out) noexcept
1056 {
1057 if (out == nullptr) return;
1058 uint32_t head = uiHead.load(std::memory_order_relaxed);
1059 const uint32_t tail = uiTail.load(std::memory_order_acquire);
1060 while (head != tail)
1061 {
1062 const UiEvent& e = uiQueue[head];
1063 if (e.kind == kUiValue)
1064 {
1065 clap_event_param_value_t ev {};
1066 ev.header.size = sizeof(ev);
1067 ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
1068 ev.header.type = CLAP_EVENT_PARAM_VALUE;
1069 ev.param_id = e.paramId;
1070 ev.note_id = -1;
1071 ev.port_index = -1;
1072 ev.channel = -1;
1073 ev.key = -1;
1074 ev.value = e.value;
1075 out->try_push(out, &ev.header);
1076 }
1077 else
1078 {
1079 clap_event_param_gesture_t ev {};
1080 ev.header.size = sizeof(ev);
1081 ev.header.space_id = CLAP_CORE_EVENT_SPACE_ID;
1082 ev.header.type = static_cast<uint16_t>(
1083 e.kind == kUiGestureBegin ? CLAP_EVENT_PARAM_GESTURE_BEGIN
1084 : CLAP_EVENT_PARAM_GESTURE_END);
1085 ev.param_id = e.paramId;
1086 out->try_push(out, &ev.header);
1087 }
1088 head = (head + 1) & (kUiQueueSize - 1);
1089 }
1090 uiHead.store(head, std::memory_order_release);
1091 }
1092#endif // DSPARK_PLUGIN_WEBVIEW
1093
1094 // --- clap_plugin_t callbacks ------------------------------------------------
1095
1096 static bool sInit(const clap_plugin_t* p) noexcept
1097 {
1098 auto* s = self(p);
1099 if (s->host != nullptr)
1100 {
1101 s->hostParams = static_cast<const clap_host_params_t*>(
1102 s->host->get_extension(s->host, CLAP_EXT_PARAMS));
1103 s->hostLatency = static_cast<const clap_host_latency_t*>(
1104 s->host->get_extension(s->host, CLAP_EXT_LATENCY));
1105 if constexpr (kNumPresets > 0)
1106 s->hostPresetLoad = static_cast<const clap_host_preset_load_t*>(
1107 s->host->get_extension(s->host, CLAP_EXT_PRESET_LOAD));
1108#if defined(DSPARK_PLUGIN_WEBVIEW)
1109 if constexpr (HasEditor<P>)
1110 s->hostGui = static_cast<const clap_host_gui_t*>(
1111 s->host->get_extension(s->host, CLAP_EXT_GUI));
1112#endif
1113 }
1114 return true;
1115 }
1116
1117 static void sDestroy(const clap_plugin_t* p) noexcept { delete self(p); }
1118
1119 static bool sActivate(const clap_plugin_t* p, double sr,
1120 uint32_t, uint32_t maxFrames) noexcept
1121 {
1122 auto* s = self(p);
1123 s->sampleRate = sr;
1124 s->maxFrames = maxFrames;
1125 dspark::AudioSpec spec { sr, static_cast<int>(maxFrames), s->currentChannels };
1126 s->user.prepare(spec);
1127 if constexpr (HasOfflineMode<P>)
1128 s->user.setOfflineRendering(s->offlineRender);
1129 s->pending.drain([](int) {}); // every value is re-applied right below
1130 for (size_t i = 0; i < kNumParams; ++i)
1131 s->user.setParameter(static_cast<int>(i),
1132 static_cast<float>(s->heardPlain(static_cast<int>(i),
1133 s->shadow[i].load(std::memory_order_relaxed))));
1134 s->dryL.assign(maxFrames, 0.0f);
1135 s->dryR.assign(maxFrames, 0.0f);
1136 if constexpr (HasSidechain<P>)
1137 s->silence.assign(maxFrames, 0.0f);
1138 s->bypassMix = s->bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1139 s->sounding.clear();
1140 s->voices.clear();
1141 s->endedCount = 0;
1142 if constexpr (HasLatency<P>)
1143 {
1144 const int latency = s->user.getLatency();
1145 s->cachedLatency.store(latency, std::memory_order_relaxed);
1146 s->dryDelay.prepare(std::max(2 * latency, kDryDelayMinCapacity),
1147 static_cast<int>(maxFrames));
1148 // clap_host_latency.changed is [main-thread & being-activated]:
1149 // this is the one place it may be called.
1150 s->latencyDirty.store(false, std::memory_order_relaxed);
1151 if (latency != s->latencyAtActivate && s->hostLatency != nullptr
1152 && s->hostLatency->changed != nullptr)
1153 s->hostLatency->changed(s->host);
1154 s->latencyAtActivate = latency;
1155 }
1156 s->prepared = true;
1157 s->active.store(true, std::memory_order_release);
1158 return true;
1159 }
1160
1161 static void sDeactivate(const clap_plugin_t* p) noexcept
1162 {
1163 auto* s = self(p);
1164 s->active.store(false, std::memory_order_release);
1165 s->voices.clear(); // the host retires its voices with the activation
1166 s->endedCount = 0;
1167 s->drainPending(); // no process()/flush() can run now (main thread)
1168 }
1169
1173 static bool sStartProcessing(const clap_plugin_t* p) noexcept
1174 {
1175 sReset(p);
1176 return true;
1177 }
1178 static void sStopProcessing(const clap_plugin_t*) noexcept {}
1179
1180 static void sReset(const clap_plugin_t* p) noexcept
1181 {
1182 auto* s = self(p);
1183 if constexpr (HasReset<P>)
1184 s->user.reset();
1185 s->dryDelay.reset();
1186 s->sounding.clear();
1187 s->voices.clear(); // reset kills every voice (CLAP reset contract)
1188 s->endedCount = 0;
1189 s->bypassMix = s->bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1190 }
1191
1194 void blendBypass(float* const* out, float* const* dry, uint32_t nCh, int outStart,
1195 int dryStart, int length) noexcept
1196 {
1197 const float target = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1198 if (bypassMix == target && target == 0.0f) return;
1199 const float step = 1.0f / static_cast<float>(kBypassRampSamples);
1200 float mix = bypassMix;
1201 for (int i = 0; i < length; ++i)
1202 {
1203 mix += (target > mix) ? step : ((target < mix) ? -step : 0.0f);
1204 mix = mix < 0.0f ? 0.0f : (mix > 1.0f ? 1.0f : mix);
1205 for (uint32_t ch = 0; ch < nCh; ++ch)
1206 out[ch][outStart + i] += (dry[ch][dryStart + i] - out[ch][outStart + i]) * mix;
1207 }
1208 bypassMix = mix;
1209 }
1210
1211 static clap_process_status sProcess(const clap_plugin_t* p,
1212 const clap_process_t* process) noexcept
1213 {
1214 auto* s = self(p);
1215
1216 // FTZ/DAZ for the whole callback: DSPark processors guard their own
1217 // hot loops, this covers user DSP in hosts that do not set it.
1218 dspark::DenormalGuard denormalGuard;
1219
1220#if defined(DSPARK_PLUGIN_WEBVIEW)
1221 s->drainUiEvents(process->out_events);
1222#endif
1223
1224 const uint32_t n = process->frames_count;
1225
1226 // Main-thread edits handed over since the last block go first, so
1227 // the host's own events below still win.
1228 bool paramsChanged = s->drainPending();
1229
1230 BlockEventList& events = s->blockEvents;
1231 events.clear();
1232 s->collectEvents(process->in_events, n, events);
1233 events.sort();
1234 const int eventCount = events.size();
1235
1236 const clap_audio_buffer_t* outPort =
1237 process->audio_outputs_count >= 1 && process->audio_outputs != nullptr
1238 ? &process->audio_outputs[0] : nullptr;
1239 float** out = outPort != nullptr ? outPort->data32 : nullptr;
1240 const uint32_t width = static_cast<uint32_t>(s->currentChannels);
1241 uint32_t nCh = out == nullptr ? 0u
1242 : (outPort->channel_count < width ? outPort->channel_count : width);
1243 // Degenerate hosts: stop at the first missing channel pointer (the
1244 // old trim only looked at the last one and wrote through a null left
1245 // channel next to a valid right one).
1246 for (uint32_t ch = 0; ch < nCh; ++ch)
1247 if (out[ch] == nullptr)
1248 {
1249 nCh = ch;
1250 break;
1251 }
1252
1253 const bool canRender = n > 0 && s->prepared && nCh >= 1;
1254 if (!canRender)
1255 {
1256 for (int i = 0; i < eventCount; ++i)
1257 paramsChanged |= s->applyBlockEvent(events[i], events[i].offset);
1258 if (paramsChanged) s->refreshLatency();
1259 s->flushEndedVoices(process->out_events, 0);
1260 return CLAP_PROCESS_CONTINUE;
1261 }
1262
1263 s->forwardTransport(process->transport);
1264
1265 const bool haveIn = !kIsInstrument && process->audio_inputs_count >= 1
1266 && process->audio_inputs != nullptr
1267 && process->audio_inputs[0].data32 != nullptr
1268 && process->audio_inputs[0].channel_count >= 1;
1269 float** in = haveIn ? process->audio_inputs[0].data32 : nullptr;
1270 const uint32_t inCh = haveIn ? process->audio_inputs[0].channel_count : 0;
1271
1272 // Sidechain: input port 1, pre-allocated silence when not routed.
1273 float* scHost[2] = { nullptr, nullptr };
1274 if constexpr (HasSidechain<P>)
1275 {
1276 if (process->audio_inputs_count >= 2
1277 && process->audio_inputs[1].data32 != nullptr)
1278 {
1279 const auto& scPort = process->audio_inputs[1];
1280 const uint32_t scCh = scPort.channel_count < 2
1281 ? scPort.channel_count : 2;
1282 for (uint32_t ch = 0; ch < scCh; ++ch)
1283 scHost[ch] = scPort.data32[ch];
1284 if (scCh == 1)
1285 scHost[1] = scPort.data32[0]; // mono key feeds both ears
1286 }
1287 }
1288
1289 // A block longer than the activated maximum runs as consecutive
1290 // chunks of at most that size: the user DSP never sees more frames
1291 // than it prepared for.
1292 const int total = static_cast<int>(n);
1293 const int chunkMax = static_cast<int>(s->dryL.size());
1294 if (chunkMax < 1) return CLAP_PROCESS_CONTINUE;
1295 float* dry[2] = { s->dryL.data(), s->dryR.data() };
1296 int evIdx = 0;
1297
1298 for (int c0 = 0; c0 < total; c0 += chunkMax)
1299 {
1300 const int len = total - c0 < chunkMax ? total - c0 : chunkMax;
1301 const int cEnd = c0 + len;
1302
1303 // Dry copy for the bypass blend; instruments start cleared (voices
1304 // ADD) and bypass toward silence (their dry vectors stay zero).
1305 // Output channels past a narrower input port repeat its last one.
1306 // An effect whose input is missing processes silence: the old
1307 // code fell back to the output buffer, feeding the host's stale
1308 // output back in as input.
1309 const size_t bytes = sizeof(float) * static_cast<size_t>(len);
1310 for (uint32_t ch = 0; ch < nCh; ++ch)
1311 {
1312 const float* src = nullptr;
1313 if (!kIsInstrument && haveIn)
1314 src = in[ch < inCh ? ch : inCh - 1];
1315 if (src == nullptr)
1316 {
1317 std::memset(out[ch] + c0, 0, bytes);
1318 if (!kIsInstrument) std::memset(dry[ch], 0, bytes);
1319 continue;
1320 }
1321 std::memcpy(dry[ch], src + c0, bytes);
1322 if (out[ch] != src)
1323 std::memcpy(out[ch] + c0, src + c0, bytes);
1324 }
1325 if constexpr (HasLatency<P> && !kIsInstrument)
1326 s->dryDelay.process(dry, static_cast<int>(nCh), len,
1327 s->cachedLatency.load(std::memory_order_relaxed));
1328
1329 float* scChunk[2] = { nullptr, nullptr };
1330 if constexpr (HasSidechain<P>)
1331 for (int ch = 0; ch < 2; ++ch)
1332 scChunk[ch] = scHost[ch] != nullptr ? scHost[ch] + c0
1333 : s->silence.data();
1334
1335 // Sub-block processing at quantum-aligned event positions (the
1336 // sample-accurate default); opted out, the chunk's events apply
1337 // up front.
1338 auto processSegment = [&](int start, int length) noexcept {
1339 float* sub[2] = { out[0] + start,
1340 nCh > 1 ? out[1] + start : out[0] + start };
1341 dspark::AudioBufferView<float> view(sub, static_cast<int>(nCh), length);
1342 if constexpr (HasSidechain<P>)
1343 {
1344 // The key view mirrors the main width (mono main, mono key).
1345 float* scSub[2] = { scChunk[0] + (start - c0),
1346 scChunk[1] + (start - c0) };
1347 dspark::AudioBufferView<float> scView(scSub,
1348 static_cast<int>(nCh), length);
1349 s->user.processBlock(view, scView);
1350 }
1351 else
1352 s->user.processBlock(view);
1353 // Soft bypass toward the (latency-aligned) dry signal, per
1354 // segment: the crossfade starts where the bypass event lands
1355 // (the old once-per-block blend started it at sample 0).
1356 s->blendBypass(out, dry, nCh, start, start - c0, length);
1357 };
1358
1359 if (!sampleAccurateOf<P>())
1360 {
1361 for (; evIdx < eventCount && events[evIdx].offset < cEnd; ++evIdx)
1362 paramsChanged |= s->applyBlockEvent(events[evIdx], c0);
1363 processSegment(c0, len);
1364 }
1365 else
1366 {
1367 int pos = c0;
1368 while (pos < cEnd)
1369 {
1370 while (evIdx < eventCount
1371 && (events[evIdx].offset / kAutomationQuantum)
1372 * kAutomationQuantum <= pos)
1373 paramsChanged |= s->applyBlockEvent(events[evIdx++], pos);
1374 int next = cEnd;
1375 if (evIdx < eventCount)
1376 {
1377 const int snapped = (events[evIdx].offset / kAutomationQuantum)
1379 if (snapped < next) next = snapped;
1380 }
1381 if (next <= pos) next = pos + kAutomationQuantum < cEnd
1382 ? pos + kAutomationQuantum : cEnd;
1383 processSegment(pos, next - pos);
1384 pos = next;
1385 }
1386 }
1387 }
1388 for (; evIdx < eventCount; ++evIdx) // safety: events at block end
1389 paramsChanged |= s->applyBlockEvent(events[evIdx], total);
1390
1391 if (paramsChanged) s->refreshLatency();
1392 s->pollVoices();
1393 s->flushEndedVoices(process->out_events, n - 1);
1394 return CLAP_PROCESS_CONTINUE;
1395 }
1396
1397 static const void* sGetExtension(const clap_plugin_t*, const char* id) noexcept
1398 {
1399 if (std::strcmp(id, CLAP_EXT_AUDIO_PORTS) == 0) return &kAudioPorts;
1400 if (std::strcmp(id, CLAP_EXT_PARAMS) == 0) return &kParams;
1401 if (std::strcmp(id, CLAP_EXT_STATE) == 0) return &kState;
1402 if (std::strcmp(id, CLAP_EXT_LATENCY) == 0) return &kLatency;
1403 if (std::strcmp(id, CLAP_EXT_TAIL) == 0) return &kTail;
1404 if (channelSupportOf<P>() == ChannelSupport::MonoAndStereo)
1405 {
1406 if (std::strcmp(id, CLAP_EXT_AUDIO_PORTS_CONFIG) == 0)
1407 return &kPortsConfig;
1408 if (std::strcmp(id, CLAP_EXT_AUDIO_PORTS_CONFIG_INFO) == 0
1409 || std::strcmp(id, CLAP_EXT_AUDIO_PORTS_CONFIG_INFO_COMPAT) == 0)
1410 return &kPortsConfigInfo;
1411 }
1412 if constexpr (HasMidi<P>)
1413 if (std::strcmp(id, CLAP_EXT_NOTE_PORTS) == 0) return &kNotePorts;
1414 if constexpr (HasOfflineMode<P>)
1415 if (std::strcmp(id, CLAP_EXT_RENDER) == 0) return &kRender;
1416 if constexpr (kNumPresets > 0)
1417 if (std::strcmp(id, CLAP_EXT_PRESET_LOAD) == 0
1418 || std::strcmp(id, CLAP_EXT_PRESET_LOAD_COMPAT) == 0)
1419 return &kPresetLoad;
1420#if defined(DSPARK_PLUGIN_WEBVIEW)
1421 if constexpr (HasEditor<P>)
1422 {
1423 if (webview_ui::Editor<P>::available() && std::strcmp(id, CLAP_EXT_GUI) == 0)
1424 return &kGui;
1425#if defined(__linux__)
1427 && std::strcmp(id, CLAP_EXT_TIMER_SUPPORT) == 0)
1428 return &kTimer;
1429#endif
1430 }
1431#endif
1432 return nullptr;
1433 }
1434
1435 static void sOnMainThread(const clap_plugin_t* p) noexcept
1436 {
1437 // Deferred latency notification (the audio thread only flags it).
1438 // clap_host_latency.changed is [main-thread & being-activated]: while
1439 // active the plugin must ask for a restart instead, and the host's
1440 // deactivate/activate cycle then lets activate() report the new
1441 // value. The old code called changed() here, outside activation,
1442 // which a conforming host ignores - the delay compensation never
1443 // followed a lookahead change.
1444 auto* s = self(p);
1445 if (!s->latencyDirty.exchange(false, std::memory_order_acq_rel)) return;
1446 if (s->active.load(std::memory_order_acquire))
1447 {
1448 if (s->host != nullptr && s->host->request_restart != nullptr)
1449 s->host->request_restart(s->host);
1450 }
1451 // Inactive: the next activate() reports the latency itself.
1452 }
1453
1454 // --- ext: audio ports ---------------------------------------------------------
1455
1456 static uint32_t sPortCount(const clap_plugin_t*, bool isInput) noexcept
1457 {
1458 if (isInput)
1459 {
1460 if (kIsInstrument) return 0;
1461 return HasSidechain<P> ? 2 : 1;
1462 }
1463 return 1;
1464 }
1465
1466 static bool sPortGet(const clap_plugin_t* p, uint32_t index, bool isInput,
1467 clap_audio_port_info_t* info) noexcept
1468 {
1469 if (info == nullptr || index >= sPortCount(p, isInput)) return false;
1470 const int width = self(p)->currentChannels;
1471 std::memset(info, 0, sizeof(*info));
1472 if (isInput && index == 1) // the sidechain: routable, never the main pair
1473 {
1474 info->id = 2;
1475 std::snprintf(info->name, sizeof(info->name), "Sidechain");
1476 info->flags = 0;
1477 info->channel_count = static_cast<uint32_t>(width);
1478 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1479 info->in_place_pair = CLAP_INVALID_ID;
1480 return true;
1481 }
1482 info->id = isInput ? 0 : 1;
1483 std::snprintf(info->name, sizeof(info->name), "%s",
1484 isInput ? "Input" : "Output");
1485 info->flags = CLAP_AUDIO_PORT_IS_MAIN;
1486 info->channel_count = static_cast<uint32_t>(width);
1487 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1488 info->in_place_pair = kIsInstrument ? CLAP_INVALID_ID
1489 : (isInput ? 1u : 0u);
1490 return true;
1491 }
1492
1493 inline static const clap_plugin_audio_ports_t kAudioPorts = { &sPortCount, &sPortGet };
1494
1495 // --- ext: audio ports config (mono / stereo selection) --------------------------
1496
1497 static uint32_t sConfigCount(const clap_plugin_t*) noexcept { return 2; }
1498
1499 static void fillConfig(clap_audio_ports_config_t* config, int width) noexcept
1500 {
1501 std::memset(config, 0, sizeof(*config));
1502 config->id = static_cast<clap_id>(width);
1503 std::snprintf(config->name, sizeof(config->name), "%s",
1504 width == 1 ? "Mono" : "Stereo");
1505 config->input_port_count = sPortCount(nullptr, true);
1506 config->output_port_count = 1;
1507 config->has_main_input = !kIsInstrument;
1508 config->main_input_channel_count = static_cast<uint32_t>(width);
1509 config->main_input_port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1510 config->has_main_output = true;
1511 config->main_output_channel_count = static_cast<uint32_t>(width);
1512 config->main_output_port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1513 }
1514
1515 static bool sConfigGet(const clap_plugin_t*, uint32_t index,
1516 clap_audio_ports_config_t* config) noexcept
1517 {
1518 if (config == nullptr || index >= 2) return false;
1519 fillConfig(config, index == 0 ? 1 : 2);
1520 return true;
1521 }
1522
1523 static bool sConfigSelect(const clap_plugin_t* p, clap_id configId) noexcept
1524 {
1525 const int width = static_cast<int>(configId);
1526 if (!supportsChannelCount<P>(width)) return false;
1527 self(p)->currentChannels = width;
1528 return true;
1529 }
1530
1531 inline static const clap_plugin_audio_ports_config_t kPortsConfig = {
1533 };
1534
1535 static clap_id sConfigCurrent(const clap_plugin_t* p) noexcept
1536 {
1537 return static_cast<clap_id>(self(p)->currentChannels);
1538 }
1539
1540 static bool sConfigInfoGet(const clap_plugin_t* p, clap_id configId,
1541 uint32_t portIndex, bool isInput,
1542 clap_audio_port_info_t* info) noexcept
1543 {
1544 const int width = static_cast<int>(configId);
1545 if (info == nullptr || !supportsChannelCount<P>(width)
1546 || portIndex >= sPortCount(p, isInput))
1547 return false;
1548 // Same shape as sPortGet, with the width of the asked-about config.
1549 std::memset(info, 0, sizeof(*info));
1550 if (isInput && portIndex == 1)
1551 {
1552 info->id = 2;
1553 std::snprintf(info->name, sizeof(info->name), "Sidechain");
1554 info->channel_count = static_cast<uint32_t>(width);
1555 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1556 info->in_place_pair = CLAP_INVALID_ID;
1557 return true;
1558 }
1559 info->id = isInput ? 0 : 1;
1560 std::snprintf(info->name, sizeof(info->name), "%s",
1561 isInput ? "Input" : "Output");
1562 info->flags = CLAP_AUDIO_PORT_IS_MAIN;
1563 info->channel_count = static_cast<uint32_t>(width);
1564 info->port_type = width == 1 ? CLAP_PORT_MONO : CLAP_PORT_STEREO;
1565 info->in_place_pair = kIsInstrument ? CLAP_INVALID_ID
1566 : (isInput ? 1u : 0u);
1567 return true;
1568 }
1569
1570 inline static const clap_plugin_audio_ports_config_info_t kPortsConfigInfo = {
1572 };
1573
1574 // --- ext: note ports (HasMidi) ----------------------------------------------------
1575
1576 static uint32_t sNotePortCount(const clap_plugin_t*, bool isInput) noexcept
1577 {
1578 return (HasMidi<P> && isInput) ? 1 : 0;
1579 }
1580
1581 static bool sNotePortGet(const clap_plugin_t*, uint32_t index, bool isInput,
1582 clap_note_port_info_t* info) noexcept
1583 {
1584 if (info == nullptr || !isInput || index != 0 || !HasMidi<P>) return false;
1585 std::memset(info, 0, sizeof(*info));
1586 info->id = 10;
1587 info->supported_dialects = CLAP_NOTE_DIALECT_CLAP | CLAP_NOTE_DIALECT_MIDI;
1588 info->preferred_dialect = CLAP_NOTE_DIALECT_CLAP;
1589 std::snprintf(info->name, sizeof(info->name), "MIDI In");
1590 return true;
1591 }
1592
1593 inline static const clap_plugin_note_ports_t kNotePorts = {
1595 };
1596
1597 // --- ext: render (HasOfflineMode) ---------------------------------------------------
1598
1599 static bool sRenderHardRealtime(const clap_plugin_t*) noexcept { return false; }
1600
1601 static bool sRenderSet(const clap_plugin_t* p, clap_plugin_render_mode mode) noexcept
1602 {
1603 auto* s = self(p);
1604 s->offlineRender = mode == CLAP_RENDER_OFFLINE;
1605 if constexpr (HasOfflineMode<P>)
1606 s->user.setOfflineRendering(s->offlineRender);
1607 return true;
1608 }
1609
1610 inline static const clap_plugin_render_t kRender = {
1612 };
1613
1614 // --- ext: preset load (factory presets; the DSO is the container) -------------------
1615
1616 static bool sPresetFromLocation(const clap_plugin_t* p, uint32_t locationKind,
1617 const char* location, const char* loadKey) noexcept
1618 {
1619 if constexpr (kNumPresets > 0)
1620 {
1621 auto* s = self(p);
1622 if (locationKind != CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN
1623 || loadKey == nullptr)
1624 return false;
1625 const int idx = std::atoi(loadKey);
1626 if (idx < 0 || idx >= kNumPresets) return false;
1627 s->applyFactoryPresetIdx(idx);
1628 s->refreshLatency();
1629 if (s->hostParams != nullptr && s->hostParams->rescan != nullptr)
1630 s->hostParams->rescan(s->host, CLAP_PARAM_RESCAN_VALUES);
1631 if (s->hostPresetLoad != nullptr && s->hostPresetLoad->loaded != nullptr)
1632 s->hostPresetLoad->loaded(s->host, locationKind, location, loadKey);
1633 return true;
1634 }
1635 else
1636 {
1637 (void) p;
1638 (void) locationKind;
1639 (void) location;
1640 (void) loadKey;
1641 return false;
1642 }
1643 }
1644
1645 inline static const clap_plugin_preset_load_t kPresetLoad = {
1647 };
1648
1649 // --- ext: params ----------------------------------------------------------------
1650
1651 static uint32_t sParamCount(const clap_plugin_t*) noexcept
1652 {
1653 return static_cast<uint32_t>(kNumParams) + 1; // + Bypass
1654 }
1655
1659 static constexpr bool isIntegerGrid(const Param& spec) noexcept
1660 {
1661 auto whole = [](double v) {
1662 const double r = static_cast<double>(static_cast<long long>(v < 0.0 ? v - 0.5
1663 : v + 0.5));
1664 return v - r < 1e-9 && r - v < 1e-9;
1665 };
1666 const double step = (static_cast<double>(spec.maxValue) - spec.minValue) / spec.steps;
1667 return whole(spec.minValue) && step > 1.0 - 1e-9 && step < 1.0 + 1e-9;
1668 }
1669
1670 static bool sParamInfo(const clap_plugin_t*, uint32_t index,
1671 clap_param_info_t* info) noexcept
1672 {
1673 if (info == nullptr || index > kNumParams) return false;
1674 std::memset(info, 0, sizeof(*info));
1675 if (index == kNumParams)
1676 {
1677 info->id = kBypassParamId;
1678 std::snprintf(info->name, sizeof(info->name), "Bypass");
1679 info->flags = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_IS_STEPPED
1680 | CLAP_PARAM_IS_BYPASS;
1681 info->min_value = 0.0;
1682 info->max_value = 1.0;
1683 info->default_value = 0.0;
1684 return true;
1685 }
1686 const auto& spec = P::parameters[index];
1687 info->id = hash32(spec.id);
1688 std::snprintf(info->name, sizeof(info->name), "%s", spec.name);
1689 info->flags = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_IS_MODULATABLE;
1690 // CLAP_PARAM_IS_STEPPED means "integer values only": hosts truncate.
1691 // Only a grid of whole numbers one apart qualifies (toggles, choices,
1692 // stepped 1..8). A finer or coarser grid stays continuous for the
1693 // host and is snapped by the wrapper; flagging it (the old code)
1694 // made a 5-position 0..1 control offer two positions.
1695 if (spec.steps > 0 && isIntegerGrid(spec)) info->flags |= CLAP_PARAM_IS_STEPPED;
1696 if (spec.labels != nullptr) info->flags |= CLAP_PARAM_IS_ENUM;
1697 // perVoice(): every modulation addressing form CLAP defines, and
1698 // per-note automation by note id, key and channel - the wrapper
1699 // resolves each one to the voices it matches. (Per-port automation
1700 // is not declared: with one note port it would mean every voice,
1701 // and hosts that fill the port of a global point keep working.)
1702 if (HasMidi<P> && spec.perVoice)
1703 info->flags |= CLAP_PARAM_IS_MODULATABLE_PER_NOTE_ID
1704 | CLAP_PARAM_IS_MODULATABLE_PER_KEY
1705 | CLAP_PARAM_IS_MODULATABLE_PER_CHANNEL
1706 | CLAP_PARAM_IS_MODULATABLE_PER_PORT
1707 | CLAP_PARAM_IS_AUTOMATABLE_PER_NOTE_ID
1708 | CLAP_PARAM_IS_AUTOMATABLE_PER_KEY
1709 | CLAP_PARAM_IS_AUTOMATABLE_PER_CHANNEL;
1710 info->min_value = spec.minValue;
1711 info->max_value = spec.maxValue;
1712 info->default_value = spec.defValue;
1713 return true;
1714 }
1715
1716 static bool sParamValue(const clap_plugin_t* p, clap_id id, double* out) noexcept
1717 {
1718 auto* s = self(p);
1719 if (out == nullptr) return false;
1720 if (id == kBypassParamId)
1721 {
1722 *out = s->bypass.load(std::memory_order_relaxed) ? 1.0 : 0.0;
1723 return true;
1724 }
1725 const int idx = indexOfParamId(id);
1726 if (idx < 0) return false;
1727 *out = toPlain(P::parameters[static_cast<size_t>(idx)],
1728 s->shadow[static_cast<size_t>(idx)].load(std::memory_order_relaxed));
1729 return true;
1730 }
1731
1732 static bool sParamValueToText(const clap_plugin_t*, clap_id id, double value,
1733 char* out, uint32_t size) noexcept
1734 {
1735 if (out == nullptr || size == 0) return false;
1736 if (id == kBypassParamId)
1737 {
1738 std::snprintf(out, size, "%s", value >= 0.5 ? "On" : "Off");
1739 return true;
1740 }
1741 const int idx = indexOfParamId(id);
1742 if (idx < 0) return false;
1743 formatValue(P::parameters[static_cast<size_t>(idx)], value, out,
1744 static_cast<int>(size));
1745 return true;
1746 }
1747
1748 static bool sParamTextToValue(const clap_plugin_t*, clap_id id,
1749 const char* text, double* out) noexcept
1750 {
1751 if (text == nullptr || out == nullptr) return false;
1752 const int toggle = parseToggleText(text);
1753 if (id == kBypassParamId)
1754 {
1755 *out = toggle >= 0 ? toggle
1756 : (std::strtod(text, nullptr) >= 0.5 ? 1.0 : 0.0);
1757 return true;
1758 }
1759 const int idx = indexOfParamId(id);
1760 if (idx < 0) return false;
1761 // Labels, On/Off or a number, clamped and snapped; "nan" and other
1762 // garbage are refused rather than passed through to the host.
1763 return parseValue(P::parameters[static_cast<size_t>(idx)], text, *out);
1764 }
1765
1766 static void sParamFlush(const clap_plugin_t* p, const clap_input_events_t* in,
1767 const clap_output_events_t* out) noexcept
1768 {
1769 auto* s = self(p);
1770 // [active ? audio-thread : main-thread], never concurrent with
1771 // process(): the place deferred main-thread edits land while the
1772 // transport is stopped.
1773 bool paramsChanged = s->drainPending();
1774 BlockEventList& events = s->blockEvents;
1775 events.clear();
1776 s->collectEvents(in, 0, events);
1777 events.sort();
1778 for (int i = 0; i < events.size(); ++i)
1779 paramsChanged |= s->applyBlockEvent(events[i], events[i].offset);
1780 if (paramsChanged) s->refreshLatency();
1781 s->flushEndedVoices(out, 0);
1782#if defined(DSPARK_PLUGIN_WEBVIEW)
1783 s->drainUiEvents(out);
1784#endif
1785 }
1786
1787 inline static const clap_plugin_params_t kParams = {
1790 };
1791
1792 // --- ext: state -------------------------------------------------------------------
1793
1794 static bool sStateSave(const clap_plugin_t* p, const clap_ostream_t* stream) noexcept
1795 {
1796 auto* s = self(p);
1797 double norm[kNumParams == 0 ? 1 : kNumParams];
1798 for (size_t i = 0; i < kNumParams; ++i)
1799 norm[i] = s->shadow[i].load(std::memory_order_relaxed);
1800 EditorSize editorSize {};
1801 const bool withSize = s->editorMemory.remembered(editorSize);
1802 const std::vector<uint8_t> blob = buildState(
1803 s->user, norm, kNumParams,
1804 kNumPresets > 0 ? s->currentProgram.load(std::memory_order_relaxed) : -1,
1805 s->bypass.load(std::memory_order_relaxed) ? 1 : 0,
1806 withSize ? &editorSize : nullptr);
1807 size_t pos = 0;
1808 while (pos < blob.size())
1809 {
1810 const int64_t put = stream->write(stream, blob.data() + pos,
1811 blob.size() - pos);
1812 if (put <= 0) return false;
1813 pos += static_cast<size_t>(put);
1814 }
1815 return true;
1816 }
1817
1818 static bool sStateLoad(const clap_plugin_t* p, const clap_istream_t* stream) noexcept
1819 {
1820 auto* s = self(p);
1821 std::vector<uint8_t> blob;
1822 uint8_t chunk[4096];
1823 for (;;)
1824 {
1825 const int64_t got = stream->read(stream, chunk, sizeof(chunk));
1826 if (got < 0) return false;
1827 if (got == 0) break;
1828 blob.insert(blob.end(), chunk, chunk + got);
1829 // Only an endless hostile stream is refused: the old 16 MiB cap
1830 // rejected states this plugin's own save() had written.
1831 if (blob.size() > kMaxStateBytes) return false;
1832 }
1833 // Parameters the blob does not carry take their DEFAULTS (the old
1834 // code kept whatever value the instance happened to hold).
1835 double norm[kNumParams == 0 ? 1 : kNumParams];
1836 loadDefaultNormalized<P>(norm);
1837 int program = -1;
1838 int bypassState = -1;
1839 EditorSize editorSize { 0, 0 };
1840 if (!applyState(s->user, blob.data(), blob.size(), norm, &program,
1841 &bypassState, &editorSize))
1842 return false;
1843 bool direct = true;
1844 for (size_t i = 0; i < kNumParams; ++i)
1845 direct &= s->applyFromUi(static_cast<int>(i), norm[i]);
1846 if (kNumPresets > 0 && program >= 0 && program < kNumPresets)
1847 s->currentProgram.store(program, std::memory_order_relaxed);
1848 if (bypassState >= 0)
1849 s->bypass.store(bypassState != 0, std::memory_order_relaxed);
1850 // The editor size the session left: the editor opens at it next time
1851 // (a state without one keeps the size this instance has), and an
1852 // editor open right now asks the host for it at once.
1853 if (editorSize.width > 0)
1854 {
1855 s->editorMemory.remember(editorSize.width, editorSize.height);
1856#if defined(DSPARK_PLUGIN_WEBVIEW)
1857 s->applyRememberedEditorSize();
1858#endif
1859 }
1860 if (direct)
1861 s->refreshLatency(); // restored state may imply a new lookahead
1862 else
1863 s->requestParamFlush(); // the audio thread applies it, then re-reads
1864 return true;
1865 }
1866
1867 inline static const clap_plugin_state_t kState = { &sStateSave, &sStateLoad };
1868
1869 // --- ext: latency / tail --------------------------------------------------------
1870
1871 static uint32_t sLatencyGet(const clap_plugin_t* p) noexcept
1872 {
1873 return static_cast<uint32_t>(
1874 self(p)->cachedLatency.load(std::memory_order_relaxed));
1875 }
1876
1877 inline static const clap_plugin_latency_t kLatency = { &sLatencyGet };
1878
1879 static uint32_t sTailGet(const clap_plugin_t* p) noexcept
1880 {
1881 auto* s = self(p);
1882 if constexpr (HasTail<P>)
1883 {
1884 const double seconds = s->user.getTailSeconds();
1885 if (!(seconds > 0.0)) return 0; // negative/NaN -> no tail
1886 const double samples = seconds * s->sampleRate;
1887 // CLAP treats anything >= INT32_MAX as an infinite tail; the cap
1888 // also avoids the double->uint32 overflow (UB).
1889 if (samples >= 4294967295.0) return 0xFFFFFFFFu;
1890 return static_cast<uint32_t>(samples);
1891 }
1892 else
1893 {
1894 (void) s;
1895 return 0;
1896 }
1897 }
1898
1899 inline static const clap_plugin_tail_t kTail = { &sTailGet };
1900
1901#if defined(DSPARK_PLUGIN_WEBVIEW)
1902 // --- ext: gui (WebView editor layer) ----------------------------------------------
1903 //
1904 // CLAP hands the parent window AFTER create(), so create() only arms the
1905 // state and set_parent() builds the actual web engine. All [main-thread].
1906
1907 static const char* clapWindowApi() noexcept
1908 {
1909#if defined(_WIN32)
1910 return CLAP_WINDOW_API_WIN32;
1911#elif defined(__APPLE__)
1912 return CLAP_WINDOW_API_COCOA;
1913#else
1914 return CLAP_WINDOW_API_X11;
1915#endif
1916 }
1917
1923 void applyRememberedEditorSize() noexcept
1924 {
1925 if (!guiActive) return;
1926 const EditorSize logical = editorMemory.current();
1927 const int w = toBoundedInt(logical.width * guiScale + 0.5,
1928 1, static_cast<int>(kEditorMaxPixels));
1929 const int h = toBoundedInt(logical.height * guiScale + 0.5,
1930 1, static_cast<int>(kEditorMaxPixels));
1931 if (w == guiWidth && h == guiHeight) return;
1932 webview_ui::debugLog("clap state load: request_resize %dx%d", w, h);
1933 if (hostGui == nullptr || hostGui->request_resize == nullptr
1934 || !hostGui->request_resize(host, static_cast<uint32_t>(w),
1935 static_cast<uint32_t>(h)))
1936 return;
1937 guiWidth = w;
1938 guiHeight = h;
1939 guiEditor.setBounds(w, h);
1940 }
1941
1942 static void cbGuiSetParam(void* context, int index, double plain) noexcept
1943 {
1944 auto* s = static_cast<Plugin*>(context);
1945 const Param& spec = P::parameters[static_cast<size_t>(index)];
1946 const double normalized = toNormalized(spec, plain);
1947 // While active the audio thread applies the edit (and re-reads the
1948 // latency there); inactive, it lands now - and the latency must be
1949 // re-read here, which the old code never did for editor edits.
1950 if (s->applyFromUi(index, normalized))
1951 s->refreshLatency();
1952 const double snapped = toPlain(spec, normalized);
1953 const uint32_t id = hash32(spec.id);
1954 if (s->guiEditActive[static_cast<size_t>(index)])
1955 s->pushUiEvent(id, kUiValue, snapped);
1956 else
1957 {
1958 // Edits outside an explicit gesture still get one (host undo).
1959 s->pushUiEvent(id, kUiGestureBegin, 0.0);
1960 s->pushUiEvent(id, kUiValue, snapped);
1961 s->pushUiEvent(id, kUiGestureEnd, 0.0);
1962 }
1963 s->requestUiFlush();
1964 }
1965
1966 static void cbGuiBeginEdit(void* context, int index) noexcept
1967 {
1968 auto* s = static_cast<Plugin*>(context);
1969 s->guiEditActive[static_cast<size_t>(index)] = true;
1970 s->pushUiEvent(hash32(P::parameters[static_cast<size_t>(index)].id),
1971 kUiGestureBegin, 0.0);
1972 s->requestUiFlush();
1973 }
1974
1975 static void cbGuiEndEdit(void* context, int index) noexcept
1976 {
1977 auto* s = static_cast<Plugin*>(context);
1978 s->guiEditActive[static_cast<size_t>(index)] = false;
1979 s->pushUiEvent(hash32(P::parameters[static_cast<size_t>(index)].id),
1980 kUiGestureEnd, 0.0);
1981 s->requestUiFlush();
1982 }
1983
1984 static bool sGuiIsApiSupported(const clap_plugin_t*, const char* api,
1985 bool isFloating) noexcept
1986 {
1987 return !isFloating && api != nullptr && std::strcmp(api, clapWindowApi()) == 0
1989 }
1990
1991 static bool sGuiGetPreferredApi(const clap_plugin_t*, const char** api,
1992 bool* isFloating) noexcept
1993 {
1994 if (api == nullptr || isFloating == nullptr) return false;
1995 *api = clapWindowApi();
1996 *isFloating = false;
1998 }
1999
2000 static bool sGuiCreate(const clap_plugin_t* p, const char* api,
2001 bool isFloating) noexcept
2002 {
2003 auto* s = self(p);
2004 if (!sGuiIsApiSupported(p, api, isFloating)) return false;
2005#if defined(__linux__)
2006 // GTK breathes only when pumped from the host's run loop; without
2007 // timer-support the page would freeze - fall back to generic UI.
2008 s->hostTimer = s->host != nullptr
2009 ? static_cast<const clap_host_timer_support_t*>(
2010 s->host->get_extension(s->host, CLAP_EXT_TIMER_SUPPORT))
2011 : nullptr;
2012 if (s->hostTimer == nullptr || s->hostTimer->register_timer == nullptr
2013 || !s->hostTimer->register_timer(s->host, 33, &s->guiTimerId))
2014 {
2015 webview_ui::debugLog("clap gui create: no host timer-support -> no editor");
2016 s->hostTimer = nullptr;
2017 s->guiTimerId = CLAP_INVALID_ID;
2018 return false;
2019 }
2020#endif
2021 // The size the user left the editor at (this session or a saved
2022 // one), else the declared size.
2023 const EditorSize logical = s->editorMemory.current();
2024 s->guiWidth = toBoundedInt(logical.width * s->guiScale + 0.5,
2025 1, static_cast<int>(kEditorMaxPixels));
2026 s->guiHeight = toBoundedInt(logical.height * s->guiScale + 0.5,
2027 1, static_cast<int>(kEditorMaxPixels));
2028 s->guiActive = true;
2029 webview_ui::debugLog("clap gui create %dx%d scale=%.2f",
2030 s->guiWidth, s->guiHeight, s->guiScale);
2031 return true;
2032 }
2033
2034 static void sGuiDestroy(const clap_plugin_t* p) noexcept
2035 {
2036 auto* s = self(p);
2037#if defined(__linux__)
2038 if (s->hostTimer != nullptr && s->guiTimerId != CLAP_INVALID_ID)
2039 s->hostTimer->unregister_timer(s->host, s->guiTimerId);
2040 s->hostTimer = nullptr;
2041 s->guiTimerId = CLAP_INVALID_ID;
2042#endif
2043 // Keep the size the editor is closed at: some hosts resize their
2044 // window without a set_size, and the window still exists here.
2045 int parentW = 0, parentH = 0;
2046 if (s->guiEditor.created() && s->guiEditor.queryParentSize(parentW, parentH))
2047 {
2048 double w = parentW;
2049 double h = parentH;
2050 constrainEditorSize<P>(w, h, s->guiScale);
2051 s->editorMemory.remember(w / s->guiScale, h / s->guiScale);
2052 }
2053 s->guiEditor.destroy();
2054 s->guiActive = false;
2055 }
2056
2057 static bool sGuiSetScale(const clap_plugin_t* p, double scale) noexcept
2058 {
2059#if defined(__APPLE__)
2060 (void) p; (void) scale;
2061 return false; // cocoa uses logical sizes; scaling is the OS's job
2062#else
2063 auto* s = self(p);
2064 if (!(scale > 0.0)) return false; // NaN included
2065 // Only the physical-size negotiation changes; the page itself never
2066 // zooms (the web engine applies the window DPI to CSS pixels itself).
2067 const double previous = s->guiScale;
2068 s->guiScale = scale;
2069 s->guiWidth = toBoundedInt(s->guiWidth * (scale / previous) + 0.5,
2070 1, static_cast<int>(kEditorMaxPixels));
2071 s->guiHeight = toBoundedInt(s->guiHeight * (scale / previous) + 0.5,
2072 1, static_cast<int>(kEditorMaxPixels));
2073 s->guiEditor.setBounds(s->guiWidth, s->guiHeight);
2074 return true;
2075#endif
2076 }
2077
2078 static bool sGuiGetSize(const clap_plugin_t* p, uint32_t* width,
2079 uint32_t* height) noexcept
2080 {
2081 auto* s = self(p);
2082 if (width == nullptr || height == nullptr || !s->guiActive) return false;
2083 *width = static_cast<uint32_t>(s->guiWidth);
2084 *height = static_cast<uint32_t>(s->guiHeight);
2085 return true;
2086 }
2087
2088 static bool sGuiCanResize(const clap_plugin_t*) noexcept
2089 {
2090 return editorResizeOf<P>() != EditorResize::Fixed;
2091 }
2092
2093 static bool sGuiGetResizeHints(const clap_plugin_t*,
2094 clap_gui_resize_hints_t* hints) noexcept
2095 {
2096 if (hints == nullptr) return false;
2097 constexpr EditorResize mode = editorResizeOf<P>();
2098 const EditorSize logical = editorSizeOf<P>();
2099 hints->can_resize_horizontally = mode != EditorResize::Fixed;
2100 hints->can_resize_vertically = mode != EditorResize::Fixed;
2101 hints->preserve_aspect_ratio = mode == EditorResize::KeepAspect;
2102 hints->aspect_ratio_width = static_cast<uint32_t>(logical.width);
2103 hints->aspect_ratio_height = static_cast<uint32_t>(logical.height);
2104 return true;
2105 }
2106
2107 static bool sGuiAdjustSize(const clap_plugin_t* p, uint32_t* width,
2108 uint32_t* height) noexcept
2109 {
2110 auto* s = self(p);
2111 if (width == nullptr || height == nullptr) return false;
2112 double w = *width;
2113 double h = *height;
2114 constrainEditorSize<P>(w, h, s->guiScale);
2115 *width = static_cast<uint32_t>(
2116 toBoundedInt(w + 0.5, 1, static_cast<int>(kEditorMaxPixels)));
2117 *height = static_cast<uint32_t>(
2118 toBoundedInt(h + 0.5, 1, static_cast<int>(kEditorMaxPixels)));
2119 return true;
2120 }
2121
2122 static bool sGuiSetSize(const clap_plugin_t* p, uint32_t width,
2123 uint32_t height) noexcept
2124 {
2125 auto* s = self(p);
2126 if (!s->guiActive) return false;
2127 // Clamp here too: not every host runs the size through adjust_size.
2128 double w = width;
2129 double h = height;
2130 constrainEditorSize<P>(w, h, s->guiScale);
2131 webview_ui::debugLog("clap gui set_size %ux%u -> %.0fx%.0f", width, height, w, h);
2132 s->guiWidth = toBoundedInt(w + 0.5, 1, static_cast<int>(kEditorMaxPixels));
2133 s->guiHeight = toBoundedInt(h + 0.5, 1, static_cast<int>(kEditorMaxPixels));
2134 s->guiEditor.setBounds(s->guiWidth, s->guiHeight);
2135 // The user's size, in logical pixels: the editor reopens at it, and
2136 // the state saves it for the next session.
2137 s->editorMemory.remember(s->guiWidth / s->guiScale, s->guiHeight / s->guiScale);
2138 return true;
2139 }
2140
2141 static bool sGuiSetParent(const clap_plugin_t* p,
2142 const clap_window_t* window) noexcept
2143 {
2144 auto* s = self(p);
2145 if (window == nullptr || !s->guiActive) return false;
2146#if defined(__linux__)
2147 // The X11 window id rides the union's dedicated field.
2148 void* parentHandle = reinterpret_cast<void*>(
2149 static_cast<std::uintptr_t>(window->x11));
2150#else
2151 void* parentHandle = window->ptr;
2152#endif
2153 webview_ui::debugLog("clap gui set_parent %p negotiated=%dx%d",
2154 parentHandle, s->guiWidth, s->guiHeight);
2155 const webview_ui::HostCallbacks callbacks {
2156 s, &cbGuiSetParam, &cbGuiBeginEdit, &cbGuiEndEdit
2157 };
2158 if (!s->guiEditor.create(parentHandle, s->shadow, callbacks))
2159 return false;
2160 // Fill whatever box the host actually built (call order differs
2161 // between hosts); fall back to the negotiated size otherwise.
2162 int parentW = 0, parentH = 0;
2163 if (s->guiEditor.queryParentSize(parentW, parentH))
2164 {
2165 s->guiWidth = parentW;
2166 s->guiHeight = parentH;
2167 }
2168 s->guiEditor.setBounds(s->guiWidth, s->guiHeight);
2169 return true;
2170 }
2171
2172 static bool sGuiSetTransient(const clap_plugin_t*, const clap_window_t*) noexcept
2173 {
2174 return false; // embedded only; no floating window mode
2175 }
2176
2177 static void sGuiSuggestTitle(const clap_plugin_t*, const char*) noexcept {}
2178
2179 static bool sGuiShow(const clap_plugin_t* p) noexcept
2180 {
2181 self(p)->guiEditor.setVisible(true);
2182 return true;
2183 }
2184
2185 static bool sGuiHide(const clap_plugin_t* p) noexcept
2186 {
2187 self(p)->guiEditor.setVisible(false);
2188 return true;
2189 }
2190
2191 inline static const clap_plugin_gui_t kGui = {
2192 &sGuiIsApiSupported, &sGuiGetPreferredApi, &sGuiCreate, &sGuiDestroy,
2193 &sGuiSetScale, &sGuiGetSize, &sGuiCanResize, &sGuiGetResizeHints,
2194 &sGuiAdjustSize, &sGuiSetSize, &sGuiSetParent, &sGuiSetTransient,
2195 &sGuiSuggestTitle, &sGuiShow, &sGuiHide
2196 };
2197
2198#if defined(__linux__)
2199
2200 // --- ext: timer-support (drives the GTK main context for the editor) -----------
2201
2202 static void sOnTimer(const clap_plugin_t* p, clap_id) noexcept
2203 {
2204 self(p)->guiEditor.pump();
2205 }
2206
2207 inline static const clap_plugin_timer_support_t kTimer = { &sOnTimer };
2208
2209#endif // __linux__
2210#endif // DSPARK_PLUGIN_WEBVIEW
2211
2212 // --- descriptor & factory ----------------------------------------------------------
2213
2214 static const clap_plugin_descriptor_t* descriptor() noexcept
2215 {
2216 static const char* features[] = {
2217 kIsInstrument ? CLAP_PLUGIN_FEATURE_INSTRUMENT
2218 : CLAP_PLUGIN_FEATURE_AUDIO_EFFECT,
2219 channelSupportOf<P>() == ChannelSupport::MonoOnly
2220 ? CLAP_PLUGIN_FEATURE_MONO : CLAP_PLUGIN_FEATURE_STEREO,
2221 nullptr
2222 };
2223 static const clap_plugin_descriptor_t desc = {
2224 CLAP_VERSION_INIT,
2225 P::descriptor.productId,
2226 P::descriptor.name,
2227 P::descriptor.vendor,
2228 P::descriptor.url,
2229 "", // manual_url
2230 P::descriptor.url, // support_url
2231 P::descriptor.version,
2232 "Built with DSPark", // description
2233 features
2234 };
2235 return &desc;
2236 }
2237
2238 static const clap_plugin_t* create(const clap_host_t* host) noexcept
2239 {
2240 auto* s = new (std::nothrow) Plugin(host);
2241 if (s == nullptr) return nullptr;
2242 s->plugin.desc = descriptor();
2243 s->plugin.plugin_data = s;
2244 s->plugin.init = &sInit;
2245 s->plugin.destroy = &sDestroy;
2246 s->plugin.activate = &sActivate;
2247 s->plugin.deactivate = &sDeactivate;
2248 s->plugin.start_processing = &sStartProcessing;
2249 s->plugin.stop_processing = &sStopProcessing;
2250 s->plugin.reset = &sReset;
2251 s->plugin.process = &sProcess;
2252 s->plugin.get_extension = &sGetExtension;
2253 s->plugin.on_main_thread = &sOnMainThread;
2254 return &s->plugin;
2255 }
2256};
2257
2258template <typename P>
2260{
2261 static uint32_t sCount(const clap_plugin_factory_t*) noexcept { return 1; }
2262
2263 static const clap_plugin_descriptor_t* sDescriptor(const clap_plugin_factory_t*,
2264 uint32_t index) noexcept
2265 {
2266 return index == 0 ? Plugin<P>::descriptor() : nullptr;
2267 }
2268
2269 static const clap_plugin_t* sCreate(const clap_plugin_factory_t*,
2270 const clap_host_t* host,
2271 const char* pluginId) noexcept
2272 {
2273 if (pluginId == nullptr
2274 || std::strcmp(pluginId, P::descriptor.productId) != 0)
2275 return nullptr;
2276 return Plugin<P>::create(host);
2277 }
2278
2279 inline static const clap_plugin_factory_t kFactory = {
2281 };
2282
2283 // --- preset discovery (factory presets live inside the plugin DSO) -------------
2284 //
2285 // The provider declares ONE location of kind PLUGIN and reports each
2286 // factory preset with its table index as the load key; preset-load's
2287 // from_location() applies it. Hosts with a preset browser (e.g. Bitwig)
2288 // index these without instantiating the plugin.
2289
2290 static constexpr int kNumPresets = factoryPresetCountOf<P>();
2291
2292 static const char* providerId() noexcept
2293 {
2294 // Magic static: the discovery factory contract is [thread-safe].
2295 static const std::array<char, 256> id = [] {
2296 std::array<char, 256> buf {};
2297 std::snprintf(buf.data(), buf.size(), "%s.presets",
2298 P::descriptor.productId);
2299 return buf;
2300 }();
2301 return id.data();
2302 }
2303
2304 static const clap_preset_discovery_provider_descriptor_t* providerDescriptor() noexcept
2305 {
2306 static const clap_preset_discovery_provider_descriptor_t desc = {
2307 CLAP_VERSION_INIT, providerId(), "DSPark Factory Presets",
2308 P::descriptor.vendor
2309 };
2310 return &desc;
2311 }
2312
2314 {
2315 clap_preset_discovery_provider_t provider {};
2316 const clap_preset_discovery_indexer_t* indexer = nullptr;
2317 };
2318
2319 static bool sProviderInit(const clap_preset_discovery_provider_t* provider) noexcept
2320 {
2321 const auto* state = static_cast<const ProviderState*>(provider->provider_data);
2322 if (state->indexer == nullptr || state->indexer->declare_location == nullptr)
2323 return false;
2324 clap_preset_discovery_location_t location {};
2325 location.flags = CLAP_PRESET_DISCOVERY_IS_FACTORY_CONTENT;
2326 location.name = "Factory Presets";
2327 location.kind = CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN;
2328 location.location = nullptr;
2329 return state->indexer->declare_location(state->indexer, &location);
2330 }
2331
2332 static void sProviderDestroy(const clap_preset_discovery_provider_t* provider) noexcept
2333 {
2334 delete static_cast<ProviderState*>(provider->provider_data);
2335 }
2336
2337 static bool sProviderGetMetadata(const clap_preset_discovery_provider_t*,
2338 uint32_t locationKind, const char*,
2339 const clap_preset_discovery_metadata_receiver_t*
2340 receiver) noexcept
2341 {
2342 if constexpr (kNumPresets > 0)
2343 {
2344 if (locationKind != CLAP_PRESET_DISCOVERY_LOCATION_PLUGIN
2345 || receiver == nullptr)
2346 return false;
2347 const clap_universal_plugin_id_t pluginId {
2348 "clap", P::descriptor.productId
2349 };
2350 for (int i = 0; i < kNumPresets; ++i)
2351 {
2352 char key[16];
2353 std::snprintf(key, sizeof(key), "%d", i);
2354 if (!receiver->begin_preset(receiver,
2355 P::factoryPresets[static_cast<size_t>(i)].name, key))
2356 return true; // the indexer asked to stop; not an error
2357 receiver->add_plugin_id(receiver, &pluginId);
2358 receiver->set_flags(receiver,
2359 CLAP_PRESET_DISCOVERY_IS_FACTORY_CONTENT);
2360 }
2361 return true;
2362 }
2363 else
2364 {
2365 (void) locationKind;
2366 (void) receiver;
2367 return false;
2368 }
2369 }
2370
2371 static const void* sProviderGetExtension(const clap_preset_discovery_provider_t*,
2372 const char*) noexcept
2373 { return nullptr; }
2374
2375 static uint32_t sDiscoveryCount(const clap_preset_discovery_factory_t*) noexcept
2376 { return kNumPresets > 0 ? 1u : 0u; }
2377
2378 static const clap_preset_discovery_provider_descriptor_t* sDiscoveryDescriptor(
2379 const clap_preset_discovery_factory_t*, uint32_t index) noexcept
2380 {
2381 return (kNumPresets > 0 && index == 0) ? providerDescriptor() : nullptr;
2382 }
2383
2384 static const clap_preset_discovery_provider_t* sDiscoveryCreate(
2385 const clap_preset_discovery_factory_t*,
2386 const clap_preset_discovery_indexer_t* indexer,
2387 const char* providerIdAsked) noexcept
2388 {
2389 if (kNumPresets == 0 || indexer == nullptr || providerIdAsked == nullptr
2390 || std::strcmp(providerIdAsked, providerId()) != 0)
2391 return nullptr;
2392 auto* state = new (std::nothrow) ProviderState();
2393 if (state == nullptr) return nullptr;
2394 state->indexer = indexer;
2395 state->provider.desc = providerDescriptor();
2396 state->provider.provider_data = state;
2397 state->provider.init = &sProviderInit;
2398 state->provider.destroy = &sProviderDestroy;
2399 state->provider.get_metadata = &sProviderGetMetadata;
2400 state->provider.get_extension = &sProviderGetExtension;
2401 return &state->provider;
2402 }
2403
2404 inline static const clap_preset_discovery_factory_t kDiscoveryFactory = {
2406 };
2407
2408 static bool sEntryInit(const char*) noexcept { return true; }
2409 static void sEntryDeinit() noexcept {}
2410
2411 static const void* sEntryGetFactory(const char* factoryId) noexcept
2412 {
2413 if (factoryId == nullptr) return nullptr;
2414 if (std::strcmp(factoryId, CLAP_PLUGIN_FACTORY_ID) == 0)
2415 return &kFactory;
2416 if (kNumPresets > 0
2417 && (std::strcmp(factoryId, CLAP_PRESET_DISCOVERY_FACTORY_ID) == 0
2418 || std::strcmp(factoryId, CLAP_PRESET_DISCOVERY_FACTORY_ID_COMPAT) == 0))
2419 return &kDiscoveryFactory;
2420 return nullptr;
2421 }
2422};
2423
2424} // namespace dspark::plugin::clap_backend
2425
2431#define DSPARK_CLAP_PLUGIN(PluginClass) \
2432 extern "C" CLAP_EXPORT const clap_plugin_entry_t clap_entry = { \
2433 CLAP_VERSION_INIT, \
2434 &dspark::plugin::clap_backend::Factory<PluginClass>::sEntryInit, \
2435 &dspark::plugin::clap_backend::Factory<PluginClass>::sEntryDeinit, \
2436 &dspark::plugin::clap_backend::Factory<PluginClass>::sEntryGetFactory \
2437 };
2438
2439#pragma pop_macro("max")
2440#pragma pop_macro("min")
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
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...
The dry signal of the wrappers' soft bypass, delayed by the plugin's latency.
The editor size the user last left, in logical pixels, kept by each backend across editor re-opens an...
Parameter changes made OFF the audio thread, handed to it.
bool drain(Apply &&apply) noexcept
void mark(size_t index) noexcept
The voices this backend started (one per NoteOn it delivered), with the host's modulation amount of e...
Definition DSParkClap.h:128
VoiceParams & paramsOf(int slot) noexcept
Definition DSParkClap.h:234
void forEachMatching(int port, int channel, int key, int32_t noteId, Fn &&fn) noexcept
Definition DSParkClap.h:216
int start(int channel, int key, int32_t noteId) noexcept
Definition DSParkClap.h:161
Voice & operator[](int slot) noexcept
Definition DSParkClap.h:231
One embedded WebView editor instance for plugin class P. Owned by the format backends (the VST3 IPlug...
void setBounds(int width, int height) noexcept
Custom-editor switch. With hasEditor = false (or absent) hosts show their generic parameter UI....
MIDI capability: void handleMidiEvent(const MidiEvent&) noexcept. Its presence grows a note/event inp...
Render-mode capability: void setOfflineRendering(bool) noexcept. The host flips it to true for non-re...
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 int kBypassRampSamples
Definition DSParkClap.h:110
constexpr uint32_t kBypassParamId
Definition DSParkClap.h:109
void debugLog(const char *format,...) noexcept
constexpr std::array< Param, sizeof...(Ps)> params(Ps... ps) noexcept
Builds the parameter table (use inside static constexpr auto).
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.
@ Instrument
Audio generator (MIDI in -> audio out, no audio input).
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 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 kDryDelayMinCapacity
Ring headroom of the bypass dry path: latencies up to this (or twice the latency at activation,...
constexpr uint32_t expressionBit(MidiEvent::ExpressionType type) noexcept
The bit of one ExpressionType in a note-expression mask.
constexpr double toNormalized(const Param &p, double plain) noexcept
Plain [min, max] -> normalized [0, 1] (steps snap on the way back).
constexpr double toPlain(const Param &p, double normalized) noexcept
Normalized [0, 1] -> plain [min, max], snapped for stepped params.
int parseToggleText(const char *text) noexcept
Case-insensitive "On"/"Off" recognition - the inverse of the toggle display below....
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 int kMaxBlockEvents
Capacity of the per-block event list. Past it the list merges rather than drops: an intermediate para...
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").
@ MonoOnly
Strictly 1->1 (rare; metering/utility plugins).
@ MonoAndStereo
Negotiates 1->1 or 2->2 with the host (default).
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.
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),...
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
One timestamped in-block event, normalised across formats: a parameter point, a bypass point,...
int32_t offset
Frame position within the block.
MidiEvent midi
Kind::Midi payload.
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.
@ 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.
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).
One automatable parameter. Plain values run [min, max]; hosts see the normalized [0,...
Host transport snapshot, delivered once per audio block.
bool playing
Transport is rolling.
const clap_preset_discovery_indexer_t * indexer
static bool sProviderInit(const clap_preset_discovery_provider_t *provider) noexcept
static const clap_preset_discovery_provider_descriptor_t * providerDescriptor() noexcept
static const char * providerId() noexcept
static const void * sEntryGetFactory(const char *factoryId) noexcept
static const clap_preset_discovery_provider_t * sDiscoveryCreate(const clap_preset_discovery_factory_t *, const clap_preset_discovery_indexer_t *indexer, const char *providerIdAsked) noexcept
static void sEntryDeinit() noexcept
static uint32_t sDiscoveryCount(const clap_preset_discovery_factory_t *) noexcept
static uint32_t sCount(const clap_plugin_factory_t *) noexcept
static bool sProviderGetMetadata(const clap_preset_discovery_provider_t *, uint32_t locationKind, const char *, const clap_preset_discovery_metadata_receiver_t *receiver) noexcept
static void sProviderDestroy(const clap_preset_discovery_provider_t *provider) noexcept
static bool sEntryInit(const char *) noexcept
static const clap_preset_discovery_provider_descriptor_t * sDiscoveryDescriptor(const clap_preset_discovery_factory_t *, uint32_t index) noexcept
static const clap_plugin_factory_t kFactory
static const void * sProviderGetExtension(const clap_preset_discovery_provider_t *, const char *) noexcept
static const clap_preset_discovery_factory_t kDiscoveryFactory
static const clap_plugin_t * sCreate(const clap_plugin_factory_t *, const clap_host_t *host, const char *pluginId) noexcept
static const clap_plugin_descriptor_t * sDescriptor(const clap_plugin_factory_t *, uint32_t index) noexcept
static uint32_t sConfigCount(const clap_plugin_t *) noexcept
static void sStopProcessing(const clap_plugin_t *) noexcept
const clap_host_params_t * hostParams
Definition DSParkClap.h:279
static void sReset(const clap_plugin_t *p) noexcept
static const clap_plugin_audio_ports_t kAudioPorts
static bool sConfigSelect(const clap_plugin_t *p, clap_id configId) noexcept
static const clap_plugin_state_t kState
static Plugin * self(const clap_plugin_t *p) noexcept
Definition DSParkClap.h:373
EndedVoice endedVoices[kMaxEndedVoices]
Definition DSParkClap.h:323
const clap_host_preset_load_t * hostPresetLoad
Definition DSParkClap.h:280
static uint32_t sParamCount(const clap_plugin_t *) noexcept
static bool sParamValue(const clap_plugin_t *p, clap_id id, double *out) noexcept
void endVoice(int slot) noexcept
Definition DSParkClap.h:526
static uint32_t sNotePortCount(const clap_plugin_t *, bool isInput) noexcept
static bool sConfigInfoGet(const clap_plugin_t *p, clap_id configId, uint32_t portIndex, bool isInput, clap_audio_port_info_t *info) noexcept
static clap_process_status sProcess(const clap_plugin_t *p, const clap_process_t *process) noexcept
void forwardTransport(const clap_event_transport_t *t) noexcept
Definition DSParkClap.h:999
static bool sPortGet(const clap_plugin_t *p, uint32_t index, bool isInput, clap_audio_port_info_t *info) noexcept
static const clap_plugin_latency_t kLatency
static bool sActivate(const clap_plugin_t *p, double sr, uint32_t, uint32_t maxFrames) noexcept
static constexpr int kMaxEndedVoices
Definition DSParkClap.h:321
void deliverToVoice(MidiEvent midi, int channel, int key, int32_t noteId) noexcept
Definition DSParkClap.h:462
static void sDeactivate(const clap_plugin_t *p) noexcept
Plugin(const clap_host_t *h) noexcept
Definition DSParkClap.h:366
static void sOnMainThread(const clap_plugin_t *p) noexcept
static bool sRenderSet(const clap_plugin_t *p, clap_plugin_render_mode mode) noexcept
static constexpr bool kIsInstrument
Definition DSParkClap.h:257
void applyFactoryPresetIdx(int idx) noexcept
Definition DSParkClap.h:671
static uint32_t sTailGet(const clap_plugin_t *p) noexcept
static bool sNotePortGet(const clap_plugin_t *, uint32_t index, bool isInput, clap_note_port_info_t *info) noexcept
static clap_id sConfigCurrent(const clap_plugin_t *p) noexcept
static constexpr size_t kNumParams
Definition DSParkClap.h:256
static constexpr size_t kNumPerVoice
Definition DSParkClap.h:270
VoiceTable< kNumPerVoice > voices
The voices delivered so far, for per-voice events (audio thread).
Definition DSParkClap.h:309
const clap_host_latency_t * hostLatency
Definition DSParkClap.h:278
double heardPlain(int index, double normalized) const noexcept
Definition DSParkClap.h:381
std::atomic< double > shadow[kNumParams==0 ? 1 :kNumParams]
Definition DSParkClap.h:326
void trackVoice(const MidiEvent &midi) noexcept
Definition DSParkClap.h:541
EditorSizeMemory< P > editorMemory
Definition DSParkClap.h:337
static bool sStateSave(const clap_plugin_t *p, const clap_ostream_t *stream) noexcept
static const clap_plugin_audio_ports_config_t kPortsConfig
static void sDestroy(const clap_plugin_t *p) noexcept
static bool sParamTextToValue(const clap_plugin_t *, clap_id id, const char *text, double *out) noexcept
void applyVoiceEvent(const BlockEvent &ev, MidiEvent midi) noexcept
Definition DSParkClap.h:578
void applyNormalized(int index, double normalized) noexcept
Definition DSParkClap.h:389
static void sParamFlush(const clap_plugin_t *p, const clap_input_events_t *in, const clap_output_events_t *out) noexcept
static const clap_plugin_render_t kRender
double modulation[kNumParams==0 ? 1 :kNumParams]
Host modulation amount per parameter, plain units (audio thread).
Definition DSParkClap.h:328
static const clap_plugin_audio_ports_config_info_t kPortsConfigInfo
bool applyBlockEvent(const BlockEvent &ev, int blockStart) noexcept
Definition DSParkClap.h:951
double voiceHeardPlain(int index, int slot, const Params &params) const noexcept
Definition DSParkClap.h:453
static bool sRenderHardRealtime(const clap_plugin_t *) noexcept
static const void * sGetExtension(const clap_plugin_t *, const char *id) noexcept
void collectEvents(const clap_input_events_t *in, uint32_t numSamples, BlockEventList &events) noexcept
Definition DSParkClap.h:940
static bool sPresetFromLocation(const clap_plugin_t *p, uint32_t locationKind, const char *location, const char *loadKey) noexcept
static bool sParamInfo(const clap_plugin_t *, uint32_t index, clap_param_info_t *info) noexcept
static const clap_plugin_descriptor_t * descriptor() noexcept
double voiceHeardPlain(int index, bool valued, double value, bool modulated, double amount) const noexcept
Definition DSParkClap.h:439
static bool sInit(const clap_plugin_t *p) noexcept
static bool sStartProcessing(const clap_plugin_t *p) noexcept
static const clap_plugin_t * create(const clap_host_t *host) noexcept
void flushEndedVoices(const clap_output_events_t *out, uint32_t time) noexcept
Definition DSParkClap.h:635
bool applyFromUi(int index, double normalized) noexcept
Definition DSParkClap.h:410
static int indexOfParamId(uint32_t id) noexcept
Definition DSParkClap.h:398
static uint32_t sLatencyGet(const clap_plugin_t *p) noexcept
static const clap_plugin_preset_load_t kPresetLoad
static constexpr bool isIntegerGrid(const Param &spec) noexcept
static const clap_plugin_params_t kParams
void collectEvent(const clap_event_header_t *ev, uint32_t numSamples, BlockEventList &events) noexcept
Definition DSParkClap.h:708
static const clap_plugin_tail_t kTail
static bool sStateLoad(const clap_plugin_t *p, const clap_istream_t *stream) noexcept
PendingParams< kNumParams > pending
Definition DSParkClap.h:304
void resendVoiceModulation(int index, int sampleOffset, bool modulationMoved) noexcept
Definition DSParkClap.h:486
static void fillConfig(clap_audio_ports_config_t *config, int width) noexcept
static bool sParamValueToText(const clap_plugin_t *, clap_id id, double value, char *out, uint32_t size) noexcept
static bool sConfigGet(const clap_plugin_t *, uint32_t index, clap_audio_ports_config_t *config) noexcept
void blendBypass(float *const *out, float *const *dry, uint32_t nCh, int outStart, int dryStart, int length) noexcept
static uint32_t sPortCount(const clap_plugin_t *, bool isInput) noexcept
static const clap_plugin_note_ports_t kNotePorts
static constexpr bool kHasPerVoice
Definition DSParkClap.h:271
What the host set for each perVoice() parameter of one voice.
Definition DSParkClap.h:145
std::array< double, kSlots > value
Per-note automation: the voice's own plain value of the parameter.
Definition DSParkClap.h:150
A voice's identity (the part every scan reads; kept small).
Definition DSParkClap.h:134
bool held
false once its NoteOff arrived
Definition DSParkClap.h:140
uint32_t serial
start order, for choosing the oldest
Definition DSParkClap.h:138