DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DSParkVst3.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
75#define DSPARK_PLUGIN_VST3_INCLUDED 1
76
77#include "../DSParkPlugin.h"
78
79// Survive a <windows.h> included earlier without NOMINMAX (restored at the end).
80#pragma push_macro("min")
81#pragma push_macro("max")
82#undef min
83#undef max
84
85#include "vst3_c_api.h"
86
87#include <array>
88#include <atomic>
89#include <bit>
90#include <cmath>
91#include <cstdint>
92#include <cstdio>
93#include <cstdlib>
94#include <cstring>
95#include <new>
96#include <thread>
97#include <utility>
98#include <vector>
99
100#if defined(__APPLE__)
101 #include <dispatch/dispatch.h> // libSystem: no extra link flag
102#elif defined(_WIN32)
103// The two user32 calls the UI tick needs, declared exactly as <windows.h>
104// declares them (so either include order compiles) instead of pulling the
105// whole Windows header - and its macros - into every plugin translation unit.
106struct HWND__;
107extern "C" __declspec(dllimport) std::uintptr_t __stdcall SetTimer(
108 HWND__* window, std::uintptr_t id, unsigned int milliseconds,
109 void (__stdcall* callback)(HWND__*, unsigned int, std::uintptr_t, unsigned long));
110extern "C" __declspec(dllimport) int __stdcall KillTimer(HWND__* window, std::uintptr_t id);
111#if defined(_MSC_VER)
112#pragma comment(lib, "user32.lib")
113#endif
114#endif
115
117
118// -- UI-thread tick ------------------------------------------------------------------
119
133{
134public:
135 using Callback = void (*)(void* context) noexcept;
136
137 UiTicker() noexcept = default;
138 UiTicker(const UiTicker&) = delete;
139 UiTicker& operator=(const UiTicker&) = delete;
140 ~UiTicker() { stop(); }
141
144 bool start(Steinberg_FUnknown* hostContext, Callback callback, void* context) noexcept
145 {
146 if (running_.load(std::memory_order_relaxed)) return true;
147 callback_ = callback;
148 context_ = context;
149#if defined(__APPLE__)
150 (void) hostContext;
151 source_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
152 dispatch_get_main_queue());
153 if (source_ == nullptr) return false;
154 dispatch_set_context(source_, this);
155 dispatch_source_set_event_handler_f(source_, &onDispatchTick);
156 dispatch_source_set_timer(source_,
157 dispatch_time(DISPATCH_TIME_NOW,
158 static_cast<int64_t>(kPeriodMs) * 1000000),
159 static_cast<uint64_t>(kPeriodMs) * 1000000u,
160 5u * 1000000u);
161 dispatch_resume(source_);
162#elif defined(_WIN32)
163 (void) hostContext;
164 timerId_ = SetTimer(nullptr, 0, kPeriodMs, &onWindowsTick);
165 if (timerId_ == 0) return false;
166 registry().emplace_back(timerId_, this);
167#elif defined(__linux__)
168 if (hostContext == nullptr) return false;
169 void* loop = nullptr;
170 if (hostContext->lpVtbl->queryInterface(hostContext, Steinberg_Linux_IRunLoop_iid,
171 &loop) != Steinberg_kResultOk
172 || loop == nullptr)
173 return false;
174 runLoop_ = static_cast<Steinberg_Linux_IRunLoop*>(loop);
175 if (runLoop_->lpVtbl->registerTimer(
176 runLoop_, reinterpret_cast<Steinberg_Linux_ITimerHandler*>(&timer_),
177 kPeriodMs) != Steinberg_kResultOk)
178 {
179 reinterpret_cast<Steinberg_FUnknown*>(runLoop_)->lpVtbl->release(runLoop_);
180 runLoop_ = nullptr;
181 return false;
182 }
183#else
184 (void) hostContext;
185 return false;
186#endif
187 running_.store(true, std::memory_order_release);
188 return true;
189 }
190
192 void stop() noexcept
193 {
194 if (!running_.load(std::memory_order_relaxed)) return;
195 running_.store(false, std::memory_order_release);
196#if defined(__APPLE__)
197 // Cancel on the main queue's own thread: no handler is mid-flight,
198 // and none is invoked after cancellation.
199 dispatch_source_cancel(source_);
200 dispatch_release(source_);
201 source_ = nullptr;
202#elif defined(_WIN32)
203 KillTimer(nullptr, timerId_);
204 auto& entries = registry();
205 for (size_t i = 0; i < entries.size(); ++i)
206 if (entries[i].first == timerId_)
207 {
208 entries.erase(entries.begin() + static_cast<std::ptrdiff_t>(i));
209 break;
210 }
211 timerId_ = 0;
212#elif defined(__linux__)
213 runLoop_->lpVtbl->unregisterTimer(
214 runLoop_, reinterpret_cast<Steinberg_Linux_ITimerHandler*>(&timer_));
215 reinterpret_cast<Steinberg_FUnknown*>(runLoop_)->lpVtbl->release(runLoop_);
216 runLoop_ = nullptr;
217#endif
218 }
219
220 [[nodiscard]] bool running() const noexcept
221 {
222 return running_.load(std::memory_order_acquire);
223 }
224
225private:
226 static constexpr unsigned int kPeriodMs = 33;
227
228 void tick() noexcept
229 {
230 if (running_.load(std::memory_order_relaxed) && callback_ != nullptr)
231 callback_(context_);
232 }
233
234 std::atomic<bool> running_ { false };
235 Callback callback_ = nullptr;
236 void* context_ = nullptr;
237
238#if defined(__APPLE__)
239 dispatch_source_t source_ = nullptr;
240 static void onDispatchTick(void* self) { static_cast<UiTicker*>(self)->tick(); }
241#elif defined(_WIN32)
242 std::uintptr_t timerId_ = 0;
243 // Thread timers carry no user pointer: map the id back (UI thread only).
244 static std::vector<std::pair<std::uintptr_t, UiTicker*>>& registry()
245 {
246 static std::vector<std::pair<std::uintptr_t, UiTicker*>> entries;
247 return entries;
248 }
249 static void __stdcall onWindowsTick(HWND__*, unsigned int, std::uintptr_t id,
250 unsigned long)
251 {
252 for (const auto& entry : registry())
253 if (entry.first == id)
254 {
255 entry.second->tick();
256 return;
257 }
258 }
259#elif defined(__linux__)
260 // A minimal ITimerHandler (static lifetime: owned by this ticker).
261 struct TimerObject
262 {
263 const Steinberg_Linux_ITimerHandlerVtbl* vtbl;
264 UiTicker* owner;
265 };
266 static Steinberg_tresult SMTG_STDMETHODCALLTYPE timerQuery(void* self_,
267 const Steinberg_TUID iid, void** obj)
268 {
269 if (obj == nullptr) return Steinberg_kInvalidArgument;
270 if (std::memcmp(iid, Steinberg_FUnknown_iid, sizeof(Steinberg_TUID)) == 0
271 || std::memcmp(iid, Steinberg_Linux_ITimerHandler_iid,
272 sizeof(Steinberg_TUID)) == 0)
273 {
274 *obj = self_;
275 return Steinberg_kResultOk;
276 }
277 *obj = nullptr;
278 return Steinberg_kNoInterface;
279 }
280 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE timerRef(void*) { return 1; }
281 static void SMTG_STDMETHODCALLTYPE timerTick(void* self_)
282 {
283 static_cast<TimerObject*>(self_)->owner->tick();
284 }
285 inline static const Steinberg_Linux_ITimerHandlerVtbl kTimerVtbl = {
286 &timerQuery, &timerRef, &timerRef, &timerTick
287 };
288 TimerObject timer_ { &kTimerVtbl, this };
289 Steinberg_Linux_IRunLoop* runLoop_ = nullptr;
290#endif
291};
292
293// -- small helpers -------------------------------------------------------------
294
295inline bool tuidEqual(const Steinberg_TUID a, const Steinberg_TUID b) noexcept
296{
297 return std::memcmp(a, b, sizeof(Steinberg_TUID)) == 0;
298}
299
309inline void utf8ToString128(const char* src, Steinberg_Vst_String128 dst) noexcept
310{
311 int n = 0;
312 const auto* s = reinterpret_cast<const unsigned char*>(src != nullptr ? src : "");
313 while (*s != 0)
314 {
315 const unsigned char lead = *s++;
316 uint32_t cp = lead;
317 int extra = 0;
318 if (lead >= 0x80u)
319 {
320 if ((lead & 0xE0u) == 0xC0u) { cp = lead & 0x1Fu; extra = 1; }
321 else if ((lead & 0xF0u) == 0xE0u) { cp = lead & 0x0Fu; extra = 2; }
322 else if ((lead & 0xF8u) == 0xF0u) { cp = lead & 0x07u; extra = 3; }
323 else { cp = 0xFFFDu; }
324 for (int k = 0; k < extra; ++k)
325 {
326 if ((*s & 0xC0u) != 0x80u) { cp = 0xFFFDu; extra = 0; break; }
327 cp = (cp << 6) | (*s++ & 0x3Fu);
328 }
329 const bool overlong = (extra == 1 && cp < 0x80u) || (extra == 2 && cp < 0x800u)
330 || (extra == 3 && cp < 0x10000u);
331 if (overlong || cp > 0x10FFFFu || (cp >= 0xD800u && cp <= 0xDFFFu))
332 cp = 0xFFFDu;
333 }
334 if (cp >= 0x10000u)
335 {
336 if (n + 2 > 127) break;
337 cp -= 0x10000u;
338 dst[n++] = static_cast<Steinberg_char16>(0xD800u + (cp >> 10));
339 dst[n++] = static_cast<Steinberg_char16>(0xDC00u + (cp & 0x3FFu));
340 }
341 else
342 {
343 if (n + 1 > 127) break;
344 dst[n++] = static_cast<Steinberg_char16>(cp);
345 }
346 }
347 dst[n] = 0;
348}
349
351inline void asciiToString128(const char* src, Steinberg_Vst_String128 dst) noexcept
352{
353 utf8ToString128(src, dst);
354}
355
358inline void string128ToUtf8(const Steinberg_char16* src, char* dst, size_t cap) noexcept
359{
360 if (dst == nullptr || cap == 0) return;
361 size_t n = 0;
362 for (int i = 0; src != nullptr && i < 128 && src[i] != 0; ++i)
363 {
364 uint32_t cp = src[i];
365 if (cp >= 0xD800u && cp <= 0xDBFFu && i + 1 < 128
366 && src[i + 1] >= 0xDC00u && src[i + 1] <= 0xDFFFu)
367 {
368 cp = 0x10000u + ((cp - 0xD800u) << 10) + (static_cast<uint32_t>(src[i + 1]) - 0xDC00u);
369 ++i;
370 }
371 else if (cp >= 0xD800u && cp <= 0xDFFFu)
372 cp = 0xFFFDu;
373 char buf[4];
374 size_t len = 0;
375 if (cp < 0x80u)
376 buf[len++] = static_cast<char>(cp);
377 else if (cp < 0x800u)
378 {
379 buf[len++] = static_cast<char>(0xC0u | (cp >> 6));
380 buf[len++] = static_cast<char>(0x80u | (cp & 0x3Fu));
381 }
382 else if (cp < 0x10000u)
383 {
384 buf[len++] = static_cast<char>(0xE0u | (cp >> 12));
385 buf[len++] = static_cast<char>(0x80u | ((cp >> 6) & 0x3Fu));
386 buf[len++] = static_cast<char>(0x80u | (cp & 0x3Fu));
387 }
388 else
389 {
390 buf[len++] = static_cast<char>(0xF0u | (cp >> 18));
391 buf[len++] = static_cast<char>(0x80u | ((cp >> 12) & 0x3Fu));
392 buf[len++] = static_cast<char>(0x80u | ((cp >> 6) & 0x3Fu));
393 buf[len++] = static_cast<char>(0x80u | (cp & 0x3Fu));
394 }
395 if (n + len + 1 > cap) break;
396 for (size_t k = 0; k < len; ++k) dst[n++] = buf[k];
397 }
398 dst[n] = '\0';
399}
400
401inline void copyAscii(const char* src, char* dst, size_t cap) noexcept
402{
403 std::snprintf(dst, cap, "%s", src ? src : "");
404}
405
407inline bool streamRead(Steinberg_IBStream* s, void* dst, Steinberg_int32 bytes) noexcept
408{
409 auto* p = static_cast<char*>(dst);
410 while (bytes > 0)
411 {
412 Steinberg_int32 got = 0;
413 if (s->lpVtbl->read(s, p, bytes, &got) != Steinberg_kResultOk || got <= 0)
414 return false;
415 p += got;
416 bytes -= got;
417 }
418 return true;
419}
420
421inline bool streamWrite(Steinberg_IBStream* s, const void* src, Steinberg_int32 bytes) noexcept
422{
423 auto* p = static_cast<const char*>(src);
424 while (bytes > 0)
425 {
426 Steinberg_int32 put = 0;
427 if (s->lpVtbl->write(s, const_cast<char*>(p), bytes, &put) != Steinberg_kResultOk
428 || put <= 0)
429 return false;
430 p += put;
431 bytes -= put;
432 }
433 return true;
434}
435
436// -- the plugin object ----------------------------------------------------------
437
438inline constexpr uint32_t kBypassParamId = 0x42595053u; // 'BYPS'
439inline constexpr uint32_t kProgramParamId = 0x5052474Du; // 'PRGM'
440inline constexpr int kBypassRampSamples = 256;
441inline constexpr Steinberg_int32 kPresetProgramListId = 1;
442
443// MIDI controllers travel as proxy parameters in VST3 (the IMidiMapping
444// scheme): one hidden ParamID per (channel, controller). Every controller
445// the VST3 numbering defines is mapped - CC 0..127, channel pressure (128)
446// and pitch bend (129) - so a plugin sees the same controllers through VST3
447// as through the raw MIDI of CLAP and AU.
448inline constexpr uint32_t kMidiProxyBase = 0x4D440000u; // 'MD' marker
449inline constexpr int kNumMidiControllers = 130; // VST3 kCountCtrlNumber
450inline constexpr int kNumMidiProxies = 16 * kNumMidiControllers;
451
452inline constexpr bool isMidiProxyId(uint32_t id) noexcept
453{
454 if ((id & 0xFFFF0000u) != kMidiProxyBase) return false;
455 const uint32_t ctrl = id & 0xFFu;
456 const uint32_t channel = (id >> 8) & 0xFFu;
457 return channel < 16 && ctrl < static_cast<uint32_t>(kNumMidiControllers);
458}
459
460inline constexpr uint32_t midiProxyId(int channel, int controller) noexcept
461{
462 return kMidiProxyBase | (static_cast<uint32_t>(channel) << 8)
463 | static_cast<uint32_t>(controller);
464}
465
467inline MidiEvent midiProxyToEvent(uint32_t id, double normalized, int offset) noexcept
468{
469 MidiEvent ev {};
470 ev.channel = static_cast<uint8_t>((id >> 8) & 0x0Fu);
471 ev.sampleOffset = offset;
472 const uint32_t ctrl = id & 0xFFu;
473 if (ctrl == 129)
474 {
476 ev.value = static_cast<float>(normalized * 2.0 - 1.0);
477 }
478 else if (ctrl == 128)
479 {
481 ev.value = static_cast<float>(normalized);
482 }
483 else
484 {
486 ev.note = static_cast<uint8_t>(ctrl);
487 ev.value = static_cast<float>(normalized);
488 }
489 return ev;
490}
491
492// -- note expressions ---------------------------------------------------------------
493
506{
507public:
508 static constexpr uint32_t kCapacity = 256; // power of two
509
510 void clear() noexcept
511 {
512 for (auto& entry : entries_) entry.noteId = -1;
513 }
514
516 void noteOn(int32_t noteId, int channel, int key) noexcept
517 {
518 if (noteId < 0) return;
519 const uint32_t home = static_cast<uint32_t>(noteId) & (kCapacity - 1);
520 uint32_t slot = home; // every slot sounding: the home slot gives way
521 for (uint32_t probe = 0; probe < kCapacity; ++probe)
522 {
523 const uint32_t at = (home + probe) & (kCapacity - 1);
524 const Entry& entry = entries_[at];
525 if (entry.noteId < 0 || !entry.held || entry.noteId == noteId)
526 {
527 slot = at;
528 break;
529 }
530 }
531 Entry& entry = entries_[slot];
532 entry.noteId = noteId;
533 entry.channel = static_cast<int16_t>(channel);
534 entry.key = static_cast<int16_t>(key);
535 entry.held = true;
536 }
537
539 void noteOff(int32_t noteId) noexcept
540 {
541 if (Entry* entry = lookup(noteId)) entry->held = false;
542 }
543
545 bool find(int32_t noteId, int& channel, int& key) noexcept
546 {
547 const Entry* entry = lookup(noteId);
548 if (entry == nullptr) return false;
549 channel = entry->channel;
550 key = entry->key;
551 return true;
552 }
553
554private:
555 struct Entry
556 {
557 int32_t noteId = -1;
558 int16_t channel = 0;
559 int16_t key = 0;
560 bool held = false;
561 };
562
564 Entry* lookup(int32_t noteId) noexcept
565 {
566 if (noteId < 0) return nullptr;
567 const uint32_t home = static_cast<uint32_t>(noteId) & (kCapacity - 1);
568 for (uint32_t probe = 0; probe < kCapacity; ++probe)
569 {
570 Entry& entry = entries_[(home + probe) & (kCapacity - 1)];
571 if (entry.noteId == noteId) return &entry;
572 if (entry.noteId < 0) return nullptr; // the chain ends here
573 }
574 return nullptr;
575 }
576
577 std::array<Entry, kCapacity> entries_ {};
578};
579
580// The six expressions VST3 defines share their numbering with ExpressionType
581// (Pressure has no VST3 type: VST3 carries it as poly pressure).
582static_assert(static_cast<int>(MidiEvent::ExpressionType::Volume)
583 == Steinberg_Vst_NoteExpressionTypeIDs_kVolumeTypeID
584 && static_cast<int>(MidiEvent::ExpressionType::Tuning)
585 == Steinberg_Vst_NoteExpressionTypeIDs_kTuningTypeID
586 && static_cast<int>(MidiEvent::ExpressionType::Brightness)
587 == Steinberg_Vst_NoteExpressionTypeIDs_kBrightnessTypeID,
588 "ExpressionType must follow the VST3 note-expression numbering");
589
593inline double vst3ExpressionValue(MidiEvent::ExpressionType type, double normalized) noexcept
594{
595 const double n = !(normalized > 0.0) ? 0.0 : (normalized > 1.0 ? 1.0 : normalized);
596 switch (type)
597 {
598 case MidiEvent::ExpressionType::Volume: return 4.0 * n;
599 case MidiEvent::ExpressionType::Tuning: return 240.0 * (n - 0.5);
600 default: return n;
601 }
602}
603
604template <typename P>
605struct Plugin
606{
607 static constexpr size_t kNumParams = P::parameters.size();
608 static constexpr bool kIsInstrument =
609 P::descriptor.category == Category::Instrument;
610 static constexpr int kNumPresets = factoryPresetCountOf<P>();
611 static_assert(!(kIsInstrument && HasSidechain<P>),
612 "an Instrument has no audio inputs; remove the sidechain "
613 "processBlock or use Category::Fx");
614 static_assert(!kIsInstrument || HasMidi<P>,
615 "an Instrument needs handleMidiEvent (see HasMidi): it has "
616 "no audio input to process");
617 static_assert(paramIdsUnique<P>(),
618 "two parameter ids share a hash32 (or collide with the "
619 "reserved PRGM/BYPS/EDSW/EDSH state ids): automation and state "
620 "would cross-wire. Rename one id.");
621
624 static constexpr uint32_t kVst3Expressions =
626 ? noteExpressionsOf<P>() & ~expressionBit(MidiEvent::ExpressionType::Pressure)
627 : 0u;
628
629 // COM lenses - consecutive vtable pointers; queryInterface returns the
630 // address of the matching slot. Standard layout is asserted below. The
631 // last three lenses surface only for the matching capability.
632 const Steinberg_Vst_IComponentVtbl* componentVtbl;
633 const Steinberg_Vst_IAudioProcessorVtbl* processorVtbl;
634 const Steinberg_Vst_IEditControllerVtbl* controllerVtbl;
635 const Steinberg_Vst_IProcessContextRequirementsVtbl* contextReqVtbl;
636 const Steinberg_Vst_IUnitInfoVtbl* unitVtbl;
637 const Steinberg_Vst_IMidiMappingVtbl* midiMapVtbl;
638 const Steinberg_Vst_INoteExpressionControllerVtbl* noteExprVtbl;
639
640 std::atomic<Steinberg_uint32> refs { 1 };
641
642 P user {};
643 Steinberg_Vst_ProcessSetup setup { 0, 0, 0, 48000.0 };
644 bool prepared = false;
651 std::atomic<int> cachedLatency { 0 };
652 int currentChannels = defaultChannelCount<P>(); // negotiated bus width
653
654 std::atomic<double> shadow[kNumParams == 0 ? 1 : kNumParams] {};
655 std::atomic<double> midiProxyShadow[HasMidi<P> ? kNumMidiProxies : 1] {};
656 std::atomic<bool> bypass { false };
657 std::atomic<int> currentProgram { 0 };
658 float bypassMix = 0.0f; // audio-thread crossfade state
659 std::vector<float> dryL, dryR; // pre-process copy for the bypass blend
660 std::vector<float> silence; // stand-in sidechain when not connected
661 DryDelay dryDelay; // latency-aligned dry path of the bypass
665
666 // Atomic pointer: refreshLatency() reads it from the audio thread while
667 // setComponentHandler writes it from the main thread. Per the VST3
668 // lifecycle the host swaps handlers only while the component is inactive,
669 // so the atomic removes the formally torn read without needing a lock.
670 std::atomic<Steinberg_Vst_IComponentHandler*> handler { nullptr };
671
672 // restartComponent() is a UI-thread call. The thread that creates and
673 // initializes the plugin is the host's UI thread; requests raised on any
674 // other thread (the audio thread, when automation moves the latency)
675 // wait in pendingRestart until the UI tick delivers them.
676 std::atomic<std::thread::id> uiThread { std::this_thread::get_id() };
677 std::atomic<Steinberg_int32> pendingRestart { 0 };
679
683 std::atomic<bool> processing { false };
685 BlockEventList blockEvents; // one block of host events (audio thread)
686 NoteIdMap noteIds; // note id -> voice, for note expressions (audio thread)
687
690 void* liveView = nullptr;
691 void (*resizeLiveView)(void* view) noexcept = nullptr;
692
693 Plugin() noexcept
694 {
702 for (size_t i = 0; i < kNumParams; ++i)
703 shadow[i].store(toNormalized(P::parameters[i], P::parameters[i].defValue),
704 std::memory_order_relaxed);
705 if constexpr (HasMidi<P>)
706 for (int ch = 0; ch < 16; ++ch) // pitch bend rests at the centre
707 midiProxyShadow[static_cast<size_t>(ch * kNumMidiControllers + 129)].store(
708 0.5, std::memory_order_relaxed);
709 }
710
711 // --- lens recovery ---------------------------------------------------------
712
713 static Plugin* fromLens(void* iface, int lens) noexcept
714 {
715 return reinterpret_cast<Plugin*>(static_cast<char*>(iface)
716 - static_cast<ptrdiff_t>(lens) * sizeof(void*));
717 }
718
719 void* lensPtr(int lens) noexcept
720 {
721 return reinterpret_cast<char*>(this) + static_cast<ptrdiff_t>(lens) * sizeof(void*);
722 }
723
724 // --- shared FUnknown --------------------------------------------------------
725
726 Steinberg_tresult query(const Steinberg_TUID iid, void** obj) noexcept
727 {
728 if (obj == nullptr) return Steinberg_kInvalidArgument;
729 *obj = nullptr;
730 if (tuidEqual(iid, Steinberg_FUnknown_iid)
731 || tuidEqual(iid, Steinberg_IPluginBase_iid)
732 || tuidEqual(iid, Steinberg_Vst_IComponent_iid))
733 *obj = lensPtr(0);
734 else if (tuidEqual(iid, Steinberg_Vst_IAudioProcessor_iid))
735 *obj = lensPtr(1);
736 else if (tuidEqual(iid, Steinberg_Vst_IEditController_iid))
737 *obj = lensPtr(2);
738 else if (tuidEqual(iid, Steinberg_Vst_IProcessContextRequirements_iid))
739 *obj = lensPtr(3);
740 else if (kNumPresets > 0 && tuidEqual(iid, Steinberg_Vst_IUnitInfo_iid))
741 *obj = lensPtr(4);
742 else if (HasMidi<P> && tuidEqual(iid, Steinberg_Vst_IMidiMapping_iid))
743 *obj = lensPtr(5);
744 else if (kVst3Expressions != 0u
745 && tuidEqual(iid, Steinberg_Vst_INoteExpressionController_iid))
746 *obj = lensPtr(6);
747 if (*obj == nullptr) return Steinberg_kNoInterface;
748 refs.fetch_add(1, std::memory_order_relaxed);
749 return Steinberg_kResultOk;
750 }
751
752 Steinberg_uint32 addRefImpl() noexcept
753 {
754 return refs.fetch_add(1, std::memory_order_relaxed) + 1;
755 }
756
757 Steinberg_uint32 releaseImpl() noexcept
758 {
759 const Steinberg_uint32 left = refs.fetch_sub(1, std::memory_order_acq_rel) - 1;
760 if (left == 0) delete this;
761 return left;
762 }
763
764 template <int Lens>
765 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sQuery(void* self_,
766 const Steinberg_TUID iid,
767 void** obj)
768 { return fromLens(self_, Lens)->query(iid, obj); }
769
770 template <int Lens>
771 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sAddRef(void* self_)
772 { return fromLens(self_, Lens)->addRefImpl(); }
773
774 template <int Lens>
775 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sRelease(void* self_)
776 { return fromLens(self_, Lens)->releaseImpl(); }
777
778 // --- parameter plumbing ------------------------------------------------------
779
780 static int indexOfParamId(Steinberg_Vst_ParamID id) noexcept
781 {
782 return paramIndexOf<P>(id);
783 }
784
786 void applyNormalized(int index, double normalized) noexcept
787 {
788 // Host values are untrusted doubles: a NaN would pass both range
789 // clamps, poison the shadow and reach the user's setter. Ignore it.
790 if (normalized != normalized) return;
791 const auto& spec = P::parameters[static_cast<size_t>(index)];
792 shadow[static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
793 user.setParameter(index, static_cast<float>(toPlain(spec, normalized)));
794 }
795
805 bool applyFromUi(int index, double normalized) noexcept
806 {
807 if (normalized != normalized) return false;
808 if (processing.load(std::memory_order_acquire))
809 {
810 shadow[static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
811 pending.mark(static_cast<size_t>(index));
812 return false;
813 }
814 applyNormalized(index, normalized);
815 return true;
816 }
817
820 bool drainPending() noexcept
821 {
822 return pending.drain([this](int i) {
823 user.setParameter(i, static_cast<float>(toPlain(
824 P::parameters[static_cast<size_t>(i)],
825 shadow[static_cast<size_t>(i)].load(std::memory_order_relaxed))));
826 });
827 }
828
829 void applyAllShadows() noexcept
830 {
831 pending.drain([](int) {}); // every value is re-applied right below
832 for (size_t i = 0; i < kNumParams; ++i)
833 user.setParameter(static_cast<int>(i),
834 static_cast<float>(toPlain(P::parameters[i],
835 shadow[i].load(std::memory_order_relaxed))));
836 }
837
841 void applyFactoryPresetIdx(int idx, bool fromUi = false) noexcept
842 {
843 if constexpr (kNumPresets > 0)
844 {
845 if (idx < 0 || idx >= kNumPresets) return;
846 for (size_t i = 0; i < kNumParams; ++i)
847 {
848 if (fromUi) applyFromUi(static_cast<int>(i), presetNormalized<P>(idx, i));
849 else applyNormalized(static_cast<int>(i), presetNormalized<P>(idx, i));
850 }
851 currentProgram.store(idx, std::memory_order_relaxed);
852 }
853 else
854 {
855 (void) idx;
856 (void) fromUi;
857 }
858 }
859
867 static int programIndexOf(Steinberg_Vst_ParamValue normalized) noexcept
868 {
869 if constexpr (kNumPresets <= 0)
870 return 0;
871 else
872 return toBoundedInt(normalized * (kNumPresets - 1) + 0.5,
873 0, kNumPresets - 1);
874 }
875
877 {
878 uiTicker.stop();
879 if (auto* h = handler.exchange(nullptr, std::memory_order_relaxed); h != nullptr)
880 reinterpret_cast<Steinberg_FUnknown*>(h)->lpVtbl->release(h);
881 }
882
886 void refreshLatency(Steinberg_int32 extraFlags = 0) noexcept
887 {
888 Steinberg_int32 flags = extraFlags;
889 if constexpr (HasLatency<P>)
890 {
891 const int now = user.getLatency();
892 if (prepared && now != cachedLatency.load(std::memory_order_relaxed))
893 {
894 cachedLatency.store(now, std::memory_order_relaxed);
895 flags |= Steinberg_Vst_RestartFlags_kLatencyChanged;
896 }
897 }
898 if (flags != 0) requestRestart(flags);
899 }
900
901 [[nodiscard]] bool onUiThread() const noexcept
902 {
903 return std::this_thread::get_id() == uiThread.load(std::memory_order_relaxed);
904 }
905
914 void requestRestart(Steinberg_int32 flags) noexcept
915 {
916 if (onUiThread())
917 {
918 flags |= pendingRestart.exchange(0, std::memory_order_acq_rel);
919 if (auto* h = handler.load(std::memory_order_relaxed); h != nullptr)
920 h->lpVtbl->restartComponent(h, flags);
921 return;
922 }
923 pendingRestart.fetch_or(flags, std::memory_order_release);
924 }
925
927 void deliverPendingRestart() noexcept
928 {
929 if (!onUiThread()) return;
930 const Steinberg_int32 flags = pendingRestart.exchange(0, std::memory_order_acq_rel);
931 if (flags != 0)
932 if (auto* h = handler.load(std::memory_order_relaxed); h != nullptr)
933 h->lpVtbl->restartComponent(h, flags);
934 }
935
936 static void onUiTick(void* self) noexcept
937 {
938 static_cast<Plugin*>(self)->deliverPendingRestart();
939 }
940
943 void attachToHost(Steinberg_FUnknown* context) noexcept
944 {
945 uiThread.store(std::this_thread::get_id(), std::memory_order_relaxed);
946 if constexpr (HasLatency<P> || kNumPresets > 0)
947 uiTicker.start(context, &onUiTick, this);
948 else
949 (void) context;
950 }
951
956 void detachFromHost() noexcept
957 {
959 uiTicker.stop();
960 if (auto* h = handler.exchange(nullptr, std::memory_order_acq_rel); h != nullptr)
961 reinterpret_cast<Steinberg_FUnknown*>(h)->lpVtbl->release(h);
962 }
963
964 // --- block event plumbing -------------------------------------------------------
965 //
966 // Every host input lands in ONE timestamped stream (parameter points,
967 // bypass points, note events), sorted and applied either at sub-block
968 // boundaries (sample-accurate, the default) or all up front.
969
976 void collectParameterChanges(Steinberg_Vst_IParameterChanges* changes,
977 Steinberg_int32 numSamples,
978 BlockEventList& events) noexcept
979 {
980 if (changes == nullptr) return;
981 const Steinberg_int32 queues = changes->lpVtbl->getParameterCount(changes);
982 for (Steinberg_int32 q = 0; q < queues; ++q)
983 {
984 Steinberg_Vst_IParamValueQueue* queue =
985 changes->lpVtbl->getParameterData(changes, q);
986 if (queue == nullptr) continue;
987 const Steinberg_int32 points = queue->lpVtbl->getPointCount(queue);
988 if (points <= 0) continue;
989 const Steinberg_Vst_ParamID id = queue->lpVtbl->getParameterId(queue);
990 const bool everyPoint = sampleAccurateOf<P>() || (HasMidi<P> && isMidiProxyId(id));
991 const Steinberg_int32 first = everyPoint ? 0 : points - 1;
992 for (Steinberg_int32 i = first; i < points; ++i)
993 {
994 Steinberg_int32 offset = 0;
995 Steinberg_Vst_ParamValue value = 0.0;
996 if (queue->lpVtbl->getPoint(queue, i, &offset, &value)
997 != Steinberg_kResultOk)
998 continue;
999 if (offset < 0) offset = 0;
1000 if (numSamples > 0 && offset >= numSamples) offset = numSamples - 1;
1001 BlockEvent ev {};
1002 ev.offset = offset;
1005 ev.paramId = id;
1006 ev.value = value;
1007 // Past the capacity an intermediate point gives way; the old
1008 // code overwrote the last slot, losing every point but the
1009 // final one - final parameter values and note-offs included.
1010 events.add(ev);
1011 }
1012 }
1013 }
1014
1016 void collectInputEvents(Steinberg_Vst_IEventList* list,
1017 Steinberg_int32 numSamples,
1018 BlockEventList& events) noexcept
1019 {
1020 if constexpr (HasMidi<P>)
1021 {
1022 if (list == nullptr) return;
1023 const Steinberg_int32 n = list->lpVtbl->getEventCount(list);
1024 for (Steinberg_int32 i = 0; i < n; ++i)
1025 {
1026 Steinberg_Vst_Event raw {};
1027 if (list->lpVtbl->getEvent(list, i, &raw) != Steinberg_kResultOk)
1028 continue;
1029 MidiEvent midi {};
1030 if (raw.type == Steinberg_Vst_Event_EventTypes_kNoteOnEvent)
1031 {
1033 midi.channel = static_cast<uint8_t>(
1034 raw.Steinberg_Vst_Event_noteOn.channel & 0x0F);
1035 midi.note = static_cast<uint8_t>(
1036 raw.Steinberg_Vst_Event_noteOn.pitch & 0x7F);
1037 midi.value = raw.Steinberg_Vst_Event_noteOn.velocity;
1038 midi.noteId = raw.Steinberg_Vst_Event_noteOn.noteId >= 0
1039 ? raw.Steinberg_Vst_Event_noteOn.noteId : -1;
1040 }
1041 else if (raw.type == Steinberg_Vst_Event_EventTypes_kNoteOffEvent)
1042 {
1043 midi.type = MidiEvent::Type::NoteOff;
1044 midi.channel = static_cast<uint8_t>(
1045 raw.Steinberg_Vst_Event_noteOff.channel & 0x0F);
1046 midi.note = static_cast<uint8_t>(
1047 raw.Steinberg_Vst_Event_noteOff.pitch & 0x7F);
1048 midi.value = raw.Steinberg_Vst_Event_noteOff.velocity;
1049 midi.noteId = raw.Steinberg_Vst_Event_noteOff.noteId >= 0
1050 ? raw.Steinberg_Vst_Event_noteOff.noteId : -1;
1051 }
1052 else if (raw.type == Steinberg_Vst_Event_EventTypes_kPolyPressureEvent)
1053 {
1055 midi.channel = static_cast<uint8_t>(
1056 raw.Steinberg_Vst_Event_polyPressure.channel & 0x0F);
1057 midi.note = static_cast<uint8_t>(
1058 raw.Steinberg_Vst_Event_polyPressure.pitch & 0x7F);
1059 midi.value = raw.Steinberg_Vst_Event_polyPressure.pressure;
1060 }
1061 else if (raw.type == Steinberg_Vst_Event_EventTypes_kNoteExpressionValueEvent)
1062 {
1063 // A declared expression of a note this plugin started:
1064 // the host names it by note id only. The old wrapper
1065 // offered no expressions and dropped these events.
1066 if constexpr (kVst3Expressions == 0u)
1067 continue;
1068 else
1069 {
1070 const auto& ne = raw.Steinberg_Vst_Event_noteExpressionValue;
1071 const double v = ne.value;
1072 if (ne.typeId > static_cast<Steinberg_Vst_NoteExpressionTypeID>(
1073 Steinberg_Vst_NoteExpressionTypeIDs_kBrightnessTypeID)
1074 || v != v)
1075 continue;
1076 const auto type = static_cast<MidiEvent::ExpressionType>(ne.typeId);
1077 int channel = 0, key = 0;
1078 if ((kVst3Expressions & expressionBit(type)) == 0u
1079 || !noteIds.find(ne.noteId, channel, key))
1080 continue;
1082 midi.expression = type;
1083 midi.channel = static_cast<uint8_t>(channel & 0x0F);
1084 midi.note = static_cast<uint8_t>(key & 0x7F);
1085 midi.noteId = ne.noteId;
1086 midi.value = static_cast<float>(vst3ExpressionValue(type, v));
1087 }
1088 }
1089 else
1090 continue;
1091 Steinberg_int32 offset = raw.sampleOffset;
1092 if (offset < 0) offset = 0;
1093 if (numSamples > 0 && offset >= numSamples) offset = numSamples - 1;
1094 BlockEvent ev {};
1095 ev.offset = offset;
1096 ev.kind = BlockEvent::Kind::Midi;
1097 ev.midi = midi;
1098 events.add(ev);
1099 if constexpr (kVst3Expressions != 0u)
1100 {
1101 if (midi.type == MidiEvent::Type::NoteOn)
1102 {
1103 noteIds.noteOn(midi.noteId, midi.channel, midi.note);
1104 // The NoteOn's own tuning (cents) is the voice's
1105 // first Tuning expression, delivered right after it.
1106 const float cents = raw.Steinberg_Vst_Event_noteOn.tuning;
1108 != 0u
1109 && cents != 0.0f && cents == cents)
1110 {
1111 BlockEvent tune = ev;
1114 const float semis = cents / 100.0f;
1115 tune.midi.value = semis < -120.0f ? -120.0f
1116 : (semis > 120.0f ? 120.0f : semis);
1117 events.add(tune);
1118 }
1119 }
1120 else if (midi.type == MidiEvent::Type::NoteOff)
1121 noteIds.noteOff(midi.noteId);
1122 }
1123 }
1124 }
1125 else
1126 {
1127 (void) list;
1128 (void) numSamples;
1129 (void) events;
1130 }
1131 }
1132
1137 bool applyBlockEvent(const BlockEvent& ev, int blockStart,
1138 bool& programChanged) noexcept
1139 {
1140 switch (ev.kind)
1141 {
1143 bypass.store(ev.value >= 0.5, std::memory_order_relaxed);
1144 return false;
1146 if constexpr (HasMidi<P>)
1147 {
1148 MidiEvent midi = ev.midi;
1149 midi.sampleOffset = ev.offset - blockStart;
1150 if (midi.sampleOffset < 0) midi.sampleOffset = 0;
1151 user.handleMidiEvent(midi);
1152 }
1153 return false;
1155 default:
1156 if constexpr (kNumPresets > 0)
1157 {
1158 if (ev.paramId == kProgramParamId)
1159 {
1161 programChanged = true;
1162 return true;
1163 }
1164 }
1165 if constexpr (HasMidi<P>)
1166 {
1167 if (isMidiProxyId(ev.paramId))
1168 {
1169 const int slot = midiProxySlot(ev.paramId);
1170 midiProxyShadow[static_cast<size_t>(slot)].store(
1171 ev.value, std::memory_order_relaxed);
1172 MidiEvent midi = midiProxyToEvent(ev.paramId, ev.value,
1173 ev.offset - blockStart);
1174 if (midi.sampleOffset < 0) midi.sampleOffset = 0;
1175 user.handleMidiEvent(midi);
1176 return false;
1177 }
1178 }
1179 if (const int idx = indexOfParamId(ev.paramId); idx >= 0)
1180 {
1181 applyNormalized(idx, ev.value);
1182 return true;
1183 }
1184 return false;
1185 }
1186 }
1187
1189 static int midiProxySlot(uint32_t id) noexcept
1190 {
1191 const int channel = static_cast<int>((id >> 8) & 0x0Fu);
1192 const int ctrl = static_cast<int>(id & 0xFFu);
1193 return channel * kNumMidiControllers
1194 + (ctrl < kNumMidiControllers ? ctrl : kNumMidiControllers - 1);
1195 }
1196
1197 // ==========================================================================
1198 // Lens 0 - IComponent (+ IPluginBase)
1199 // ==========================================================================
1200
1201 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sInitialize(void* self_,
1202 Steinberg_FUnknown* context)
1203 {
1204 fromLens(self_, 0)->attachToHost(context);
1205 return Steinberg_kResultOk;
1206 }
1207
1208 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sTerminate(void* self_)
1209 {
1210 fromLens(self_, 0)->detachFromHost();
1211 return Steinberg_kResultOk;
1212 }
1213
1214 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetControllerClassId(void*, Steinberg_TUID)
1215 { return Steinberg_kResultFalse; } // single component: no separate controller
1216
1217 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetIoMode(void*, Steinberg_Vst_IoMode)
1218 { return Steinberg_kResultOk; }
1219
1222 static Steinberg_int32 numInputBuses() noexcept
1223 {
1224 if (kIsInstrument) return 0;
1225 return HasSidechain<P> ? 2 : 1;
1226 }
1227
1228 static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetBusCount(void*,
1229 Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir)
1230 {
1231 if (type == Steinberg_Vst_MediaTypes_kEvent)
1232 return (HasMidi<P> && dir == Steinberg_Vst_BusDirections_kInput) ? 1 : 0;
1233 if (type != Steinberg_Vst_MediaTypes_kAudio) return 0;
1234 return dir == Steinberg_Vst_BusDirections_kInput ? numInputBuses() : 1;
1235 }
1236
1237 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetBusInfo(void* self_,
1238 Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir,
1239 Steinberg_int32 index, Steinberg_Vst_BusInfo* bus)
1240 {
1241 if (bus == nullptr) return Steinberg_kInvalidArgument;
1242 if (type == Steinberg_Vst_MediaTypes_kEvent)
1243 {
1244 if (!HasMidi<P> || dir != Steinberg_Vst_BusDirections_kInput
1245 || index != 0)
1246 return Steinberg_kInvalidArgument;
1247 bus->mediaType = Steinberg_Vst_MediaTypes_kEvent;
1248 bus->direction = dir;
1249 bus->channelCount = 16;
1250 bus->busType = Steinberg_Vst_BusTypes_kMain;
1251 bus->flags = Steinberg_Vst_BusInfo_BusFlags_kDefaultActive;
1252 asciiToString128("MIDI In", bus->name);
1253 return Steinberg_kResultOk;
1254 }
1255 const Steinberg_int32 count =
1256 dir == Steinberg_Vst_BusDirections_kInput ? numInputBuses() : 1;
1257 if (type != Steinberg_Vst_MediaTypes_kAudio || index < 0 || index >= count)
1258 return Steinberg_kInvalidArgument;
1259 bus->mediaType = Steinberg_Vst_MediaTypes_kAudio;
1260 bus->direction = dir;
1261 bus->channelCount = fromLens(self_, 0)->currentChannels;
1262 bus->busType = index == 0 ? Steinberg_Vst_BusTypes_kMain
1263 : Steinberg_Vst_BusTypes_kAux;
1264 bus->flags = Steinberg_Vst_BusInfo_BusFlags_kDefaultActive;
1265 asciiToString128(index == 1 ? "Sidechain"
1266 : (dir == Steinberg_Vst_BusDirections_kInput ? "Input"
1267 : "Output"),
1268 bus->name);
1269 return Steinberg_kResultOk;
1270 }
1271
1272 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetRoutingInfo(void*,
1273 Steinberg_Vst_RoutingInfo*, Steinberg_Vst_RoutingInfo*)
1274 { return Steinberg_kNotImplemented; }
1275
1276 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sActivateBus(void*,
1277 Steinberg_Vst_MediaType, Steinberg_Vst_BusDirection, Steinberg_int32,
1278 Steinberg_TBool)
1279 { return Steinberg_kResultOk; }
1280
1281 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetActive(void* self_, Steinberg_TBool state)
1282 {
1283 auto* p = fromLens(self_, 0);
1284 if (state)
1285 {
1286 const int maxBlock = p->setup.maxSamplesPerBlock > 0
1287 ? p->setup.maxSamplesPerBlock : 512;
1288 const double sr = p->setup.sampleRate > 0.0 ? p->setup.sampleRate : 48000.0;
1289 dspark::AudioSpec spec { sr, maxBlock, p->currentChannels };
1290 p->user.prepare(spec);
1291 if constexpr (HasOfflineMode<P>)
1292 p->user.setOfflineRendering(
1293 p->setup.processMode == Steinberg_Vst_ProcessModes_kOffline);
1294 p->applyAllShadows();
1295 p->dryL.assign(static_cast<size_t>(maxBlock), 0.0f);
1296 p->dryR.assign(static_cast<size_t>(maxBlock), 0.0f);
1297 if constexpr (HasSidechain<P>)
1298 p->silence.assign(static_cast<size_t>(maxBlock), 0.0f);
1299 p->bypassMix = p->bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1300 if constexpr (HasLatency<P>)
1301 {
1302 const int latency = p->user.getLatency();
1303 p->cachedLatency.store(latency, std::memory_order_relaxed);
1304 p->dryDelay.prepare(std::max(2 * latency, kDryDelayMinCapacity), maxBlock);
1305 }
1306 p->noteIds.clear(); // the host starts its notes again
1307 p->prepared = true;
1308 }
1309 else
1310 {
1311 // Processing is over: UI-side changes may reach the DSP directly.
1312 p->processing.store(false, std::memory_order_release);
1313 p->drainPending();
1314 }
1315 p->deliverPendingRestart();
1316 return Steinberg_kResultOk;
1317 }
1318
1319 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sComponentSetState(void* self_,
1320 Steinberg_IBStream* state)
1321 {
1322 auto* p = fromLens(self_, 0);
1323 if (state == nullptr) return Steinberg_kInvalidArgument;
1324 // Read whatever the host hands us (chunked). The cap only stops a
1325 // hostile endless stream: getState() has no size limit, so the old
1326 // 16 MiB cap refused states this plugin had itself written.
1327 std::vector<uint8_t> blob;
1328 char chunk[4096];
1329 for (;;)
1330 {
1331 Steinberg_int32 got = 0;
1332 if (state->lpVtbl->read(state, chunk, static_cast<Steinberg_int32>(sizeof(chunk)),
1333 &got) != Steinberg_kResultOk || got <= 0)
1334 break;
1335 blob.insert(blob.end(), chunk, chunk + got);
1336 if (blob.size() > kMaxStateBytes) return Steinberg_kResultFalse;
1337 }
1338 // Parameters the blob does not carry take their DEFAULTS (the old
1339 // code kept whatever value the instance happened to hold).
1340 double norm[kNumParams == 0 ? 1 : kNumParams];
1341 loadDefaultNormalized<P>(norm);
1342 int program = -1;
1343 int bypassState = -1;
1344 EditorSize editorSize { 0, 0 };
1345 if (!applyState(p->user, blob.data(), blob.size(), norm, &program,
1346 &bypassState, &editorSize))
1347 return Steinberg_kResultFalse;
1348 for (size_t i = 0; i < kNumParams; ++i)
1349 p->applyFromUi(static_cast<int>(i), norm[i]);
1350 if (kNumPresets > 0 && program >= 0 && program < kNumPresets)
1351 p->currentProgram.store(program, std::memory_order_relaxed);
1352 if (bypassState >= 0)
1353 p->bypass.store(bypassState != 0, std::memory_order_relaxed);
1354 // The editor size the session left: the next view opens at it (a
1355 // state without one keeps the size this instance has), and a view
1356 // that exists right now takes it at once (the old code waited for
1357 // the next view).
1358 if (editorSize.width > 0)
1359 {
1360 p->editorMemory.remember(editorSize.width, editorSize.height);
1361 if (p->liveView != nullptr && p->resizeLiveView != nullptr)
1362 p->resizeLiveView(p->liveView);
1363 }
1364 p->refreshLatency(); // restored state may imply a new lookahead
1365 return Steinberg_kResultOk;
1366 }
1367
1368 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sComponentGetState(void* self_,
1369 Steinberg_IBStream* state)
1370 {
1371 auto* p = fromLens(self_, 0);
1372 if (state == nullptr) return Steinberg_kInvalidArgument;
1373 p->deliverPendingRestart(); // hosts autosave from the UI thread
1374 double norm[kNumParams == 0 ? 1 : kNumParams];
1375 for (size_t i = 0; i < kNumParams; ++i)
1376 norm[i] = p->shadow[i].load(std::memory_order_relaxed);
1377 EditorSize editorSize {};
1378 const bool withSize = p->editorMemory.remembered(editorSize);
1379 const std::vector<uint8_t> blob = buildState(
1380 p->user, norm, kNumParams,
1381 kNumPresets > 0 ? p->currentProgram.load(std::memory_order_relaxed) : -1,
1382 p->bypass.load(std::memory_order_relaxed) ? 1 : 0,
1383 withSize ? &editorSize : nullptr);
1384 return streamWrite(state, blob.data(), static_cast<Steinberg_int32>(blob.size()))
1385 ? Steinberg_kResultOk : Steinberg_kResultFalse;
1386 }
1387
1388 inline static const Steinberg_Vst_IComponentVtbl kComponentVtbl = {
1389 &sQuery<0>, &sAddRef<0>, &sRelease<0>,
1394 };
1395
1396 // ==========================================================================
1397 // Lens 1 - IAudioProcessor
1398 // ==========================================================================
1399
1402 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetBusArrangements(void* self_,
1403 Steinberg_Vst_SpeakerArrangement* inputs, Steinberg_int32 numIns,
1404 Steinberg_Vst_SpeakerArrangement* outputs, Steinberg_int32 numOuts)
1405 {
1406 if (numIns != numInputBuses() || numOuts != 1
1407 || (numIns > 0 && inputs == nullptr) || outputs == nullptr)
1408 return Steinberg_kResultFalse;
1409 const Steinberg_Vst_SpeakerArrangement want = outputs[0];
1410 int channels = 0;
1411 if (want == Steinberg_Vst_SpeakerArr_kMono) channels = 1;
1412 else if (want == Steinberg_Vst_SpeakerArr_kStereo) channels = 2;
1413 if (channels == 0 || !supportsChannelCount<P>(channels))
1414 return Steinberg_kResultFalse;
1415 for (Steinberg_int32 i = 0; i < numIns; ++i)
1416 if (inputs[i] != want)
1417 return Steinberg_kResultFalse;
1418 fromLens(self_, 1)->currentChannels = channels;
1419 return Steinberg_kResultTrue;
1420 }
1421
1422 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetBusArrangement(void* self_,
1423 Steinberg_Vst_BusDirection dir, Steinberg_int32 index,
1424 Steinberg_Vst_SpeakerArrangement* arr)
1425 {
1426 const Steinberg_int32 count =
1427 dir == Steinberg_Vst_BusDirections_kInput ? numInputBuses() : 1;
1428 if (index < 0 || index >= count || arr == nullptr)
1429 return Steinberg_kInvalidArgument;
1430 *arr = fromLens(self_, 1)->currentChannels == 1
1431 ? Steinberg_Vst_SpeakerArr_kMono : Steinberg_Vst_SpeakerArr_kStereo;
1432 return Steinberg_kResultOk;
1433 }
1434
1435 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCanProcessSampleSize(void*,
1436 Steinberg_int32 size)
1437 {
1438 return size == Steinberg_Vst_SymbolicSampleSizes_kSample32
1439 ? Steinberg_kResultTrue : Steinberg_kResultFalse;
1440 }
1441
1442 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sGetLatencySamples(void* self_)
1443 {
1444 return static_cast<Steinberg_uint32>(
1445 fromLens(self_, 1)->cachedLatency.load(std::memory_order_relaxed));
1446 }
1447
1448 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetupProcessing(void* self_,
1449 Steinberg_Vst_ProcessSetup* setup)
1450 {
1451 if (setup == nullptr) return Steinberg_kInvalidArgument;
1452 fromLens(self_, 1)->setup = *setup;
1453 return Steinberg_kResultOk;
1454 }
1455
1463 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetProcessing(void* self_,
1464 Steinberg_TBool state)
1465 {
1466 auto* p = fromLens(self_, 1);
1467 if (state)
1468 {
1469 p->processing.store(true, std::memory_order_release);
1470 p->clearHistory();
1471 return Steinberg_kResultOk;
1472 }
1473 p->processing.store(false, std::memory_order_release);
1474 p->drainPending();
1475 p->clearHistory();
1476 return Steinberg_kResultOk;
1477 }
1478
1481 void clearHistory() noexcept
1482 {
1483 if constexpr (HasReset<P>)
1484 user.reset();
1485 dryDelay.reset();
1486 bypassMix = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1487 }
1488
1491 void blendBypass(float* const* out, float* const* dry, int nCh, int outStart,
1492 int dryStart, int length) noexcept
1493 {
1494 const float target = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1495 if (bypassMix == target && target == 0.0f) return;
1496 const float step = 1.0f / static_cast<float>(kBypassRampSamples);
1497 float mix = bypassMix;
1498 for (int i = 0; i < length; ++i)
1499 {
1500 mix += (target > mix) ? step : ((target < mix) ? -step : 0.0f);
1501 mix = mix < 0.0f ? 0.0f : (mix > 1.0f ? 1.0f : mix);
1502 for (int ch = 0; ch < nCh; ++ch)
1503 out[ch][outStart + i] += (dry[ch][dryStart + i] - out[ch][outStart + i]) * mix;
1504 }
1505 bypassMix = mix;
1506 }
1507
1509 void forwardTransport(const Steinberg_Vst_ProcessContext* ctx) noexcept
1510 {
1511 if constexpr (HasTransport<P>)
1512 {
1513 if (ctx == nullptr) return;
1514 TransportInfo t {};
1515 const Steinberg_uint32 s = ctx->state;
1516 t.playing = (s & Steinberg_Vst_ProcessContext_StatesAndFlags_kPlaying) != 0;
1517 t.recording = (s & Steinberg_Vst_ProcessContext_StatesAndFlags_kRecording) != 0;
1518 t.looping = (s & Steinberg_Vst_ProcessContext_StatesAndFlags_kCycleActive) != 0;
1519 if ((s & Steinberg_Vst_ProcessContext_StatesAndFlags_kTempoValid) != 0)
1520 {
1521 t.tempoBpm = ctx->tempo;
1522 t.tempoValid = true;
1523 }
1524 if ((s & Steinberg_Vst_ProcessContext_StatesAndFlags_kProjectTimeMusicValid) != 0)
1525 {
1526 t.ppqPosition = ctx->projectTimeMusic;
1527 t.positionValid = true;
1528 }
1529 if ((s & Steinberg_Vst_ProcessContext_StatesAndFlags_kBarPositionValid) != 0)
1530 t.barStartPpq = ctx->barPositionMusic;
1531 if ((s & Steinberg_Vst_ProcessContext_StatesAndFlags_kTimeSigValid) != 0)
1532 {
1533 t.timeSigNumerator = ctx->timeSigNumerator;
1534 t.timeSigDenominator = ctx->timeSigDenominator;
1535 t.timeSigValid = true;
1536 }
1537 if ((s & Steinberg_Vst_ProcessContext_StatesAndFlags_kCycleValid) != 0)
1538 {
1539 t.loopStartPpq = ctx->cycleStartMusic;
1540 t.loopEndPpq = ctx->cycleEndMusic;
1541 t.loopValid = true;
1542 }
1543 user.setTransport(t);
1544 }
1545 else
1546 (void) ctx;
1547 }
1548
1549 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sProcess(void* self_,
1550 Steinberg_Vst_ProcessData* data)
1551 {
1552 auto* p = fromLens(self_, 1);
1553 if (data == nullptr) return Steinberg_kInvalidArgument;
1554
1555 // FTZ/DAZ for the whole callback: DSPark processors guard their own
1556 // hot loops, this covers user DSP in hosts that do not set it.
1557 dspark::DenormalGuard denormalGuard;
1558
1559 const Steinberg_int32 n = data->numSamples;
1560
1561 // From here on the audio thread owns setParameter (a host that never
1562 // calls setProcessing(true) still gets the single-writer rule), and
1563 // it first applies what the UI thread handed over since the last
1564 // block, so the host's own queue points below still win.
1565 p->processing.store(true, std::memory_order_relaxed);
1566 bool paramsChanged = p->drainPending();
1567 bool programChanged = false;
1568
1569 // One timestamped stream for everything the host handed us.
1570 BlockEventList& events = p->blockEvents;
1571 events.clear();
1572 p->collectParameterChanges(data->inputParameterChanges, n, events);
1573 p->collectInputEvents(data->inputEvents, n, events);
1574 events.sort();
1575 const int eventCount = events.size();
1576
1577 const bool canRender = n > 0
1578 && data->symbolicSampleSize == Steinberg_Vst_SymbolicSampleSizes_kSample32
1579 && data->numOutputs >= 1 && data->outputs != nullptr && p->prepared;
1580 if (!canRender)
1581 {
1582 // Parameter flush (n == 0) or unrenderable block: still apply
1583 // every event so automation/state never desynchronises.
1584 for (int i = 0; i < eventCount; ++i)
1585 paramsChanged |= p->applyBlockEvent(events[i], events[i].offset,
1586 programChanged);
1587 if (paramsChanged || programChanged)
1588 p->refreshLatency(programChanged
1589 ? Steinberg_Vst_RestartFlags_kParamValuesChanged : 0);
1590 if (n <= 0) return Steinberg_kResultOk;
1591 return data->symbolicSampleSize
1592 == Steinberg_Vst_SymbolicSampleSizes_kSample32
1593 ? Steinberg_kResultOk : Steinberg_kResultFalse;
1594 }
1595
1596 p->forwardTransport(data->processContext);
1597
1598 auto& outBus = data->outputs[0];
1599 float** out = outBus.Steinberg_Vst_AudioBusBuffers_channelBuffers32;
1600 const int width = p->currentChannels;
1601 int nCh = out == nullptr ? 0 : (outBus.numChannels < width ? outBus.numChannels : width);
1602 // Degenerate hosts: stop at the first missing channel pointer. The old
1603 // trim only looked at the last one, so a null left channel next to a
1604 // valid right one was written through.
1605 for (int ch = 0; ch < nCh; ++ch)
1606 if (out[ch] == nullptr)
1607 {
1608 nCh = ch;
1609 break;
1610 }
1611 if (nCh < 1)
1612 {
1613 // Nothing to render into: still apply the block's events, so
1614 // automation, notes and state never desynchronise.
1615 for (int i = 0; i < eventCount; ++i)
1616 paramsChanged |= p->applyBlockEvent(events[i], events[i].offset,
1617 programChanged);
1618 if (paramsChanged || programChanged)
1619 p->refreshLatency(programChanged
1620 ? Steinberg_Vst_RestartFlags_kParamValuesChanged : 0);
1621 return Steinberg_kResultOk;
1622 }
1623
1624 const bool haveIn = !kIsInstrument
1625 && data->numInputs >= 1 && data->inputs != nullptr
1626 && data->inputs[0].Steinberg_Vst_AudioBusBuffers_channelBuffers32 != nullptr
1627 && data->inputs[0].numChannels >= 1;
1628 float** in = haveIn
1629 ? data->inputs[0].Steinberg_Vst_AudioBusBuffers_channelBuffers32 : nullptr;
1630 const int inCh = haveIn ? static_cast<int>(data->inputs[0].numChannels) : 0;
1631
1632 // Sidechain: aux bus 1, pre-allocated silence when nothing is
1633 // routed (same frame count, no branches user-side). Read-only.
1634 float* scHost[2] = { nullptr, nullptr };
1635 if constexpr (HasSidechain<P>)
1636 {
1637 if (data->numInputs >= 2 && data->inputs != nullptr
1638 && data->inputs[1].Steinberg_Vst_AudioBusBuffers_channelBuffers32
1639 != nullptr)
1640 {
1641 const auto& scBus = data->inputs[1];
1642 float** sc = scBus.Steinberg_Vst_AudioBusBuffers_channelBuffers32;
1643 const int scCh = scBus.numChannels < 2 ? scBus.numChannels : 2;
1644 for (int ch = 0; ch < scCh; ++ch)
1645 scHost[ch] = sc[ch];
1646 if (scCh == 1)
1647 scHost[1] = sc[0]; // mono key feeds both detector ears
1648 }
1649 }
1650
1651 // A block longer than the prepared maximum (hosts that ignore
1652 // maxSamplesPerBlock) runs as consecutive chunks of at most that
1653 // size: the user DSP never sees more frames than it prepared for.
1654 const int chunkMax = static_cast<int>(p->dryL.size());
1655 if (chunkMax < 1) return Steinberg_kResultOk;
1656 float* dry[2] = { p->dryL.data(), p->dryR.data() };
1657 int evIdx = 0;
1658
1659 for (int c0 = 0; c0 < n; c0 += chunkMax)
1660 {
1661 const int len = n - c0 < chunkMax ? n - c0 : chunkMax;
1662 const int cEnd = c0 + len;
1663
1664 // Keep the dry signal for the bypass blend, then process the
1665 // output buffers in place (copying input over first when
1666 // distinct). An instrument has no input: its output starts
1667 // cleared (voices ADD) and its bypass blends toward silence (the
1668 // dry vectors stay zero). Output channels past a narrower input
1669 // bus (a host that ignored the arrangement) repeat its last one.
1670 // An effect whose input is missing (no bus, a deactivated bus, a
1671 // null channel pointer) processes silence: the old code fell back
1672 // to the output buffer, feeding the host's stale output - often
1673 // the previous block - back in as input.
1674 const size_t bytes = sizeof(float) * static_cast<size_t>(len);
1675 for (int ch = 0; ch < nCh; ++ch)
1676 {
1677 const float* src = nullptr;
1678 if (!kIsInstrument && haveIn)
1679 src = in[ch < inCh ? ch : inCh - 1];
1680 if (src == nullptr)
1681 {
1682 std::memset(out[ch] + c0, 0, bytes);
1683 if (!kIsInstrument) std::memset(dry[ch], 0, bytes);
1684 continue;
1685 }
1686 std::memcpy(dry[ch], src + c0, bytes);
1687 if (out[ch] != src)
1688 std::memcpy(out[ch] + c0, src + c0, bytes);
1689 }
1690 if constexpr (HasLatency<P> && !kIsInstrument)
1691 p->dryDelay.process(dry, nCh, len,
1692 p->cachedLatency.load(std::memory_order_relaxed));
1693
1694 float* scChunk[2] = { nullptr, nullptr };
1695 if constexpr (HasSidechain<P>)
1696 for (int ch = 0; ch < 2; ++ch)
1697 scChunk[ch] = scHost[ch] != nullptr ? scHost[ch] + c0
1698 : p->silence.data();
1699
1700 // Process in sub-blocks split at quantum-aligned event positions
1701 // (sample-accurate default); without splitting, apply the
1702 // chunk's events up front and run it in one call.
1703 auto processSegment = [&](int start, int length) noexcept {
1704 float* sub[2] = { out[0] + start,
1705 nCh > 1 ? out[1] + start : out[0] + start };
1706 dspark::AudioBufferView<float> view(sub, nCh, length);
1707 if constexpr (HasSidechain<P>)
1708 {
1709 // The key view mirrors the main width (mono main, mono key).
1710 float* scSub[2] = { scChunk[0] + (start - c0),
1711 scChunk[1] + (start - c0) };
1712 dspark::AudioBufferView<float> scView(scSub, nCh, length);
1713 p->user.processBlock(view, scView);
1714 }
1715 else
1716 p->user.processBlock(view);
1717 // Soft bypass, per segment: a bypass point starts its short
1718 // linear crossfade toward the (latency-aligned) dry signal at
1719 // the segment where it lands. The old blend ran once per
1720 // block with the final target, so the fade began at sample 0
1721 // whatever the point's offset.
1722 p->blendBypass(out, dry, nCh, start, start - c0, length);
1723 };
1724
1725 if (!sampleAccurateOf<P>())
1726 {
1727 for (; evIdx < eventCount && events[evIdx].offset < cEnd; ++evIdx)
1728 paramsChanged |= p->applyBlockEvent(events[evIdx], c0, programChanged);
1729 processSegment(c0, len);
1730 }
1731 else
1732 {
1733 int pos = c0;
1734 while (pos < cEnd)
1735 {
1736 while (evIdx < eventCount
1737 && (events[evIdx].offset / kAutomationQuantum)
1738 * kAutomationQuantum <= pos)
1739 paramsChanged |= p->applyBlockEvent(events[evIdx++], pos,
1740 programChanged);
1741 int next = cEnd;
1742 if (evIdx < eventCount)
1743 {
1744 const int snapped = (events[evIdx].offset / kAutomationQuantum)
1746 if (snapped < next) next = snapped;
1747 }
1748 if (next <= pos) next = pos + kAutomationQuantum < cEnd
1749 ? pos + kAutomationQuantum : cEnd;
1750 processSegment(pos, next - pos);
1751 pos = next;
1752 }
1753 }
1754 }
1755 for (; evIdx < eventCount; ++evIdx) // safety: events at block end
1756 paramsChanged |= p->applyBlockEvent(events[evIdx], n, programChanged);
1757
1758 if (paramsChanged || programChanged)
1759 p->refreshLatency(programChanged
1760 ? Steinberg_Vst_RestartFlags_kParamValuesChanged : 0);
1761
1762 outBus.silenceFlags = 0;
1763 return Steinberg_kResultOk;
1764 }
1765
1766 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sGetTailSamples(void* self_)
1767 {
1768 auto* p = fromLens(self_, 1);
1769 if constexpr (HasTail<P>)
1770 {
1771 const double seconds = p->user.getTailSeconds();
1772 if (!(seconds > 0.0)) return 0; // negative/NaN -> no tail
1773 const double samples = seconds
1774 * (p->setup.sampleRate > 0 ? p->setup.sampleRate : 48000.0);
1775 // Infinite or absurd tails map to kInfiniteTail instead of a
1776 // double->uint32 overflow (UB).
1777 if (samples >= 4294967295.0) return 0xFFFFFFFFu;
1778 return static_cast<Steinberg_uint32>(samples);
1779 }
1780 else
1781 {
1782 (void) p;
1783 return 0;
1784 }
1785 }
1786
1787 inline static const Steinberg_Vst_IAudioProcessorVtbl kProcessorVtbl = {
1788 &sQuery<1>, &sAddRef<1>, &sRelease<1>,
1792 };
1793
1794 // ==========================================================================
1795 // Lens 2 - IEditController (+ IPluginBase)
1796 // ==========================================================================
1797
1798 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlInitialize(void* self_,
1799 Steinberg_FUnknown* context)
1800 {
1801 fromLens(self_, 2)->attachToHost(context);
1802 return Steinberg_kResultOk;
1803 }
1804
1805 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlTerminate(void* self_)
1806 {
1807 fromLens(self_, 2)->detachFromHost();
1808 return Steinberg_kResultOk;
1809 }
1810
1811 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetComponentState(void* self_,
1812 Steinberg_IBStream* state)
1813 {
1814 // Single component: identical to IComponent::setState (lens offset!).
1815 return sComponentSetState(fromLens(self_, 2)->lensPtr(0), state);
1816 }
1817
1818 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlSetState(void*, Steinberg_IBStream*)
1819 { return Steinberg_kResultOk; } // no controller-only state
1820
1821 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlGetState(void*, Steinberg_IBStream*)
1822 { return Steinberg_kResultOk; }
1823
1824 // Parameter index layout: [0, N) the user table, N the bypass, N+1 the
1825 // program change (factory presets only), then the hidden MIDI proxies.
1826 static constexpr Steinberg_int32 kBypassIndex =
1827 static_cast<Steinberg_int32>(kNumParams);
1828 static constexpr Steinberg_int32 kProgramIndex =
1829 kNumPresets > 0 ? kBypassIndex + 1 : -1;
1830 static constexpr Steinberg_int32 kFirstProxyIndex =
1831 kBypassIndex + 1 + (kNumPresets > 0 ? 1 : 0);
1832
1833 static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetParameterCount(void*)
1834 {
1836 }
1837
1838 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetParameterInfo(void* self_,
1839 Steinberg_int32 index, Steinberg_Vst_ParameterInfo* info)
1840 {
1841 (void) self_;
1842 if (info == nullptr || index < 0 || index >= sGetParameterCount(self_))
1843 return Steinberg_kInvalidArgument;
1844 std::memset(info, 0, sizeof(*info));
1845 if (index == kBypassIndex)
1846 {
1847 info->id = kBypassParamId;
1848 asciiToString128("Bypass", info->title);
1849 asciiToString128("Byp", info->shortTitle);
1850 info->stepCount = 1;
1851 info->defaultNormalizedValue = 0.0;
1852 info->flags = Steinberg_Vst_ParameterInfo_ParameterFlags_kCanAutomate
1853 | Steinberg_Vst_ParameterInfo_ParameterFlags_kIsBypass;
1854 return Steinberg_kResultOk;
1855 }
1856 if (kNumPresets > 0 && index == kProgramIndex)
1857 {
1858 info->id = kProgramParamId;
1859 asciiToString128("Program", info->title);
1860 asciiToString128("Prog", info->shortTitle);
1861 info->stepCount = kNumPresets - 1;
1862 info->defaultNormalizedValue = 0.0;
1863 info->unitId = Steinberg_Vst_kRootUnitId;
1864 info->flags = Steinberg_Vst_ParameterInfo_ParameterFlags_kCanAutomate
1865 | Steinberg_Vst_ParameterInfo_ParameterFlags_kIsList
1866 | Steinberg_Vst_ParameterInfo_ParameterFlags_kIsProgramChange;
1867 return Steinberg_kResultOk;
1868 }
1869 if (HasMidi<P> && index >= kFirstProxyIndex)
1870 {
1871 // Hidden conduits for IMidiMapping: hosts write MIDI controller
1872 // motion into them; they never show in generic UIs.
1873 const int slot = index - kFirstProxyIndex;
1874 const int channel = slot / kNumMidiControllers;
1875 const int ctrl = slot % kNumMidiControllers;
1876 info->id = midiProxyId(channel, ctrl);
1877 asciiToString128("MIDI", info->title);
1878 asciiToString128("MIDI", info->shortTitle);
1879 info->stepCount = 0;
1880 info->defaultNormalizedValue = ctrl == 129 ? 0.5 : 0.0;
1881 info->flags = Steinberg_Vst_ParameterInfo_ParameterFlags_kIsHidden;
1882 return Steinberg_kResultOk;
1883 }
1884 const auto& spec = P::parameters[static_cast<size_t>(index)];
1885 info->id = hash32(spec.id);
1886 asciiToString128(spec.name, info->title);
1887 asciiToString128(spec.name, info->shortTitle);
1888 asciiToString128(spec.unit, info->units);
1889 info->stepCount = spec.steps;
1890 info->defaultNormalizedValue = toNormalized(spec, spec.defValue);
1891 info->flags = Steinberg_Vst_ParameterInfo_ParameterFlags_kCanAutomate;
1892 if (spec.labels != nullptr) // named choice: hosts offer a list
1893 info->flags |= Steinberg_Vst_ParameterInfo_ParameterFlags_kIsList;
1894 return Steinberg_kResultOk;
1895 }
1896
1897 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetParamStringByValue(void* self_,
1898 Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue normalized,
1899 Steinberg_Vst_String128 out)
1900 {
1901 (void) self_;
1902 if (out == nullptr) return Steinberg_kInvalidArgument;
1903 char text[64] = "";
1904 if (id == kBypassParamId)
1905 std::snprintf(text, sizeof(text), "%s", normalized >= 0.5 ? "On" : "Off");
1906 else if (kNumPresets > 0 && id == kProgramParamId)
1907 {
1908 if constexpr (HasFactoryPresets<P>)
1909 {
1910 const int idx = programIndexOf(normalized);
1911 std::snprintf(text, sizeof(text), "%s",
1912 P::factoryPresets[static_cast<size_t>(idx)].name);
1913 }
1914 }
1915 else if (HasMidi<P> && isMidiProxyId(id))
1916 std::snprintf(text, sizeof(text), "%.3f", normalized);
1917 else
1918 {
1919 const int idx = indexOfParamId(id);
1920 if (idx < 0) return Steinberg_kInvalidArgument;
1921 const auto& spec = P::parameters[static_cast<size_t>(idx)];
1922 formatValue(spec, toPlain(spec, normalized), text, sizeof(text));
1923 }
1924 asciiToString128(text, out);
1925 return Steinberg_kResultOk;
1926 }
1927
1928 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetParamValueByString(void* self_,
1929 Steinberg_Vst_ParamID id, Steinberg_Vst_TChar* string,
1930 Steinberg_Vst_ParamValue* normalized)
1931 {
1932 (void) self_;
1933 if (string == nullptr || normalized == nullptr) return Steinberg_kInvalidArgument;
1934 char ascii[512]; // UTF-8: a choice label may be non-ASCII
1935 string128ToUtf8(string, ascii, sizeof(ascii));
1936 const int toggle = parseToggleText(ascii);
1937 if (id == kBypassParamId)
1938 {
1939 *normalized = toggle >= 0 ? toggle
1940 : (std::strtod(ascii, nullptr) >= 0.5 ? 1.0 : 0.0);
1941 return Steinberg_kResultOk;
1942 }
1943 if (kNumPresets > 0 && id == kProgramParamId)
1944 {
1945 if constexpr (HasFactoryPresets<P>)
1946 {
1947 for (int presetIdx = 0; presetIdx < kNumPresets; ++presetIdx)
1948 if (std::strcmp(ascii,
1949 P::factoryPresets[static_cast<size_t>(presetIdx)].name)
1950 == 0)
1951 {
1952 *normalized = kNumPresets > 1
1953 ? static_cast<double>(presetIdx) / (kNumPresets - 1)
1954 : 0.0;
1955 return Steinberg_kResultOk;
1956 }
1957 }
1958 const double v = std::strtod(ascii, nullptr);
1959 *normalized = kNumPresets > 1 ? v / (kNumPresets - 1) : 0.0;
1960 return Steinberg_kResultOk;
1961 }
1962 if (HasMidi<P> && isMidiProxyId(id))
1963 {
1964 const double v = std::strtod(ascii, nullptr);
1965 *normalized = v < 0.0 ? 0.0 : (v > 1.0 ? 1.0 : v);
1966 return Steinberg_kResultOk;
1967 }
1968 const int idx = indexOfParamId(id);
1969 if (idx < 0) return Steinberg_kInvalidArgument;
1970 const Param& spec = P::parameters[static_cast<size_t>(idx)];
1971 double plain = 0.0;
1972 if (!parseValue(spec, ascii, plain)) return Steinberg_kResultFalse;
1973 *normalized = toNormalized(spec, plain);
1974 return Steinberg_kResultOk;
1975 }
1976
1977 static Steinberg_Vst_ParamValue SMTG_STDMETHODCALLTYPE sNormalizedParamToPlain(void*,
1978 Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue normalized)
1979 {
1980 if (id == kBypassParamId) return normalized >= 0.5 ? 1.0 : 0.0;
1981 if (kNumPresets > 0 && id == kProgramParamId)
1982 return static_cast<double>(programIndexOf(normalized));
1983 if (HasMidi<P> && isMidiProxyId(id)) return normalized;
1984 const int idx = indexOfParamId(id);
1985 return idx < 0 ? 0.0 : toPlain(P::parameters[static_cast<size_t>(idx)], normalized);
1986 }
1987
1988 static Steinberg_Vst_ParamValue SMTG_STDMETHODCALLTYPE sPlainParamToNormalized(void*,
1989 Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue plain)
1990 {
1991 if (id == kBypassParamId) return plain >= 0.5 ? 1.0 : 0.0;
1992 if (kNumPresets > 0 && id == kProgramParamId)
1993 return kNumPresets > 1 ? plain / (kNumPresets - 1) : 0.0;
1994 if (HasMidi<P> && isMidiProxyId(id)) return plain;
1995 const int idx = indexOfParamId(id);
1996 return idx < 0 ? 0.0 : toNormalized(P::parameters[static_cast<size_t>(idx)], plain);
1997 }
1998
1999 static Steinberg_Vst_ParamValue SMTG_STDMETHODCALLTYPE sGetParamNormalized(void* self_,
2000 Steinberg_Vst_ParamID id)
2001 {
2002 auto* p = fromLens(self_, 2);
2003 p->deliverPendingRestart(); // hosts poll this from the UI thread
2004 if (id == kBypassParamId)
2005 return p->bypass.load(std::memory_order_relaxed) ? 1.0 : 0.0;
2006 if (kNumPresets > 0 && id == kProgramParamId)
2007 return kNumPresets > 1
2008 ? static_cast<double>(p->currentProgram.load(std::memory_order_relaxed))
2009 / (kNumPresets - 1)
2010 : 0.0;
2011 if constexpr (HasMidi<P>)
2012 {
2013 if (isMidiProxyId(id))
2014 return p->midiProxyShadow[static_cast<size_t>(midiProxySlot(id))]
2015 .load(std::memory_order_relaxed);
2016 }
2017 const int idx = indexOfParamId(id);
2018 return idx < 0 ? 0.0
2019 : p->shadow[static_cast<size_t>(idx)].load(std::memory_order_relaxed);
2020 }
2021
2022 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetParamNormalized(void* self_,
2023 Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue value)
2024 {
2025 auto* p = fromLens(self_, 2);
2026 if (id == kBypassParamId)
2027 {
2028 p->bypass.store(value >= 0.5, std::memory_order_relaxed);
2029 return Steinberg_kResultOk;
2030 }
2031 if (kNumPresets > 0 && id == kProgramParamId)
2032 {
2033 // A program change from the host UI: apply the preset and tell
2034 // the host every other parameter moved (main-thread call).
2035 p->applyFactoryPresetIdx(programIndexOf(value), true);
2036 p->refreshLatency(Steinberg_Vst_RestartFlags_kParamValuesChanged);
2037 return Steinberg_kResultOk;
2038 }
2039 if constexpr (HasMidi<P>)
2040 {
2041 // Live MIDI rides the process() queues; a main-thread write only
2042 // keeps the proxy shadow coherent for host round-trips.
2043 if (isMidiProxyId(id))
2044 {
2045 p->midiProxyShadow[static_cast<size_t>(midiProxySlot(id))]
2046 .store(value, std::memory_order_relaxed);
2047 return Steinberg_kResultOk;
2048 }
2049 }
2050 const int idx = indexOfParamId(id);
2051 if (idx < 0) return Steinberg_kInvalidArgument;
2052 // While processing, the host also delivers this value through
2053 // process(); the audio thread applies it either way (see applyFromUi).
2054 if (p->applyFromUi(idx, value))
2055 p->refreshLatency();
2056 p->deliverPendingRestart();
2057 return Steinberg_kResultOk;
2058 }
2059
2060 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetComponentHandler(void* self_,
2061 Steinberg_Vst_IComponentHandler* handler)
2062 {
2063 auto* p = fromLens(self_, 2);
2064 // Take the new reference before dropping the old one: a host that
2065 // re-sets the same handler must not see it released to zero first.
2066 if (handler != nullptr)
2067 reinterpret_cast<Steinberg_FUnknown*>(handler)->lpVtbl->addRef(handler);
2068 auto* old = p->handler.exchange(handler, std::memory_order_relaxed);
2069 if (old != nullptr)
2070 reinterpret_cast<Steinberg_FUnknown*>(old)->lpVtbl->release(old);
2071 p->deliverPendingRestart();
2072 return Steinberg_kResultOk;
2073 }
2074
2075 static Steinberg_IPlugView* SMTG_STDMETHODCALLTYPE sCreateView(void* self_,
2076 Steinberg_FIDString name);
2077
2088
2089 // ==========================================================================
2090 // Lens 3 - IProcessContextRequirements
2091 // ==========================================================================
2092
2093 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sGetProcessContextRequirements(void*)
2094 {
2095 if constexpr (HasTransport<P>)
2096 return Steinberg_Vst_IProcessContextRequirements_Flags_kNeedTempo
2097 | Steinberg_Vst_IProcessContextRequirements_Flags_kNeedTransportState
2098 | Steinberg_Vst_IProcessContextRequirements_Flags_kNeedProjectTimeMusic
2099 | Steinberg_Vst_IProcessContextRequirements_Flags_kNeedBarPositionMusic
2100 | Steinberg_Vst_IProcessContextRequirements_Flags_kNeedTimeSignature
2101 | Steinberg_Vst_IProcessContextRequirements_Flags_kNeedCycleMusic;
2102 else
2103 return 0;
2104 }
2105
2106 inline static const Steinberg_Vst_IProcessContextRequirementsVtbl kContextReqVtbl = {
2107 &sQuery<3>, &sAddRef<3>, &sRelease<3>,
2109 };
2110
2111 // ==========================================================================
2112 // Lens 4 - IUnitInfo (factory presets as a program list; surfaced by
2113 // queryInterface only when the class declares factoryPresets)
2114 // ==========================================================================
2115
2116 static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetUnitCount(void*) { return 1; }
2117
2118 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetUnitInfo(void*,
2119 Steinberg_int32 unitIndex, Steinberg_Vst_UnitInfo* info)
2120 {
2121 if (unitIndex != 0 || info == nullptr) return Steinberg_kInvalidArgument;
2122 std::memset(info, 0, sizeof(*info));
2123 info->id = Steinberg_Vst_kRootUnitId;
2124 info->parentUnitId = Steinberg_Vst_kNoParentUnitId;
2125 info->programListId = kNumPresets > 0 ? kPresetProgramListId
2126 : Steinberg_Vst_kNoProgramListId;
2127 asciiToString128("Root", info->name);
2128 return Steinberg_kResultOk;
2129 }
2130
2131 static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetProgramListCount(void*)
2132 {
2133 return kNumPresets > 0 ? 1 : 0;
2134 }
2135
2136 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramListInfo(void*,
2137 Steinberg_int32 listIndex, Steinberg_Vst_ProgramListInfo* info)
2138 {
2139 if (listIndex != 0 || info == nullptr || kNumPresets == 0)
2140 return Steinberg_kInvalidArgument;
2141 std::memset(info, 0, sizeof(*info));
2142 info->id = kPresetProgramListId;
2143 info->programCount = kNumPresets;
2144 asciiToString128("Factory Presets", info->name);
2145 return Steinberg_kResultOk;
2146 }
2147
2148 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramName(void*,
2149 Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex,
2150 Steinberg_Vst_String128 name)
2151 {
2152 if constexpr (HasFactoryPresets<P>)
2153 {
2154 if (listId != kPresetProgramListId || name == nullptr
2155 || programIndex < 0 || programIndex >= kNumPresets)
2156 return Steinberg_kInvalidArgument;
2158 P::factoryPresets[static_cast<size_t>(programIndex)].name, name);
2159 return Steinberg_kResultOk;
2160 }
2161 else
2162 {
2163 (void) listId;
2164 (void) programIndex;
2165 (void) name;
2166 return Steinberg_kInvalidArgument;
2167 }
2168 }
2169
2170 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramInfo(void*,
2171 Steinberg_Vst_ProgramListID, Steinberg_int32, Steinberg_Vst_CString,
2172 Steinberg_Vst_String128)
2173 { return Steinberg_kResultFalse; }
2174
2175 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sHasProgramPitchNames(void*,
2176 Steinberg_Vst_ProgramListID, Steinberg_int32)
2177 { return Steinberg_kResultFalse; }
2178
2179 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramPitchName(void*,
2180 Steinberg_Vst_ProgramListID, Steinberg_int32, Steinberg_int16,
2181 Steinberg_Vst_String128)
2182 { return Steinberg_kResultFalse; }
2183
2184 static Steinberg_Vst_UnitID SMTG_STDMETHODCALLTYPE sGetSelectedUnit(void*)
2185 { return Steinberg_Vst_kRootUnitId; }
2186
2187 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSelectUnit(void*,
2188 Steinberg_Vst_UnitID unitId)
2189 { return unitId == Steinberg_Vst_kRootUnitId ? Steinberg_kResultOk
2190 : Steinberg_kInvalidArgument; }
2191
2192 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetUnitByBus(void*,
2193 Steinberg_Vst_MediaType, Steinberg_Vst_BusDirection, Steinberg_int32,
2194 Steinberg_int32, Steinberg_Vst_UnitID* unitId)
2195 {
2196 if (unitId == nullptr) return Steinberg_kInvalidArgument;
2197 *unitId = Steinberg_Vst_kRootUnitId;
2198 return Steinberg_kResultOk;
2199 }
2200
2201 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetUnitProgramData(void*,
2202 Steinberg_int32, Steinberg_int32, struct Steinberg_IBStream*)
2203 { return Steinberg_kNotImplemented; }
2204
2205 inline static const Steinberg_Vst_IUnitInfoVtbl kUnitVtbl = {
2206 &sQuery<4>, &sAddRef<4>, &sRelease<4>,
2211 };
2212
2213 // ==========================================================================
2214 // Lens 5 - IMidiMapping (every CC, channel pressure and pitch bend
2215 // arrive as proxy-parameter automation; surfaced only for HasMidi)
2216 // ==========================================================================
2217
2218 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetMidiControllerAssignment(void*,
2219 Steinberg_int32 busIndex, Steinberg_int16 channel,
2220 Steinberg_Vst_CtrlNumber midiControllerNumber, Steinberg_Vst_ParamID* id)
2221 {
2222 if (!HasMidi<P> || id == nullptr || busIndex != 0
2223 || channel < 0 || channel >= 16)
2224 return Steinberg_kResultFalse;
2225 // Every controller: CC 0..127, channel pressure 128, pitch bend 129
2226 // (the old table mapped only 1, 64, 128 and 129, so expression,
2227 // breath, filter and every other CC never reached a VST3 plugin).
2228 const int ctrl = midiControllerNumber;
2229 if (ctrl < 0 || ctrl >= kNumMidiControllers)
2230 return Steinberg_kResultFalse;
2231 *id = midiProxyId(channel, ctrl);
2232 return Steinberg_kResultTrue;
2233 }
2234
2235 inline static const Steinberg_Vst_IMidiMappingVtbl kMidiMapVtbl = {
2236 &sQuery<5>, &sAddRef<5>, &sRelease<5>,
2238 };
2239
2240 // ==========================================================================
2241 // Lens 6 - INoteExpressionController (the declared note expressions;
2242 // surfaced only when the class declares noteExpressions)
2243 // ==========================================================================
2244
2246 static int offeredExpression(Steinberg_int32 index) noexcept
2247 {
2248 if (index < 0) return -1;
2249 int seen = 0;
2250 for (int t = 0; t < 32; ++t)
2251 if ((kVst3Expressions & (1u << t)) != 0u && seen++ == index) return t;
2252 return -1;
2253 }
2254
2255 static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetNoteExpressionCount(void*,
2256 Steinberg_int32 busIndex, Steinberg_int16 channel)
2257 {
2258 if (busIndex != 0 || channel < 0 || channel >= 16) return 0;
2259 return static_cast<Steinberg_int32>(std::popcount(kVst3Expressions));
2260 }
2261
2262 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetNoteExpressionInfo(void*,
2263 Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_int32 index,
2264 struct Steinberg_Vst_NoteExpressionTypeInfo* info)
2265 {
2266 const int type = offeredExpression(index);
2267 if (info == nullptr || busIndex != 0 || channel < 0 || channel >= 16 || type < 0)
2268 return Steinberg_kInvalidArgument;
2269 std::memset(info, 0, sizeof(*info));
2270 struct Names { const char* title; const char* shortTitle; const char* units; double def; };
2271 static constexpr Names kNames[] = {
2272 { "Volume", "Vol", "dB", 0.25 }, { "Pan", "Pan", "", 0.5 },
2273 { "Tuning", "Tune", "st", 0.5 }, { "Vibrato", "Vib", "%", 0.0 },
2274 { "Expression", "Expr", "%", 0.0 }, { "Brightness", "Brit", "%", 0.0 },
2275 };
2276 const Names& names = kNames[type];
2277 info->typeId = static_cast<Steinberg_Vst_NoteExpressionTypeID>(type);
2278 utf8ToString128(names.title, info->title);
2279 utf8ToString128(names.shortTitle, info->shortTitle);
2280 utf8ToString128(names.units, info->units);
2281 info->unitId = -1;
2282 info->valueDesc.defaultValue = names.def;
2283 info->valueDesc.minimum = 0.0;
2284 info->valueDesc.maximum = 1.0;
2285 info->valueDesc.stepCount = 0;
2286 info->associatedParameterId = 0xFFFFFFFFu; // none
2287 // Statements of value (absolute); Pan and Tuning sit at the centre.
2288 info->flags = Steinberg_Vst_NoteExpressionTypeInfo_NoteExpressionTypeFlags_kIsAbsolute;
2289 if (type == static_cast<int>(MidiEvent::ExpressionType::Pan)
2290 || type == static_cast<int>(MidiEvent::ExpressionType::Tuning))
2291 info->flags |= Steinberg_Vst_NoteExpressionTypeInfo_NoteExpressionTypeFlags_kIsBipolar;
2292 return Steinberg_kResultOk;
2293 }
2294
2296 static bool offersExpression(Steinberg_Vst_NoteExpressionTypeID id) noexcept
2297 {
2298 return id < 32u && (kVst3Expressions & (1u << id)) != 0u;
2299 }
2300
2301 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetNoteExpressionStringByValue(void*,
2302 Steinberg_int32 busIndex, Steinberg_int16, Steinberg_Vst_NoteExpressionTypeID id,
2303 Steinberg_Vst_NoteExpressionValue valueNormalized, Steinberg_Vst_String128 string)
2304 {
2305 if (string == nullptr || busIndex != 0 || !offersExpression(id))
2306 return Steinberg_kInvalidArgument;
2307 const auto type = static_cast<MidiEvent::ExpressionType>(id);
2308 const double v = vst3ExpressionValue(type, valueNormalized);
2309 char text[64];
2310 switch (type)
2311 {
2313 if (v > 0.0) std::snprintf(text, sizeof(text), "%.2f dB", 20.0 * std::log10(v));
2314 else std::snprintf(text, sizeof(text), "-inf dB");
2315 break;
2317 std::snprintf(text, sizeof(text), "%+.0f %%", (v - 0.5) * 200.0);
2318 break;
2320 std::snprintf(text, sizeof(text), "%+.2f st", v);
2321 break;
2322 default:
2323 std::snprintf(text, sizeof(text), "%.0f %%", v * 100.0);
2324 break;
2325 }
2326 utf8ToString128(text, string);
2327 return Steinberg_kResultOk;
2328 }
2329
2330 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetNoteExpressionValueByString(void*,
2331 Steinberg_int32 busIndex, Steinberg_int16, Steinberg_Vst_NoteExpressionTypeID id,
2332 const Steinberg_Vst_TChar* string, Steinberg_Vst_NoteExpressionValue* valueNormalized)
2333 {
2334 if (string == nullptr || valueNormalized == nullptr || busIndex != 0
2335 || !offersExpression(id))
2336 return Steinberg_kInvalidArgument;
2337 char text[512];
2338 string128ToUtf8(string, text, sizeof(text));
2339 const auto type = static_cast<MidiEvent::ExpressionType>(id);
2340 double n = 0.0;
2341 if (type == MidiEvent::ExpressionType::Volume && std::strstr(text, "-inf") != nullptr)
2342 n = 0.0;
2343 else
2344 {
2345 char* end = nullptr;
2346 const double x = std::strtod(text, &end);
2347 if (end == text || x != x) return Steinberg_kResultFalse;
2348 switch (type)
2349 {
2351 n = std::pow(10.0, x / 20.0) / 4.0;
2352 break;
2354 n = x / 200.0 + 0.5;
2355 break;
2357 n = x / 240.0 + 0.5;
2358 break;
2359 default:
2360 n = x / 100.0;
2361 break;
2362 }
2363 }
2364 *valueNormalized = !(n > 0.0) ? 0.0 : (n > 1.0 ? 1.0 : n);
2365 return Steinberg_kResultOk;
2366 }
2367
2368 inline static const Steinberg_Vst_INoteExpressionControllerVtbl kNoteExprVtbl = {
2369 &sQuery<6>, &sAddRef<6>, &sRelease<6>,
2372 };
2373};
2374
2375// -- the editor view (WebView editor layer) ---------------------------------------
2376//
2377// Compiled only when plugin/webview/DSParkWebViewEditor.h was included before
2378// this header, and created only for plugin classes that declare an editor.
2379// Without either, createView answers nullptr and hosts show their generic UI.
2380
2381#if defined(DSPARK_PLUGIN_WEBVIEW)
2382
2388template <typename P>
2389struct View
2390{
2391 static constexpr size_t kNumParams = Plugin<P>::kNumParams;
2392
2393 // COM lenses, same layout trick as the plugin object. The timer lens is
2394 // Linux-only: it receives the host IRunLoop ticks that drive GTK.
2395 const Steinberg_IPlugViewVtbl* viewVtbl;
2396 const Steinberg_IPlugViewContentScaleSupportVtbl* scaleVtbl;
2397#if defined(__linux__)
2398 const Steinberg_Linux_ITimerHandlerVtbl* timerVtbl;
2399#endif
2400
2401 std::atomic<Steinberg_uint32> refs { 1 };
2402 Plugin<P>* owner;
2403 Steinberg_IPlugFrame* frame = nullptr;
2404 webview_ui::Editor<P> editor;
2405 int width; // current physical size (host units)
2406 int height;
2407 double scale = 1.0;
2408 bool correctingSize = false; // re-entrancy guard for resizeView round-trips
2409 bool editActive[kNumParams == 0 ? 1 : kNumParams] {};
2410#if defined(__linux__)
2411 Steinberg_Linux_IRunLoop* runLoop = nullptr;
2412 bool timerRegistered = false;
2413#endif
2414
2415 explicit View(Plugin<P>* plugin) noexcept : owner(plugin)
2416 {
2417 viewVtbl = &kViewVtbl;
2418 scaleVtbl = &kScaleVtbl;
2419#if defined(__linux__)
2420 timerVtbl = &kTimerVtbl;
2421#endif
2422 owner->addRefImpl();
2423 // The size the user left the editor at (this session or a saved
2424 // one), else the declared size; the content scale rescales it later.
2425 const EditorSize logical = owner->editorMemory.current();
2426 width = logical.width;
2427 height = logical.height;
2428 // A state the host loads while this view exists resizes it.
2429 owner->liveView = this;
2430 owner->resizeLiveView = &sApplyRememberedSize;
2431 }
2432
2433 ~View()
2434 {
2435 if (owner->liveView == this) owner->liveView = nullptr;
2436#if defined(__linux__)
2437 releaseRunLoop();
2438#endif
2439 editor.destroy();
2440 if (frame != nullptr)
2441 reinterpret_cast<Steinberg_FUnknown*>(frame)->lpVtbl->release(frame);
2442 owner->releaseImpl();
2443 }
2444
2445#if defined(__linux__)
2446
2447 // --- host run loop: GTK breathes only when pumped from here ---------------------
2448
2449 void acquireRunLoop() noexcept
2450 {
2451 if (frame == nullptr || runLoop != nullptr) return;
2452 void* loop = nullptr;
2453 if (reinterpret_cast<Steinberg_FUnknown*>(frame)->lpVtbl->queryInterface(
2454 frame, Steinberg_Linux_IRunLoop_iid, &loop) == Steinberg_kResultOk)
2455 runLoop = static_cast<Steinberg_Linux_IRunLoop*>(loop);
2456 }
2457
2458 void startTimer() noexcept
2459 {
2460 acquireRunLoop();
2461 if (runLoop != nullptr && !timerRegistered && editor.created())
2462 timerRegistered = runLoop->lpVtbl->registerTimer(runLoop,
2463 reinterpret_cast<Steinberg_Linux_ITimerHandler*>(lensPtr(2)),
2464 33) == Steinberg_kResultOk;
2465 }
2466
2467 void stopTimer() noexcept
2468 {
2469 if (runLoop != nullptr && timerRegistered)
2470 runLoop->lpVtbl->unregisterTimer(runLoop,
2471 reinterpret_cast<Steinberg_Linux_ITimerHandler*>(lensPtr(2)));
2472 timerRegistered = false;
2473 }
2474
2475 void releaseRunLoop() noexcept
2476 {
2477 stopTimer();
2478 if (runLoop != nullptr)
2479 {
2480 reinterpret_cast<Steinberg_FUnknown*>(runLoop)->lpVtbl->release(runLoop);
2481 runLoop = nullptr;
2482 }
2483 }
2484
2485 static void SMTG_STDMETHODCALLTYPE sOnTimer(void* self_)
2486 {
2487 View* view = fromLens(self_, 2);
2488 view->editor.pump();
2489 view->owner->deliverPendingRestart(); // the frame's run loop ticks too
2490 }
2491
2492#endif // __linux__
2493
2494 static View* fromLens(void* iface, int lens) noexcept
2495 {
2496 return reinterpret_cast<View*>(static_cast<char*>(iface)
2497 - static_cast<ptrdiff_t>(lens) * sizeof(void*));
2498 }
2499
2504 static void sApplyRememberedSize(void* self) noexcept
2505 {
2506 auto* view = static_cast<View*>(self);
2507 const EditorSize logical = view->owner->editorMemory.current();
2508 const int w = toBoundedInt(logical.width * view->scale + 0.5,
2509 1, static_cast<int>(kEditorMaxPixels));
2510 const int h = toBoundedInt(logical.height * view->scale + 0.5,
2511 1, static_cast<int>(kEditorMaxPixels));
2512 if (w == view->width && h == view->height) return;
2513 webview_ui::debugLog("vst3 state load: editor %dx%d -> %dx%d",
2514 view->width, view->height, w, h);
2515 if (view->editor.created() && view->frame != nullptr)
2516 {
2517 Steinberg_ViewRect rect { 0, 0, w, h };
2518 view->correctingSize = true; // the host's onSize echoes this size
2519 const Steinberg_tresult result = view->frame->lpVtbl->resizeView(view->frame,
2520 reinterpret_cast<Steinberg_IPlugView*>(view->lensPtr(0)), &rect);
2521 view->correctingSize = false;
2522 if (result != Steinberg_kResultOk) return;
2523 view->editor.setBounds(w, h);
2524 }
2525 view->width = w;
2526 view->height = h;
2527 }
2528
2529 void* lensPtr(int lens) noexcept
2530 {
2531 return reinterpret_cast<char*>(this) + static_cast<ptrdiff_t>(lens) * sizeof(void*);
2532 }
2533
2534 static const char* platformType() noexcept
2535 {
2536#if defined(_WIN32)
2537 return Steinberg_kPlatformTypeHWND;
2538#elif defined(__APPLE__)
2539 return Steinberg_kPlatformTypeNSView;
2540#else
2541 return Steinberg_kPlatformTypeX11EmbedWindowID;
2542#endif
2543 }
2544
2545 // --- editor -> host/DSP bridge ------------------------------------------------
2546
2547 static void cbSetParam(void* context, int index, double plain) noexcept
2548 {
2549 auto* view = static_cast<View*>(context);
2550 const Param& spec = P::parameters[static_cast<size_t>(index)];
2551 const double normalized = toNormalized(spec, plain);
2552 if (view->owner->applyFromUi(index, normalized))
2553 view->owner->refreshLatency();
2554 if (auto* handler = view->owner->handler.load(std::memory_order_relaxed))
2555 {
2556 const Steinberg_Vst_ParamID id = hash32(spec.id);
2557 if (view->editActive[static_cast<size_t>(index)])
2558 handler->lpVtbl->performEdit(handler, id, normalized);
2559 else
2560 {
2561 // Edits outside an explicit gesture still need one for host undo.
2562 handler->lpVtbl->beginEdit(handler, id);
2563 handler->lpVtbl->performEdit(handler, id, normalized);
2564 handler->lpVtbl->endEdit(handler, id);
2565 }
2566 }
2567 }
2568
2569 static void cbBeginEdit(void* context, int index) noexcept
2570 {
2571 auto* view = static_cast<View*>(context);
2572 view->editActive[static_cast<size_t>(index)] = true;
2573 if (auto* handler = view->owner->handler.load(std::memory_order_relaxed))
2574 handler->lpVtbl->beginEdit(handler,
2575 hash32(P::parameters[static_cast<size_t>(index)].id));
2576 }
2577
2578 static void cbEndEdit(void* context, int index) noexcept
2579 {
2580 auto* view = static_cast<View*>(context);
2581 view->editActive[static_cast<size_t>(index)] = false;
2582 if (auto* handler = view->owner->handler.load(std::memory_order_relaxed))
2583 handler->lpVtbl->endEdit(handler,
2584 hash32(P::parameters[static_cast<size_t>(index)].id));
2585 }
2586
2587 // --- FUnknown -------------------------------------------------------------------
2588
2589 Steinberg_tresult query(const Steinberg_TUID iid, void** obj) noexcept
2590 {
2591 if (obj == nullptr) return Steinberg_kInvalidArgument;
2592 *obj = nullptr;
2593 if (tuidEqual(iid, Steinberg_FUnknown_iid)
2594 || tuidEqual(iid, Steinberg_IPlugView_iid))
2595 *obj = lensPtr(0);
2596 else if (tuidEqual(iid, Steinberg_IPlugViewContentScaleSupport_iid))
2597 *obj = lensPtr(1);
2598#if defined(__linux__)
2599 else if (tuidEqual(iid, Steinberg_Linux_ITimerHandler_iid))
2600 *obj = lensPtr(2);
2601#endif
2602 if (*obj == nullptr) return Steinberg_kNoInterface;
2603 refs.fetch_add(1, std::memory_order_relaxed);
2604 return Steinberg_kResultOk;
2605 }
2606
2607 template <int Lens>
2608 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sQuery(void* self_,
2609 const Steinberg_TUID iid,
2610 void** obj)
2611 { return fromLens(self_, Lens)->query(iid, obj); }
2612
2613 template <int Lens>
2614 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sAddRef(void* self_)
2615 { return fromLens(self_, Lens)->refs.fetch_add(1, std::memory_order_relaxed) + 1; }
2616
2617 template <int Lens>
2618 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sRelease(void* self_)
2619 {
2620 auto* view = fromLens(self_, Lens);
2621 const Steinberg_uint32 left = view->refs.fetch_sub(1, std::memory_order_acq_rel) - 1;
2622 if (left == 0) delete view;
2623 return left;
2624 }
2625
2626 // --- IPlugView --------------------------------------------------------------------
2627
2628 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sIsPlatformTypeSupported(void*,
2629 Steinberg_FIDString type)
2630 {
2631 return (webview_ui::Editor<P>::available() && type != nullptr
2632 && std::strcmp(type, platformType()) == 0)
2633 ? Steinberg_kResultTrue : Steinberg_kResultFalse;
2634 }
2635
2636 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sAttached(void* self_, void* parent,
2637 Steinberg_FIDString type)
2638 {
2639 auto* view = fromLens(self_, 0);
2640 webview_ui::debugLog("vst3 attached(parent=%p type=%s) negotiated=%dx%d scale=%.2f",
2641 parent, type != nullptr ? type : "?",
2642 view->width, view->height, view->scale);
2643 if (sIsPlatformTypeSupported(self_, type) != Steinberg_kResultTrue
2644 || parent == nullptr)
2645 return Steinberg_kResultFalse;
2646 const webview_ui::HostCallbacks callbacks {
2647 view, &cbSetParam, &cbBeginEdit, &cbEndEdit
2648 };
2649 if (!view->editor.create(parent, view->owner->shadow, callbacks))
2650 return Steinberg_kResultFalse;
2651 // Fill the box the host ACTUALLY built - hosts differ in whether
2652 // getSize/setContentScaleFactor/attached arrive in spec order, so the
2653 // parent's real client size wins over the negotiated one.
2654 int parentW = 0, parentH = 0;
2655 if (view->editor.queryParentSize(parentW, parentH))
2656 {
2657 view->width = parentW;
2658 view->height = parentH;
2659 }
2660 view->editor.setBounds(view->width, view->height);
2661 view->editor.setVisible(true);
2662#if defined(__linux__)
2663 // GTK breathes only when pumped from the host's run loop; without a
2664 // usable IRunLoop the page would freeze, so fall back to generic UI.
2665 view->startTimer();
2666 if (!view->timerRegistered)
2667 {
2668 webview_ui::debugLog("vst3 attached: no usable IRunLoop -> no editor");
2669 view->editor.destroy();
2670 return Steinberg_kResultFalse;
2671 }
2672#endif
2673 return Steinberg_kResultOk;
2674 }
2675
2676 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sRemoved(void* self_)
2677 {
2678 auto* view = fromLens(self_, 0);
2679#if defined(__linux__)
2680 view->stopTimer();
2681#endif
2682 // Keep the size the editor is closed at: some hosts resize their
2683 // window without an onSize, and the window still exists here.
2684 int parentW = 0, parentH = 0;
2685 if (view->editor.created() && view->editor.queryParentSize(parentW, parentH))
2686 {
2687 double w = parentW;
2688 double h = parentH;
2689 constrainEditorSize<P>(w, h, view->scale);
2690 view->owner->editorMemory.remember(w / view->scale, h / view->scale);
2691 }
2692 view->editor.destroy();
2693 return Steinberg_kResultOk;
2694 }
2695
2696 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sOnWheel(void*, float)
2697 { return Steinberg_kResultFalse; }
2698
2699 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sOnKeyDown(void*, Steinberg_char16,
2700 Steinberg_int16, Steinberg_int16)
2701 { return Steinberg_kResultFalse; }
2702
2703 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sOnKeyUp(void*, Steinberg_char16,
2704 Steinberg_int16, Steinberg_int16)
2705 { return Steinberg_kResultFalse; }
2706
2707 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetSize(void* self_,
2708 Steinberg_ViewRect* size)
2709 {
2710 auto* view = fromLens(self_, 0);
2711 if (size == nullptr) return Steinberg_kInvalidArgument;
2712 size->left = 0;
2713 size->top = 0;
2714 size->right = view->width;
2715 size->bottom = view->height;
2716 webview_ui::debugLog("vst3 getSize -> %dx%d", view->width, view->height);
2717 return Steinberg_kResultOk;
2718 }
2719
2720 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sOnSize(void* self_,
2721 Steinberg_ViewRect* newSize)
2722 {
2723 auto* view = fromLens(self_, 0);
2724 if (newSize == nullptr) return Steinberg_kInvalidArgument;
2725 const double proposedW = newSize->right - newSize->left;
2726 const double proposedH = newSize->bottom - newSize->top;
2727 double w = proposedW;
2728 double h = proposedH;
2729 // Enforce the resize policy HERE, not only in checkSizeConstraint:
2730 // some hosts drag-resize freely and only report the result. When the
2731 // host overshot, apply the constrained size and ask it to follow.
2732 if (!view->correctingSize)
2733 constrainEditorSize<P>(w, h, view->scale);
2734 webview_ui::debugLog("vst3 onSize %.0fx%.0f -> %.0fx%.0f%s",
2735 proposedW, proposedH, w, h,
2736 view->correctingSize ? " (correction round-trip)" : "");
2737 view->width = toBoundedInt(w + 0.5, 1, static_cast<int>(kEditorMaxPixels));
2738 view->height = toBoundedInt(h + 0.5, 1, static_cast<int>(kEditorMaxPixels));
2739 view->editor.setBounds(view->width, view->height);
2740 // The user's size, in logical pixels: the next view opens at it, and
2741 // the state saves it for the next session.
2742 view->owner->editorMemory.remember(view->width / view->scale,
2743 view->height / view->scale);
2744 if (!view->correctingSize && view->frame != nullptr
2745 && (view->width - proposedW > 1.0 || proposedW - view->width > 1.0
2746 || view->height - proposedH > 1.0 || proposedH - view->height > 1.0))
2747 {
2748 view->correctingSize = true;
2749 Steinberg_ViewRect corrected { 0, 0, view->width, view->height };
2750 view->frame->lpVtbl->resizeView(view->frame,
2751 reinterpret_cast<Steinberg_IPlugView*>(view->lensPtr(0)), &corrected);
2752 view->correctingSize = false;
2753 }
2754 return Steinberg_kResultOk;
2755 }
2756
2757 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sOnFocus(void*, Steinberg_TBool)
2758 { return Steinberg_kResultOk; }
2759
2760 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetFrame(void* self_,
2761 Steinberg_IPlugFrame* frame)
2762 {
2763 auto* view = fromLens(self_, 0);
2764#if defined(__linux__)
2765 view->releaseRunLoop(); // the run loop belongs to the old frame
2766#endif
2767 if (view->frame != nullptr)
2768 reinterpret_cast<Steinberg_FUnknown*>(view->frame)
2769 ->lpVtbl->release(view->frame);
2770 view->frame = frame;
2771 if (view->frame != nullptr)
2772 reinterpret_cast<Steinberg_FUnknown*>(view->frame)
2773 ->lpVtbl->addRef(view->frame);
2774#if defined(__linux__)
2775 if (view->editor.created())
2776 view->startTimer(); // frame arrived after attach (rare order)
2777#endif
2778 return Steinberg_kResultOk;
2779 }
2780
2781 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCanResize(void*)
2782 {
2783 return editorResizeOf<P>() != EditorResize::Fixed ? Steinberg_kResultTrue
2784 : Steinberg_kResultFalse;
2785 }
2786
2787 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCheckSizeConstraint(void* self_,
2788 Steinberg_ViewRect* rect)
2789 {
2790 auto* view = fromLens(self_, 0);
2791 if (rect == nullptr) return Steinberg_kInvalidArgument;
2792 const double proposedW = rect->right - rect->left;
2793 const double proposedH = rect->bottom - rect->top;
2794 double w = proposedW;
2795 double h = proposedH;
2796 constrainEditorSize<P>(w, h, view->scale);
2797 rect->right = rect->left
2798 + toBoundedInt(w + 0.5, 1, static_cast<int>(kEditorMaxPixels));
2799 rect->bottom = rect->top
2800 + toBoundedInt(h + 0.5, 1, static_cast<int>(kEditorMaxPixels));
2801 webview_ui::debugLog("vst3 checkSizeConstraint %.0fx%.0f -> %.0fx%.0f",
2802 proposedW, proposedH, w, h);
2803 return Steinberg_kResultTrue;
2804 }
2805
2806 inline static const Steinberg_IPlugViewVtbl kViewVtbl = {
2807 &sQuery<0>, &sAddRef<0>, &sRelease<0>,
2808 &sIsPlatformTypeSupported, &sAttached, &sRemoved,
2809 &sOnWheel, &sOnKeyDown, &sOnKeyUp,
2810 &sGetSize, &sOnSize, &sOnFocus,
2811 &sSetFrame, &sCanResize, &sCheckSizeConstraint
2812 };
2813
2814 // --- IPlugViewContentScaleSupport ----------------------------------------------
2815
2816 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetContentScaleFactor(void* self_,
2817 Steinberg_IPlugViewContentScaleSupport_ScaleFactor factor)
2818 {
2819 auto* view = fromLens(self_, 1);
2820 if (!(factor > 0.0f)) return Steinberg_kInvalidArgument; // NaN included
2821 const double previous = view->scale;
2822 view->scale = factor;
2823 webview_ui::debugLog("vst3 setContentScaleFactor %.2f (was %.2f)",
2824 view->scale, previous);
2825 // Rescale the negotiated physical size (the page itself never zooms:
2826 // the web engine applies the window DPI to CSS pixels on its own).
2827 view->width = toBoundedInt(view->width * (view->scale / previous) + 0.5,
2828 1, static_cast<int>(kEditorMaxPixels));
2829 view->height = toBoundedInt(view->height * (view->scale / previous) + 0.5,
2830 1, static_cast<int>(kEditorMaxPixels));
2831 if (view->editor.created() && view->frame != nullptr)
2832 {
2833 // Already on screen (e.g. dragged to another monitor): ask the
2834 // host to rebuild the window at the new physical size.
2835 Steinberg_ViewRect rect { 0, 0, view->width, view->height };
2836 view->frame->lpVtbl->resizeView(view->frame,
2837 reinterpret_cast<Steinberg_IPlugView*>(view->lensPtr(0)), &rect);
2838 }
2839 return Steinberg_kResultOk;
2840 }
2841
2842 inline static const Steinberg_IPlugViewContentScaleSupportVtbl kScaleVtbl = {
2843 &sQuery<1>, &sAddRef<1>, &sRelease<1>,
2844 &sSetContentScaleFactor
2845 };
2846
2847#if defined(__linux__)
2848 // Defined after the FUnknown thunks: a static member INITIALIZER has no
2849 // complete-class context, so every name it uses must be declared above.
2850 inline static const Steinberg_Linux_ITimerHandlerVtbl kTimerVtbl = {
2851 &sQuery<2>, &sAddRef<2>, &sRelease<2>, &sOnTimer
2852 };
2853#endif
2854};
2855
2856#endif // DSPARK_PLUGIN_WEBVIEW
2857
2858template <typename P>
2859Steinberg_IPlugView* SMTG_STDMETHODCALLTYPE Plugin<P>::sCreateView(void* self_,
2860 Steinberg_FIDString name)
2861{
2862 (void) self_;
2863 (void) name;
2864#if defined(DSPARK_PLUGIN_WEBVIEW)
2865 if constexpr (HasEditor<P>)
2866 {
2867 if (webview_ui::Editor<P>::available() && name != nullptr
2868 && std::strcmp(name, "editor") == 0)
2869 {
2870 auto* view = new (std::nothrow) View<P>(fromLens(self_, 2));
2871 if (view != nullptr)
2872 return reinterpret_cast<Steinberg_IPlugView*>(view->lensPtr(0));
2873 }
2874 }
2875#endif
2876 return nullptr; // no editor: the host shows its generic parameter UI
2877}
2878
2879// -- factory --------------------------------------------------------------------
2880
2881template <typename P>
2883{
2884 const Steinberg_IPluginFactory3Vtbl* vtbl;
2885
2886 Factory() noexcept { vtbl = &kVtbl; }
2887
2888 static std::array<uint8_t, 16> classUid() noexcept
2889 {
2890 return makeUid(P::descriptor.productId, 0x56535433ull); // 'VST3'
2891 }
2892
2893 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sQuery(void* self_,
2894 const Steinberg_TUID iid, void** obj)
2895 {
2896 if (obj == nullptr) return Steinberg_kInvalidArgument;
2897 if (tuidEqual(iid, Steinberg_FUnknown_iid)
2898 || tuidEqual(iid, Steinberg_IPluginFactory_iid)
2899 || tuidEqual(iid, Steinberg_IPluginFactory2_iid)
2900 || tuidEqual(iid, Steinberg_IPluginFactory3_iid))
2901 {
2902 *obj = self_;
2903 return Steinberg_kResultOk;
2904 }
2905 *obj = nullptr;
2906 return Steinberg_kNoInterface;
2907 }
2908
2909 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sAddRef(void*) { return 100; }
2910 static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sRelease(void*) { return 100; }
2911
2912 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetFactoryInfo(void*,
2913 Steinberg_PFactoryInfo* info)
2914 {
2915 if (info == nullptr) return Steinberg_kInvalidArgument;
2916 std::memset(info, 0, sizeof(*info));
2917 copyAscii(P::descriptor.vendor, info->vendor, sizeof(info->vendor));
2918 copyAscii(P::descriptor.url, info->url, sizeof(info->url));
2919 copyAscii(P::descriptor.email, info->email, sizeof(info->email));
2920 info->flags = Steinberg_PFactoryInfo_FactoryFlags_kUnicode;
2921 return Steinberg_kResultOk;
2922 }
2923
2924 static Steinberg_int32 SMTG_STDMETHODCALLTYPE sCountClasses(void*) { return 1; }
2925
2926 static void fillClassCommon(Steinberg_TUID cid) noexcept
2927 {
2928 const auto uid = classUid();
2929 std::memcpy(cid, uid.data(), 16);
2930 }
2931
2932 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetClassInfo(void*,
2933 Steinberg_int32 index, Steinberg_PClassInfo* info)
2934 {
2935 if (index != 0 || info == nullptr) return Steinberg_kInvalidArgument;
2936 std::memset(info, 0, sizeof(*info));
2937 fillClassCommon(info->cid);
2938 info->cardinality = 0x7FFFFFFF; // kManyInstances
2939 copyAscii("Audio Module Class", info->category, sizeof(info->category));
2940 copyAscii(P::descriptor.name, info->name, sizeof(info->name));
2941 return Steinberg_kResultOk;
2942 }
2943
2944 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetClassInfo2(void*,
2945 Steinberg_int32 index, Steinberg_PClassInfo2* info)
2946 {
2947 if (index != 0 || info == nullptr) return Steinberg_kInvalidArgument;
2948 std::memset(info, 0, sizeof(*info));
2949 fillClassCommon(info->cid);
2950 info->cardinality = 0x7FFFFFFF;
2951 copyAscii("Audio Module Class", info->category, sizeof(info->category));
2952 copyAscii(P::descriptor.name, info->name, sizeof(info->name));
2953 info->classFlags = 0;
2954 copyAscii(P::descriptor.category == Category::Instrument ? "Instrument" : "Fx",
2955 info->subCategories, sizeof(info->subCategories));
2956 copyAscii(P::descriptor.vendor, info->vendor, sizeof(info->vendor));
2957 copyAscii(P::descriptor.version, info->version, sizeof(info->version));
2958 copyAscii("VST 3.7.9", info->sdkVersion, sizeof(info->sdkVersion));
2959 return Steinberg_kResultOk;
2960 }
2961
2962 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetClassInfoUnicode(void*,
2963 Steinberg_int32 index, Steinberg_PClassInfoW* info)
2964 {
2965 if (index != 0 || info == nullptr) return Steinberg_kInvalidArgument;
2966 std::memset(info, 0, sizeof(*info));
2967 fillClassCommon(info->cid);
2968 info->cardinality = 0x7FFFFFFF;
2969 copyAscii("Audio Module Class", info->category, sizeof(info->category));
2970 asciiToString128(P::descriptor.name, info->name);
2971 info->classFlags = 0;
2972 copyAscii(P::descriptor.category == Category::Instrument ? "Instrument" : "Fx",
2973 info->subCategories, sizeof(info->subCategories));
2974 asciiToString128(P::descriptor.vendor, info->vendor);
2975 asciiToString128(P::descriptor.version, info->version);
2976 asciiToString128("VST 3.7.9", info->sdkVersion);
2977 return Steinberg_kResultOk;
2978 }
2979
2980 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCreateInstance(void*,
2981 Steinberg_FIDString cid, Steinberg_FIDString iid, void** obj)
2982 {
2983 if (cid == nullptr || iid == nullptr || obj == nullptr)
2984 return Steinberg_kInvalidArgument;
2985 *obj = nullptr;
2986 const auto uid = classUid();
2987 if (std::memcmp(cid, uid.data(), 16) != 0)
2988 return Steinberg_kNoInterface;
2989
2990 auto* plugin = new (std::nothrow) Plugin<P>();
2991 if (plugin == nullptr) return Steinberg_kResultFalse;
2992
2993 Steinberg_TUID requested;
2994 std::memcpy(requested, iid, sizeof(requested));
2995 const Steinberg_tresult r = plugin->query(requested, obj);
2996 plugin->releaseImpl(); // drop the construction reference
2997 return r == Steinberg_kResultOk ? Steinberg_kResultOk : Steinberg_kNoInterface;
2998 }
2999
3000 static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetHostContext(void*, Steinberg_FUnknown*)
3001 { return Steinberg_kResultOk; }
3002
3003 inline static const Steinberg_IPluginFactory3Vtbl kVtbl = {
3004 &sQuery, &sAddRef, &sRelease,
3008 };
3009};
3010
3011} // namespace dspark::plugin::vst3
3012
3013// -- module entry ----------------------------------------------------------------
3014
3015#if defined(_WIN32)
3016#define DSPARK_VST3_EXPORT __declspec(dllexport)
3017#else
3018#define DSPARK_VST3_EXPORT __attribute__((visibility("default")))
3019#endif
3020
3025#define DSPARK_VST3_PLUGIN(PluginClass) \
3026 static dspark::plugin::vst3::Factory<PluginClass> gDsparkVst3Factory; \
3027 extern "C" { \
3028 DSPARK_VST3_EXPORT Steinberg_IPluginFactory* SMTG_STDMETHODCALLTYPE \
3029 GetPluginFactory() \
3030 { \
3031 return reinterpret_cast<Steinberg_IPluginFactory*>(&gDsparkVst3Factory); \
3032 } \
3033 DSPARK_VST3_EXPORT bool InitDll() { return true; } \
3034 DSPARK_VST3_EXPORT bool ExitDll() { return true; } \
3035 DSPARK_VST3_EXPORT bool ModuleEntry(void*) { return true; } \
3036 DSPARK_VST3_EXPORT bool ModuleExit() { return true; } \
3037 DSPARK_VST3_EXPORT bool bundleEntry(void*) { return true; } \
3038 DSPARK_VST3_EXPORT bool bundleExit() { return true; } \
3039 }
3040
3041#pragma pop_macro("max")
3042#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 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 notes the host started, by VST3 note id. A note expression event names its note by id only,...
Definition DSParkVst3.h:506
void noteOff(int32_t noteId) noexcept
Definition DSParkVst3.h:539
static constexpr uint32_t kCapacity
Definition DSParkVst3.h:508
void noteOn(int32_t noteId, int channel, int key) noexcept
Definition DSParkVst3.h:516
bool find(int32_t noteId, int &channel, int &key) noexcept
Definition DSParkVst3.h:545
A ~30 Hz tick on the host's UI thread.
Definition DSParkVst3.h:133
bool start(Steinberg_FUnknown *hostContext, Callback callback, void *context) noexcept
Definition DSParkVst3.h:144
bool running() const noexcept
Definition DSParkVst3.h:220
void(*)(void *context) noexcept Callback
Definition DSParkVst3.h:135
UiTicker() noexcept=default
One embedded WebView editor instance for plugin class P. Owned by the format backends (the VST3 IPlug...
Custom-editor switch. With hasEditor = false (or absent) hosts show their generic parameter UI....
Factory-preset capability: a static constexpr auto factoryPresets table built with presets()....
MIDI capability: void handleMidiEvent(const MidiEvent&) noexcept. Its presence grows a note/event inp...
Optional note-expression declaration: static constexpr uint32_t noteExpressions = expressions(....
Render-mode capability: void setOfflineRendering(bool) noexcept. The host flips it to true for non-re...
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,...
void utf8ToString128(const char *src, Steinberg_Vst_String128 dst) noexcept
UTF-8 -> the UTF-16 String128 every VST3 name/unit/text field uses.
Definition DSParkVst3.h:309
constexpr uint32_t midiProxyId(int channel, int controller) noexcept
Definition DSParkVst3.h:460
bool streamRead(Steinberg_IBStream *s, void *dst, Steinberg_int32 bytes) noexcept
Reads the full requested range from an IBStream (hosts may chunk).
Definition DSParkVst3.h:407
void string128ToUtf8(const Steinberg_char16 *src, char *dst, size_t cap) noexcept
The inverse, for host text (getParamValueByString): UTF-16 -> UTF-8 into dst, always terminated; unpa...
Definition DSParkVst3.h:358
constexpr uint32_t kBypassParamId
Definition DSParkVst3.h:438
constexpr uint32_t kMidiProxyBase
Definition DSParkVst3.h:448
constexpr int kNumMidiProxies
Definition DSParkVst3.h:450
bool tuidEqual(const Steinberg_TUID a, const Steinberg_TUID b) noexcept
Definition DSParkVst3.h:295
bool streamWrite(Steinberg_IBStream *s, const void *src, Steinberg_int32 bytes) noexcept
Definition DSParkVst3.h:421
double vst3ExpressionValue(MidiEvent::ExpressionType type, double normalized) noexcept
A VST3 normalized note-expression value in MidiEvent units: Volume a linear gain 0....
Definition DSParkVst3.h:593
constexpr int kNumMidiControllers
Definition DSParkVst3.h:449
constexpr Steinberg_int32 kPresetProgramListId
Definition DSParkVst3.h:441
void asciiToString128(const char *src, Steinberg_Vst_String128 dst) noexcept
Kept for source compatibility: every String128 is filled from UTF-8.
Definition DSParkVst3.h:351
constexpr bool isMidiProxyId(uint32_t id) noexcept
Definition DSParkVst3.h:452
MidiEvent midiProxyToEvent(uint32_t id, double normalized, int offset) noexcept
Proxy parameter (normalized) -> the framework-neutral MidiEvent.
Definition DSParkVst3.h:467
constexpr uint32_t kProgramParamId
Definition DSParkVst3.h:439
constexpr int kBypassRampSamples
Definition DSParkVst3.h:440
void copyAscii(const char *src, char *dst, size_t cap) noexcept
Definition DSParkVst3.h:401
@ Instrument
Audio generator (MIDI in -> audio out, no audio input).
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 std::array< uint8_t, 16 > makeUid(const char *productId, uint64_t salt) noexcept
Deterministic 16-byte class UID from the stable productId. Each backend salts differently so VST3/CLA...
constexpr double toNormalized(const Param &p, double plain) noexcept
Plain [min, max] -> normalized [0, 1] (steps snap on the way back).
constexpr 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.
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").
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),...
Param
Every parameter, in the order of the parameter table.
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.
@ Volume
Linear gain 0..4 (1 = unchanged).
@ Pan
0 left, 0.5 centre, 1 right.
@ NoteOn
note = key, value = velocity 0..1.
@ NoteExpression
One voice: expression, value (see above).
@ PolyPressure
note = key, value = pressure 0..1.
@ NoteOff
note = key, value = release velocity 0..1.
@ ControlChange
note = controller number, value = 0..1.
@ ChannelPressure
value = pressure 0..1 (note unused).
@ PitchBend
value = bend -1..+1 (note unused).
float value
Velocity / CC / pressure 0..1; bend -1..+1.
ExpressionType expression
NoteExpression only.
int sampleOffset
Frames into the NEXT processBlock call.
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.
static std::array< uint8_t, 16 > classUid() noexcept
static Steinberg_int32 SMTG_STDMETHODCALLTYPE sCountClasses(void *)
static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sRelease(void *)
static void fillClassCommon(Steinberg_TUID cid) noexcept
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetHostContext(void *, Steinberg_FUnknown *)
static const Steinberg_IPluginFactory3Vtbl kVtbl
static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sAddRef(void *)
const Steinberg_IPluginFactory3Vtbl * vtbl
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sQuery(void *self_, const Steinberg_TUID iid, void **obj)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetClassInfoUnicode(void *, Steinberg_int32 index, Steinberg_PClassInfoW *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCreateInstance(void *, Steinberg_FIDString cid, Steinberg_FIDString iid, void **obj)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetClassInfo(void *, Steinberg_int32 index, Steinberg_PClassInfo *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetClassInfo2(void *, Steinberg_int32 index, Steinberg_PClassInfo2 *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetFactoryInfo(void *, Steinberg_PFactoryInfo *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetNoteExpressionValueByString(void *, Steinberg_int32 busIndex, Steinberg_int16, Steinberg_Vst_NoteExpressionTypeID id, const Steinberg_Vst_TChar *string, Steinberg_Vst_NoteExpressionValue *valueNormalized)
static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetProgramListCount(void *)
static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sGetLatencySamples(void *self_)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sComponentSetState(void *self_, Steinberg_IBStream *state)
static Steinberg_Vst_ParamValue SMTG_STDMETHODCALLTYPE sGetParamNormalized(void *self_, Steinberg_Vst_ParamID id)
std::atomic< double > shadow[kNumParams==0 ? 1 :kNumParams]
Definition DSParkVst3.h:654
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetupProcessing(void *self_, Steinberg_Vst_ProcessSetup *setup)
static constexpr Steinberg_int32 kFirstProxyIndex
static int offeredExpression(Steinberg_int32 index) noexcept
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetUnitByBus(void *, Steinberg_Vst_MediaType, Steinberg_Vst_BusDirection, Steinberg_int32, Steinberg_int32, Steinberg_Vst_UnitID *unitId)
const Steinberg_Vst_IComponentVtbl * componentVtbl
Definition DSParkVst3.h:632
bool onUiThread() const noexcept
Definition DSParkVst3.h:901
static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sRelease(void *self_)
Definition DSParkVst3.h:775
const Steinberg_Vst_IProcessContextRequirementsVtbl * contextReqVtbl
Definition DSParkVst3.h:635
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetRoutingInfo(void *, Steinberg_Vst_RoutingInfo *, Steinberg_Vst_RoutingInfo *)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetMidiControllerAssignment(void *, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_Vst_CtrlNumber midiControllerNumber, Steinberg_Vst_ParamID *id)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlSetState(void *, Steinberg_IBStream *)
static Steinberg_Vst_ParamValue SMTG_STDMETHODCALLTYPE sPlainParamToNormalized(void *, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue plain)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sComponentGetState(void *self_, Steinberg_IBStream *state)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sInitialize(void *self_, Steinberg_FUnknown *context)
std::atomic< double > midiProxyShadow[HasMidi< P > ? kNumMidiProxies :1]
Definition DSParkVst3.h:655
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlGetState(void *, Steinberg_IBStream *)
static int programIndexOf(Steinberg_Vst_ParamValue normalized) noexcept
Definition DSParkVst3.h:867
static constexpr Steinberg_int32 kBypassIndex
const Steinberg_Vst_IMidiMappingVtbl * midiMapVtbl
Definition DSParkVst3.h:637
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sHasProgramPitchNames(void *, Steinberg_Vst_ProgramListID, Steinberg_int32)
static constexpr size_t kNumParams
Definition DSParkVst3.h:607
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sTerminate(void *self_)
static const Steinberg_Vst_INoteExpressionControllerVtbl kNoteExprVtbl
static const Steinberg_Vst_IUnitInfoVtbl kUnitVtbl
void collectInputEvents(Steinberg_Vst_IEventList *list, Steinberg_int32 numSamples, BlockEventList &events) noexcept
void applyAllShadows() noexcept
Definition DSParkVst3.h:829
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCanProcessSampleSize(void *, Steinberg_int32 size)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetIoMode(void *, Steinberg_Vst_IoMode)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlInitialize(void *self_, Steinberg_FUnknown *context)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sQuery(void *self_, const Steinberg_TUID iid, void **obj)
Definition DSParkVst3.h:765
static int indexOfParamId(Steinberg_Vst_ParamID id) noexcept
Definition DSParkVst3.h:780
static Steinberg_int32 numInputBuses() noexcept
void blendBypass(float *const *out, float *const *dry, int nCh, int outStart, int dryStart, int length) noexcept
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetComponentHandler(void *self_, Steinberg_Vst_IComponentHandler *handler)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramName(void *, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex, Steinberg_Vst_String128 name)
static bool offersExpression(Steinberg_Vst_NoteExpressionTypeID id) noexcept
std::atomic< std::thread::id > uiThread
Definition DSParkVst3.h:676
static const Steinberg_Vst_IComponentVtbl kComponentVtbl
void refreshLatency(Steinberg_int32 extraFlags=0) noexcept
Definition DSParkVst3.h:886
bool applyBlockEvent(const BlockEvent &ev, int blockStart, bool &programChanged) noexcept
void collectParameterChanges(Steinberg_Vst_IParameterChanges *changes, Steinberg_int32 numSamples, BlockEventList &events) noexcept
Definition DSParkVst3.h:976
void deliverPendingRestart() noexcept
Definition DSParkVst3.h:927
std::atomic< Steinberg_uint32 > refs
Definition DSParkVst3.h:640
const Steinberg_Vst_INoteExpressionControllerVtbl * noteExprVtbl
Definition DSParkVst3.h:638
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetActive(void *self_, Steinberg_TBool state)
static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetParameterCount(void *)
Steinberg_tresult query(const Steinberg_TUID iid, void **obj) noexcept
Definition DSParkVst3.h:726
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSelectUnit(void *, Steinberg_Vst_UnitID unitId)
static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sAddRef(void *self_)
Definition DSParkVst3.h:771
static void onUiTick(void *self) noexcept
Definition DSParkVst3.h:936
const Steinberg_Vst_IUnitInfoVtbl * unitVtbl
Definition DSParkVst3.h:636
Steinberg_uint32 addRefImpl() noexcept
Definition DSParkVst3.h:752
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetNoteExpressionStringByValue(void *, Steinberg_int32 busIndex, Steinberg_int16, Steinberg_Vst_NoteExpressionTypeID id, Steinberg_Vst_NoteExpressionValue valueNormalized, Steinberg_Vst_String128 string)
static const Steinberg_Vst_IProcessContextRequirementsVtbl kContextReqVtbl
static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetUnitCount(void *)
void forwardTransport(const Steinberg_Vst_ProcessContext *ctx) noexcept
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramListInfo(void *, Steinberg_int32 listIndex, Steinberg_Vst_ProgramListInfo *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetBusArrangement(void *self_, Steinberg_Vst_BusDirection dir, Steinberg_int32 index, Steinberg_Vst_SpeakerArrangement *arr)
std::vector< float > silence
Definition DSParkVst3.h:660
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetUnitInfo(void *, Steinberg_int32 unitIndex, Steinberg_Vst_UnitInfo *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetProcessing(void *self_, Steinberg_TBool state)
std::atomic< int > currentProgram
Definition DSParkVst3.h:657
std::atomic< int > cachedLatency
Definition DSParkVst3.h:651
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetParamStringByValue(void *self_, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue normalized, Steinberg_Vst_String128 out)
static const Steinberg_Vst_IAudioProcessorVtbl kProcessorVtbl
const Steinberg_Vst_IEditControllerVtbl * controllerVtbl
Definition DSParkVst3.h:634
void(* resizeLiveView)(void *view) noexcept
Definition DSParkVst3.h:691
static const Steinberg_Vst_IMidiMappingVtbl kMidiMapVtbl
static const Steinberg_Vst_IEditControllerVtbl kControllerVtbl
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sActivateBus(void *, Steinberg_Vst_MediaType, Steinberg_Vst_BusDirection, Steinberg_int32, Steinberg_TBool)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramPitchName(void *, Steinberg_Vst_ProgramListID, Steinberg_int32, Steinberg_int16, Steinberg_Vst_String128)
static constexpr Steinberg_int32 kProgramIndex
static constexpr int kNumPresets
Definition DSParkVst3.h:610
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetBusInfo(void *self_, Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir, Steinberg_int32 index, Steinberg_Vst_BusInfo *bus)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetParamValueByString(void *self_, Steinberg_Vst_ParamID id, Steinberg_Vst_TChar *string, Steinberg_Vst_ParamValue *normalized)
static Steinberg_Vst_ParamValue SMTG_STDMETHODCALLTYPE sNormalizedParamToPlain(void *, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue normalized)
EditorSizeMemory< P > editorMemory
Definition DSParkVst3.h:664
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetProgramInfo(void *, Steinberg_Vst_ProgramListID, Steinberg_int32, Steinberg_Vst_CString, Steinberg_Vst_String128)
std::vector< float > dryR
Definition DSParkVst3.h:659
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetNoteExpressionInfo(void *, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_int32 index, struct Steinberg_Vst_NoteExpressionTypeInfo *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetUnitProgramData(void *, Steinberg_int32, Steinberg_int32, struct Steinberg_IBStream *)
Steinberg_Vst_ProcessSetup setup
Definition DSParkVst3.h:643
static Plugin * fromLens(void *iface, int lens) noexcept
Definition DSParkVst3.h:713
static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetNoteExpressionCount(void *, Steinberg_int32 busIndex, Steinberg_int16 channel)
void attachToHost(Steinberg_FUnknown *context) noexcept
Definition DSParkVst3.h:943
std::vector< float > dryL
Definition DSParkVst3.h:659
std::atomic< bool > processing
Definition DSParkVst3.h:683
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sCtrlTerminate(void *self_)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sProcess(void *self_, Steinberg_Vst_ProcessData *data)
std::atomic< bool > bypass
Definition DSParkVst3.h:656
static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sGetTailSamples(void *self_)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetParamNormalized(void *self_, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue value)
static Steinberg_Vst_UnitID SMTG_STDMETHODCALLTYPE sGetSelectedUnit(void *)
Steinberg_uint32 releaseImpl() noexcept
Definition DSParkVst3.h:757
bool applyFromUi(int index, double normalized) noexcept
Definition DSParkVst3.h:805
void * lensPtr(int lens) noexcept
Definition DSParkVst3.h:719
static constexpr uint32_t kVst3Expressions
Definition DSParkVst3.h:624
static Steinberg_IPlugView *SMTG_STDMETHODCALLTYPE sCreateView(void *self_, Steinberg_FIDString name)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetParameterInfo(void *self_, Steinberg_int32 index, Steinberg_Vst_ParameterInfo *info)
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetComponentState(void *self_, Steinberg_IBStream *state)
bool drainPending() noexcept
Definition DSParkVst3.h:820
std::atomic< Steinberg_int32 > pendingRestart
Definition DSParkVst3.h:677
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sGetControllerClassId(void *, Steinberg_TUID)
static constexpr bool kIsInstrument
Definition DSParkVst3.h:608
static Steinberg_uint32 SMTG_STDMETHODCALLTYPE sGetProcessContextRequirements(void *)
const Steinberg_Vst_IAudioProcessorVtbl * processorVtbl
Definition DSParkVst3.h:633
std::atomic< Steinberg_Vst_IComponentHandler * > handler
Definition DSParkVst3.h:670
static Steinberg_int32 SMTG_STDMETHODCALLTYPE sGetBusCount(void *, Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir)
void applyNormalized(int index, double normalized) noexcept
Definition DSParkVst3.h:786
PendingParams< kNumParams > pending
Definition DSParkVst3.h:684
static Steinberg_tresult SMTG_STDMETHODCALLTYPE sSetBusArrangements(void *self_, Steinberg_Vst_SpeakerArrangement *inputs, Steinberg_int32 numIns, Steinberg_Vst_SpeakerArrangement *outputs, Steinberg_int32 numOuts)
static int midiProxySlot(uint32_t id) noexcept
void applyFactoryPresetIdx(int idx, bool fromUi=false) noexcept
Definition DSParkVst3.h:841
void detachFromHost() noexcept
Definition DSParkVst3.h:956
void requestRestart(Steinberg_int32 flags) noexcept
Definition DSParkVst3.h:914