DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DSParkAu.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
101#define DSPARK_PLUGIN_AU_INCLUDED 1
102
103#if defined(__APPLE__)
104
105#include "../DSParkPlugin.h"
106
107#include <AudioToolbox/AudioToolbox.h>
108#include <CoreFoundation/CoreFoundation.h>
109
110// AUParameterListenerNotify (state / preset loads), AUParameterSet and
111// AUEventListenerNotify (editor gestures): all in AudioToolbox.framework.
112#include <AudioToolbox/AudioUnitUtilities.h>
113
114// MIDI 2.0 event lists (MusicDeviceMIDIEventList and the AudioUnitMIDIProtocol
115// property, SDK 12 and later): the Universal MIDI Packet types come from the
116// CoreMIDI header alone - no CoreMIDI function is called, nothing more to link.
117#if defined(__has_include)
118#if __has_include(<CoreMIDI/MIDIServices.h>) && (defined(__MAC_12_0) || defined(__IPHONE_15_0))
119#include <CoreMIDI/MIDIServices.h>
120#define DSPARK_AU_HAVE_MIDI2 1
121#endif
122#endif
123#if !defined(DSPARK_AU_HAVE_MIDI2)
124#define DSPARK_AU_HAVE_MIDI2 0
125#endif
126
127#if defined(DSPARK_PLUGIN_WEBVIEW)
128#include <dlfcn.h>
129#include <objc/message.h>
130#include <objc/runtime.h>
131#endif
132
133#include <dispatch/dispatch.h>
134#include <pthread.h>
135
136#include <atomic>
137#include <cmath>
138#include <cstring>
139#include <new>
140#include <thread>
141#include <vector>
142
143// Survive a <windows.h>-style min/max macro (restored at the end).
144#pragma push_macro("min")
145#pragma push_macro("max")
146#undef min
147#undef max
148
149namespace dspark::plugin::au {
150
151inline constexpr uint32_t kBypassParamId = 0x42595053u; // matches VST3/CLAP
152inline constexpr int kBypassRampSamples = 256;
153
154inline OSType fourCC(const char* s) noexcept
155{
156 return (static_cast<OSType>(static_cast<unsigned char>(s[0])) << 24)
157 | (static_cast<OSType>(static_cast<unsigned char>(s[1])) << 16)
158 | (static_cast<OSType>(static_cast<unsigned char>(s[2])) << 8)
159 | static_cast<OSType>(static_cast<unsigned char>(s[3]));
160}
161
162#if defined(DSPARK_PLUGIN_WEBVIEW)
163
164// -- WebView editor glue (Cocoa view factory) -----------------------------------
165//
166// AUv2 has no IPlugView: the host reads kAudioUnitProperty_CocoaUI, loads the
167// announced bundle, instantiates the named factory class and asks it for an
168// NSView. Both classes here (factory + container view) are registered through
169// the Objective-C runtime on first use - no Objective-C sources, no AppKit
170// link dependency in the plugin. The factory is stateless: it recovers the
171// C++ plugin instance through a PRIVATE property on the AudioUnit handle
172// (IDs >= 64000 are reserved for third parties), so one process-wide class
173// serves every DSPark plugin loaded in the host, whichever binary won the
174// registration race (same policy as the WebView message relay).
175
177inline constexpr AudioUnitPropertyID kDsparkEditorHookProperty = 64537;
178
182struct EditorHook
183{
184 void* context = nullptr;
185 void* (*createView)(void* context, double width, double height) = nullptr;
186};
187
189struct ViewSize
190{
191 double width = 0, height = 0;
192};
193
196struct EditorViewSink
197{
198 void (*onDealloc)(void* context) = nullptr;
199 void* context = nullptr;
201 void (*onResize)(void* context, double width, double height) = nullptr;
202};
203
204inline Class editorContainerClass() noexcept;
205
206inline void editorContainerDealloc(void* self, SEL) noexcept
207{
208 // Instances exist only after the class registered, so the lookup cannot
209 // miss; the superclass is resolved from the registered class (NOT from
210 // object_getClass) so a future subclass would not recurse.
211 Class cls = editorContainerClass();
212 if (cls == nullptr) return;
213 if (Ivar ivar = class_getInstanceVariable(cls, "dsparkSink"))
214 {
215 auto* sink = reinterpret_cast<EditorViewSink*>(
216 object_getIvar(static_cast<id>(self), ivar));
217 if (sink != nullptr && sink->onDealloc != nullptr)
218 sink->onDealloc(sink->context);
219 }
220 objc_super super { static_cast<id>(self), class_getSuperclass(cls) };
221 reinterpret_cast<void (*)(objc_super*, SEL)>(&objc_msgSendSuper)(
222 &super, sel_registerName("dealloc"));
223}
224
228inline void editorContainerSetFrameSize(void* self, SEL selector, ViewSize size) noexcept
229{
230 Class cls = editorContainerClass();
231 if (cls == nullptr) return;
232 objc_super super { static_cast<id>(self), class_getSuperclass(cls) };
233 reinterpret_cast<void (*)(objc_super*, SEL, ViewSize)>(&objc_msgSendSuper)(
234 &super, selector, size);
235 if (Ivar ivar = class_getInstanceVariable(cls, "dsparkSink"))
236 {
237 auto* sink = reinterpret_cast<EditorViewSink*>(
238 object_getIvar(static_cast<id>(self), ivar));
239 if (sink != nullptr && sink->onResize != nullptr)
240 sink->onResize(sink->context, size.width, size.height);
241 }
242}
243
246inline Class editorContainerClass() noexcept
247{
248 // The class name carries this binary's own suffix: a process-wide name
249 // let the first DSPark plugin loaded register it, and every later plugin
250 // binary then ran THAT binary's dealloc code (another DSPark version, or
251 // an image the host may since have unloaded).
252 static Class registered = []() -> Class {
253 Class viewCls = objc_getClass("NSView");
254 if (viewCls == nullptr) return nullptr;
255 static char name[96];
256 webview_ui::objc_glue::imageUniqueClassName("DSParkAUEditorContainer",
257 name, sizeof(name));
258 Class c = objc_allocateClassPair(viewCls, name, 0);
259 if (c == nullptr) // this image registered it already
260 return objc_getClass(name);
261 class_addIvar(c, "dsparkSink", sizeof(void*), alignof(void*) == 8 ? 3 : 2, "^v");
262 class_addMethod(c, sel_registerName("dealloc"),
263 reinterpret_cast<IMP>(&editorContainerDealloc), "v@:");
264 class_addMethod(c, sel_registerName("setFrameSize:"),
265 reinterpret_cast<IMP>(&editorContainerSetFrameSize),
266 "v@:{CGSize=dd}");
267 objc_registerClassPair(c);
268 return c;
269 }();
270 return registered;
271}
272
273inline unsigned int editorFactoryInterfaceVersion(void*, SEL) noexcept
274{
275 return 0; // AUCocoaUIBase protocol version
276}
277
278inline void* editorFactoryUiView(void*, SEL, void* audioUnit, ViewSize size) noexcept
279{
280 EditorHook hook {};
281 UInt32 ioSize = sizeof(hook);
282 if (audioUnit == nullptr
283 || AudioUnitGetProperty(static_cast<AudioUnit>(audioUnit),
284 kDsparkEditorHookProperty, kAudioUnitScope_Global,
285 0, &hook, &ioSize) != noErr
286 || hook.createView == nullptr)
287 return nullptr;
288 return hook.createView(hook.context, size.width, size.height);
289}
290
292inline Class editorFactoryClass() noexcept
293{
294 static Class registered = []() -> Class {
295 static char name[96]; // per-binary name, see editorContainerClass()
296 webview_ui::objc_glue::imageUniqueClassName("DSParkAUCocoaViewFactory",
297 name, sizeof(name));
298 Class c = objc_allocateClassPair(objc_getClass("NSObject"), name, 0);
299 if (c == nullptr)
300 return objc_getClass(name);
301 class_addMethod(c, sel_registerName("interfaceVersion"),
302 reinterpret_cast<IMP>(&editorFactoryInterfaceVersion), "I@:");
303 class_addMethod(c, sel_registerName("uiViewForAudioUnit:withSize:"),
304 reinterpret_cast<IMP>(&editorFactoryUiView),
305 "@@:^{ComponentInstanceRecord=}{CGSize=dd}");
306 // Hosts overwhelmingly probe by respondsToSelector; declare the formal
307 // protocol too when some loaded image has registered it.
308 if (Protocol* proto = objc_getProtocol("AUCocoaUIBase"))
309 class_addProtocol(c, proto);
310 objc_registerClassPair(c);
311 return c;
312 }();
313 return registered;
314}
315
319inline CFURLRef copyOwningBundleUrl() noexcept
320{
321 static const int anchor = 0; // any address inside THIS image
322 Dl_info info {};
323 if (dladdr(&anchor, &info) == 0 || info.dli_fname == nullptr) return nullptr;
324 const char* path = info.dli_fname;
325 const char* marker = nullptr;
326 for (const char* p = std::strstr(path, "/Contents/MacOS/"); p != nullptr;
327 p = std::strstr(p + 1, "/Contents/MacOS/"))
328 marker = p; // last occurrence wins (nested bundle layouts)
329 size_t length = marker != nullptr ? static_cast<size_t>(marker - path) : 0;
330 if (length == 0)
331 if (const char* slash = std::strrchr(path, '/'))
332 length = static_cast<size_t>(slash - path);
333 if (length == 0) return nullptr;
334 return CFURLCreateFromFileSystemRepresentation(
335 kCFAllocatorDefault, reinterpret_cast<const UInt8*>(path),
336 static_cast<CFIndex>(length), true);
337}
338
339#endif // DSPARK_PLUGIN_WEBVIEW
340
341template <typename P>
342struct Plugin
343{
344 static constexpr size_t kNumParams = P::parameters.size();
345 static constexpr bool kIsInstrument =
346 P::descriptor.category == Category::Instrument;
347 static constexpr int kNumPresets = factoryPresetCountOf<P>();
348 static_assert(!(kIsInstrument && HasSidechain<P>),
349 "an Instrument has no audio inputs; remove the sidechain "
350 "processBlock or use Category::Fx");
351 static_assert(!kIsInstrument || HasMidi<P>,
352 "an Instrument needs handleMidiEvent (see HasMidi): it has "
353 "no audio input to process");
354 static_assert(paramIdsUnique<P>(),
355 "two parameter ids share a hash32 (or collide with the "
356 "reserved PRGM/BYPS/EDSW/EDSH state ids): automation and state "
357 "would cross-wire. Rename one id.");
358
360 static OSType expectedType() noexcept
361 {
362 if (kIsInstrument) return fourCC("aumu");
363 if (HasMidi<P>) return fourCC("aumf");
364 return fourCC("aufx");
365 }
366
367 AudioComponentInstance instance = nullptr;
368 OSType subtype = 0, manufacturer = 0;
369
370 double sampleRate = 44100.0;
371 UInt32 maxFrames = 1156; // CoreAudio's historical default
374 std::atomic<bool> initialized { false };
375 int currentChannels = defaultChannelCount<P>(); // negotiated width
376 UInt32 offlineRender = 0;
377
378 P user {};
379 std::atomic<double> shadow[kNumParams == 0 ? 1 : kNumParams] {};
380 std::atomic<bool> bypass { false };
381 float bypassMix = 0.0f;
388 std::atomic<int> cachedLatency { 0 };
389
390 // Input elements: 0 = main, 1 = sidechain. An instrument has none.
391 static constexpr UInt32 kNumInputElements =
392 kIsInstrument ? 0 : (HasSidechain<P> ? 2 : 1);
393 AURenderCallbackStruct inputCallback[2] {};
394 AudioUnit inputConnection[2] = { nullptr, nullptr };
395 UInt32 inputConnectionBus[2] = { 0, 0 };
396
397 std::vector<float> pullL, pullR, dryL, dryR, scL, scR;
398 DryDelay dryDelay; // latency-aligned dry path of the bypass
399
400 // Host transport callbacks (kAudioUnitProperty_HostCallbacks).
401 HostCallbackInfo hostCallbacks {};
402
403 // Incoming MIDI: the MusicDevice selectors push, render() drains. Any
404 // number of threads may push at once - the host's MIDI thread, its
405 // render thread, an on-screen keyboard on the main thread - so this is a
406 // bounded multi-producer queue: a producer claims a position with one
407 // compare-exchange and publishes its cell with a release store of the
408 // cell's sequence number; the render thread is the one consumer. (The
409 // old single-producer ring let two pushing threads take the same slot:
410 // events were lost, duplicated or torn.)
411 static constexpr uint32_t kMidiRingSize = 256; // power of two
412 struct MidiCell
413 {
414 std::atomic<uint32_t> seq { 0 };
415 MidiEvent event {};
416 };
417 MidiCell midiRing[HasMidi<P> ? kMidiRingSize : 1] {};
418 std::atomic<uint32_t> midiEnqueue { 0 }; // the next position a producer claims
419 uint32_t midiDequeue = 0; // the render thread's position
420 // Reset discards the MIDI queued before it (a transport stop must not
421 // replay notes into the next run): positions before this mark are
422 // drained without being delivered.
423 std::atomic<uint32_t> midiDiscardBefore { 0 };
424
425 // Render notifications (AudioUnitAddRenderNotify): host callbacks run
426 // before and after every render - hosts schedule parameters from the
427 // pre-render one and meter from the post-render one. Add/remove arrive
428 // on a control thread and reach the render thread through a
429 // single-producer queue; the render thread owns the list it calls.
430 struct RenderNotify
431 {
432 AURenderCallback proc = nullptr;
433 void* refCon = nullptr;
434 };
435 static constexpr int kMaxRenderNotifies = 16;
436 RenderNotify renderNotifies[kMaxRenderNotifies] {};
437 int renderNotifyCount = 0;
438 struct NotifyCommand
439 {
440 RenderNotify target {};
441 bool add = false;
442 };
443 static constexpr uint32_t kNotifyQueueSize = 64; // power of two
444 NotifyCommand notifyQueue[kNotifyQueueSize] {};
445 std::atomic<uint32_t> notifyHead { 0 }, notifyTail { 0 };
446
447 // Sample-accurate parameter events (kAudioUnitScheduleParametersSelect
448 // arrives on the render thread, right before the matching render call).
449 // Immediate events and bypass points go straight into the block list
450 // (merging past its capacity instead of dropping the newest); ramps are
451 // kept whole and evaluated against the slice length inside render().
452 BlockEventList blockEvents;
453 struct Ramp
454 {
455 uint32_t paramId;
456 SInt32 startOffset; // may be negative: began in an earlier slice
457 UInt32 duration;
458 float startValue, endValue; // plain
459 };
460 static constexpr int kMaxRamps = 64;
461 Ramp ramps[kMaxRamps] {};
462 int rampCount = 0;
463
464 // One writer for the user's setParameter: the render thread while the
465 // unit is initialized; edits from any other thread are handed over.
466 PendingParams<kNumParams> pending;
467 std::atomic<std::thread::id> renderThread {};
468 UInt32 sidechainChannels = 0; // input element 1 width (0: follow main)
469
470 // Factory presets: AUPreset records plus the lazily built CFArray the
471 // property hands out (retained per get; the strings live here).
472 std::vector<AUPreset> presetStorage;
473 CFArrayRef presetArray = nullptr;
474 SInt32 currentPresetNumber = -1;
475
476 // Property listeners (registered/fired on the host's main thread) and
477 // the user-preset name AU hosts expect through kAudioUnitProperty_PresentPreset.
478 struct Listener
479 {
480 AudioUnitPropertyID id;
481 AudioUnitPropertyListenerProc proc;
482 void* user;
483 };
484 std::vector<Listener> listeners;
485 CFStringRef presetName = nullptr;
486
488 std::atomic<double> cachedTail { 0.0 };
490 double latencySecondsAtInit = 0.0;
493 EditorSizeMemory<P> editorMemory;
494
499 std::atomic<OSStatus> lastRenderError { noErr };
500
510 bool allocateInput[2] = { true, true };
511 bool allocateOutput = true;
512
514 [[nodiscard]] bool ownsMainBuffers() const noexcept
515 {
516 if constexpr (kIsInstrument)
517 return allocateOutput;
518 else
519 return allocateInput[0] || allocateOutput;
520 }
521
522#if defined(DSPARK_PLUGIN_WEBVIEW)
523 webview_ui::Editor<P> editor;
524 void* editorContainer = nullptr; // NSView* the HOST owns; weak here
525 EditorViewSink editorSink {};
526 bool editActive[kNumParams == 0 ? 1 : kNumParams] {};
527#endif
528
529 ~Plugin() noexcept
530 {
531 stopTick(false); // disposing: no listener call from here
532#if defined(DSPARK_PLUGIN_WEBVIEW)
533 teardownEditor();
534#endif
535 if (presetName != nullptr) CFRelease(presetName);
536 for (auto& preset : presetStorage)
537 if (preset.presetName != nullptr) CFRelease(preset.presetName);
538 if (presetArray != nullptr) CFRelease(presetArray);
539 }
540
542 void applyFactoryPresetIdx(int idx) noexcept
543 {
544 if constexpr (kNumPresets > 0)
545 {
546 if (idx < 0 || idx >= kNumPresets) return;
547 for (size_t i = 0; i < kNumParams; ++i)
548 applyFromAnyThread(static_cast<int>(i), presetNormalized<P>(idx, i));
549 currentPresetNumber = idx;
550 }
551 else
552 (void) idx;
553 }
554
557 double tailSecondsNow() const noexcept
558 {
559 if constexpr (HasTail<P>)
560 {
561 const double tail = user.getTailSeconds();
562 return tail > 0.0 ? tail : 0.0;
563 }
564 else
565 return 0.0;
566 }
567
575 void refreshReported() noexcept
576 {
577 uint32_t bits = 0;
578 if constexpr (HasLatency<P>)
579 {
580 const int now = user.getLatency();
581 if (initialized && now != cachedLatency.load(std::memory_order_relaxed))
582 {
583 cachedLatency.store(now, std::memory_order_relaxed);
584 bits |= kNotifyLatency;
585 }
586 }
587 if constexpr (HasTail<P>)
588 {
589 const double now = tailSecondsNow();
590 if (initialized && now != cachedTail.load(std::memory_order_relaxed))
591 {
592 cachedTail.store(now, std::memory_order_relaxed);
593 bits |= kNotifyTail;
594 }
595 }
596 if (bits != 0) announce(bits);
597 }
598
599 // --- property notifications (main thread; ~30 Hz main-queue tick) ------------------
600
601 enum : uint32_t
602 {
603 kNotifyLatency = 1u, kNotifyTail = 2u, kNotifyBypass = 4u, kNotifyRenderError = 8u
604 };
605 std::atomic<uint32_t> notifyPending { 0u };
606 std::atomic<bool> tickRunning { false };
607 dispatch_source_t tick = nullptr;
608
611 void announce(uint32_t bits) noexcept
612 {
613 if (pthread_main_np() != 0 || !tickRunning.load(std::memory_order_acquire))
614 deliverNotifications(bits);
615 else
616 notifyPending.fetch_or(bits, std::memory_order_release);
617 }
618
622 void announceFromRender(uint32_t bits) noexcept
623 {
624 if (pthread_main_np() != 0)
625 deliverNotifications(bits);
626 else
627 notifyPending.fetch_or(bits, std::memory_order_release);
628 }
629
634 void recordRenderError(OSStatus error) noexcept
635 {
636 if (error == noErr) return;
637 OSStatus none = noErr;
638 if (lastRenderError.compare_exchange_strong(none, error, std::memory_order_relaxed))
639 announceFromRender(kNotifyRenderError);
640 }
641
642 void deliverNotifications(uint32_t bits) noexcept
643 {
644 if ((bits & kNotifyLatency) != 0u)
645 notifyProperty(kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0);
646 if ((bits & kNotifyTail) != 0u)
647 notifyProperty(kAudioUnitProperty_TailTime, kAudioUnitScope_Global, 0);
648 // The host's bypass button follows the property, not the bypass
649 // parameter the host itself moved (automation, a state load).
650 if ((bits & kNotifyBypass) != 0u)
651 notifyProperty(kAudioUnitProperty_BypassEffect, kAudioUnitScope_Global, 0);
652 if ((bits & kNotifyRenderError) != 0u)
653 notifyProperty(kAudioUnitProperty_LastRenderError, kAudioUnitScope_Global, 0);
654 }
655
656 static void onTick(void* self)
657 {
658 auto* plugin = static_cast<Plugin*>(self);
659 const uint32_t bits = plugin->notifyPending.exchange(0u, std::memory_order_acq_rel);
660 if (bits != 0u) plugin->deliverNotifications(bits);
661 }
662
663 void startTick() noexcept
664 {
665 if (tick != nullptr) return;
666 tick = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
667 dispatch_get_main_queue());
668 if (tick == nullptr) return;
669 dispatch_set_context(tick, this);
670 dispatch_source_set_event_handler_f(tick, &onTick);
671 dispatch_source_set_timer(tick, dispatch_time(DISPATCH_TIME_NOW, 33 * 1000000),
672 33u * 1000000u, 5u * 1000000u);
673 dispatch_resume(tick);
674 tickRunning.store(true, std::memory_order_release);
675 // A render error raised while no tick ran (a refused render before
676 // initialize) reaches its listeners now, on the main thread.
677 const uint32_t bits = notifyPending.exchange(0u, std::memory_order_acq_rel);
678 if (bits != 0u) deliverNotifications(bits);
679 }
680
683 void stopTick(bool flush = true) noexcept
684 {
685 if (tick == nullptr) return;
686 tickRunning.store(false, std::memory_order_release);
687 dispatch_source_cancel(tick);
688 dispatch_release(tick);
689 tick = nullptr;
690 const uint32_t bits = notifyPending.exchange(0u, std::memory_order_acq_rel);
691 if (bits != 0u && flush) deliverNotifications(bits);
692 }
693
695 void notifyParameterChanged(AudioUnitParameterID id) noexcept
696 {
697 AudioUnitParameter parameter {};
698 parameter.mAudioUnit = instance;
699 parameter.mParameterID = id;
700 parameter.mScope = kAudioUnitScope_Global;
701 parameter.mElement = 0;
702 AUParameterListenerNotify(nullptr, nullptr, &parameter);
703 }
704
706 bool setBypass(bool on) noexcept
707 {
708 return bypass.exchange(on, std::memory_order_relaxed) != on;
709 }
710
711 void notifyProperty(AudioUnitPropertyID id, AudioUnitScope scope,
712 AudioUnitElement element) noexcept
713 {
714 for (const auto& l : listeners)
715 if (l.id == id && l.proc != nullptr)
716 l.proc(l.user, instance, id, scope, element);
717 }
718
719 Plugin() noexcept
720 {
721 for (size_t i = 0; i < kNumParams; ++i)
722 shadow[i].store(toNormalized(P::parameters[i], P::parameters[i].defValue),
723 std::memory_order_relaxed);
724 uint32_t position = 0;
725 for (auto& cell : midiRing) // each cell open for its first position
726 cell.seq.store(position++, std::memory_order_relaxed);
727 }
728
729 static int indexOfParamId(AudioUnitParameterID id) noexcept
730 {
731 return paramIndexOf<P>(id);
732 }
733
734 void applyNormalized(int index, double normalized) noexcept
735 {
736 // Host values are untrusted doubles: a NaN would pass both range
737 // clamps, poison the shadow and reach the user's setter. Ignore it.
738 if (normalized != normalized) return;
739 const auto& spec = P::parameters[static_cast<size_t>(index)];
740 shadow[static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
741 user.setParameter(index, static_cast<float>(toPlain(spec, normalized)));
742 }
743
752 bool applyFromAnyThread(int index, double normalized) noexcept
753 {
754 if (normalized != normalized) return false;
755 if (initialized
756 && std::this_thread::get_id() != renderThread.load(std::memory_order_relaxed))
757 {
758 shadow[static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
759 pending.mark(static_cast<size_t>(index));
760 return false;
761 }
762 applyNormalized(index, normalized);
763 return true;
764 }
765
766 bool drainPending() noexcept
767 {
768 return pending.drain([this](int i) {
769 user.setParameter(i, static_cast<float>(toPlain(
770 P::parameters[static_cast<size_t>(i)],
771 shadow[static_cast<size_t>(i)].load(std::memory_order_relaxed))));
772 });
773 }
774
778 CFStringRef copyPresetName() const noexcept
779 {
780 if (presetName != nullptr)
781 return static_cast<CFStringRef>(CFRetain(presetName));
782 const char* name = "Untitled";
783 if constexpr (kNumPresets > 0)
784 if (currentPresetNumber >= 0 && currentPresetNumber < kNumPresets)
785 name = P::factoryPresets[static_cast<size_t>(currentPresetNumber)].name;
786 return CFStringCreateWithCString(nullptr, name, kCFStringEncodingUTF8);
787 }
788
792 void notifyAllParameters() noexcept
793 {
794 AudioUnitParameter any {};
795 any.mAudioUnit = instance;
796 any.mParameterID = kAUParameterListener_AnyParameter;
797 any.mScope = kAudioUnitScope_Global;
798 any.mElement = 0;
799 AUParameterListenerNotify(nullptr, nullptr, &any);
800 }
801
802 void applyAllShadows() noexcept
803 {
804 pending.drain([](int) {}); // every value is re-applied right below
805 for (size_t i = 0; i < kNumParams; ++i)
806 user.setParameter(static_cast<int>(i),
807 static_cast<float>(toPlain(P::parameters[i],
808 shadow[i].load(std::memory_order_relaxed))));
809 }
810
811#if defined(DSPARK_PLUGIN_WEBVIEW)
812
813 // --- WebView editor (all on the host's main thread) -----------------------------
814
815 static constexpr bool kHasWebEditor =
816 HasEditor<P> && webview_ui::Editor<P>::kAvailable;
817
818 void sendGesture(int index, AudioUnitEventType type) noexcept
819 {
820 AudioUnitEvent event {};
821 event.mEventType = type;
822 event.mArgument.mParameter = AudioUnitParameter {
823 instance, hash32(P::parameters[static_cast<size_t>(index)].id),
824 kAudioUnitScope_Global, 0 };
825 AUEventListenerNotify(nullptr, nullptr, &event);
826 }
827
828 // Editor -> host/DSP bridge. AUParameterSet routes through our own
829 // SetParameter (shadow + user setter) AND notifies host listeners, which
830 // is how AU hosts observe UI edits for automation recording.
831 static void cbSetParam(void* context, int index, double plain) noexcept
832 {
833 auto* self = static_cast<Plugin*>(context);
834 const AudioUnitParameter parameter {
835 self->instance, hash32(P::parameters[static_cast<size_t>(index)].id),
836 kAudioUnitScope_Global, 0 };
837 const bool inGesture = self->editActive[static_cast<size_t>(index)];
838 if (!inGesture) // edits outside a drag still need a gesture for undo
839 self->sendGesture(index, kAudioUnitEvent_BeginParameterChangeGesture);
840 AUParameterSet(nullptr, nullptr, &parameter,
841 static_cast<AudioUnitParameterValue>(plain), 0);
842 if (!inGesture)
843 self->sendGesture(index, kAudioUnitEvent_EndParameterChangeGesture);
844 }
845
846 static void cbBeginEdit(void* context, int index) noexcept
847 {
848 auto* self = static_cast<Plugin*>(context);
849 self->editActive[static_cast<size_t>(index)] = true;
850 self->sendGesture(index, kAudioUnitEvent_BeginParameterChangeGesture);
851 }
852
853 static void cbEndEdit(void* context, int index) noexcept
854 {
855 auto* self = static_cast<Plugin*>(context);
856 self->editActive[static_cast<size_t>(index)] = false;
857 self->sendGesture(index, kAudioUnitEvent_EndParameterChangeGesture);
858 }
859
860 static void sOnContainerDealloc(void* context) noexcept
861 {
862 auto* self = static_cast<Plugin*>(context);
863 self->editorContainer = nullptr; // the host is destroying the view
864 self->editor.destroy();
865 }
866
869 static void sOnContainerResize(void* context, double width, double height) noexcept
870 {
871 static_cast<Plugin*>(context)->editorMemory.remember(width, height);
872 }
873
876 void teardownEditor() noexcept
877 {
878 if (editorContainer != nullptr)
879 {
880 Class cls = editorContainerClass();
881 if (Ivar ivar = cls != nullptr
882 ? class_getInstanceVariable(cls, "dsparkSink") : nullptr)
883 object_setIvar(static_cast<id>(editorContainer), ivar, nullptr);
884 editorContainer = nullptr;
885 }
886 editor.destroy();
887 }
888
889 static void* sCreateEditorView(void* context, double width, double height) noexcept
890 {
891 return static_cast<Plugin*>(context)->createEditorView(width, height);
892 }
893
898 void applyRememberedEditorSize() noexcept
899 {
900 if constexpr (kHasWebEditor)
901 {
902 if (editorContainer == nullptr) return;
903 namespace og = webview_ui::objc_glue;
904 const EditorSize logical = editorMemory.current();
905 og::call<void>(static_cast<og::ObjId>(editorContainer), "setFrameSize:",
906 ViewSize { static_cast<double>(logical.width),
907 static_cast<double>(logical.height) });
908 editor.setBounds(logical.width, logical.height);
909 }
910 }
911
918 void* createEditorView(double, double) noexcept
919 {
920 namespace og = webview_ui::objc_glue;
921 teardownEditor(); // hosts may ask again without releasing the first view
922 Class cls = editorContainerClass();
923 if (cls == nullptr) return nullptr; // AppKit absent: faceless host
924 const EditorSize logical = editorMemory.current();
925 const og::Rect frame { 0.0, 0.0, static_cast<double>(logical.width),
926 static_cast<double>(logical.height) };
927 og::ObjId view = og::call(og::call(reinterpret_cast<og::ObjId>(cls), "alloc"),
928 "initWithFrame:", frame);
929 if (view == nullptr) return nullptr;
930 const webview_ui::HostCallbacks callbacks {
931 this, &cbSetParam, &cbBeginEdit, &cbEndEdit
932 };
933 if (!editor.create(view, shadow, callbacks))
934 {
935 og::call<void>(view, "release");
936 return nullptr;
937 }
938 editorSink = { &sOnContainerDealloc, this, &sOnContainerResize };
939 if (Ivar ivar = class_getInstanceVariable(cls, "dsparkSink"))
940 object_setIvar(static_cast<id>(view),
941 ivar, reinterpret_cast<id>(&editorSink));
942 editorContainer = view;
943 editor.setBounds(logical.width, logical.height);
944 editor.setVisible(true);
945 webview_ui::debugLog("au createEditorView %dx%d container=%p",
946 logical.width, logical.height, view);
947 return og::call(view, "autorelease");
948 }
949
950#endif // DSPARK_PLUGIN_WEBVIEW
951
952 // --- lifecycle ---------------------------------------------------------------
953
954 OSStatus initialize() noexcept
955 {
956 dspark::AudioSpec spec { sampleRate, static_cast<int>(maxFrames),
957 currentChannels };
958 const double tailBefore = cachedTail.load(std::memory_order_relaxed);
959 user.prepare(spec);
960 if constexpr (HasOfflineMode<P>)
961 user.setOfflineRendering(offlineRender != 0);
962 applyAllShadows();
963 if (ownsMainBuffers())
964 {
965 pullL.assign(maxFrames, 0.0f);
966 pullR.assign(maxFrames, 0.0f);
967 }
968 else
969 {
970 // ShouldAllocateBuffer false on the main input and the output:
971 // the memory is released, not just left unused.
972 std::vector<float>().swap(pullL);
973 std::vector<float>().swap(pullR);
974 }
975 dryL.assign(maxFrames, 0.0f);
976 dryR.assign(maxFrames, 0.0f);
977 if constexpr (HasSidechain<P>)
978 {
979 scL.assign(maxFrames, 0.0f);
980 scR.assign(maxFrames, 0.0f);
981 }
982 bypassMix = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
983 uint32_t changed = 0;
984 if constexpr (HasLatency<P>)
985 {
986 const int latency = user.getLatency();
987 cachedLatency.store(latency, std::memory_order_relaxed);
988 dryDelay.prepare(std::max(2 * latency, kDryDelayMinCapacity),
989 static_cast<int>(maxFrames));
990 // The property is in seconds: a new latency or a new rate moves
991 // it. Listeners hear of it here; the old code only updated the
992 // cache, so a host that read it before initializing kept 0.
993 const double seconds = sampleRate > 0.0 ? latency / sampleRate : 0.0;
994 if (seconds != latencySecondsAtInit) changed |= kNotifyLatency;
995 latencySecondsAtInit = seconds;
996 }
997 if constexpr (HasTail<P>)
998 {
999 const double tail = tailSecondsNow();
1000 cachedTail.store(tail, std::memory_order_relaxed);
1001 if (tail != tailBefore) changed |= kNotifyTail;
1002 }
1003 else
1004 (void) tailBefore;
1005 blockEvents.clear();
1006 rampCount = 0;
1007 if constexpr (HasMidi<P>) // MIDI queued while uninitialized is stale
1008 midiDiscardBefore.store(midiEnqueue.load(std::memory_order_acquire),
1009 std::memory_order_release);
1010 applyNotifyCommands(); // no render runs before `initialized` below
1011 renderThread.store(std::thread::id {}, std::memory_order_relaxed);
1012 startTick();
1013 initialized = true;
1014 if (changed != 0u) deliverNotifications(changed); // main thread
1015 return noErr;
1016 }
1017
1018 OSStatus uninitialize() noexcept
1019 {
1020 initialized = false;
1021 drainPending(); // no render can run now: hand edits over directly
1022 stopTick();
1023 return noErr;
1024 }
1025
1029 OSStatus reset() noexcept
1030 {
1031 if constexpr (HasReset<P>)
1032 user.reset();
1033 dryDelay.reset();
1034 bypassMix = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1035 if constexpr (HasMidi<P>)
1036 midiDiscardBefore.store(midiEnqueue.load(std::memory_order_acquire),
1037 std::memory_order_release);
1038 return noErr;
1039 }
1040
1041 // --- render notifications -------------------------------------------------------
1042
1046 OSStatus queueRenderNotify(AURenderCallback proc, void* refCon, bool add) noexcept
1047 {
1048 if (proc == nullptr) return kAudio_ParamError;
1049 if (!initialized)
1050 {
1051 applyNotifyCommands();
1052 applyNotifyCommand(RenderNotify { proc, refCon }, add);
1053 return noErr;
1054 }
1055 const uint32_t tail = notifyTail.load(std::memory_order_relaxed);
1056 const uint32_t next = (tail + 1) & (kNotifyQueueSize - 1);
1057 if (next == notifyHead.load(std::memory_order_acquire))
1058 return kAudio_MemFullError; // 63 changes with no render in between
1059 notifyQueue[tail] = NotifyCommand { RenderNotify { proc, refCon }, add };
1060 notifyTail.store(next, std::memory_order_release);
1061 return noErr;
1062 }
1063
1064 void applyNotifyCommand(RenderNotify target, bool add) noexcept
1065 {
1066 int found = -1;
1067 for (int i = 0; i < renderNotifyCount; ++i)
1068 if (renderNotifies[i].proc == target.proc
1069 && renderNotifies[i].refCon == target.refCon)
1070 found = i;
1071 if (add)
1072 {
1073 // A second add of the same pair is a no-op, as the format defines.
1074 if (found < 0 && renderNotifyCount < kMaxRenderNotifies)
1075 renderNotifies[renderNotifyCount++] = target;
1076 }
1077 else if (found >= 0)
1078 {
1079 for (int i = found; i + 1 < renderNotifyCount; ++i)
1080 renderNotifies[i] = renderNotifies[i + 1];
1081 --renderNotifyCount;
1082 }
1083 }
1084
1086 void applyNotifyCommands() noexcept
1087 {
1088 uint32_t head = notifyHead.load(std::memory_order_relaxed);
1089 const uint32_t tail = notifyTail.load(std::memory_order_acquire);
1090 while (head != tail)
1091 {
1092 applyNotifyCommand(notifyQueue[head].target, notifyQueue[head].add);
1093 head = (head + 1) & (kNotifyQueueSize - 1);
1094 }
1095 notifyHead.store(head, std::memory_order_release);
1096 }
1097
1098 void callRenderNotifies(AudioUnitRenderActionFlags flags,
1099 const AudioTimeStamp* timeStamp, UInt32 busNumber,
1100 UInt32 frames, AudioBufferList* ioData) noexcept
1101 {
1102 for (int i = 0; i < renderNotifyCount; ++i)
1103 renderNotifies[i].proc(renderNotifies[i].refCon, &flags, timeStamp,
1104 busNumber, frames, ioData);
1105 }
1106
1112 void discardSlice() noexcept
1113 {
1114 for (int i = 0; i < blockEvents.size(); ++i)
1115 {
1116 const BlockEvent& ev = blockEvents[i];
1117 if (ev.kind == BlockEvent::Kind::Bypass)
1118 {
1119 if (setBypass(ev.value >= 0.5)) announce(kNotifyBypass);
1120 }
1121 else if (ev.kind == BlockEvent::Kind::Param)
1122 {
1123 if (const int idx = indexOfParamId(ev.paramId); idx >= 0)
1124 {
1125 shadow[static_cast<size_t>(idx)].store(ev.value,
1126 std::memory_order_relaxed);
1127 pending.mark(static_cast<size_t>(idx));
1128 }
1129 }
1130 }
1131 blockEvents.clear();
1132 rampCount = 0;
1133 }
1134
1135 // --- stream format helpers -----------------------------------------------------
1136
1137 void fillStreamFormat(AudioStreamBasicDescription& f) const noexcept
1138 {
1139 std::memset(&f, 0, sizeof(f));
1140 f.mSampleRate = sampleRate;
1141 f.mFormatID = kAudioFormatLinearPCM;
1142 f.mFormatFlags = static_cast<AudioFormatFlags>(kAudioFormatFlagsNativeFloatPacked)
1143 | static_cast<AudioFormatFlags>(kAudioFormatFlagIsNonInterleaved);
1144 f.mBytesPerPacket = sizeof(float);
1145 f.mFramesPerPacket = 1;
1146 f.mBytesPerFrame = sizeof(float);
1147 f.mChannelsPerFrame = static_cast<UInt32>(currentChannels);
1148 f.mBitsPerChannel = 32;
1149 }
1150
1151 bool acceptableFormat(const AudioStreamBasicDescription& f) const noexcept
1152 {
1153 return f.mFormatID == kAudioFormatLinearPCM
1154 && (f.mFormatFlags & kAudioFormatFlagIsFloat) != 0
1155 && (f.mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0
1156 && supportsChannelCount<P>(static_cast<int>(f.mChannelsPerFrame))
1157 && f.mBitsPerChannel == 32
1158 && f.mSampleRate > 0.0;
1159 }
1160
1161 // --- properties -------------------------------------------------------------------
1162
1163 static constexpr int numChannelConfigs() noexcept
1164 {
1165 return channelSupportOf<P>() == ChannelSupport::MonoAndStereo ? 2 : 1;
1166 }
1167
1169 static constexpr bool isIoElement(AudioUnitScope scope, AudioUnitElement element) noexcept
1170 {
1171 if (scope == kAudioUnitScope_Input)
1172 {
1173 if constexpr (kNumInputElements == 0) // an instrument: none
1174 return false;
1175 else
1176 return element < kNumInputElements;
1177 }
1178 return scope == kAudioUnitScope_Output && element == 0;
1179 }
1180
1183 void buildPresetArray() noexcept
1184 {
1185 if constexpr (kNumPresets > 0)
1186 {
1187 if (presetArray != nullptr) return;
1188 presetStorage.resize(static_cast<size_t>(kNumPresets));
1189 const void* pointers[kNumPresets == 0 ? 1 : kNumPresets];
1190 for (int i = 0; i < kNumPresets; ++i)
1191 {
1192 presetStorage[static_cast<size_t>(i)].presetNumber = i;
1193 presetStorage[static_cast<size_t>(i)].presetName =
1194 CFStringCreateWithCString(
1195 nullptr, P::factoryPresets[static_cast<size_t>(i)].name,
1196 kCFStringEncodingUTF8);
1197 pointers[i] = &presetStorage[static_cast<size_t>(i)];
1198 }
1199 presetArray = CFArrayCreate(nullptr, pointers,
1200 static_cast<CFIndex>(kNumPresets), nullptr);
1201 }
1202 }
1203
1204 OSStatus getPropertyInfo(AudioUnitPropertyID id, AudioUnitScope scope,
1205 AudioUnitElement element, UInt32* outSize,
1206 Boolean* outWritable) noexcept
1207 {
1208 UInt32 size = 0;
1209 Boolean writable = false;
1210 switch (id)
1211 {
1212 // Formats are fixed while initialized (see setProperty).
1213 case kAudioUnitProperty_StreamFormat:
1214 size = sizeof(AudioStreamBasicDescription); writable = !initialized; break;
1215 case kAudioUnitProperty_SampleRate:
1216 size = sizeof(Float64); writable = !initialized; break;
1217 case kAudioUnitProperty_MaximumFramesPerSlice:
1218 size = sizeof(UInt32); writable = true; break;
1219 case kAudioUnitProperty_ElementCount:
1220 size = sizeof(UInt32); break;
1221 case kAudioUnitProperty_SupportedNumChannels:
1222 size = static_cast<UInt32>(numChannelConfigs() * sizeof(AUChannelInfo));
1223 break;
1224 case kAudioUnitProperty_HostCallbacks:
1225 size = sizeof(HostCallbackInfo); writable = true; break;
1226 case kAudioUnitProperty_OfflineRender:
1227 size = sizeof(UInt32); writable = true; break;
1228 case kAudioUnitProperty_FactoryPresets:
1229 if (kNumPresets == 0) return kAudioUnitErr_InvalidProperty;
1230 size = sizeof(CFArrayRef);
1231 break;
1232 case kAudioUnitProperty_ParameterList:
1233 size = scope == kAudioUnitScope_Global
1234 ? static_cast<UInt32>((kNumParams + 1) * sizeof(AudioUnitParameterID))
1235 : 0;
1236 break;
1237 case kAudioUnitProperty_ParameterInfo:
1238 size = sizeof(AudioUnitParameterInfo); break;
1239 case kAudioUnitProperty_ParameterValueStrings:
1240 {
1241 const int idx = indexOfParamId(element);
1242 if (idx < 0 || P::parameters[static_cast<size_t>(idx)].labels == nullptr)
1243 return kAudioUnitErr_InvalidProperty;
1244 size = sizeof(CFArrayRef);
1245 break;
1246 }
1247 case kAudioUnitProperty_ParameterStringFromValue:
1248 size = sizeof(AudioUnitParameterStringFromValue); break;
1249 case kAudioUnitProperty_ParameterValueFromString:
1250 size = sizeof(AudioUnitParameterValueFromString); break;
1251 case kAudioUnitProperty_Latency:
1252 case kAudioUnitProperty_TailTime:
1253 size = sizeof(Float64); break;
1254 case kAudioUnitProperty_BypassEffect:
1255 size = sizeof(UInt32); writable = true; break;
1256 case kAudioUnitProperty_ClassInfo:
1257 size = sizeof(CFPropertyListRef); writable = true; break;
1258 case kAudioUnitProperty_SetRenderCallback:
1259 size = sizeof(AURenderCallbackStruct); writable = true; break;
1260 case kAudioUnitProperty_MakeConnection:
1261 size = sizeof(AudioUnitConnection); writable = true; break;
1262 case kAudioUnitProperty_InPlaceProcessing:
1263 size = sizeof(UInt32); break;
1264 case kAudioUnitProperty_PresentPreset:
1265 case kAudioUnitProperty_CurrentPreset:
1266 size = sizeof(AUPreset); writable = true; break;
1267 case kAudioUnitProperty_LastRenderError:
1268 if (scope != kAudioUnitScope_Global) return kAudioUnitErr_InvalidScope;
1269 size = sizeof(OSStatus); break;
1270 case kAudioUnitProperty_ShouldAllocateBuffer:
1271 if (scope != kAudioUnitScope_Input && scope != kAudioUnitScope_Output)
1272 return kAudioUnitErr_InvalidScope;
1273 if (!isIoElement(scope, element)) return kAudioUnitErr_InvalidElement;
1274 size = sizeof(UInt32); writable = true; break;
1275#if DSPARK_AU_HAVE_MIDI2
1276 case kAudioUnitProperty_AudioUnitMIDIProtocol:
1277 if constexpr (!HasMidi<P>) return kAudioUnitErr_InvalidProperty;
1278 if (scope != kAudioUnitScope_Global) return kAudioUnitErr_InvalidScope;
1279 size = sizeof(SInt32); break;
1280#endif
1281#if defined(DSPARK_PLUGIN_WEBVIEW)
1282 case kAudioUnitProperty_CocoaUI:
1283 if constexpr (!kHasWebEditor) return kAudioUnitErr_InvalidProperty;
1284 size = sizeof(AudioUnitCocoaViewInfo);
1285 break;
1286 case kDsparkEditorHookProperty:
1287 if constexpr (!kHasWebEditor) return kAudioUnitErr_InvalidProperty;
1288 size = sizeof(EditorHook);
1289 break;
1290#endif
1291 default:
1292 (void) element;
1293 return kAudioUnitErr_InvalidProperty;
1294 }
1295 if (outSize) *outSize = size;
1296 if (outWritable) *outWritable = writable;
1297 return noErr;
1298 }
1299
1300 OSStatus getProperty(AudioUnitPropertyID id, AudioUnitScope scope,
1301 AudioUnitElement element, void* outData,
1302 UInt32* ioSize) noexcept
1303 {
1304 if (ioSize == nullptr) return kAudio_ParamError;
1305 if (outData == nullptr)
1306 {
1307 Boolean w = false;
1308 return getPropertyInfo(id, scope, element, ioSize, &w);
1309 }
1310 switch (id)
1311 {
1312 case kAudioUnitProperty_StreamFormat:
1313 {
1314 if (*ioSize < sizeof(AudioStreamBasicDescription))
1315 return kAudioUnitErr_InvalidPropertyValue;
1316 auto& f = *static_cast<AudioStreamBasicDescription*>(outData);
1317 fillStreamFormat(f);
1318 if (scope == kAudioUnitScope_Input && element == 1 && sidechainChannels != 0)
1319 f.mChannelsPerFrame = sidechainChannels;
1320 *ioSize = sizeof(AudioStreamBasicDescription);
1321 return noErr;
1322 }
1323 case kAudioUnitProperty_SampleRate:
1324 if (*ioSize < sizeof(Float64)) return kAudioUnitErr_InvalidPropertyValue;
1325 *static_cast<Float64*>(outData) = sampleRate;
1326 *ioSize = sizeof(Float64);
1327 return noErr;
1328 case kAudioUnitProperty_MaximumFramesPerSlice:
1329 if (*ioSize < sizeof(UInt32)) return kAudioUnitErr_InvalidPropertyValue;
1330 *static_cast<UInt32*>(outData) = maxFrames;
1331 *ioSize = sizeof(UInt32);
1332 return noErr;
1333 case kAudioUnitProperty_ElementCount:
1334 if (*ioSize < sizeof(UInt32)) return kAudioUnitErr_InvalidPropertyValue;
1335 *static_cast<UInt32*>(outData) =
1336 scope == kAudioUnitScope_Input ? kNumInputElements : 1;
1337 *ioSize = sizeof(UInt32);
1338 return noErr;
1339 case kAudioUnitProperty_SupportedNumChannels:
1340 {
1341 const UInt32 want =
1342 static_cast<UInt32>(numChannelConfigs() * sizeof(AUChannelInfo));
1343 if (*ioSize < want) return kAudioUnitErr_InvalidPropertyValue;
1344 auto* info = static_cast<AUChannelInfo*>(outData);
1345 int slot = 0;
1346 // An instrument declares 0 inputs; effects run symmetric widths.
1347 if (supportsChannelCount<P>(1))
1348 {
1349 info[slot].inChannels = kIsInstrument ? 0 : 1;
1350 info[slot].outChannels = 1;
1351 ++slot;
1352 }
1353 if (supportsChannelCount<P>(2))
1354 {
1355 info[slot].inChannels = kIsInstrument ? 0 : 2;
1356 info[slot].outChannels = 2;
1357 ++slot;
1358 }
1359 *ioSize = want;
1360 return noErr;
1361 }
1362 case kAudioUnitProperty_HostCallbacks:
1363 if (*ioSize < sizeof(HostCallbackInfo))
1364 return kAudioUnitErr_InvalidPropertyValue;
1365 *static_cast<HostCallbackInfo*>(outData) = hostCallbacks;
1366 *ioSize = sizeof(HostCallbackInfo);
1367 return noErr;
1368 case kAudioUnitProperty_OfflineRender:
1369 if (*ioSize < sizeof(UInt32)) return kAudioUnitErr_InvalidPropertyValue;
1370 *static_cast<UInt32*>(outData) = offlineRender;
1371 *ioSize = sizeof(UInt32);
1372 return noErr;
1373 case kAudioUnitProperty_FactoryPresets:
1374 {
1375 if (kNumPresets == 0) return kAudioUnitErr_InvalidProperty;
1376 if (*ioSize < sizeof(CFArrayRef))
1377 return kAudioUnitErr_InvalidPropertyValue;
1378 buildPresetArray();
1379 if (presetArray == nullptr) return kAudioUnitErr_InvalidProperty;
1380 *static_cast<CFArrayRef*>(outData) =
1381 static_cast<CFArrayRef>(CFRetain(presetArray)); // caller releases
1382 *ioSize = sizeof(CFArrayRef);
1383 return noErr;
1384 }
1385 case kAudioUnitProperty_ParameterList:
1386 {
1387 if (scope != kAudioUnitScope_Global)
1388 {
1389 *ioSize = 0;
1390 return noErr;
1391 }
1392 const UInt32 want =
1393 static_cast<UInt32>((kNumParams + 1) * sizeof(AudioUnitParameterID));
1394 if (*ioSize < want) return kAudioUnitErr_InvalidPropertyValue;
1395 auto* ids = static_cast<AudioUnitParameterID*>(outData);
1396 for (size_t i = 0; i < kNumParams; ++i)
1397 ids[i] = hash32(P::parameters[i].id);
1399 *ioSize = want;
1400 return noErr;
1401 }
1402 case kAudioUnitProperty_ParameterInfo:
1403 {
1404 if (*ioSize < sizeof(AudioUnitParameterInfo))
1405 return kAudioUnitErr_InvalidPropertyValue;
1406 auto* info = static_cast<AudioUnitParameterInfo*>(outData);
1407 std::memset(info, 0, sizeof(*info));
1408 // IsHighResolution: a host that limits the control resolution of
1409 // parameters (automation, control surfaces) gives these the
1410 // highest it has; the old code left every parameter without it.
1411 info->flags = kAudioUnitParameterFlag_IsReadable
1412 | kAudioUnitParameterFlag_IsWritable
1413 | kAudioUnitParameterFlag_HasCFNameString
1414 | kAudioUnitParameterFlag_CFNameRelease
1415 | kAudioUnitParameterFlag_IsHighResolution;
1416 if (element == kBypassParamId)
1417 {
1418 std::snprintf(info->name, sizeof(info->name), "Bypass");
1419 info->cfNameString = CFStringCreateWithCString(
1420 nullptr, "Bypass", kCFStringEncodingUTF8);
1421 info->unit = kAudioUnitParameterUnit_Boolean;
1422 info->minValue = 0.0f;
1423 info->maxValue = 1.0f;
1424 info->defaultValue = 0.0f;
1425 *ioSize = sizeof(AudioUnitParameterInfo);
1426 return noErr;
1427 }
1428 const int idx = indexOfParamId(element);
1429 if (idx < 0) return kAudioUnitErr_InvalidParameter;
1430 const auto& spec = P::parameters[static_cast<size_t>(idx)];
1431 std::snprintf(info->name, sizeof(info->name), "%s", spec.name);
1432 info->cfNameString = CFStringCreateWithCString(
1433 nullptr, spec.name, kCFStringEncodingUTF8);
1434 info->unit = isToggle(spec) ? kAudioUnitParameterUnit_Boolean
1435 : spec.steps > 0 && spec.minValue == 0.0f
1436 && spec.maxValue == static_cast<float>(spec.steps)
1437 ? kAudioUnitParameterUnit_Indexed // 0..N, choices
1438 : (std::strcmp(spec.unit, "dB") == 0
1439 ? kAudioUnitParameterUnit_Decibels
1440 : kAudioUnitParameterUnit_Generic);
1441 if (spec.labels != nullptr)
1442 info->flags |= kAudioUnitParameterFlag_ValuesHaveStrings;
1443 info->minValue = spec.minValue;
1444 info->maxValue = spec.maxValue;
1445 info->defaultValue = spec.defValue;
1446 *ioSize = sizeof(AudioUnitParameterInfo);
1447 return noErr;
1448 }
1449 case kAudioUnitProperty_ParameterValueStrings:
1450 {
1451 // A choice's labels, one CFString per position (caller releases).
1452 const int idx = indexOfParamId(element);
1453 if (idx < 0) return kAudioUnitErr_InvalidParameter;
1454 const Param& spec = P::parameters[static_cast<size_t>(idx)];
1455 if (spec.labels == nullptr) return kAudioUnitErr_InvalidProperty;
1456 if (*ioSize < sizeof(CFArrayRef)) return kAudioUnitErr_InvalidPropertyValue;
1457 CFMutableArrayRef strings = CFArrayCreateMutable(
1458 nullptr, static_cast<CFIndex>(spec.steps + 1), &kCFTypeArrayCallBacks);
1459 if (strings == nullptr) return kAudioUnitErr_InvalidProperty;
1460 for (int i = 0; i <= spec.steps; ++i)
1461 {
1462 const char* label = spec.labels[i] != nullptr ? spec.labels[i] : "";
1463 CFStringRef text = CFStringCreateWithCString(nullptr, label,
1464 kCFStringEncodingUTF8);
1465 if (text == nullptr) continue;
1466 CFArrayAppendValue(strings, text);
1467 CFRelease(text);
1468 }
1469 *static_cast<CFArrayRef*>(outData) = strings;
1470 *ioSize = sizeof(CFArrayRef);
1471 return noErr;
1472 }
1473 case kAudioUnitProperty_ParameterStringFromValue:
1474 {
1475 // Host display text (a choice's label, "3.50 dB"); caller releases.
1476 if (*ioSize < sizeof(AudioUnitParameterStringFromValue))
1477 return kAudioUnitErr_InvalidPropertyValue;
1478 auto* request = static_cast<AudioUnitParameterStringFromValue*>(outData);
1479 const int idx = indexOfParamId(request->inParamID);
1480 if (idx < 0) return kAudioUnitErr_InvalidParameter;
1481 const Param& spec = P::parameters[static_cast<size_t>(idx)];
1482 const double plain = request->inValue != nullptr
1483 ? static_cast<double>(*request->inValue)
1484 : toPlain(spec, shadow[static_cast<size_t>(idx)].load(std::memory_order_relaxed));
1485 char text[128];
1486 formatValue(spec, plain, text, static_cast<int>(sizeof(text)));
1487 request->outString = CFStringCreateWithCString(nullptr, text,
1488 kCFStringEncodingUTF8);
1489 *ioSize = sizeof(AudioUnitParameterStringFromValue);
1490 return noErr;
1491 }
1492 case kAudioUnitProperty_ParameterValueFromString:
1493 {
1494 // The inverse: labels, On/Off or a number; garbage is refused.
1495 if (*ioSize < sizeof(AudioUnitParameterValueFromString))
1496 return kAudioUnitErr_InvalidPropertyValue;
1497 auto* request = static_cast<AudioUnitParameterValueFromString*>(outData);
1498 const int idx = indexOfParamId(request->inParamID);
1499 if (idx < 0) return kAudioUnitErr_InvalidParameter;
1500 char text[128];
1501 double plain = 0.0;
1502 if (request->inString == nullptr
1503 || !CFStringGetCString(request->inString, text,
1504 static_cast<CFIndex>(sizeof(text)),
1505 kCFStringEncodingUTF8)
1506 || !parseValue(P::parameters[static_cast<size_t>(idx)], text, plain))
1507 return kAudioUnitErr_InvalidPropertyValue;
1508 request->outValue = static_cast<AudioUnitParameterValue>(plain);
1509 *ioSize = sizeof(AudioUnitParameterValueFromString);
1510 return noErr;
1511 }
1512 case kAudioUnitProperty_Latency:
1513 if (*ioSize < sizeof(Float64)) return kAudioUnitErr_InvalidPropertyValue;
1514 *static_cast<Float64*>(outData) =
1515 sampleRate > 0.0
1516 ? cachedLatency.load(std::memory_order_relaxed) / sampleRate
1517 : 0.0;
1518 *ioSize = sizeof(Float64);
1519 return noErr;
1520 case kAudioUnitProperty_TailTime:
1521 {
1522 if (*ioSize < sizeof(Float64)) return kAudioUnitErr_InvalidPropertyValue;
1523 *static_cast<Float64*>(outData) = tailSecondsNow();
1524 *ioSize = sizeof(Float64);
1525 return noErr;
1526 }
1527 case kAudioUnitProperty_BypassEffect:
1528 if (*ioSize < sizeof(UInt32)) return kAudioUnitErr_InvalidPropertyValue;
1529 *static_cast<UInt32*>(outData) =
1530 bypass.load(std::memory_order_relaxed) ? 1 : 0;
1531 *ioSize = sizeof(UInt32);
1532 return noErr;
1533 case kAudioUnitProperty_InPlaceProcessing:
1534 if (*ioSize < sizeof(UInt32)) return kAudioUnitErr_InvalidPropertyValue;
1535 *static_cast<UInt32*>(outData) = 1;
1536 *ioSize = sizeof(UInt32);
1537 return noErr;
1538 case kAudioUnitProperty_LastRenderError:
1539 // Read and cleared, as the format defines (the next error is
1540 // recorded afresh).
1541 if (scope != kAudioUnitScope_Global) return kAudioUnitErr_InvalidScope;
1542 if (*ioSize < sizeof(OSStatus)) return kAudioUnitErr_InvalidPropertyValue;
1543 *static_cast<OSStatus*>(outData) =
1544 lastRenderError.exchange(noErr, std::memory_order_relaxed);
1545 *ioSize = sizeof(OSStatus);
1546 return noErr;
1547 case kAudioUnitProperty_ShouldAllocateBuffer:
1548 if (scope != kAudioUnitScope_Input && scope != kAudioUnitScope_Output)
1549 return kAudioUnitErr_InvalidScope;
1550 if (!isIoElement(scope, element)) return kAudioUnitErr_InvalidElement;
1551 if (*ioSize < sizeof(UInt32)) return kAudioUnitErr_InvalidPropertyValue;
1552 *static_cast<UInt32*>(outData) =
1553 (scope == kAudioUnitScope_Input ? allocateInput[element] : allocateOutput)
1554 ? 1u : 0u;
1555 *ioSize = sizeof(UInt32);
1556 return noErr;
1557#if DSPARK_AU_HAVE_MIDI2
1558 case kAudioUnitProperty_AudioUnitMIDIProtocol:
1559 // MIDI 2.0: event lists then keep 16-bit velocity and 32-bit
1560 // controllers (the framework converts MIDI 1.0 sources up).
1561 if constexpr (!HasMidi<P>) return kAudioUnitErr_InvalidProperty;
1562 if (scope != kAudioUnitScope_Global) return kAudioUnitErr_InvalidScope;
1563 if (*ioSize < sizeof(SInt32)) return kAudioUnitErr_InvalidPropertyValue;
1564 *static_cast<SInt32*>(outData) = static_cast<SInt32>(kMIDIProtocol_2_0);
1565 *ioSize = sizeof(SInt32);
1566 return noErr;
1567#endif
1568 case kAudioUnitProperty_PresentPreset:
1569 case kAudioUnitProperty_CurrentPreset:
1570 {
1571 if (*ioSize < sizeof(AUPreset)) return kAudioUnitErr_InvalidPropertyValue;
1572 auto* preset = static_cast<AUPreset*>(outData);
1573 preset->presetNumber = currentPresetNumber;
1574 preset->presetName = copyPresetName();
1575 *ioSize = sizeof(AUPreset);
1576 return noErr;
1577 }
1578 case kAudioUnitProperty_ClassInfo:
1579 {
1580 if (*ioSize < sizeof(CFPropertyListRef))
1581 return kAudioUnitErr_InvalidPropertyValue;
1582 double norm[kNumParams == 0 ? 1 : kNumParams];
1583 for (size_t i = 0; i < kNumParams; ++i)
1584 norm[i] = shadow[i].load(std::memory_order_relaxed);
1585 EditorSize editorSize {};
1586 const bool withSize = editorMemory.remembered(editorSize);
1587 const std::vector<uint8_t> blob = buildState(
1588 user, norm, kNumParams,
1589 kNumPresets > 0 ? currentPresetNumber : -1,
1590 bypass.load(std::memory_order_relaxed) ? 1 : 0,
1591 withSize ? &editorSize : nullptr);
1592
1593 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(
1594 nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
1595 &kCFTypeDictionaryValueCallBacks);
1596 auto putInt = [&](const char* key, SInt32 v) {
1597 CFNumberRef n = CFNumberCreate(nullptr, kCFNumberSInt32Type, &v);
1598 CFStringRef k = CFStringCreateWithCString(nullptr, key,
1599 kCFStringEncodingUTF8);
1600 CFDictionarySetValue(dict, k, n);
1601 CFRelease(k);
1602 CFRelease(n);
1603 };
1604 putInt("version", 0);
1605 putInt("type", static_cast<SInt32>(expectedType()));
1606 putInt("subtype", static_cast<SInt32>(subtype));
1607 putInt("manufacturer", static_cast<SInt32>(manufacturer));
1608 // "name" is the PRESET's name (the aupreset convention hosts
1609 // display and the reference implementation writes); the old code
1610 // wrote the plugin's.
1611 CFStringRef nameVal = copyPresetName();
1612 CFDictionarySetValue(dict, CFSTR("name"), nameVal);
1613 CFRelease(nameVal);
1614 CFDataRef data = CFDataCreate(nullptr, blob.data(),
1615 static_cast<CFIndex>(blob.size()));
1616 CFDictionarySetValue(dict, CFSTR("dspark-state"), data);
1617 CFRelease(data);
1618
1619 *static_cast<CFPropertyListRef*>(outData) = dict; // caller releases
1620 *ioSize = sizeof(CFPropertyListRef);
1621 return noErr;
1622 }
1623#if defined(DSPARK_PLUGIN_WEBVIEW)
1624 case kAudioUnitProperty_CocoaUI:
1625 {
1626 if constexpr (!kHasWebEditor) return kAudioUnitErr_InvalidProperty;
1627 if (*ioSize < sizeof(AudioUnitCocoaViewInfo))
1628 return kAudioUnitErr_InvalidPropertyValue;
1629 Class factory = editorFactoryClass(); // registered before the host
1630 CFURLRef url = copyOwningBundleUrl(); // looks the class name up
1631 if (factory == nullptr || url == nullptr)
1632 {
1633 if (url != nullptr) CFRelease(url);
1634 return kAudioUnitErr_InvalidProperty;
1635 }
1636 auto* viewInfo = static_cast<AudioUnitCocoaViewInfo*>(outData);
1637 viewInfo->mCocoaAUViewBundleLocation = url; // caller releases both
1638 viewInfo->mCocoaAUViewClass[0] = CFStringCreateWithCString(
1639 nullptr, class_getName(factory), kCFStringEncodingUTF8);
1640 *ioSize = sizeof(AudioUnitCocoaViewInfo);
1641 return noErr;
1642 }
1643 case kDsparkEditorHookProperty:
1644 {
1645 if constexpr (!kHasWebEditor) return kAudioUnitErr_InvalidProperty;
1646 if (*ioSize < sizeof(EditorHook))
1647 return kAudioUnitErr_InvalidPropertyValue;
1648 *static_cast<EditorHook*>(outData) = EditorHook { this, &sCreateEditorView };
1649 *ioSize = sizeof(EditorHook);
1650 return noErr;
1651 }
1652#endif
1653 default:
1654 return kAudioUnitErr_InvalidProperty;
1655 }
1656 }
1657
1658 OSStatus setProperty(AudioUnitPropertyID id, AudioUnitScope scope,
1659 AudioUnitElement element, const void* inData,
1660 UInt32 inSize) noexcept
1661 {
1662 switch (id)
1663 {
1664 case kAudioUnitProperty_StreamFormat:
1665 {
1666 if (inData == nullptr || inSize < sizeof(AudioStreamBasicDescription))
1667 return kAudioUnitErr_InvalidPropertyValue;
1668 const auto* f = static_cast<const AudioStreamBasicDescription*>(inData);
1669 if (!acceptableFormat(*f)) return kAudioUnitErr_FormatNotSupported;
1670 // While initialized the format is fixed: the plugin was prepared
1671 // for this rate and width. Re-applying the same format is fine;
1672 // a different one is refused, and the host uninitializes, sets
1673 // it and initializes again. Accepting it (the old behaviour) let
1674 // processBlock see a width it was never prepared for and made
1675 // kAudioUnitProperty_Latency divide by a rate the DSP never ran.
1676 if (HasSidechain<P> && scope == kAudioUnitScope_Input && element == 1)
1677 {
1678 // The sidechain's own width: a mono key on a stereo main is
1679 // pulled mono and fed to both detector ears. It never sets
1680 // the main width - the old code let this element switch the
1681 // whole unit, and a stereo track then rendered one channel.
1682 const UInt32 current = sidechainChannels != 0
1683 ? sidechainChannels : static_cast<UInt32>(currentChannels);
1684 if (initialized && f->mChannelsPerFrame != current)
1685 return kAudioUnitErr_PropertyNotWritable;
1686 sidechainChannels = f->mChannelsPerFrame;
1687 return noErr;
1688 }
1689 if (initialized
1690 && (f->mSampleRate != sampleRate
1691 || static_cast<int>(f->mChannelsPerFrame) != currentChannels))
1692 return kAudioUnitErr_PropertyNotWritable;
1693 sampleRate = f->mSampleRate;
1694 // The negotiated width: the main elements follow it (initialize()
1695 // prepares the plugin at this count).
1696 currentChannels = static_cast<int>(f->mChannelsPerFrame);
1697 return noErr;
1698 }
1699 case kAudioUnitProperty_SampleRate:
1700 {
1701 if (inData == nullptr || inSize < sizeof(Float64))
1702 return kAudioUnitErr_InvalidPropertyValue;
1703 const Float64 rate = *static_cast<const Float64*>(inData);
1704 if (!(rate > 0.0)) return kAudioUnitErr_FormatNotSupported; // NaN too
1705 if (initialized && rate != sampleRate)
1706 return kAudioUnitErr_PropertyNotWritable; // see StreamFormat
1707 sampleRate = rate;
1708 return noErr;
1709 }
1710 case kAudioUnitProperty_MaximumFramesPerSlice:
1711 {
1712 if (inData == nullptr || inSize < sizeof(UInt32))
1713 return kAudioUnitErr_InvalidPropertyValue;
1714 const UInt32 frames = *static_cast<const UInt32*>(inData);
1715 if (frames == maxFrames) return noErr;
1716 // initialize() sizes the buffers for this value, so a change
1717 // while initialized is refused (kAudioUnitErr_Initialized tells
1718 // the host to uninitialize, set it and initialize again).
1719 // Accepting it (the old behaviour) answered noErr and then
1720 // failed every slice longer than the allocation with
1721 // kAudioUnitErr_TooManyFramesToProcess: silence. render() still
1722 // refuses such a slice as a last guard.
1723 if (initialized) return kAudioUnitErr_Initialized;
1724 maxFrames = frames;
1725 notifyProperty(id, scope, element);
1726 return noErr;
1727 }
1728 case kAudioUnitProperty_PresentPreset:
1729 case kAudioUnitProperty_CurrentPreset:
1730 {
1731 if (inData == nullptr || inSize < sizeof(AUPreset))
1732 return kAudioUnitErr_InvalidPropertyValue;
1733 const auto* preset = static_cast<const AUPreset*>(inData);
1734 if (preset->presetNumber >= 0)
1735 {
1736 // A factory preset by number: apply its parameter values.
1737 if (preset->presetNumber >= kNumPresets)
1738 return kAudioUnitErr_InvalidPropertyValue;
1739 applyFactoryPresetIdx(preset->presetNumber);
1740 refreshReported();
1741 notifyAllParameters();
1742 if (presetName != nullptr) CFRelease(presetName);
1743 presetName = preset->presetName != nullptr
1744 ? static_cast<CFStringRef>(CFRetain(preset->presetName))
1745 : CFStringCreateWithCString(
1746 nullptr,
1747 [&]() -> const char* {
1748 if constexpr (kNumPresets > 0)
1749 return P::factoryPresets[static_cast<size_t>(
1750 preset->presetNumber)].name;
1751 else
1752 return "";
1753 }(),
1754 kCFStringEncodingUTF8);
1755 notifyProperty(id, scope, element);
1756 return noErr;
1757 }
1758 currentPresetNumber = -1; // back to a user preset
1759 if (presetName != nullptr) CFRelease(presetName);
1760 presetName = preset->presetName != nullptr
1761 ? static_cast<CFStringRef>(CFRetain(preset->presetName))
1762 : nullptr;
1763 notifyProperty(id, scope, element);
1764 return noErr;
1765 }
1766 case kAudioUnitProperty_HostCallbacks:
1767 {
1768 if (inData == nullptr) return kAudioUnitErr_InvalidPropertyValue;
1769 // Hosts may pass a truncated struct (older callback sets).
1770 std::memset(&hostCallbacks, 0, sizeof(hostCallbacks));
1771 std::memcpy(&hostCallbacks, inData,
1772 inSize < sizeof(hostCallbacks) ? inSize
1773 : sizeof(hostCallbacks));
1774 return noErr;
1775 }
1776 case kAudioUnitProperty_ShouldAllocateBuffer:
1777 {
1778 // Per element, before initialize (it decides which buffers the
1779 // render uses); the old code refused the property entirely.
1780 if (scope != kAudioUnitScope_Input && scope != kAudioUnitScope_Output)
1781 return kAudioUnitErr_InvalidScope;
1782 if (!isIoElement(scope, element)) return kAudioUnitErr_InvalidElement;
1783 if (inData == nullptr || inSize < sizeof(UInt32))
1784 return kAudioUnitErr_InvalidPropertyValue;
1785 if (initialized) return kAudioUnitErr_Initialized;
1786 const bool allocate = *static_cast<const UInt32*>(inData) != 0;
1787 if (scope == kAudioUnitScope_Input)
1788 allocateInput[element] = allocate;
1789 else
1790 allocateOutput = allocate;
1791 return noErr;
1792 }
1793 case kAudioUnitProperty_OfflineRender:
1794 if (inData == nullptr || inSize < sizeof(UInt32))
1795 return kAudioUnitErr_InvalidPropertyValue;
1796 offlineRender = *static_cast<const UInt32*>(inData);
1797 if constexpr (HasOfflineMode<P>)
1798 user.setOfflineRendering(offlineRender != 0);
1799 return noErr;
1800 case kAudioUnitProperty_BypassEffect:
1801 if (inData == nullptr || inSize < sizeof(UInt32))
1802 return kAudioUnitErr_InvalidPropertyValue;
1803 // The bypass is also a parameter: its listeners (an automation
1804 // lane, the generic view) follow the host's button. The old code
1805 // left them showing the previous state.
1806 if (setBypass(*static_cast<const UInt32*>(inData) != 0))
1807 notifyParameterChanged(kBypassParamId);
1808 return noErr;
1809 case kAudioUnitProperty_SetRenderCallback:
1810 {
1811 // Instruments have no input elements yet must still ACCEPT a
1812 // render callback (auval and some hosts set one regardless);
1813 // it is stored and never pulled.
1814 constexpr UInt32 storable = kIsInstrument ? 2 : kNumInputElements;
1815 if (scope != kAudioUnitScope_Input || element >= storable
1816 || inData == nullptr || inSize < sizeof(AURenderCallbackStruct))
1817 return kAudioUnitErr_InvalidPropertyValue;
1818 inputCallback[element] = *static_cast<const AURenderCallbackStruct*>(inData);
1819 inputConnection[element] = nullptr;
1820 return noErr;
1821 }
1822 case kAudioUnitProperty_MakeConnection:
1823 {
1824 if (inData == nullptr || inSize < sizeof(AudioUnitConnection))
1825 return kAudioUnitErr_InvalidPropertyValue;
1826 const auto* c = static_cast<const AudioUnitConnection*>(inData);
1827 constexpr UInt32 storable = kIsInstrument ? 2 : kNumInputElements;
1828 if (c->destInputNumber >= storable)
1829 return kAudioUnitErr_InvalidPropertyValue;
1830 inputConnection[c->destInputNumber] = c->sourceAudioUnit;
1831 inputConnectionBus[c->destInputNumber] = c->sourceOutputNumber;
1832 inputCallback[c->destInputNumber] = {};
1833 return noErr;
1834 }
1835 case kAudioUnitProperty_ClassInfo:
1836 {
1837 if (inData == nullptr || inSize < sizeof(CFPropertyListRef))
1838 return kAudioUnitErr_InvalidPropertyValue;
1839 CFPropertyListRef plist = *static_cast<const CFPropertyListRef*>(inData);
1840 if (plist == nullptr || CFGetTypeID(plist) != CFDictionaryGetTypeID())
1841 return kAudioUnitErr_InvalidPropertyValue;
1842 auto dict = static_cast<CFDictionaryRef>(plist);
1843 // A preset of another unit is refused, as the format requires: the old
1844 // code loaded any dictionary carrying this format's key - a
1845 // preset of a different DSPark plugin fed this one its user
1846 // section.
1847 auto numberIs = [&](CFStringRef key, OSType expected) {
1848 auto number = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, key));
1849 if (number == nullptr) return true; // absent: tolerated
1850 SInt32 value = 0;
1851 return CFGetTypeID(number) == CFNumberGetTypeID()
1852 && CFNumberGetValue(number, kCFNumberSInt32Type, &value)
1853 && static_cast<OSType>(value) == expected;
1854 };
1855 if (!numberIs(CFSTR("subtype"), subtype)
1856 || !numberIs(CFSTR("manufacturer"), manufacturer))
1857 return kAudioUnitErr_InvalidPropertyValue;
1858 auto data = static_cast<CFDataRef>(
1859 CFDictionaryGetValue(dict, CFSTR("dspark-state")));
1860 if (data == nullptr || CFGetTypeID(data) != CFDataGetTypeID())
1861 return noErr; // foreign preset: keep current state
1862 // Parameters the blob does not carry take their DEFAULTS (the old
1863 // code kept whatever value the instance happened to hold).
1864 double norm[kNumParams == 0 ? 1 : kNumParams];
1865 loadDefaultNormalized<P>(norm);
1866 int program = -1;
1867 int bypassState = -1;
1868 EditorSize editorSize { 0, 0 };
1869 if (applyState(user,
1870 CFDataGetBytePtr(data),
1871 static_cast<size_t>(CFDataGetLength(data)), norm,
1872 &program, &bypassState, &editorSize))
1873 {
1874 for (size_t i = 0; i < kNumParams; ++i)
1875 applyFromAnyThread(static_cast<int>(i), norm[i]);
1876 currentPresetNumber =
1877 kNumPresets > 0 && program >= 0 && program < kNumPresets ? program : -1;
1878 // The preset name travels with the state (the host shows it).
1879 auto name = static_cast<CFStringRef>(CFDictionaryGetValue(dict, CFSTR("name")));
1880 if (presetName != nullptr) CFRelease(presetName);
1881 presetName = name != nullptr && CFGetTypeID(name) == CFStringGetTypeID()
1882 ? static_cast<CFStringRef>(CFRetain(name)) : nullptr;
1883 if (bypassState >= 0 && setBypass(bypassState != 0))
1884 announce(kNotifyBypass);
1885 if (editorSize.width > 0)
1886 {
1887 editorMemory.remember(editorSize.width, editorSize.height);
1888#if defined(DSPARK_PLUGIN_WEBVIEW)
1889 applyRememberedEditorSize();
1890#endif
1891 }
1892 refreshReported(); // restored state may imply a new lookahead
1893 notifyAllParameters();
1894 notifyProperty(kAudioUnitProperty_PresentPreset, kAudioUnitScope_Global, 0);
1895 }
1896 return noErr;
1897 }
1898 default:
1899 return kAudioUnitErr_InvalidProperty;
1900 }
1901 }
1902
1903 // --- parameters ----------------------------------------------------------------
1904
1905 OSStatus getParameter(AudioUnitParameterID id, AudioUnitScope scope,
1906 AudioUnitParameterValue* outValue) noexcept
1907 {
1908 if (scope != kAudioUnitScope_Global || outValue == nullptr)
1909 return kAudioUnitErr_InvalidParameter;
1910 if (id == kBypassParamId)
1911 {
1912 *outValue = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
1913 return noErr;
1914 }
1915 const int idx = indexOfParamId(id);
1916 if (idx < 0) return kAudioUnitErr_InvalidParameter;
1917 *outValue = static_cast<AudioUnitParameterValue>(
1918 toPlain(P::parameters[static_cast<size_t>(idx)],
1919 shadow[static_cast<size_t>(idx)].load(std::memory_order_relaxed)));
1920 return noErr;
1921 }
1922
1923 OSStatus setParameter(AudioUnitParameterID id, AudioUnitScope scope,
1924 AudioUnitParameterValue value) noexcept
1925 {
1926 if (scope != kAudioUnitScope_Global) return kAudioUnitErr_InvalidParameter;
1927 // A non-finite value is refused, as the format requires: the plain ->
1928 // normalized mapping sends NaN to 0 and +Inf to 1, so the old code
1929 // moved the parameter to an end of its range.
1930 if (!std::isfinite(value)) return kAudioUnitErr_InvalidParameterValue;
1931 if (id == kBypassParamId)
1932 {
1933 if (setBypass(value >= 0.5f)) announce(kNotifyBypass);
1934 return noErr;
1935 }
1936 const int idx = indexOfParamId(id);
1937 if (idx < 0) return kAudioUnitErr_InvalidParameter;
1938 if (applyFromAnyThread(idx,
1939 toNormalized(P::parameters[static_cast<size_t>(idx)], value)))
1940 refreshReported();
1941 return noErr;
1942 }
1943
1944 // --- MIDI (MusicDevice selectors -> lock-free ring -> render) ---------------------
1945
1947 OSStatus pushMidi(UInt32 status, UInt32 data1, UInt32 data2,
1948 UInt32 offsetFrame) noexcept
1949 {
1950 if constexpr (HasMidi<P>)
1951 {
1952 MidiEvent ev {};
1953 ev.channel = static_cast<uint8_t>(status & 0x0Fu);
1954 ev.sampleOffset = static_cast<int>(offsetFrame);
1955 const uint8_t d1 = static_cast<uint8_t>(data1 & 0x7Fu);
1956 const uint8_t d2 = static_cast<uint8_t>(data2 & 0x7Fu);
1957 switch (status & 0xF0u)
1958 {
1959 case 0x90: // wire convention: velocity 0 means note off
1960 ev.type = d2 > 0 ? MidiEvent::Type::NoteOn : MidiEvent::Type::NoteOff;
1961 ev.note = d1;
1962 ev.value = static_cast<float>(d2) / 127.0f;
1963 break;
1964 case 0x80:
1965 ev.type = MidiEvent::Type::NoteOff;
1966 ev.note = d1;
1967 ev.value = static_cast<float>(d2) / 127.0f;
1968 break;
1969 case 0xA0:
1970 ev.type = MidiEvent::Type::PolyPressure;
1971 ev.note = d1;
1972 ev.value = static_cast<float>(d2) / 127.0f;
1973 break;
1974 case 0xB0:
1975 ev.type = MidiEvent::Type::ControlChange;
1976 ev.note = d1;
1977 ev.value = static_cast<float>(d2) / 127.0f;
1978 break;
1979 case 0xD0:
1980 ev.type = MidiEvent::Type::ChannelPressure;
1981 ev.value = static_cast<float>(d1) / 127.0f;
1982 break;
1983 case 0xE0:
1984 ev.type = MidiEvent::Type::PitchBend;
1985 ev.value = (static_cast<float>((d2 << 7) | d1) - 8192.0f) / 8192.0f;
1986 break;
1987 default:
1988 return noErr; // system messages: accepted, ignored
1989 }
1990 (void) queueMidi(ev); // full: dropped (never block the caller)
1991 return noErr;
1992 }
1993 else
1994 {
1995 (void) status;
1996 (void) data1;
1997 (void) data2;
1998 (void) offsetFrame;
1999 return kAudioUnitErr_InvalidProperty;
2000 }
2001 }
2002
2006 bool queueMidi(const MidiEvent& ev) noexcept
2007 {
2008 constexpr uint32_t mask = kMidiRingSize - 1;
2009 uint32_t position = midiEnqueue.load(std::memory_order_relaxed);
2010 for (;;)
2011 {
2012 MidiCell& cell = midiRing[position & mask];
2013 const uint32_t seq = cell.seq.load(std::memory_order_acquire);
2014 const auto lag = static_cast<int32_t>(seq - position);
2015 if (lag == 0)
2016 {
2017 if (midiEnqueue.compare_exchange_weak(position, position + 1,
2018 std::memory_order_relaxed))
2019 {
2020 cell.event = ev;
2021 cell.seq.store(position + 1, std::memory_order_release);
2022 return true;
2023 }
2024 }
2025 else if (lag < 0)
2026 return false; // the consumer has not freed this cell yet: full
2027 else
2028 position = midiEnqueue.load(std::memory_order_relaxed);
2029 }
2030 }
2031
2032#if DSPARK_AU_HAVE_MIDI2
2040 void queueMidi2(UInt32 status, UInt32 index, UInt32 data, UInt32 offsetFrame) noexcept
2041 {
2042 MidiEvent ev {};
2043 ev.channel = static_cast<uint8_t>(status & 0x0Fu);
2044 ev.note = static_cast<uint8_t>(index & 0x7Fu);
2045 ev.sampleOffset = static_cast<int>(offsetFrame);
2046 constexpr double k32 = 4294967295.0;
2047 switch (status & 0xF0u)
2048 {
2049 case 0x90:
2050 ev.type = MidiEvent::Type::NoteOn;
2051 ev.value = static_cast<float>((data >> 16) / 65535.0);
2052 break;
2053 case 0x80:
2054 ev.type = MidiEvent::Type::NoteOff;
2055 ev.value = static_cast<float>((data >> 16) / 65535.0);
2056 break;
2057 case 0xA0:
2058 ev.type = MidiEvent::Type::PolyPressure;
2059 ev.value = static_cast<float>(data / k32);
2060 break;
2061 case 0xB0:
2062 ev.type = MidiEvent::Type::ControlChange;
2063 ev.value = static_cast<float>(data / k32);
2064 break;
2065 case 0xD0:
2066 ev.type = MidiEvent::Type::ChannelPressure;
2067 ev.note = 0;
2068 ev.value = static_cast<float>(data / k32);
2069 break;
2070 case 0xE0:
2071 ev.type = MidiEvent::Type::PitchBend;
2072 ev.note = 0;
2073 ev.value = static_cast<float>((static_cast<double>(data) - 2147483648.0)
2074 / 2147483648.0);
2075 break;
2076 default:
2077 return;
2078 }
2079 (void) queueMidi(ev);
2080 }
2081
2089 OSStatus pushEventList(UInt32 offsetFrame, const MIDIEventList* list) noexcept
2090 {
2091 if constexpr (HasMidi<P>)
2092 {
2093 if (list == nullptr) return kAudio_ParamError;
2094 // UMP sizes in 32-bit words, by message type.
2095 static constexpr UInt32 kWords[16] = { 1, 1, 1, 2, 2, 4, 1, 1,
2096 2, 2, 2, 3, 3, 4, 4, 4 };
2097 const MIDIEventPacket* packet = &list->packet[0];
2098 for (UInt32 p = 0; p < list->numPackets; ++p)
2099 {
2100 const UInt32 count = packet->wordCount;
2101 if (count > 64) break; // malformed: the packet cannot hold it
2102 const uint64_t stamp = static_cast<uint64_t>(packet->timeStamp);
2103 uint64_t at = static_cast<uint64_t>(offsetFrame)
2104 + (stamp < (uint64_t { 1 } << 24) ? stamp : 0u);
2105 if (at > 0x7FFFFFFFu) at = 0x7FFFFFFFu;
2106 const auto offset = static_cast<UInt32>(at);
2107 for (UInt32 w = 0; w < count;)
2108 {
2109 const UInt32 word = packet->words[w];
2110 const UInt32 type = word >> 28;
2111 const UInt32 size = kWords[type];
2112 if (w + size > count) break; // truncated message
2113 const UInt32 status = (word >> 16) & 0xFFu;
2114 const UInt32 index = (word >> 8) & 0xFFu;
2115 if (type == 0x2u)
2116 (void) pushMidi(status, index, word & 0xFFu, offset);
2117 else if (type == 0x4u)
2118 queueMidi2(status, index, packet->words[w + 1], offset);
2119 w += size;
2120 }
2121 packet = reinterpret_cast<const MIDIEventPacket*>(packet->words + count);
2122 }
2123 return noErr;
2124 }
2125 else
2126 {
2127 (void) offsetFrame;
2128 (void) list;
2129 return kAudioUnitErr_InvalidProperty;
2130 }
2131 }
2132#endif // DSPARK_AU_HAVE_MIDI2
2133
2135 void forwardTransport() noexcept
2136 {
2137 if constexpr (HasTransport<P>)
2138 {
2139 TransportInfo info {};
2140 bool any = false;
2141 if (hostCallbacks.beatAndTempoProc != nullptr)
2142 {
2143 Float64 beat = 0.0, tempo = 0.0;
2144 if (hostCallbacks.beatAndTempoProc(hostCallbacks.hostUserData,
2145 &beat, &tempo) == noErr)
2146 {
2147 if (tempo > 0.0)
2148 {
2149 info.tempoBpm = tempo;
2150 info.tempoValid = true;
2151 }
2152 info.ppqPosition = beat;
2153 info.positionValid = true;
2154 any = true;
2155 }
2156 }
2157 if (hostCallbacks.musicalTimeLocationProc != nullptr)
2158 {
2159 UInt32 deltaToNextBeat = 0;
2160 Float32 num = 4.0f;
2161 UInt32 den = 4;
2162 Float64 downbeat = 0.0;
2163 if (hostCallbacks.musicalTimeLocationProc(
2164 hostCallbacks.hostUserData, &deltaToNextBeat, &num, &den,
2165 &downbeat) == noErr)
2166 {
2167 // The host WRITES the numerator, and this is the one
2168 // format that delivers it as a floating-point number
2169 // (VST3 sends an int32, CLAP a uint16), so it is the one
2170 // place the value has to be bounded before it is
2171 // converted: a conversion that does not fit an int is
2172 // undefined, and a NaN would sail through a test written
2173 // the obvious way. The ceiling is far above any meter a
2174 // sequencer can express and the floor keeps the field
2175 // usable as a divisor.
2176 info.timeSigNumerator = toBoundedInt(num, 1, 255);
2177 info.timeSigDenominator = static_cast<int>(den);
2178 info.timeSigValid = true;
2179 info.barStartPpq = downbeat;
2180 any = true;
2181 }
2182 }
2183 if (hostCallbacks.transportStateProc != nullptr)
2184 {
2185 Boolean isPlaying = false, changed = false, isCycling = false;
2186 Float64 samplePos = 0.0, cycleStart = 0.0, cycleEnd = 0.0;
2187 if (hostCallbacks.transportStateProc(
2188 hostCallbacks.hostUserData, &isPlaying, &changed,
2189 &samplePos, &isCycling, &cycleStart, &cycleEnd) == noErr)
2190 {
2191 info.playing = isPlaying;
2192 info.looping = isCycling;
2193 info.loopStartPpq = cycleStart;
2194 info.loopEndPpq = cycleEnd;
2195 info.loopValid = isCycling;
2196 any = true;
2197 }
2198 }
2199 if (any)
2200 user.setTransport(info);
2201 }
2202 }
2203
2204 // --- render ----------------------------------------------------------------------
2205
2209 OSStatus pullInput(UInt32 element, float* dst[2],
2210 const AudioTimeStamp* timeStamp, UInt32 frames) noexcept
2211 {
2212 // AudioBufferList declares mBuffers[1] (variable length): a stack
2213 // instance has storage for ONE AudioBuffer, so writing mBuffers[1]
2214 // corrupts the frame. Give the list real storage and lend it out
2215 // as AudioBufferList* - the canonical CoreAudio pattern.
2216 struct StereoBufferList
2217 {
2218 UInt32 mNumberBuffers;
2219 ::AudioBuffer mBuffers[2]; // CoreAudio's, not dspark::AudioBuffer
2220 } list {};
2221 // The sidechain element pulls at its own negotiated width.
2222 const UInt32 elementWidth = element == 1 && sidechainChannels != 0
2223 ? sidechainChannels
2224 : static_cast<UInt32>(currentChannels);
2225 const UInt32 width = elementWidth < 2u ? elementWidth : 2u;
2226 // ShouldAllocateBuffer false: the source supplies the buffers, so
2227 // the pull lends none (the format's convention for that element).
2228 const bool lendBuffers = allocateInput[element < 2u ? element : 0u];
2229 list.mNumberBuffers = width;
2230 for (UInt32 ch = 0; ch < width; ++ch)
2231 {
2232 list.mBuffers[ch].mNumberChannels = 1;
2233 list.mBuffers[ch].mDataByteSize = frames * sizeof(float);
2234 list.mBuffers[ch].mData = lendBuffers ? dst[ch] : nullptr;
2235 }
2236 auto* abl = reinterpret_cast<AudioBufferList*>(&list);
2237 OSStatus status = noErr;
2238 AudioUnitRenderActionFlags flags = 0;
2239 bool pulled = true;
2240 if (inputCallback[element].inputProc != nullptr)
2241 status = inputCallback[element].inputProc(
2242 inputCallback[element].inputProcRefCon, &flags, timeStamp,
2243 element, frames, abl);
2244 else if (inputConnection[element] != nullptr)
2245 status = AudioUnitRender(inputConnection[element], &flags, timeStamp,
2246 inputConnectionBus[element], frames, abl);
2247 else
2248 pulled = false;
2249 if (status != noErr) return status;
2250 for (UInt32 ch = 0; ch < width; ++ch)
2251 {
2252 // A source that supplied a buffer of its own is read in place;
2253 // one that left the lent-out slot empty yields silence.
2254 if (pulled && ch < list.mNumberBuffers && list.mBuffers[ch].mData != nullptr)
2255 dst[ch] = static_cast<float*>(list.mBuffers[ch].mData);
2256 else if (!pulled || !lendBuffers)
2257 std::memset(dst[ch], 0, frames * sizeof(float));
2258 }
2259 if (width == 1 && currentChannels > 1)
2260 dst[1] = dst[0]; // a mono key feeds both detector ears
2261 return noErr;
2262 }
2263
2272 void expandRamps(int frames) noexcept
2273 {
2274 for (int r = 0; r < rampCount; ++r)
2275 {
2276 const Ramp& ramp = ramps[r];
2277 const int idx = indexOfParamId(ramp.paramId);
2278 if (idx < 0) continue;
2279 const long long start = ramp.startOffset;
2280 const long long end = start + static_cast<long long>(ramp.duration);
2281 auto valueAt = [&](long long offset) {
2282 if (ramp.duration == 0 || offset >= end) return static_cast<double>(ramp.endValue);
2283 const double t = static_cast<double>(offset - start)
2284 / static_cast<double>(ramp.duration);
2285 const double u = t < 0.0 ? 0.0 : (t > 1.0 ? 1.0 : t);
2286 return ramp.startValue + (static_cast<double>(ramp.endValue) - ramp.startValue) * u;
2287 };
2288 auto push = [&](long long offset) {
2289 BlockEvent ev {};
2290 ev.offset = static_cast<int32_t>(offset);
2291 ev.kind = BlockEvent::Kind::Param;
2292 ev.paramId = ramp.paramId;
2293 ev.value = toNormalized(P::parameters[static_cast<size_t>(idx)], valueAt(offset));
2294 blockEvents.add(ev);
2295 };
2296 long long first = start > 0 ? start : 0;
2297 if (first >= frames) continue;
2298 push(first);
2299 for (long long q = (first / kAutomationQuantum + 1) * kAutomationQuantum;
2300 q < frames && q < end; q += kAutomationQuantum)
2301 push(q);
2302 if (end > first && end < frames && end % kAutomationQuantum != 0)
2303 push(end);
2304 }
2305 rampCount = 0;
2306 }
2307
2310 void blendBypass(float* const* out, float* const* dry, UInt32 outCh, int start,
2311 int length) noexcept
2312 {
2313 const float target = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
2314 if (bypassMix == target && target == 0.0f) return;
2315 const float step = 1.0f / static_cast<float>(kBypassRampSamples);
2316 float mix = bypassMix;
2317 for (int i = 0; i < length; ++i)
2318 {
2319 mix += (target > mix) ? step : ((target < mix) ? -step : 0.0f);
2320 mix = mix < 0.0f ? 0.0f : (mix > 1.0f ? 1.0f : mix);
2321 for (UInt32 ch = 0; ch < outCh; ++ch)
2322 out[ch][start + i] += (dry[ch][start + i] - out[ch][start + i]) * mix;
2323 }
2324 bypassMix = mix;
2325 }
2326
2337 OSStatus render(AudioUnitRenderActionFlags* ioFlags,
2338 const AudioTimeStamp* timeStamp, UInt32 busNumber,
2339 UInt32 frames, AudioBufferList* ioData) noexcept
2340 {
2341 auto refuseEarly = [&](OSStatus error) noexcept {
2342 discardSlice();
2343 recordRenderError(error);
2344 return error;
2345 };
2346 if (ioData == nullptr) return refuseEarly(kAudio_ParamError);
2347 // One output element. Rendering any other (the old code ignored the
2348 // number) ran the DSP a second time in the same cycle.
2349 if (busNumber != 0) return refuseEarly(kAudioUnitErr_InvalidElement);
2350 if (!initialized) return refuseEarly(kAudioUnitErr_Uninitialized);
2351
2352 // FTZ/DAZ for the whole callback (the notifications included):
2353 // DSPark processors guard their own hot loops, this covers user DSP
2354 // in hosts that do not set it.
2355 dspark::DenormalGuard denormalGuard;
2356
2357 applyNotifyCommands(); // this thread owns the notification list
2358 using Flags = AudioUnitRenderActionFlags;
2359 const Flags flags = ioFlags != nullptr ? *ioFlags : Flags { 0 };
2360 constexpr Flags kPre = static_cast<Flags>(kAudioUnitRenderAction_PreRender);
2361 constexpr Flags kPost = static_cast<Flags>(kAudioUnitRenderAction_PostRender);
2362 constexpr Flags kError = static_cast<Flags>(kAudioUnitRenderAction_PostRenderError);
2363 auto refuse = [&](OSStatus error) noexcept {
2364 discardSlice();
2365 recordRenderError(error);
2366 callRenderNotifies(flags | kPost | kError, timeStamp, busNumber, frames, ioData);
2367 return error;
2368 };
2369 // Bound by the property and by what initialize() allocated (the
2370 // property cannot change while initialized; the second test is a
2371 // last guard for the buffers).
2372 if (frames > maxFrames || frames > dryL.size())
2373 return refuse(kAudioUnitErr_TooManyFramesToProcess);
2374 // A host buffer shorter than the slice is refused, as the format requires:
2375 // the old code wrote `frames` samples into it regardless.
2376 const UInt32 bytes = frames * static_cast<UInt32>(sizeof(float));
2377 for (UInt32 b = 0; b < ioData->mNumberBuffers; ++b)
2378 if (ioData->mBuffers[b].mData != nullptr && ioData->mBuffers[b].mDataByteSize < bytes)
2379 return refuse(kAudio_ParamError);
2380 // ShouldAllocateBuffer false on the output (and the main input): the
2381 // unit holds no buffer to render into, so the host must pass one per
2382 // channel it reads, as the format's reference implementation requires.
2383 if (pullL.empty())
2384 {
2385 const UInt32 width = static_cast<UInt32>(currentChannels);
2386 const UInt32 used = ioData->mNumberBuffers < width ? ioData->mNumberBuffers : width;
2387 for (UInt32 b = 0; b < used; ++b)
2388 if (ioData->mBuffers[b].mData == nullptr)
2389 return refuse(kAudioUnitErr_InvalidPropertyValue);
2390 }
2391
2392 callRenderNotifies(flags | kPre, timeStamp, busNumber, frames, ioData);
2393 OSStatus status = noErr;
2394 if (frames == 0)
2395 discardSlice();
2396 else
2397 status = renderSlice(timeStamp, frames, ioData);
2398 recordRenderError(status);
2399 callRenderNotifies(flags | kPost | (status != noErr ? kError : Flags { 0 }),
2400 timeStamp, busNumber, frames, ioData);
2401 return status;
2402 }
2403
2405 OSStatus renderSlice(const AudioTimeStamp* timeStamp, UInt32 frames,
2406 AudioBufferList* ioData) noexcept
2407 {
2408 // This thread now owns setParameter; first apply what other threads
2409 // handed over, so the slice's scheduled events below still win.
2410 renderThread.store(std::this_thread::get_id(), std::memory_order_relaxed);
2411 bool paramsChanged = drainPending();
2412 bool bypassChanged = false;
2413
2414 forwardTransport();
2415
2416 // One timestamped stream: scheduled parameter events and ramps
2417 // (already on this thread) plus the queued MIDI from the MusicDevice
2418 // selectors.
2419 expandRamps(static_cast<int>(frames));
2420 if constexpr (HasMidi<P>)
2421 {
2422 // Every published event, in position order; a claimed position
2423 // still being written ends the drain (it arrives next slice).
2424 constexpr uint32_t mask = kMidiRingSize - 1;
2425 const uint32_t discardBefore = midiDiscardBefore.load(std::memory_order_acquire);
2426 uint32_t position = midiDequeue;
2427 for (;;)
2428 {
2429 MidiCell& cell = midiRing[position & mask];
2430 if (cell.seq.load(std::memory_order_acquire) != position + 1) break;
2431 const MidiEvent midi = cell.event;
2432 cell.seq.store(position + kMidiRingSize, std::memory_order_release);
2433 // Queued after the last Reset: delivered (wrap-safe order).
2434 if (static_cast<int32_t>(position - discardBefore) >= 0)
2435 {
2436 BlockEvent ev {};
2437 ev.kind = BlockEvent::Kind::Midi;
2438 ev.midi = midi;
2439 ev.offset = midi.sampleOffset;
2440 blockEvents.add(ev);
2441 }
2442 ++position;
2443 }
2444 midiDequeue = position;
2445 // Once passed, the mark follows the drain so the wrap-safe order
2446 // above stays valid; a newer Reset's mark wins the exchange.
2447 uint32_t mark = discardBefore;
2448 if (static_cast<int32_t>(position - mark) > 0)
2449 (void) midiDiscardBefore.compare_exchange_strong(mark, position,
2450 std::memory_order_acq_rel);
2451 }
2452 BlockEventList& events = blockEvents;
2453 for (int i = 0; i < events.size(); ++i)
2454 {
2455 if (events[i].offset >= static_cast<int32_t>(frames))
2456 events[i].offset = static_cast<int32_t>(frames) - 1;
2457 if (events[i].offset < 0) events[i].offset = 0;
2458 }
2459 events.sort();
2460 const int eventCount = events.size();
2461
2462 auto applyEvent = [&](const BlockEvent& ev, int blockStart) noexcept -> bool {
2463 switch (ev.kind)
2464 {
2465 case BlockEvent::Kind::Bypass:
2466 bypassChanged |= setBypass(ev.value >= 0.5);
2467 return false;
2468 case BlockEvent::Kind::Midi:
2469 if constexpr (HasMidi<P>)
2470 {
2471 MidiEvent midi = ev.midi;
2472 midi.sampleOffset = ev.offset - blockStart;
2473 if (midi.sampleOffset < 0) midi.sampleOffset = 0;
2474 user.handleMidiEvent(midi);
2475 }
2476 return false;
2477 case BlockEvent::Kind::Param:
2478 default:
2479 if (const int idx = indexOfParamId(ev.paramId); idx >= 0)
2480 {
2481 applyNormalized(idx, ev.value);
2482 return true;
2483 }
2484 return false;
2485 }
2486 };
2487 auto finish = [&]() noexcept {
2488 events.clear();
2489 if (paramsChanged) refreshReported();
2490 if (bypassChanged) announce(kNotifyBypass);
2491 };
2492
2493 const UInt32 width = static_cast<UInt32>(currentChannels);
2494 const UInt32 outCh = ioData->mNumberBuffers < width
2495 ? ioData->mNumberBuffers : width;
2496 if (outCh < 1)
2497 {
2498 for (int i = 0; i < eventCount; ++i)
2499 paramsChanged |= applyEvent(events[i], events[i].offset);
2500 finish();
2501 return noErr;
2502 }
2503
2504 // Pull the main input through the registered callback or connection
2505 // into our own buffers (instruments have no input: silence), then
2506 // process and write to the host's buffers.
2507 float* pull[2] = { pullL.data(), pullR.data() };
2508 if (pullL.empty())
2509 {
2510 // No main pull buffers (ShouldAllocateBuffer false on the main
2511 // input and the output): the source supplies its buffers and the
2512 // host's output buffers, checked by render(), take the silence of
2513 // a missing source.
2514 pull[0] = static_cast<float*>(ioData->mBuffers[0].mData);
2515 pull[1] = outCh > 1 ? static_cast<float*>(ioData->mBuffers[1].mData) : pull[0];
2516 }
2517 if constexpr (!kIsInstrument)
2518 {
2519 const OSStatus pullStatus = pullInput(0, pull, timeStamp, frames);
2520 if (pullStatus != noErr)
2521 {
2522 for (int i = 0; i < eventCount; ++i) // never lose the slice's events
2523 paramsChanged |= applyEvent(events[i], events[i].offset);
2524 finish();
2525 return pullStatus;
2526 }
2527 }
2528
2529 float* out[2] = { nullptr, nullptr };
2530 for (UInt32 ch = 0; ch < outCh; ++ch)
2531 {
2532 if (ioData->mBuffers[ch].mData == nullptr)
2533 ioData->mBuffers[ch].mData = pull[ch];
2534 out[ch] = static_cast<float*>(ioData->mBuffers[ch].mData);
2535 ioData->mBuffers[ch].mDataByteSize = frames * sizeof(float);
2536 }
2537
2538 // Dry copy for the bypass blend; an instrument starts cleared
2539 // (voices ADD) and its bypass blends toward silence (dry stays 0).
2540 float* dry[2] = { dryL.data(), dryR.data() };
2541 for (UInt32 ch = 0; ch < outCh; ++ch)
2542 {
2543 if (kIsInstrument)
2544 {
2545 std::memset(out[ch], 0, frames * sizeof(float));
2546 continue;
2547 }
2548 std::memcpy(dry[ch], pull[ch], frames * sizeof(float));
2549 if (out[ch] != pull[ch])
2550 std::memcpy(out[ch], pull[ch], frames * sizeof(float));
2551 }
2552 if constexpr (HasLatency<P> && !kIsInstrument)
2553 dryDelay.process(dry, static_cast<int>(outCh), static_cast<int>(frames),
2554 cachedLatency.load(std::memory_order_relaxed));
2555
2556 // Sidechain: input element 1; a missing or failing source must
2557 // never take the main path down - fall back to silence.
2558 float* sc[2] = { nullptr, nullptr };
2559 if constexpr (HasSidechain<P>)
2560 {
2561 sc[0] = scL.data();
2562 sc[1] = scR.data();
2563 if (pullInput(1, sc, timeStamp, frames) != noErr)
2564 {
2565 sc[0] = scL.data();
2566 sc[1] = scR.data();
2567 std::memset(sc[0], 0, frames * sizeof(float));
2568 std::memset(sc[1], 0, frames * sizeof(float));
2569 }
2570 }
2571
2572 // Sub-block processing at quantum-aligned event positions (the
2573 // sample-accurate default); opted out, everything applies up front.
2574 auto processSegment = [&](int start, int length) noexcept {
2575 float* sub[2] = { out[0] + start,
2576 outCh > 1 ? out[1] + start : out[0] + start };
2577 dspark::AudioBufferView<float> view(sub, static_cast<int>(outCh),
2578 length);
2579 if constexpr (HasSidechain<P>)
2580 {
2581 // The key view mirrors the main width (mono main, mono key).
2582 float* scSub[2] = { sc[0] + start, sc[1] + start };
2583 dspark::AudioBufferView<float> scView(scSub,
2584 static_cast<int>(outCh), length);
2585 user.processBlock(view, scView);
2586 }
2587 else
2588 user.processBlock(view);
2589 // Soft bypass per segment: a scheduled bypass point starts its
2590 // crossfade where it lands (the old once-per-slice blend began
2591 // it at frame 0).
2592 blendBypass(out, dry, outCh, start, length);
2593 };
2594
2595 const int total = static_cast<int>(frames);
2596 int evIdx = 0;
2597 if (!sampleAccurateOf<P>())
2598 {
2599 for (; evIdx < eventCount; ++evIdx)
2600 paramsChanged |= applyEvent(events[evIdx], 0);
2601 processSegment(0, total);
2602 }
2603 else
2604 {
2605 int pos = 0;
2606 while (pos < total)
2607 {
2608 while (evIdx < eventCount
2609 && (events[evIdx].offset / kAutomationQuantum)
2610 * kAutomationQuantum <= pos)
2611 paramsChanged |= applyEvent(events[evIdx++], pos);
2612 int next = total;
2613 if (evIdx < eventCount)
2614 {
2615 const int snapped = (events[evIdx].offset / kAutomationQuantum)
2616 * kAutomationQuantum;
2617 if (snapped < next) next = snapped;
2618 }
2619 if (next <= pos) next = pos + kAutomationQuantum < total
2620 ? pos + kAutomationQuantum : total;
2621 processSegment(pos, next - pos);
2622 pos = next;
2623 }
2624 for (; evIdx < eventCount; ++evIdx)
2625 paramsChanged |= applyEvent(events[evIdx], total);
2626 }
2627
2628 finish();
2629 return noErr;
2630 }
2631};
2632
2633// -- component plug-in interface -----------------------------------------------------
2634
2635template <typename P>
2636struct Component
2637{
2638 AudioComponentPlugInInterface iface {};
2639 Plugin<P>* state = nullptr;
2640
2641 static Component* fromSelf(void* self) noexcept
2642 {
2643 return static_cast<Component*>(self);
2644 }
2645
2646 static OSStatus sOpen(void* self, AudioComponentInstance instance) noexcept
2647 {
2648 auto* c = fromSelf(self);
2649 c->state = new (std::nothrow) Plugin<P>();
2650 if (c->state == nullptr) return kAudio_MemFullError;
2651 c->state->instance = instance;
2652 c->state->subtype = gSubtype;
2653 c->state->manufacturer = gManufacturer;
2654 return noErr;
2655 }
2656
2657 static OSStatus sClose(void* self) noexcept
2658 {
2659 auto* c = fromSelf(self);
2660 delete c->state;
2661 delete c;
2662 return noErr;
2663 }
2664
2665 // Selector implementations (signatures from AUComponent.h).
2666
2667 static OSStatus sInitialize(void* self) noexcept
2668 { return fromSelf(self)->state->initialize(); }
2669
2670 static OSStatus sUninitialize(void* self) noexcept
2671 { return fromSelf(self)->state->uninitialize(); }
2672
2673 static OSStatus sGetPropertyInfo(void* self, AudioUnitPropertyID id,
2674 AudioUnitScope scope, AudioUnitElement element,
2675 UInt32* outSize, Boolean* outWritable) noexcept
2676 { return fromSelf(self)->state->getPropertyInfo(id, scope, element, outSize, outWritable); }
2677
2678 static OSStatus sGetProperty(void* self, AudioUnitPropertyID id,
2679 AudioUnitScope scope, AudioUnitElement element,
2680 void* outData, UInt32* ioSize) noexcept
2681 { return fromSelf(self)->state->getProperty(id, scope, element, outData, ioSize); }
2682
2683 static OSStatus sSetProperty(void* self, AudioUnitPropertyID id,
2684 AudioUnitScope scope, AudioUnitElement element,
2685 const void* inData, UInt32 inSize) noexcept
2686 { return fromSelf(self)->state->setProperty(id, scope, element, inData, inSize); }
2687
2688 static OSStatus sGetParameter(void* self, AudioUnitParameterID id,
2689 AudioUnitScope scope, AudioUnitElement element,
2690 AudioUnitParameterValue* outValue) noexcept
2691 {
2692 (void) element;
2693 return fromSelf(self)->state->getParameter(id, scope, outValue);
2694 }
2695
2696 static OSStatus sSetParameter(void* self, AudioUnitParameterID id,
2697 AudioUnitScope scope, AudioUnitElement element,
2698 AudioUnitParameterValue value,
2699 UInt32 bufferOffset) noexcept
2700 {
2701 (void) element;
2702 (void) bufferOffset;
2703 return fromSelf(self)->state->setParameter(id, scope, value);
2704 }
2705
2706 static OSStatus sReset(void* self, AudioUnitScope scope,
2707 AudioUnitElement element) noexcept
2708 {
2709 (void) scope;
2710 (void) element;
2711 return fromSelf(self)->state->reset();
2712 }
2713
2714 static OSStatus sRender(void* self, AudioUnitRenderActionFlags* ioFlags,
2715 const AudioTimeStamp* timeStamp, UInt32 busNumber,
2716 UInt32 frames, AudioBufferList* ioData) noexcept
2717 { return fromSelf(self)->state->render(ioFlags, timeStamp, busNumber, frames, ioData); }
2718
2719 static OSStatus sAddPropertyListener(void* self, AudioUnitPropertyID id,
2720 AudioUnitPropertyListenerProc proc,
2721 void* user) noexcept
2722 {
2723 auto* state = fromSelf(self)->state;
2724 state->listeners.push_back({ id, proc, user });
2725 return noErr;
2726 }
2727
2728 static OSStatus sRemovePropertyListener(void* self, AudioUnitPropertyID id,
2729 AudioUnitPropertyListenerProc proc) noexcept
2730 {
2731 auto& ls = fromSelf(self)->state->listeners;
2732 for (size_t i = ls.size(); i > 0; --i)
2733 if (ls[i - 1].id == id && ls[i - 1].proc == proc)
2734 ls.erase(ls.begin() + static_cast<ptrdiff_t>(i - 1));
2735 return noErr;
2736 }
2737
2738 static OSStatus sRemovePropertyListenerWithUserData(void* self, AudioUnitPropertyID id,
2739 AudioUnitPropertyListenerProc proc,
2740 void* user) noexcept
2741 {
2742 auto& ls = fromSelf(self)->state->listeners;
2743 for (size_t i = ls.size(); i > 0; --i)
2744 if (ls[i - 1].id == id && ls[i - 1].proc == proc && ls[i - 1].user == user)
2745 ls.erase(ls.begin() + static_cast<ptrdiff_t>(i - 1));
2746 return noErr;
2747 }
2748
2752 static OSStatus sAddRenderNotify(void* self, AURenderCallback proc, void* refCon) noexcept
2753 { return fromSelf(self)->state->queueRenderNotify(proc, refCon, true); }
2754
2755 static OSStatus sRemoveRenderNotify(void* self, AURenderCallback proc, void* refCon) noexcept
2756 { return fromSelf(self)->state->queueRenderNotify(proc, refCon, false); }
2757
2763 static OSStatus sScheduleParameters(void* self,
2764 const AudioUnitParameterEvent* events,
2765 UInt32 numEvents) noexcept
2766 {
2767 auto* state = fromSelf(self)->state;
2768 // A non-finite value refuses the whole call, as the format requires (NaN
2769 // used to map to the bottom of the range).
2770 for (UInt32 i = 0; events != nullptr && i < numEvents; ++i)
2771 {
2772 const auto& ev = events[i];
2773 if (ev.eventType == kParameterEvent_Immediate
2774 ? !std::isfinite(ev.eventValues.immediate.value)
2775 : (ev.eventType == kParameterEvent_Ramped
2776 && (!std::isfinite(ev.eventValues.ramp.startValue)
2777 || !std::isfinite(ev.eventValues.ramp.endValue))))
2778 return kAudioUnitErr_InvalidParameterValue;
2779 }
2780 // Immediate points (bypass included, as a timestamped event so its
2781 // crossfade starts where it lands) go into the block list; the list
2782 // merges past its capacity instead of dropping the newest points
2783 // (the old fixed array ignored every event after the 256th).
2784 auto push = [&](AudioUnitParameterID id, float plain, SInt32 offset, bool immediate) {
2785 BlockEvent ev {};
2786 ev.offset = offset < 0 ? 0 : offset;
2787 if (id == kBypassParamId)
2788 {
2789 ev.kind = BlockEvent::Kind::Bypass;
2790 ev.paramId = kBypassParamId;
2791 ev.value = plain >= 0.5f ? 1.0 : 0.0;
2792 }
2793 else
2794 {
2795 const int idx = Plugin<P>::indexOfParamId(id);
2796 if (idx < 0) return;
2797 ev.kind = BlockEvent::Kind::Param;
2798 ev.paramId = id;
2799 ev.value = toNormalized(P::parameters[static_cast<size_t>(idx)], plain);
2800 // The host reads an immediate value back at once (the format sets
2801 // it when scheduled); the DSP still hears it at its offset.
2802 if (immediate)
2803 state->shadow[static_cast<size_t>(idx)].store(ev.value,
2804 std::memory_order_relaxed);
2805 }
2806 state->blockEvents.add(ev);
2807 };
2808 for (UInt32 i = 0; events != nullptr && i < numEvents; ++i)
2809 {
2810 const auto& ev = events[i];
2811 if (ev.scope != kAudioUnitScope_Global) continue;
2812 if (ev.eventType == kParameterEvent_Immediate)
2813 push(ev.parameter, ev.eventValues.immediate.value,
2814 static_cast<SInt32>(ev.eventValues.immediate.bufferOffset), true);
2815 else if (ev.eventType == kParameterEvent_Ramped)
2816 {
2817 // Kept whole: render() evaluates it against the slice length.
2818 if (ev.parameter != kBypassParamId && state->rampCount < Plugin<P>::kMaxRamps)
2819 state->ramps[state->rampCount++] = typename Plugin<P>::Ramp {
2820 ev.parameter, ev.eventValues.ramp.startBufferOffset,
2821 ev.eventValues.ramp.durationInFrames,
2822 ev.eventValues.ramp.startValue, ev.eventValues.ramp.endValue };
2823 else
2824 push(ev.parameter, ev.eventValues.ramp.endValue,
2825 ev.eventValues.ramp.startBufferOffset
2826 + static_cast<SInt32>(ev.eventValues.ramp.durationInFrames),
2827 false);
2828 }
2829 }
2830 return noErr;
2831 }
2832
2833 // MusicDevice selectors (aumu / aumf): raw MIDI in, queued lock-free.
2834
2835 static OSStatus sMidiEvent(void* self, UInt32 status, UInt32 data1,
2836 UInt32 data2, UInt32 offsetSampleFrame) noexcept
2837 {
2838 return fromSelf(self)->state->pushMidi(status, data1, data2,
2839 offsetSampleFrame);
2840 }
2841
2842 static OSStatus sSysEx(void* self, const UInt8*, UInt32) noexcept
2843 {
2844 (void) self;
2845 return noErr; // accepted, ignored (no sysex contract in v1)
2846 }
2847
2848#if DSPARK_AU_HAVE_MIDI2
2852 static OSStatus sMidiEventList(void* self, UInt32 offsetSampleFrame,
2853 const MIDIEventList* list) noexcept
2854 {
2855 return fromSelf(self)->state->pushEventList(offsetSampleFrame, list);
2856 }
2857#endif
2858
2859 static AudioComponentMethod sLookup(SInt16 selector) noexcept
2860 {
2861 if constexpr (HasMidi<P>)
2862 {
2863 if (selector == kMusicDeviceMIDIEventSelect)
2864 return reinterpret_cast<AudioComponentMethod>(&sMidiEvent);
2865 if (selector == kMusicDeviceSysExSelect)
2866 return reinterpret_cast<AudioComponentMethod>(&sSysEx);
2867#if DSPARK_AU_HAVE_MIDI2
2868 if (selector == kMusicDeviceMIDIEventListSelect)
2869 return reinterpret_cast<AudioComponentMethod>(&sMidiEventList);
2870#endif
2871 }
2872 switch (selector)
2873 {
2874 case kAudioUnitInitializeSelect:
2875 return reinterpret_cast<AudioComponentMethod>(&sInitialize);
2876 case kAudioUnitUninitializeSelect:
2877 return reinterpret_cast<AudioComponentMethod>(&sUninitialize);
2878 case kAudioUnitGetPropertyInfoSelect:
2879 return reinterpret_cast<AudioComponentMethod>(&sGetPropertyInfo);
2880 case kAudioUnitGetPropertySelect:
2881 return reinterpret_cast<AudioComponentMethod>(&sGetProperty);
2882 case kAudioUnitSetPropertySelect:
2883 return reinterpret_cast<AudioComponentMethod>(&sSetProperty);
2884 case kAudioUnitGetParameterSelect:
2885 return reinterpret_cast<AudioComponentMethod>(&sGetParameter);
2886 case kAudioUnitSetParameterSelect:
2887 return reinterpret_cast<AudioComponentMethod>(&sSetParameter);
2888 case kAudioUnitResetSelect:
2889 return reinterpret_cast<AudioComponentMethod>(&sReset);
2890 case kAudioUnitRenderSelect:
2891 return reinterpret_cast<AudioComponentMethod>(&sRender);
2892 case kAudioUnitAddPropertyListenerSelect:
2893 return reinterpret_cast<AudioComponentMethod>(&sAddPropertyListener);
2894 case kAudioUnitRemovePropertyListenerSelect:
2895 return reinterpret_cast<AudioComponentMethod>(&sRemovePropertyListener);
2896 case kAudioUnitRemovePropertyListenerWithUserDataSelect:
2897 return reinterpret_cast<AudioComponentMethod>(&sRemovePropertyListenerWithUserData);
2898 case kAudioUnitAddRenderNotifySelect:
2899 return reinterpret_cast<AudioComponentMethod>(&sAddRenderNotify);
2900 case kAudioUnitRemoveRenderNotifySelect:
2901 return reinterpret_cast<AudioComponentMethod>(&sRemoveRenderNotify);
2902 case kAudioUnitScheduleParametersSelect:
2903 return reinterpret_cast<AudioComponentMethod>(&sScheduleParameters);
2904 default:
2905 return nullptr;
2906 }
2907 }
2908
2909 inline static OSType gSubtype = 0;
2910 inline static OSType gManufacturer = 0;
2911
2912 static void* factory(const AudioComponentDescription* desc) noexcept
2913 {
2914 // The Info.plist entry must declare the type the class implies:
2915 // aumu (Instrument), aumf (HasMidi effect) or aufx.
2916 if (desc != nullptr && desc->componentType != Plugin<P>::expectedType())
2917 return nullptr;
2918 auto* c = new (std::nothrow) Component();
2919 if (c == nullptr) return nullptr;
2920 c->iface.Open = &sOpen;
2921 c->iface.Close = &sClose;
2922 c->iface.Lookup = &sLookup;
2923 c->iface.reserved = nullptr;
2924 return c;
2925 }
2926};
2927
2928} // namespace dspark::plugin::au
2929
2936#define DSPARK_AU_PLUGIN(PluginClass, subtype4, manufacturer4) \
2937 extern "C" __attribute__((visibility("default"))) \
2938 void* DSParkAuFactory(const AudioComponentDescription* desc) \
2939 { \
2940 using Comp = dspark::plugin::au::Component<PluginClass>; \
2941 Comp::gSubtype = dspark::plugin::au::fourCC(subtype4); \
2942 Comp::gManufacturer = dspark::plugin::au::fourCC(manufacturer4); \
2943 return Comp::factory(desc); \
2944 }
2945
2946#pragma pop_macro("max")
2947#pragma pop_macro("min")
2948
2949#else // !__APPLE__
2950
2951// Self-disabling off macOS so one translation unit can target every format.
2952#define DSPARK_AU_PLUGIN(PluginClass, subtype4, manufacturer4)
2953
2954#endif // __APPLE__
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
constexpr int kBypassRampSamples
Definition DSParkClap.h:110
constexpr uint32_t kBypassParamId
Definition DSParkClap.h:109
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 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.
constexpr int kAutomationQuantum
Sub-block grain: automation/event splits snap to this many frames (bounds the per-call overhead; ~0....
constexpr uint32_t hash32(const char *s) noexcept
FNV-1a 32-bit over a C string - the per-parameter host id.
constexpr bool isToggle(const Param &p) noexcept
True for an on/off parameter (two unnamed positions).
constexpr PresetDef< sizeof...(Vs)> preset(const char *name, Vs... values) noexcept
Builds one factory preset: preset("Warm", 6.0f, 0.8f, ...) - one PLAIN value per parameter,...
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),...
void add(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, int count) noexcept
Adds source samples into a destination buffer (no scaling).
Definition SimdOps.h:829
constexpr int kNumParams
Param
Every parameter, in the order of the parameter table.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37