101#define DSPARK_PLUGIN_AU_INCLUDED 1
103#if defined(__APPLE__)
105#include "../DSParkPlugin.h"
107#include <AudioToolbox/AudioToolbox.h>
108#include <CoreFoundation/CoreFoundation.h>
112#include <AudioToolbox/AudioUnitUtilities.h>
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
123#if !defined(DSPARK_AU_HAVE_MIDI2)
124#define DSPARK_AU_HAVE_MIDI2 0
127#if defined(DSPARK_PLUGIN_WEBVIEW)
129#include <objc/message.h>
130#include <objc/runtime.h>
133#include <dispatch/dispatch.h>
144#pragma push_macro("min")
145#pragma push_macro("max")
149namespace dspark::plugin::au {
154inline OSType fourCC(
const char* s)
noexcept
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]));
162#if defined(DSPARK_PLUGIN_WEBVIEW)
177inline constexpr AudioUnitPropertyID kDsparkEditorHookProperty = 64537;
184 void* context =
nullptr;
185 void* (*createView)(
void* context,
double width,
double height) =
nullptr;
191 double width = 0, height = 0;
198 void (*onDealloc)(
void* context) =
nullptr;
199 void* context =
nullptr;
201 void (*onResize)(
void* context,
double width,
double height) =
nullptr;
204inline Class editorContainerClass() noexcept;
206inline
void editorContainerDealloc(
void* self,
SEL) noexcept
211 Class cls = editorContainerClass();
212 if (cls ==
nullptr)
return;
213 if (Ivar ivar = class_getInstanceVariable(cls,
"dsparkSink"))
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);
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"));
228inline void editorContainerSetFrameSize(
void* self,
SEL selector, ViewSize size)
noexcept
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"))
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);
246inline Class editorContainerClass() noexcept
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",
258 Class c = objc_allocateClassPair(viewCls, name, 0);
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),
267 objc_registerClassPair(c);
273inline unsigned int editorFactoryInterfaceVersion(
void*,
SEL)
noexcept
278inline void* editorFactoryUiView(
void*,
SEL,
void* audioUnit, ViewSize size)
noexcept
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)
288 return hook.createView(hook.context, size.width, size.height);
292inline Class editorFactoryClass() noexcept
294 static Class registered = []() -> Class {
295 static char name[96];
296 webview_ui::objc_glue::imageUniqueClassName(
"DSParkAUCocoaViewFactory",
298 Class c = objc_allocateClassPair(objc_getClass(
"NSObject"), name, 0);
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}");
308 if (Protocol* proto = objc_getProtocol(
"AUCocoaUIBase"))
309 class_addProtocol(c, proto);
310 objc_registerClassPair(c);
319inline CFURLRef copyOwningBundleUrl() noexcept
321 static const int anchor = 0;
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/"))
329 size_t length = marker !=
nullptr ?
static_cast<size_t>(marker - path) : 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);
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.");
360 static OSType expectedType() noexcept
362 if (kIsInstrument)
return fourCC(
"aumu");
363 if (HasMidi<P>)
return fourCC(
"aumf");
364 return fourCC(
"aufx");
367 AudioComponentInstance instance =
nullptr;
368 OSType subtype = 0, manufacturer = 0;
370 double sampleRate = 44100.0;
371 UInt32 maxFrames = 1156;
374 std::atomic<bool> initialized {
false };
375 int currentChannels = defaultChannelCount<P>();
376 UInt32 offlineRender = 0;
380 std::atomic<bool> bypass {
false };
381 float bypassMix = 0.0f;
388 std::atomic<int> cachedLatency { 0 };
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 };
397 std::vector<float> pullL, pullR, dryL, dryR, scL, scR;
401 HostCallbackInfo hostCallbacks {};
411 static constexpr uint32_t kMidiRingSize = 256;
414 std::atomic<uint32_t> seq { 0 };
417 MidiCell midiRing[HasMidi<P> ? kMidiRingSize : 1] {};
418 std::atomic<uint32_t> midiEnqueue { 0 };
419 uint32_t midiDequeue = 0;
423 std::atomic<uint32_t> midiDiscardBefore { 0 };
432 AURenderCallback proc =
nullptr;
433 void* refCon =
nullptr;
435 static constexpr int kMaxRenderNotifies = 16;
436 RenderNotify renderNotifies[kMaxRenderNotifies] {};
437 int renderNotifyCount = 0;
440 RenderNotify target {};
443 static constexpr uint32_t kNotifyQueueSize = 64;
444 NotifyCommand notifyQueue[kNotifyQueueSize] {};
445 std::atomic<uint32_t> notifyHead { 0 }, notifyTail { 0 };
452 BlockEventList blockEvents;
458 float startValue, endValue;
460 static constexpr int kMaxRamps = 64;
461 Ramp ramps[kMaxRamps] {};
466 PendingParams<kNumParams> pending;
467 std::atomic<std::thread::id> renderThread {};
468 UInt32 sidechainChannels = 0;
472 std::vector<AUPreset> presetStorage;
473 CFArrayRef presetArray =
nullptr;
474 SInt32 currentPresetNumber = -1;
480 AudioUnitPropertyID id;
481 AudioUnitPropertyListenerProc proc;
484 std::vector<Listener> listeners;
485 CFStringRef presetName =
nullptr;
488 std::atomic<double> cachedTail { 0.0 };
490 double latencySecondsAtInit = 0.0;
493 EditorSizeMemory<P> editorMemory;
499 std::atomic<OSStatus> lastRenderError { noErr };
510 bool allocateInput[2] = {
true,
true };
511 bool allocateOutput =
true;
514 [[nodiscard]]
bool ownsMainBuffers() const noexcept
516 if constexpr (kIsInstrument)
517 return allocateOutput;
519 return allocateInput[0] || allocateOutput;
522#if defined(DSPARK_PLUGIN_WEBVIEW)
523 webview_ui::Editor<P> editor;
524 void* editorContainer =
nullptr;
525 EditorViewSink editorSink {};
532#if defined(DSPARK_PLUGIN_WEBVIEW)
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);
542 void applyFactoryPresetIdx(
int idx)
noexcept
544 if constexpr (kNumPresets > 0)
546 if (idx < 0 || idx >= kNumPresets)
return;
548 applyFromAnyThread(
static_cast<int>(i), presetNormalized<P>(idx, i));
549 currentPresetNumber = idx;
557 double tailSecondsNow() const noexcept
559 if constexpr (HasTail<P>)
561 const double tail = user.getTailSeconds();
562 return tail > 0.0 ? tail : 0.0;
575 void refreshReported() noexcept
578 if constexpr (HasLatency<P>)
580 const int now = user.getLatency();
581 if (initialized && now != cachedLatency.load(std::memory_order_relaxed))
583 cachedLatency.store(now, std::memory_order_relaxed);
584 bits |= kNotifyLatency;
587 if constexpr (HasTail<P>)
589 const double now = tailSecondsNow();
590 if (initialized && now != cachedTail.load(std::memory_order_relaxed))
592 cachedTail.store(now, std::memory_order_relaxed);
596 if (bits != 0) announce(bits);
603 kNotifyLatency = 1u, kNotifyTail = 2u, kNotifyBypass = 4u, kNotifyRenderError = 8u
605 std::atomic<uint32_t> notifyPending { 0u };
606 std::atomic<bool> tickRunning {
false };
607 dispatch_source_t tick =
nullptr;
611 void announce(uint32_t bits)
noexcept
613 if (pthread_main_np() != 0 || !tickRunning.load(std::memory_order_acquire))
614 deliverNotifications(bits);
616 notifyPending.fetch_or(bits, std::memory_order_release);
622 void announceFromRender(uint32_t bits)
noexcept
624 if (pthread_main_np() != 0)
625 deliverNotifications(bits);
627 notifyPending.fetch_or(bits, std::memory_order_release);
634 void recordRenderError(OSStatus error)
noexcept
636 if (error == noErr)
return;
637 OSStatus none = noErr;
638 if (lastRenderError.compare_exchange_strong(none, error, std::memory_order_relaxed))
639 announceFromRender(kNotifyRenderError);
642 void deliverNotifications(uint32_t bits)
noexcept
644 if ((bits & kNotifyLatency) != 0u)
645 notifyProperty(kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0);
646 if ((bits & kNotifyTail) != 0u)
647 notifyProperty(kAudioUnitProperty_TailTime, kAudioUnitScope_Global, 0);
650 if ((bits & kNotifyBypass) != 0u)
651 notifyProperty(kAudioUnitProperty_BypassEffect, kAudioUnitScope_Global, 0);
652 if ((bits & kNotifyRenderError) != 0u)
653 notifyProperty(kAudioUnitProperty_LastRenderError, kAudioUnitScope_Global, 0);
656 static void onTick(
void* self)
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);
663 void startTick() noexcept
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);
677 const uint32_t bits = notifyPending.exchange(0u, std::memory_order_acq_rel);
678 if (bits != 0u) deliverNotifications(bits);
683 void stopTick(
bool flush =
true) noexcept
685 if (tick ==
nullptr)
return;
686 tickRunning.store(
false, std::memory_order_release);
687 dispatch_source_cancel(tick);
688 dispatch_release(tick);
690 const uint32_t bits = notifyPending.exchange(0u, std::memory_order_acq_rel);
691 if (bits != 0u && flush) deliverNotifications(bits);
695 void notifyParameterChanged(AudioUnitParameterID
id)
noexcept
697 AudioUnitParameter parameter {};
698 parameter.mAudioUnit = instance;
699 parameter.mParameterID = id;
700 parameter.mScope = kAudioUnitScope_Global;
701 parameter.mElement = 0;
702 AUParameterListenerNotify(
nullptr,
nullptr, ¶meter);
706 bool setBypass(
bool on)
noexcept
708 return bypass.exchange(on, std::memory_order_relaxed) != on;
711 void notifyProperty(AudioUnitPropertyID
id, AudioUnitScope scope,
712 AudioUnitElement element)
noexcept
714 for (
const auto& l : listeners)
715 if (l.id == id && l.proc != nullptr)
716 l.proc(l.user, instance, id, scope, element);
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)
726 cell.seq.store(position++, std::memory_order_relaxed);
729 static int indexOfParamId(AudioUnitParameterID
id)
noexcept
731 return paramIndexOf<P>(
id);
734 void applyNormalized(
int index,
double normalized)
noexcept
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)));
752 bool applyFromAnyThread(
int index,
double normalized)
noexcept
754 if (normalized != normalized)
return false;
756 && std::this_thread::get_id() != renderThread.load(std::memory_order_relaxed))
758 shadow[
static_cast<size_t>(index)].store(normalized, std::memory_order_relaxed);
759 pending.mark(
static_cast<size_t>(index));
762 applyNormalized(index, normalized);
766 bool drainPending() noexcept
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))));
778 CFStringRef copyPresetName() const noexcept
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);
792 void notifyAllParameters() noexcept
794 AudioUnitParameter any {};
795 any.mAudioUnit = instance;
796 any.mParameterID = kAUParameterListener_AnyParameter;
797 any.mScope = kAudioUnitScope_Global;
799 AUParameterListenerNotify(
nullptr,
nullptr, &any);
802 void applyAllShadows() noexcept
804 pending.drain([](
int) {});
806 user.setParameter(
static_cast<int>(i),
807 static_cast<float>(
toPlain(P::parameters[i],
808 shadow[i].load(std::memory_order_relaxed))));
811#if defined(DSPARK_PLUGIN_WEBVIEW)
815 static constexpr bool kHasWebEditor =
816 HasEditor<P> && webview_ui::Editor<P>::kAvailable;
818 void sendGesture(
int index, AudioUnitEventType type)
noexcept
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);
831 static void cbSetParam(
void* context,
int index,
double plain)
noexcept
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)];
839 self->sendGesture(index, kAudioUnitEvent_BeginParameterChangeGesture);
840 AUParameterSet(
nullptr,
nullptr, ¶meter,
841 static_cast<AudioUnitParameterValue
>(plain), 0);
843 self->sendGesture(index, kAudioUnitEvent_EndParameterChangeGesture);
846 static void cbBeginEdit(
void* context,
int index)
noexcept
848 auto* self =
static_cast<Plugin*
>(context);
849 self->editActive[
static_cast<size_t>(index)] =
true;
850 self->sendGesture(index, kAudioUnitEvent_BeginParameterChangeGesture);
853 static void cbEndEdit(
void* context,
int index)
noexcept
855 auto* self =
static_cast<Plugin*
>(context);
856 self->editActive[
static_cast<size_t>(index)] =
false;
857 self->sendGesture(index, kAudioUnitEvent_EndParameterChangeGesture);
860 static void sOnContainerDealloc(
void* context)
noexcept
862 auto* self =
static_cast<Plugin*
>(context);
863 self->editorContainer =
nullptr;
864 self->editor.destroy();
869 static void sOnContainerResize(
void* context,
double width,
double height)
noexcept
871 static_cast<Plugin*
>(context)->editorMemory.remember(width, height);
876 void teardownEditor() noexcept
878 if (editorContainer !=
nullptr)
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;
889 static void* sCreateEditorView(
void* context,
double width,
double height)
noexcept
891 return static_cast<Plugin*
>(context)->createEditorView(width, height);
898 void applyRememberedEditorSize() noexcept
900 if constexpr (kHasWebEditor)
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);
918 void* createEditorView(
double,
double)
noexcept
920 namespace og = webview_ui::objc_glue;
922 Class cls = editorContainerClass();
923 if (cls ==
nullptr)
return nullptr;
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
933 if (!editor.create(view, shadow, callbacks))
935 og::call<void>(view,
"release");
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");
954 OSStatus initialize() noexcept
958 const double tailBefore = cachedTail.load(std::memory_order_relaxed);
960 if constexpr (HasOfflineMode<P>)
961 user.setOfflineRendering(offlineRender != 0);
963 if (ownsMainBuffers())
965 pullL.assign(maxFrames, 0.0f);
966 pullR.assign(maxFrames, 0.0f);
972 std::vector<float>().swap(pullL);
973 std::vector<float>().swap(pullR);
975 dryL.assign(maxFrames, 0.0f);
976 dryR.assign(maxFrames, 0.0f);
977 if constexpr (HasSidechain<P>)
979 scL.assign(maxFrames, 0.0f);
980 scR.assign(maxFrames, 0.0f);
982 bypassMix = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
983 uint32_t changed = 0;
984 if constexpr (HasLatency<P>)
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));
993 const double seconds = sampleRate > 0.0 ?
latency / sampleRate : 0.0;
994 if (seconds != latencySecondsAtInit) changed |= kNotifyLatency;
995 latencySecondsAtInit = seconds;
997 if constexpr (HasTail<P>)
999 const double tail = tailSecondsNow();
1000 cachedTail.store(tail, std::memory_order_relaxed);
1001 if (tail != tailBefore) changed |= kNotifyTail;
1005 blockEvents.clear();
1007 if constexpr (HasMidi<P>)
1008 midiDiscardBefore.store(midiEnqueue.load(std::memory_order_acquire),
1009 std::memory_order_release);
1010 applyNotifyCommands();
1011 renderThread.store(std::thread::id {}, std::memory_order_relaxed);
1014 if (changed != 0u) deliverNotifications(changed);
1018 OSStatus uninitialize() noexcept
1020 initialized =
false;
1029 OSStatus reset() noexcept
1031 if constexpr (HasReset<P>)
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);
1046 OSStatus queueRenderNotify(AURenderCallback proc,
void* refCon,
bool add)
noexcept
1048 if (proc ==
nullptr)
return kAudio_ParamError;
1051 applyNotifyCommands();
1052 applyNotifyCommand(RenderNotify { proc, refCon },
add);
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;
1059 notifyQueue[tail] = NotifyCommand { RenderNotify { proc, refCon },
add };
1060 notifyTail.store(next, std::memory_order_release);
1064 void applyNotifyCommand(RenderNotify target,
bool add)
noexcept
1067 for (
int i = 0; i < renderNotifyCount; ++i)
1068 if (renderNotifies[i].proc == target.proc
1069 && renderNotifies[i].refCon == target.refCon)
1074 if (found < 0 && renderNotifyCount < kMaxRenderNotifies)
1075 renderNotifies[renderNotifyCount++] = target;
1077 else if (found >= 0)
1079 for (
int i = found; i + 1 < renderNotifyCount; ++i)
1080 renderNotifies[i] = renderNotifies[i + 1];
1081 --renderNotifyCount;
1086 void applyNotifyCommands() noexcept
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)
1092 applyNotifyCommand(notifyQueue[head].target, notifyQueue[head].add);
1093 head = (head + 1) & (kNotifyQueueSize - 1);
1095 notifyHead.store(head, std::memory_order_release);
1098 void callRenderNotifies(AudioUnitRenderActionFlags flags,
1099 const AudioTimeStamp* timeStamp, UInt32 busNumber,
1100 UInt32 frames, AudioBufferList* ioData)
noexcept
1102 for (
int i = 0; i < renderNotifyCount; ++i)
1103 renderNotifies[i].proc(renderNotifies[i].refCon, &flags, timeStamp,
1104 busNumber, frames, ioData);
1112 void discardSlice() noexcept
1114 for (
int i = 0; i < blockEvents.size(); ++i)
1116 const BlockEvent& ev = blockEvents[i];
1117 if (ev.kind == BlockEvent::Kind::Bypass)
1119 if (setBypass(ev.value >= 0.5)) announce(kNotifyBypass);
1121 else if (ev.kind == BlockEvent::Kind::Param)
1123 if (
const int idx = indexOfParamId(ev.paramId); idx >= 0)
1125 shadow[
static_cast<size_t>(idx)].store(ev.value,
1126 std::memory_order_relaxed);
1127 pending.mark(
static_cast<size_t>(idx));
1131 blockEvents.clear();
1137 void fillStreamFormat(AudioStreamBasicDescription& f)
const noexcept
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;
1151 bool acceptableFormat(
const AudioStreamBasicDescription& f)
const noexcept
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;
1163 static constexpr int numChannelConfigs() noexcept
1165 return channelSupportOf<P>() == ChannelSupport::MonoAndStereo ? 2 : 1;
1169 static constexpr bool isIoElement(AudioUnitScope scope, AudioUnitElement element)
noexcept
1171 if (scope == kAudioUnitScope_Input)
1173 if constexpr (kNumInputElements == 0)
1176 return element < kNumInputElements;
1178 return scope == kAudioUnitScope_Output && element == 0;
1183 void buildPresetArray() noexcept
1185 if constexpr (kNumPresets > 0)
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)
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)];
1199 presetArray = CFArrayCreate(
nullptr, pointers,
1200 static_cast<CFIndex
>(kNumPresets),
nullptr);
1204 OSStatus getPropertyInfo(AudioUnitPropertyID
id, AudioUnitScope scope,
1205 AudioUnitElement element, UInt32* outSize,
1206 Boolean* outWritable)
noexcept
1209 Boolean writable =
false;
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));
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);
1232 case kAudioUnitProperty_ParameterList:
1233 size = scope == kAudioUnitScope_Global
1234 ?
static_cast<UInt32
>((
kNumParams + 1) *
sizeof(AudioUnitParameterID))
1237 case kAudioUnitProperty_ParameterInfo:
1238 size =
sizeof(AudioUnitParameterInfo);
break;
1239 case kAudioUnitProperty_ParameterValueStrings:
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);
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;
1281#if defined(DSPARK_PLUGIN_WEBVIEW)
1282 case kAudioUnitProperty_CocoaUI:
1283 if constexpr (!kHasWebEditor)
return kAudioUnitErr_InvalidProperty;
1284 size =
sizeof(AudioUnitCocoaViewInfo);
1286 case kDsparkEditorHookProperty:
1287 if constexpr (!kHasWebEditor)
return kAudioUnitErr_InvalidProperty;
1288 size =
sizeof(EditorHook);
1293 return kAudioUnitErr_InvalidProperty;
1295 if (outSize) *outSize = size;
1296 if (outWritable) *outWritable = writable;
1300 OSStatus getProperty(AudioUnitPropertyID
id, AudioUnitScope scope,
1301 AudioUnitElement element,
void* outData,
1302 UInt32* ioSize)
noexcept
1304 if (ioSize ==
nullptr)
return kAudio_ParamError;
1305 if (outData ==
nullptr)
1308 return getPropertyInfo(
id, scope, element, ioSize, &w);
1312 case kAudioUnitProperty_StreamFormat:
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);
1323 case kAudioUnitProperty_SampleRate:
1324 if (*ioSize <
sizeof(Float64))
return kAudioUnitErr_InvalidPropertyValue;
1325 *
static_cast<Float64*
>(outData) = sampleRate;
1326 *ioSize =
sizeof(Float64);
1328 case kAudioUnitProperty_MaximumFramesPerSlice:
1329 if (*ioSize <
sizeof(UInt32))
return kAudioUnitErr_InvalidPropertyValue;
1330 *
static_cast<UInt32*
>(outData) = maxFrames;
1331 *ioSize =
sizeof(UInt32);
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);
1339 case kAudioUnitProperty_SupportedNumChannels:
1342 static_cast<UInt32
>(numChannelConfigs() *
sizeof(AUChannelInfo));
1343 if (*ioSize < want)
return kAudioUnitErr_InvalidPropertyValue;
1344 auto* info =
static_cast<AUChannelInfo*
>(outData);
1347 if (supportsChannelCount<P>(1))
1349 info[slot].inChannels = kIsInstrument ? 0 : 1;
1350 info[slot].outChannels = 1;
1353 if (supportsChannelCount<P>(2))
1355 info[slot].inChannels = kIsInstrument ? 0 : 2;
1356 info[slot].outChannels = 2;
1362 case kAudioUnitProperty_HostCallbacks:
1363 if (*ioSize <
sizeof(HostCallbackInfo))
1364 return kAudioUnitErr_InvalidPropertyValue;
1365 *
static_cast<HostCallbackInfo*
>(outData) = hostCallbacks;
1366 *ioSize =
sizeof(HostCallbackInfo);
1368 case kAudioUnitProperty_OfflineRender:
1369 if (*ioSize <
sizeof(UInt32))
return kAudioUnitErr_InvalidPropertyValue;
1370 *
static_cast<UInt32*
>(outData) = offlineRender;
1371 *ioSize =
sizeof(UInt32);
1373 case kAudioUnitProperty_FactoryPresets:
1375 if (kNumPresets == 0)
return kAudioUnitErr_InvalidProperty;
1376 if (*ioSize <
sizeof(CFArrayRef))
1377 return kAudioUnitErr_InvalidPropertyValue;
1379 if (presetArray ==
nullptr)
return kAudioUnitErr_InvalidProperty;
1380 *
static_cast<CFArrayRef*
>(outData) =
1381 static_cast<CFArrayRef
>(CFRetain(presetArray));
1382 *ioSize =
sizeof(CFArrayRef);
1385 case kAudioUnitProperty_ParameterList:
1387 if (scope != kAudioUnitScope_Global)
1393 static_cast<UInt32
>((
kNumParams + 1) *
sizeof(AudioUnitParameterID));
1394 if (*ioSize < want)
return kAudioUnitErr_InvalidPropertyValue;
1395 auto* ids =
static_cast<AudioUnitParameterID*
>(outData);
1397 ids[i] =
hash32(P::parameters[i].
id);
1402 case kAudioUnitProperty_ParameterInfo:
1404 if (*ioSize <
sizeof(AudioUnitParameterInfo))
1405 return kAudioUnitErr_InvalidPropertyValue;
1406 auto* info =
static_cast<AudioUnitParameterInfo*
>(outData);
1407 std::memset(info, 0,
sizeof(*info));
1411 info->flags = kAudioUnitParameterFlag_IsReadable
1412 | kAudioUnitParameterFlag_IsWritable
1413 | kAudioUnitParameterFlag_HasCFNameString
1414 | kAudioUnitParameterFlag_CFNameRelease
1415 | kAudioUnitParameterFlag_IsHighResolution;
1416 if (element == kBypassParamId)
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);
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
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);
1449 case kAudioUnitProperty_ParameterValueStrings:
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)
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);
1469 *
static_cast<CFArrayRef*
>(outData) = strings;
1470 *ioSize =
sizeof(CFArrayRef);
1473 case kAudioUnitProperty_ParameterStringFromValue:
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));
1486 formatValue(spec, plain, text,
static_cast<int>(
sizeof(text)));
1487 request->outString = CFStringCreateWithCString(
nullptr, text,
1488 kCFStringEncodingUTF8);
1489 *ioSize =
sizeof(AudioUnitParameterStringFromValue);
1492 case kAudioUnitProperty_ParameterValueFromString:
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;
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);
1512 case kAudioUnitProperty_Latency:
1513 if (*ioSize <
sizeof(Float64))
return kAudioUnitErr_InvalidPropertyValue;
1514 *
static_cast<Float64*
>(outData) =
1516 ? cachedLatency.load(std::memory_order_relaxed) / sampleRate
1518 *ioSize =
sizeof(Float64);
1520 case kAudioUnitProperty_TailTime:
1522 if (*ioSize <
sizeof(Float64))
return kAudioUnitErr_InvalidPropertyValue;
1523 *
static_cast<Float64*
>(outData) = tailSecondsNow();
1524 *ioSize =
sizeof(Float64);
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);
1533 case kAudioUnitProperty_InPlaceProcessing:
1534 if (*ioSize <
sizeof(UInt32))
return kAudioUnitErr_InvalidPropertyValue;
1535 *
static_cast<UInt32*
>(outData) = 1;
1536 *ioSize =
sizeof(UInt32);
1538 case kAudioUnitProperty_LastRenderError:
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);
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)
1555 *ioSize =
sizeof(UInt32);
1557#if DSPARK_AU_HAVE_MIDI2
1558 case kAudioUnitProperty_AudioUnitMIDIProtocol:
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);
1568 case kAudioUnitProperty_PresentPreset:
1569 case kAudioUnitProperty_CurrentPreset:
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);
1578 case kAudioUnitProperty_ClassInfo:
1580 if (*ioSize <
sizeof(CFPropertyListRef))
1581 return kAudioUnitErr_InvalidPropertyValue;
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);
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);
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));
1611 CFStringRef nameVal = copyPresetName();
1612 CFDictionarySetValue(dict, CFSTR(
"name"), nameVal);
1614 CFDataRef data = CFDataCreate(
nullptr, blob.data(),
1615 static_cast<CFIndex
>(blob.size()));
1616 CFDictionarySetValue(dict, CFSTR(
"dspark-state"), data);
1619 *
static_cast<CFPropertyListRef*
>(outData) = dict;
1620 *ioSize =
sizeof(CFPropertyListRef);
1623#if defined(DSPARK_PLUGIN_WEBVIEW)
1624 case kAudioUnitProperty_CocoaUI:
1626 if constexpr (!kHasWebEditor)
return kAudioUnitErr_InvalidProperty;
1627 if (*ioSize <
sizeof(AudioUnitCocoaViewInfo))
1628 return kAudioUnitErr_InvalidPropertyValue;
1629 Class factory = editorFactoryClass();
1630 CFURLRef url = copyOwningBundleUrl();
1631 if (factory ==
nullptr || url ==
nullptr)
1633 if (url !=
nullptr) CFRelease(url);
1634 return kAudioUnitErr_InvalidProperty;
1636 auto* viewInfo =
static_cast<AudioUnitCocoaViewInfo*
>(outData);
1637 viewInfo->mCocoaAUViewBundleLocation = url;
1638 viewInfo->mCocoaAUViewClass[0] = CFStringCreateWithCString(
1639 nullptr, class_getName(factory), kCFStringEncodingUTF8);
1640 *ioSize =
sizeof(AudioUnitCocoaViewInfo);
1643 case kDsparkEditorHookProperty:
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);
1654 return kAudioUnitErr_InvalidProperty;
1658 OSStatus setProperty(AudioUnitPropertyID
id, AudioUnitScope scope,
1659 AudioUnitElement element,
const void* inData,
1660 UInt32 inSize)
noexcept
1664 case kAudioUnitProperty_StreamFormat:
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;
1676 if (HasSidechain<P> && scope == kAudioUnitScope_Input && element == 1)
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;
1690 && (f->mSampleRate != sampleRate
1691 ||
static_cast<int>(f->mChannelsPerFrame) != currentChannels))
1692 return kAudioUnitErr_PropertyNotWritable;
1693 sampleRate = f->mSampleRate;
1696 currentChannels =
static_cast<int>(f->mChannelsPerFrame);
1699 case kAudioUnitProperty_SampleRate:
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;
1705 if (initialized && rate != sampleRate)
1706 return kAudioUnitErr_PropertyNotWritable;
1710 case kAudioUnitProperty_MaximumFramesPerSlice:
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;
1723 if (initialized)
return kAudioUnitErr_Initialized;
1725 notifyProperty(
id, scope, element);
1728 case kAudioUnitProperty_PresentPreset:
1729 case kAudioUnitProperty_CurrentPreset:
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)
1737 if (
preset->presetNumber >= kNumPresets)
1738 return kAudioUnitErr_InvalidPropertyValue;
1739 applyFactoryPresetIdx(
preset->presetNumber);
1741 notifyAllParameters();
1742 if (presetName !=
nullptr) CFRelease(presetName);
1743 presetName =
preset->presetName !=
nullptr
1744 ?
static_cast<CFStringRef
>(CFRetain(
preset->presetName))
1745 : CFStringCreateWithCString(
1747 [&]() -> const char* {
1748 if constexpr (kNumPresets > 0)
1749 return P::factoryPresets[
static_cast<size_t>(
1750 preset->presetNumber)].name;
1754 kCFStringEncodingUTF8);
1755 notifyProperty(
id, scope, element);
1758 currentPresetNumber = -1;
1759 if (presetName !=
nullptr) CFRelease(presetName);
1760 presetName =
preset->presetName !=
nullptr
1761 ?
static_cast<CFStringRef
>(CFRetain(
preset->presetName))
1763 notifyProperty(
id, scope, element);
1766 case kAudioUnitProperty_HostCallbacks:
1768 if (inData ==
nullptr)
return kAudioUnitErr_InvalidPropertyValue;
1770 std::memset(&hostCallbacks, 0,
sizeof(hostCallbacks));
1771 std::memcpy(&hostCallbacks, inData,
1772 inSize <
sizeof(hostCallbacks) ? inSize
1773 : sizeof(hostCallbacks));
1776 case kAudioUnitProperty_ShouldAllocateBuffer:
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;
1790 allocateOutput = allocate;
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);
1800 case kAudioUnitProperty_BypassEffect:
1801 if (inData ==
nullptr || inSize <
sizeof(UInt32))
1802 return kAudioUnitErr_InvalidPropertyValue;
1806 if (setBypass(*
static_cast<const UInt32*
>(inData) != 0))
1807 notifyParameterChanged(kBypassParamId);
1809 case kAudioUnitProperty_SetRenderCallback:
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;
1822 case kAudioUnitProperty_MakeConnection:
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] = {};
1835 case kAudioUnitProperty_ClassInfo:
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);
1847 auto numberIs = [&](CFStringRef key, OSType expected) {
1848 auto number =
static_cast<CFNumberRef
>(CFDictionaryGetValue(dict, key));
1849 if (number ==
nullptr)
return true;
1851 return CFGetTypeID(number) == CFNumberGetTypeID()
1852 && CFNumberGetValue(number, kCFNumberSInt32Type, &value)
1853 &&
static_cast<OSType
>(value) == expected;
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())
1865 loadDefaultNormalized<P>(norm);
1867 int bypassState = -1;
1868 EditorSize editorSize { 0, 0 };
1870 CFDataGetBytePtr(data),
1871 static_cast<size_t>(CFDataGetLength(data)), norm,
1872 &program, &bypassState, &editorSize))
1875 applyFromAnyThread(
static_cast<int>(i), norm[i]);
1876 currentPresetNumber =
1877 kNumPresets > 0 && program >= 0 && program < kNumPresets ? program : -1;
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)
1887 editorMemory.remember(editorSize.width, editorSize.height);
1888#if defined(DSPARK_PLUGIN_WEBVIEW)
1889 applyRememberedEditorSize();
1893 notifyAllParameters();
1894 notifyProperty(kAudioUnitProperty_PresentPreset, kAudioUnitScope_Global, 0);
1899 return kAudioUnitErr_InvalidProperty;
1905 OSStatus getParameter(AudioUnitParameterID
id, AudioUnitScope scope,
1906 AudioUnitParameterValue* outValue)
noexcept
1908 if (scope != kAudioUnitScope_Global || outValue ==
nullptr)
1909 return kAudioUnitErr_InvalidParameter;
1910 if (
id == kBypassParamId)
1912 *outValue = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
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)));
1923 OSStatus setParameter(AudioUnitParameterID
id, AudioUnitScope scope,
1924 AudioUnitParameterValue value)
noexcept
1926 if (scope != kAudioUnitScope_Global)
return kAudioUnitErr_InvalidParameter;
1930 if (!std::isfinite(value))
return kAudioUnitErr_InvalidParameterValue;
1931 if (
id == kBypassParamId)
1933 if (setBypass(value >= 0.5f)) announce(kNotifyBypass);
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)))
1947 OSStatus pushMidi(UInt32 status, UInt32 data1, UInt32 data2,
1948 UInt32 offsetFrame)
noexcept
1950 if constexpr (HasMidi<P>)
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)
1960 ev.type = d2 > 0 ? MidiEvent::Type::NoteOn : MidiEvent::Type::NoteOff;
1962 ev.value =
static_cast<float>(d2) / 127.0f;
1965 ev.type = MidiEvent::Type::NoteOff;
1967 ev.value =
static_cast<float>(d2) / 127.0f;
1970 ev.type = MidiEvent::Type::PolyPressure;
1972 ev.value =
static_cast<float>(d2) / 127.0f;
1975 ev.type = MidiEvent::Type::ControlChange;
1977 ev.value =
static_cast<float>(d2) / 127.0f;
1980 ev.type = MidiEvent::Type::ChannelPressure;
1981 ev.value =
static_cast<float>(d1) / 127.0f;
1984 ev.type = MidiEvent::Type::PitchBend;
1985 ev.value = (
static_cast<float>((d2 << 7) | d1) - 8192.0f) / 8192.0f;
1990 (void) queueMidi(ev);
1999 return kAudioUnitErr_InvalidProperty;
2006 bool queueMidi(
const MidiEvent& ev)
noexcept
2008 constexpr uint32_t mask = kMidiRingSize - 1;
2009 uint32_t position = midiEnqueue.load(std::memory_order_relaxed);
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);
2017 if (midiEnqueue.compare_exchange_weak(position, position + 1,
2018 std::memory_order_relaxed))
2021 cell.seq.store(position + 1, std::memory_order_release);
2028 position = midiEnqueue.load(std::memory_order_relaxed);
2032#if DSPARK_AU_HAVE_MIDI2
2040 void queueMidi2(UInt32 status, UInt32 index, UInt32 data, UInt32 offsetFrame)
noexcept
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)
2050 ev.type = MidiEvent::Type::NoteOn;
2051 ev.value =
static_cast<float>((data >> 16) / 65535.0);
2054 ev.type = MidiEvent::Type::NoteOff;
2055 ev.value =
static_cast<float>((data >> 16) / 65535.0);
2058 ev.type = MidiEvent::Type::PolyPressure;
2059 ev.value =
static_cast<float>(data / k32);
2062 ev.type = MidiEvent::Type::ControlChange;
2063 ev.value =
static_cast<float>(data / k32);
2066 ev.type = MidiEvent::Type::ChannelPressure;
2068 ev.value =
static_cast<float>(data / k32);
2071 ev.type = MidiEvent::Type::PitchBend;
2073 ev.value =
static_cast<float>((
static_cast<double>(data) - 2147483648.0)
2079 (void) queueMidi(ev);
2089 OSStatus pushEventList(UInt32 offsetFrame,
const MIDIEventList* list)
noexcept
2091 if constexpr (HasMidi<P>)
2093 if (list ==
nullptr)
return kAudio_ParamError;
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)
2100 const UInt32 count = packet->wordCount;
2101 if (count > 64)
break;
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;)
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;
2113 const UInt32 status = (word >> 16) & 0xFFu;
2114 const UInt32 index = (word >> 8) & 0xFFu;
2116 (void) pushMidi(status, index, word & 0xFFu, offset);
2117 else if (type == 0x4u)
2118 queueMidi2(status, index, packet->words[w + 1], offset);
2121 packet =
reinterpret_cast<const MIDIEventPacket*
>(packet->words + count);
2129 return kAudioUnitErr_InvalidProperty;
2135 void forwardTransport() noexcept
2137 if constexpr (HasTransport<P>)
2139 TransportInfo info {};
2141 if (hostCallbacks.beatAndTempoProc !=
nullptr)
2143 Float64 beat = 0.0, tempo = 0.0;
2144 if (hostCallbacks.beatAndTempoProc(hostCallbacks.hostUserData,
2145 &beat, &tempo) == noErr)
2149 info.tempoBpm = tempo;
2150 info.tempoValid =
true;
2152 info.ppqPosition = beat;
2153 info.positionValid =
true;
2157 if (hostCallbacks.musicalTimeLocationProc !=
nullptr)
2159 UInt32 deltaToNextBeat = 0;
2162 Float64 downbeat = 0.0;
2163 if (hostCallbacks.musicalTimeLocationProc(
2164 hostCallbacks.hostUserData, &deltaToNextBeat, &num, &den,
2165 &downbeat) == noErr)
2177 info.timeSigDenominator =
static_cast<int>(den);
2178 info.timeSigValid =
true;
2179 info.barStartPpq = downbeat;
2183 if (hostCallbacks.transportStateProc !=
nullptr)
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)
2191 info.playing = isPlaying;
2192 info.looping = isCycling;
2193 info.loopStartPpq = cycleStart;
2194 info.loopEndPpq = cycleEnd;
2195 info.loopValid = isCycling;
2200 user.setTransport(info);
2209 OSStatus pullInput(UInt32 element,
float* dst[2],
2210 const AudioTimeStamp* timeStamp, UInt32 frames)
noexcept
2216 struct StereoBufferList
2218 UInt32 mNumberBuffers;
2219 ::AudioBuffer mBuffers[2];
2222 const UInt32 elementWidth = element == 1 && sidechainChannels != 0
2224 :
static_cast<UInt32
>(currentChannels);
2225 const UInt32 width = elementWidth < 2u ? elementWidth : 2u;
2228 const bool lendBuffers = allocateInput[element < 2u ? element : 0u];
2229 list.mNumberBuffers = width;
2230 for (UInt32 ch = 0; ch < width; ++ch)
2232 list.mBuffers[ch].mNumberChannels = 1;
2233 list.mBuffers[ch].mDataByteSize = frames *
sizeof(float);
2234 list.mBuffers[ch].mData = lendBuffers ? dst[ch] :
nullptr;
2236 auto* abl =
reinterpret_cast<AudioBufferList*
>(&list);
2237 OSStatus status = noErr;
2238 AudioUnitRenderActionFlags flags = 0;
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);
2249 if (status != noErr)
return status;
2250 for (UInt32 ch = 0; ch < width; ++ch)
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));
2259 if (width == 1 && currentChannels > 1)
2272 void expandRamps(
int frames)
noexcept
2274 for (
int r = 0; r < rampCount; ++r)
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;
2288 auto push = [&](
long long offset) {
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);
2296 long long first = start > 0 ? start : 0;
2297 if (first >= frames)
continue;
2299 for (
long long q = (first / kAutomationQuantum + 1) * kAutomationQuantum;
2302 if (end > first && end < frames && end % kAutomationQuantum != 0)
2310 void blendBypass(
float*
const* out,
float*
const* dry, UInt32 outCh,
int start,
2311 int length)
noexcept
2313 const float target = bypass.load(std::memory_order_relaxed) ? 1.0f : 0.0f;
2314 if (bypassMix == target && target == 0.0f)
return;
2316 float mix = bypassMix;
2317 for (
int i = 0; i < length; ++i)
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;
2337 OSStatus render(AudioUnitRenderActionFlags* ioFlags,
2338 const AudioTimeStamp* timeStamp, UInt32 busNumber,
2339 UInt32 frames, AudioBufferList* ioData)
noexcept
2341 auto refuseEarly = [&](OSStatus error)
noexcept {
2343 recordRenderError(error);
2346 if (ioData ==
nullptr)
return refuseEarly(kAudio_ParamError);
2349 if (busNumber != 0)
return refuseEarly(kAudioUnitErr_InvalidElement);
2350 if (!initialized)
return refuseEarly(kAudioUnitErr_Uninitialized);
2357 applyNotifyCommands();
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 {
2365 recordRenderError(error);
2366 callRenderNotifies(flags | kPost | kError, timeStamp, busNumber, frames, ioData);
2372 if (frames > maxFrames || frames > dryL.size())
2373 return refuse(kAudioUnitErr_TooManyFramesToProcess);
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);
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);
2392 callRenderNotifies(flags | kPre, timeStamp, busNumber, frames, ioData);
2393 OSStatus status = noErr;
2397 status = renderSlice(timeStamp, frames, ioData);
2398 recordRenderError(status);
2399 callRenderNotifies(flags | kPost | (status != noErr ? kError : Flags { 0 }),
2400 timeStamp, busNumber, frames, ioData);
2405 OSStatus renderSlice(
const AudioTimeStamp* timeStamp, UInt32 frames,
2406 AudioBufferList* ioData)
noexcept
2410 renderThread.store(std::this_thread::get_id(), std::memory_order_relaxed);
2411 bool paramsChanged = drainPending();
2412 bool bypassChanged =
false;
2419 expandRamps(
static_cast<int>(frames));
2420 if constexpr (HasMidi<P>)
2424 constexpr uint32_t mask = kMidiRingSize - 1;
2425 const uint32_t discardBefore = midiDiscardBefore.load(std::memory_order_acquire);
2426 uint32_t position = midiDequeue;
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);
2434 if (
static_cast<int32_t
>(position - discardBefore) >= 0)
2437 ev.kind = BlockEvent::Kind::Midi;
2439 ev.offset = midi.sampleOffset;
2440 blockEvents.add(ev);
2444 midiDequeue = position;
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);
2452 BlockEventList& events = blockEvents;
2453 for (
int i = 0; i < events.size(); ++i)
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;
2460 const int eventCount = events.size();
2462 auto applyEvent = [&](
const BlockEvent& ev,
int blockStart)
noexcept ->
bool {
2465 case BlockEvent::Kind::Bypass:
2466 bypassChanged |= setBypass(ev.value >= 0.5);
2468 case BlockEvent::Kind::Midi:
2469 if constexpr (HasMidi<P>)
2471 MidiEvent midi = ev.midi;
2472 midi.sampleOffset = ev.offset - blockStart;
2473 if (midi.sampleOffset < 0) midi.sampleOffset = 0;
2474 user.handleMidiEvent(midi);
2477 case BlockEvent::Kind::Param:
2479 if (
const int idx = indexOfParamId(ev.paramId); idx >= 0)
2481 applyNormalized(idx, ev.value);
2487 auto finish = [&]()
noexcept {
2489 if (paramsChanged) refreshReported();
2490 if (bypassChanged) announce(kNotifyBypass);
2493 const UInt32 width =
static_cast<UInt32
>(currentChannels);
2494 const UInt32 outCh = ioData->mNumberBuffers < width
2495 ? ioData->mNumberBuffers : width;
2498 for (
int i = 0; i < eventCount; ++i)
2499 paramsChanged |= applyEvent(events[i], events[i].offset);
2507 float* pull[2] = { pullL.data(), pullR.data() };
2514 pull[0] =
static_cast<float*
>(ioData->mBuffers[0].mData);
2515 pull[1] = outCh > 1 ?
static_cast<float*
>(ioData->mBuffers[1].mData) : pull[0];
2517 if constexpr (!kIsInstrument)
2519 const OSStatus pullStatus = pullInput(0, pull, timeStamp, frames);
2520 if (pullStatus != noErr)
2522 for (
int i = 0; i < eventCount; ++i)
2523 paramsChanged |= applyEvent(events[i], events[i].offset);
2529 float* out[2] = {
nullptr,
nullptr };
2530 for (UInt32 ch = 0; ch < outCh; ++ch)
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);
2540 float* dry[2] = { dryL.data(), dryR.data() };
2541 for (UInt32 ch = 0; ch < outCh; ++ch)
2545 std::memset(out[ch], 0, frames *
sizeof(
float));
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));
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));
2558 float* sc[2] = {
nullptr,
nullptr };
2559 if constexpr (HasSidechain<P>)
2563 if (pullInput(1, sc, timeStamp, frames) != noErr)
2567 std::memset(sc[0], 0, frames *
sizeof(
float));
2568 std::memset(sc[1], 0, frames *
sizeof(
float));
2574 auto processSegment = [&](
int start,
int length)
noexcept {
2575 float* sub[2] = { out[0] + start,
2576 outCh > 1 ? out[1] + start : out[0] + start };
2579 if constexpr (HasSidechain<P>)
2582 float* scSub[2] = { sc[0] + start, sc[1] + start };
2584 static_cast<int>(outCh), length);
2585 user.processBlock(view, scView);
2588 user.processBlock(view);
2592 blendBypass(out, dry, outCh, start, length);
2595 const int total =
static_cast<int>(frames);
2597 if (!sampleAccurateOf<P>())
2599 for (; evIdx < eventCount; ++evIdx)
2600 paramsChanged |= applyEvent(events[evIdx], 0);
2601 processSegment(0, total);
2608 while (evIdx < eventCount
2609 && (events[evIdx].offset / kAutomationQuantum)
2610 * kAutomationQuantum <= pos)
2611 paramsChanged |= applyEvent(events[evIdx++], pos);
2613 if (evIdx < eventCount)
2616 * kAutomationQuantum;
2617 if (snapped < next) next = snapped;
2621 processSegment(pos, next - pos);
2624 for (; evIdx < eventCount; ++evIdx)
2625 paramsChanged |= applyEvent(events[evIdx], total);
2635template <
typename P>
2638 AudioComponentPlugInInterface iface {};
2639 Plugin<P>* state =
nullptr;
2641 static Component* fromSelf(
void* self)
noexcept
2643 return static_cast<Component*
>(self);
2646 static OSStatus sOpen(
void* self, AudioComponentInstance instance)
noexcept
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;
2657 static OSStatus sClose(
void* self)
noexcept
2659 auto* c = fromSelf(self);
2667 static OSStatus sInitialize(
void* self)
noexcept
2668 {
return fromSelf(self)->state->initialize(); }
2670 static OSStatus sUninitialize(
void* self)
noexcept
2671 {
return fromSelf(self)->state->uninitialize(); }
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); }
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); }
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); }
2688 static OSStatus sGetParameter(
void* self, AudioUnitParameterID
id,
2689 AudioUnitScope scope, AudioUnitElement element,
2690 AudioUnitParameterValue* outValue)
noexcept
2693 return fromSelf(self)->state->getParameter(
id, scope, outValue);
2696 static OSStatus sSetParameter(
void* self, AudioUnitParameterID
id,
2697 AudioUnitScope scope, AudioUnitElement element,
2698 AudioUnitParameterValue value,
2699 UInt32 bufferOffset)
noexcept
2702 (void) bufferOffset;
2703 return fromSelf(self)->state->setParameter(
id, scope, value);
2706 static OSStatus sReset(
void* self, AudioUnitScope scope,
2707 AudioUnitElement element)
noexcept
2711 return fromSelf(self)->state->reset();
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); }
2719 static OSStatus sAddPropertyListener(
void* self, AudioUnitPropertyID
id,
2720 AudioUnitPropertyListenerProc proc,
2721 void* user)
noexcept
2723 auto* state = fromSelf(self)->state;
2724 state->listeners.push_back({ id, proc, user });
2728 static OSStatus sRemovePropertyListener(
void* self, AudioUnitPropertyID
id,
2729 AudioUnitPropertyListenerProc proc)
noexcept
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));
2738 static OSStatus sRemovePropertyListenerWithUserData(
void* self, AudioUnitPropertyID
id,
2739 AudioUnitPropertyListenerProc proc,
2740 void* user)
noexcept
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));
2752 static OSStatus sAddRenderNotify(
void* self, AURenderCallback proc,
void* refCon)
noexcept
2753 {
return fromSelf(self)->state->queueRenderNotify(proc, refCon,
true); }
2755 static OSStatus sRemoveRenderNotify(
void* self, AURenderCallback proc,
void* refCon)
noexcept
2756 {
return fromSelf(self)->state->queueRenderNotify(proc, refCon,
false); }
2763 static OSStatus sScheduleParameters(
void* self,
2764 const AudioUnitParameterEvent* events,
2765 UInt32 numEvents)
noexcept
2767 auto* state = fromSelf(self)->state;
2770 for (UInt32 i = 0; events !=
nullptr && i < numEvents; ++i)
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;
2784 auto push = [&](AudioUnitParameterID id,
float plain, SInt32 offset,
bool immediate) {
2786 ev.offset = offset < 0 ? 0 : offset;
2787 if (
id == kBypassParamId)
2789 ev.kind = BlockEvent::Kind::Bypass;
2791 ev.value = plain >= 0.5f ? 1.0 : 0.0;
2795 const int idx = Plugin<P>::indexOfParamId(
id);
2796 if (idx < 0)
return;
2797 ev.kind = BlockEvent::Kind::Param;
2799 ev.value =
toNormalized(P::parameters[
static_cast<size_t>(idx)], plain);
2803 state->shadow[
static_cast<size_t>(idx)].store(ev.value,
2804 std::memory_order_relaxed);
2806 state->blockEvents.add(ev);
2808 for (UInt32 i = 0; events !=
nullptr && i < numEvents; ++i)
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)
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 };
2824 push(ev.parameter, ev.eventValues.ramp.endValue,
2825 ev.eventValues.ramp.startBufferOffset
2826 +
static_cast<SInt32
>(ev.eventValues.ramp.durationInFrames),
2835 static OSStatus sMidiEvent(
void* self, UInt32 status, UInt32 data1,
2836 UInt32 data2, UInt32 offsetSampleFrame)
noexcept
2838 return fromSelf(self)->state->pushMidi(status, data1, data2,
2842 static OSStatus sSysEx(
void* self,
const UInt8*, UInt32)
noexcept
2848#if DSPARK_AU_HAVE_MIDI2
2852 static OSStatus sMidiEventList(
void* self, UInt32 offsetSampleFrame,
2853 const MIDIEventList* list)
noexcept
2855 return fromSelf(self)->state->pushEventList(offsetSampleFrame, list);
2859 static AudioComponentMethod sLookup(SInt16 selector)
noexcept
2861 if constexpr (HasMidi<P>)
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);
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);
2909 inline static OSType gSubtype = 0;
2910 inline static OSType gManufacturer = 0;
2912 static void* factory(
const AudioComponentDescription* desc)
noexcept
2916 if (desc !=
nullptr && desc->componentType != Plugin<P>::expectedType())
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;
2936#define DSPARK_AU_PLUGIN(PluginClass, subtype4, manufacturer4) \
2937 extern "C" __attribute__((visibility("default"))) \
2938 void* DSParkAuFactory(const AudioComponentDescription* desc) \
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); \
2946#pragma pop_macro("max")
2947#pragma pop_macro("min")
2952#define DSPARK_AU_PLUGIN(PluginClass, subtype4, manufacturer4)
Non-owning view over audio channel data.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
constexpr int kBypassRampSamples
constexpr uint32_t kBypassParamId
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).
Param
Every parameter, in the order of the parameter table.
Describes the audio environment for a DSP processor.