The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

734 lines
27KB

  1. /*!
  2. @file AudioUnitSDK/AUBase.h
  3. @copyright © 2000-2021 Apple Inc. All rights reserved.
  4. */
  5. #ifndef AudioUnitSDK_AUBase_h
  6. #define AudioUnitSDK_AUBase_h
  7. // module
  8. #include <AudioUnitSDK/AUBuffer.h>
  9. #include <AudioUnitSDK/AUInputElement.h>
  10. #include <AudioUnitSDK/AUMIDIUtility.h>
  11. #include <AudioUnitSDK/AUOutputElement.h>
  12. #include <AudioUnitSDK/AUPlugInDispatch.h>
  13. #include <AudioUnitSDK/AUScopeElement.h>
  14. #include <AudioUnitSDK/AUUtility.h>
  15. // OS
  16. #include <TargetConditionals.h>
  17. // std
  18. #include <algorithm>
  19. #include <array>
  20. #include <memory>
  21. #include <mutex>
  22. #include <thread>
  23. #include <vector>
  24. // ________________________________________________________________________
  25. namespace ausdk {
  26. /*!
  27. @class AUBase
  28. @brief Abstract base class for an Audio Unit implementation.
  29. */
  30. class AUBase : public ComponentBase {
  31. public:
  32. constexpr static double kAUDefaultSampleRate = 44100.0;
  33. #if !TARGET_OS_WIN32
  34. constexpr static UInt32 kAUDefaultMaxFramesPerSlice = 1156;
  35. // this allows enough default frames for a 512 dest 44K and SRC from 96K
  36. // add a padding of 4 frames for any vector rounding
  37. #else
  38. constexpr static UInt32 kAUDefaultMaxFramesPerSlice = 2048;
  39. #endif
  40. AUBase(AudioComponentInstance inInstance, UInt32 numInputElements, UInt32 numOutputElements,
  41. UInt32 numGroupElements = 0);
  42. ~AUBase() override;
  43. AUBase(const AUBase&) = delete;
  44. AUBase(AUBase&&) = delete;
  45. AUBase& operator=(const AUBase&) = delete;
  46. AUBase& operator=(AUBase&&) = delete;
  47. /// Called immediately after construction, when virtual methods work. Or, a subclass may call
  48. /// this in order to have access to elements in its constructor.
  49. void CreateElements();
  50. virtual void CreateExtendedElements() {}
  51. #pragma mark -
  52. #pragma mark AU dispatch
  53. // ________________________________________________________________________
  54. // Virtual methods (mostly) directly corresponding to the entry points. Many of these
  55. // have useful implementations here and will not need overriding.
  56. /// Implements the entry point and ensures that Initialize is called exactly once from an
  57. /// uninitialized state.
  58. OSStatus DoInitialize();
  59. // Overrides to this method can assume that they will only be called exactly once
  60. // when transitioning from an uninitialized state.
  61. virtual OSStatus Initialize();
  62. [[nodiscard]] bool IsInitialized() const noexcept { return mInitialized; }
  63. [[nodiscard]] bool HasBegunInitializing() const noexcept { return mHasBegunInitializing; }
  64. /// Implements the entry point and ensures that Cleanup is called exactly once from an
  65. /// initialized state.
  66. void DoCleanup();
  67. // Overrides to this method can assume that they will only be called exactly once
  68. // when transitioning from an initialized state to an uninitialized state.
  69. virtual void Cleanup();
  70. virtual OSStatus Reset(AudioUnitScope inScope, AudioUnitElement inElement);
  71. // Note about GetPropertyInfo, GetProperty, SetProperty:
  72. // Certain properties are trapped out in these dispatch functions and handled with different
  73. // virtual methods. (To discourage hacks and keep vtable size down, these are non-virtual)
  74. OSStatus DispatchGetPropertyInfo(AudioUnitPropertyID inID, AudioUnitScope inScope,
  75. AudioUnitElement inElement, UInt32& outDataSize, bool& outWritable);
  76. OSStatus DispatchGetProperty(AudioUnitPropertyID inID, AudioUnitScope inScope,
  77. AudioUnitElement inElement, void* outData);
  78. OSStatus DispatchSetProperty(AudioUnitPropertyID inID, AudioUnitScope inScope,
  79. AudioUnitElement inElement, const void* inData, UInt32 inDataSize);
  80. OSStatus DispatchRemovePropertyValue(
  81. AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement);
  82. virtual OSStatus GetPropertyInfo(AudioUnitPropertyID inID, AudioUnitScope inScope,
  83. AudioUnitElement inElement, UInt32& outDataSize, bool& outWritable);
  84. virtual OSStatus GetProperty(AudioUnitPropertyID inID, AudioUnitScope inScope,
  85. AudioUnitElement inElement, void* outData);
  86. virtual OSStatus SetProperty(AudioUnitPropertyID inID, AudioUnitScope inScope,
  87. AudioUnitElement inElement, const void* inData, UInt32 inDataSize);
  88. virtual OSStatus RemovePropertyValue(
  89. AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement);
  90. virtual OSStatus AddPropertyListener(
  91. AudioUnitPropertyID inID, AudioUnitPropertyListenerProc inProc, void* inProcRefCon);
  92. virtual OSStatus RemovePropertyListener(AudioUnitPropertyID inID,
  93. AudioUnitPropertyListenerProc inProc, void* inProcRefCon, bool refConSpecified);
  94. virtual OSStatus SetRenderNotification(AURenderCallback inProc, void* inRefCon);
  95. virtual OSStatus RemoveRenderNotification(AURenderCallback inProc, void* inRefCon);
  96. virtual OSStatus GetParameter(AudioUnitParameterID inID, AudioUnitScope inScope,
  97. AudioUnitElement inElement, AudioUnitParameterValue& outValue);
  98. virtual OSStatus SetParameter(AudioUnitParameterID inID, AudioUnitScope inScope,
  99. AudioUnitElement inElement, AudioUnitParameterValue inValue, UInt32 inBufferOffsetInFrames);
  100. [[nodiscard]] virtual bool CanScheduleParameters() const = 0;
  101. virtual OSStatus ScheduleParameter(
  102. const AudioUnitParameterEvent* inParameterEvent, UInt32 inNumEvents);
  103. OSStatus DoRender(AudioUnitRenderActionFlags& ioActionFlags, const AudioTimeStamp& inTimeStamp,
  104. UInt32 inBusNumber, UInt32 inFramesToProcess, AudioBufferList& ioData);
  105. OSStatus DoProcess(AudioUnitRenderActionFlags& ioActionFlags, const AudioTimeStamp& inTimeStamp,
  106. UInt32 inFramesToProcess, AudioBufferList& ioData);
  107. OSStatus DoProcessMultiple(AudioUnitRenderActionFlags& ioActionFlags,
  108. const AudioTimeStamp& inTimeStamp, UInt32 inFramesToProcess,
  109. UInt32 inNumberInputBufferLists, const AudioBufferList** inInputBufferLists,
  110. UInt32 inNumberOutputBufferLists, AudioBufferList** ioOutputBufferLists);
  111. virtual OSStatus ProcessBufferLists(AudioUnitRenderActionFlags& /*ioActionFlags*/,
  112. const AudioBufferList& /*inBuffer*/, AudioBufferList& /*outBuffer*/,
  113. UInt32 /*inFramesToProcess*/)
  114. {
  115. return kAudio_UnimplementedError;
  116. }
  117. virtual OSStatus ProcessMultipleBufferLists(AudioUnitRenderActionFlags& /*ioActionFlags*/,
  118. UInt32 /*inFramesToProcess*/, UInt32 /*inNumberInputBufferLists*/,
  119. const AudioBufferList** /*inInputBufferLists*/, UInt32 /*inNumberOutputBufferLists*/,
  120. AudioBufferList** /*ioOutputBufferLists*/)
  121. {
  122. return kAudio_UnimplementedError;
  123. }
  124. virtual OSStatus ComplexRender(AudioUnitRenderActionFlags& /*ioActionFlags*/,
  125. const AudioTimeStamp& /*inTimeStamp*/, UInt32 /*inOutputBusNumber*/,
  126. UInt32 /*inNumberOfPackets*/, UInt32* /*outNumberOfPackets*/,
  127. AudioStreamPacketDescription* /*outPacketDescriptions*/, AudioBufferList& /*ioData*/,
  128. void* /*outMetadata*/, UInt32* /*outMetadataByteSize*/)
  129. {
  130. return kAudio_UnimplementedError;
  131. }
  132. // Override this method if your AU processes multiple output busses completely independently --
  133. // you'll want to just call Render without the NeedsToRender check.
  134. // Otherwise, override Render().
  135. //
  136. // N.B. Implementations of this method can assume that the output's buffer list has already been
  137. // prepared and access it with GetOutput(inBusNumber)->GetBufferList() instead of
  138. // GetOutput(inBusNumber)->PrepareBuffer(nFrames) -- if PrepareBuffer is called, a
  139. // copy may occur after rendering.
  140. virtual OSStatus RenderBus(AudioUnitRenderActionFlags& ioActionFlags,
  141. const AudioTimeStamp& inTimeStamp, UInt32 /*inBusNumber*/, UInt32 inNumberFrames)
  142. {
  143. if (NeedsToRender(inTimeStamp)) {
  144. return Render(ioActionFlags, inTimeStamp, inNumberFrames);
  145. }
  146. return noErr; // was presumably already rendered via another bus
  147. }
  148. // N.B. For a unit with only one output bus, it can assume in its implementation of this
  149. // method that the output's buffer list has already been prepared and access it with
  150. // GetOutput(0)->GetBufferList() instead of GetOutput(0)->PrepareBuffer(nFrames)
  151. // -- if PrepareBuffer is called, a copy may occur after rendering.
  152. virtual OSStatus Render(AudioUnitRenderActionFlags& /*ioActionFlags*/,
  153. const AudioTimeStamp& /*inTimeStamp*/, UInt32 /*inNumberFrames*/)
  154. {
  155. return noErr;
  156. }
  157. #pragma mark -
  158. #pragma mark Property Dispatch
  159. // ________________________________________________________________________
  160. // These are called from DispatchGetProperty/DispatchGetPropertyInfo/DispatchSetProperty
  161. virtual bool BusCountWritable(AudioUnitScope /*inScope*/) { return false; }
  162. virtual OSStatus SetBusCount(AudioUnitScope inScope, UInt32 inCount);
  163. virtual OSStatus SetConnection(const AudioUnitConnection& inConnection);
  164. virtual OSStatus SetInputCallback(
  165. UInt32 inPropertyID, AudioUnitElement inElement, AURenderCallback inProc, void* inRefCon);
  166. virtual OSStatus GetParameterList(
  167. AudioUnitScope inScope, AudioUnitParameterID* outParameterList, UInt32& outNumParameters);
  168. // outParameterList may be a null pointer
  169. virtual OSStatus GetParameterInfo(AudioUnitScope inScope, AudioUnitParameterID inParameterID,
  170. AudioUnitParameterInfo& outParameterInfo);
  171. virtual OSStatus GetParameterHistoryInfo(AudioUnitScope inScope,
  172. AudioUnitParameterID inParameterID, Float32& outUpdatesPerSecond,
  173. Float32& outHistoryDurationInSeconds);
  174. virtual OSStatus SaveState(CFPropertyListRef* outData);
  175. virtual void SaveExtendedScopes(CFMutableDataRef /*outData*/) {}
  176. virtual OSStatus RestoreState(CFPropertyListRef plist);
  177. virtual OSStatus GetParameterValueStrings(
  178. AudioUnitScope inScope, AudioUnitParameterID inParameterID, CFArrayRef* outStrings);
  179. virtual OSStatus CopyClumpName(AudioUnitScope inScope, UInt32 inClumpID,
  180. UInt32 inDesiredNameLength, CFStringRef* outClumpName);
  181. virtual OSStatus GetPresets(CFArrayRef* outData) const;
  182. /// Set the default preset for the unit. The number of the preset must be >= 0 and the name
  183. /// should be valid, or the preset will be rejected.
  184. bool SetAFactoryPresetAsCurrent(const AUPreset& inPreset);
  185. // Called when the host sets a new, valid preset.
  186. // If this is a valid preset, then the subclass sets its state to that preset
  187. // and returns noErr.
  188. // If not a valid preset, return an error, and the pre-existing preset is restored.
  189. virtual OSStatus NewFactoryPresetSet(const AUPreset& inNewFactoryPreset);
  190. virtual OSStatus NewCustomPresetSet(const AUPreset& inNewCustomPreset);
  191. virtual CFURLRef CopyIconLocation();
  192. // default is no latency, and unimplemented tail time
  193. virtual Float64 GetLatency() { return 0.0; }
  194. virtual Float64 GetTailTime() { return 0.0; }
  195. virtual bool SupportsTail() { return false; }
  196. // Stream formats: scope will always be input or output
  197. bool IsStreamFormatWritable(AudioUnitScope scope, AudioUnitElement element);
  198. virtual bool StreamFormatWritable(AudioUnitScope scope, AudioUnitElement element) = 0;
  199. // pass in a pointer to get the struct, and num channel infos
  200. // you can pass in NULL to just get the number
  201. // a return value of 0 (the default in AUBase) means the property is not supported...
  202. virtual UInt32 SupportedNumChannels(const AUChannelInfo** outInfo);
  203. /// Will only be called after StreamFormatWritable has succeeded. Default implementation
  204. /// requires non-interleaved native-endian 32-bit float, any sample rate, any number of
  205. /// channels; override when other formats are supported. A subclass's override can choose to
  206. /// always return true and trap invalid formats in ChangeStreamFormat.
  207. virtual bool ValidFormat(AudioUnitScope inScope, AudioUnitElement inElement,
  208. const AudioStreamBasicDescription& inNewFormat);
  209. virtual AudioStreamBasicDescription GetStreamFormat(
  210. AudioUnitScope inScope, AudioUnitElement inElement);
  211. // Will only be called after StreamFormatWritable
  212. // and ValidFormat have succeeded.
  213. virtual OSStatus ChangeStreamFormat(AudioUnitScope inScope, AudioUnitElement inElement,
  214. const AudioStreamBasicDescription& inPrevFormat,
  215. const AudioStreamBasicDescription& inNewFormat);
  216. // ________________________________________________________________________
  217. // Methods useful for subclasses
  218. AUScope& GetScope(AudioUnitScope inScope)
  219. {
  220. if (inScope >= kNumScopes) {
  221. AUScope* const scope = GetScopeExtended(inScope);
  222. ThrowQuietIf(scope == nullptr, kAudioUnitErr_InvalidScope);
  223. return *scope;
  224. }
  225. return mScopes[inScope]; // NOLINT
  226. }
  227. virtual AUScope* GetScopeExtended(AudioUnitScope /*inScope*/) { return nullptr; }
  228. AUScope& GlobalScope() { return mScopes[kAudioUnitScope_Global]; }
  229. AUScope& Inputs() { return mScopes[kAudioUnitScope_Input]; }
  230. AUScope& Outputs() { return mScopes[kAudioUnitScope_Output]; }
  231. AUScope& Groups() { return mScopes[kAudioUnitScope_Group]; }
  232. AUElement* Globals() { return mScopes[kAudioUnitScope_Global].GetElement(0); }
  233. void SetNumberOfElements(AudioUnitScope inScope, UInt32 numElements);
  234. virtual std::unique_ptr<AUElement> CreateElement(
  235. AudioUnitScope scope, AudioUnitElement element);
  236. AUElement* GetElement(AudioUnitScope inScope, AudioUnitElement inElement)
  237. {
  238. return GetScope(inScope).GetElement(inElement);
  239. }
  240. AUSDK_DEPRECATED("Use IOElement()")
  241. AUIOElement* GetIOElement(AudioUnitScope inScope, AudioUnitElement inElement)
  242. {
  243. return &IOElement(inScope, inElement);
  244. }
  245. AUIOElement& IOElement(AudioUnitScope inScope, AudioUnitElement inElement)
  246. {
  247. return *GetScope(inScope).GetIOElement(inElement);
  248. }
  249. AUSDK_DEPRECATED("Use Element()")
  250. AUElement* SafeGetElement(AudioUnitScope inScope, AudioUnitElement inElement)
  251. {
  252. return &Element(inScope, inElement);
  253. }
  254. AUElement& Element(AudioUnitScope inScope, AudioUnitElement inElement)
  255. {
  256. return *GetScope(inScope).SafeGetElement(inElement);
  257. }
  258. AUSDK_DEPRECATED("Use Input()")
  259. AUInputElement* GetInput(AudioUnitElement inElement) { return &Input(inElement); }
  260. AUInputElement& Input(AudioUnitElement inElement)
  261. {
  262. return static_cast<AUInputElement&>(*Inputs().SafeGetElement(inElement)); // NOLINT downcast
  263. }
  264. AUSDK_DEPRECATED("Use Output()")
  265. AUOutputElement* GetOutput(AudioUnitElement inElement) { return &Output(inElement); }
  266. AUOutputElement& Output(AudioUnitElement inElement)
  267. {
  268. return static_cast<AUOutputElement&>( // NOLINT downcast
  269. *Outputs().SafeGetElement(inElement));
  270. }
  271. AUSDK_DEPRECATED("Use Group()")
  272. AUElement* GetGroup(AudioUnitElement inElement) { return &Group(inElement); }
  273. AUElement& Group(AudioUnitElement inElement) { return *Groups().SafeGetElement(inElement); }
  274. OSStatus PullInput(UInt32 inBusNumber, AudioUnitRenderActionFlags& ioActionFlags,
  275. const AudioTimeStamp& inTimeStamp, UInt32 inNumberFrames)
  276. {
  277. AUInputElement& input = Input(inBusNumber); // throws if error
  278. return input.PullInput(ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames);
  279. }
  280. [[nodiscard]] UInt32 GetMaxFramesPerSlice() const noexcept { return mMaxFramesPerSlice; }
  281. [[nodiscard]] bool UsesFixedBlockSize() const noexcept { return mUsesFixedBlockSize; }
  282. void SetUsesFixedBlockSize(bool inUsesFixedBlockSize) noexcept
  283. {
  284. mUsesFixedBlockSize = inUsesFixedBlockSize;
  285. }
  286. [[nodiscard]] virtual bool InRenderThread() const
  287. {
  288. return std::this_thread::get_id() == mRenderThreadID;
  289. }
  290. /// Says whether an input is connected or has a callback.
  291. bool HasInput(AudioUnitElement inElement)
  292. {
  293. auto* const in =
  294. static_cast<AUInputElement*>(Inputs().GetElement(inElement)); // NOLINT downcast
  295. return in != nullptr && in->IsActive();
  296. }
  297. virtual void PropertyChanged(
  298. AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement);
  299. // These calls can be used to call a Host's Callbacks. The method returns -1 if the host
  300. // hasn't supplied the callback. Any other result is returned by the host.
  301. // As in the API contract, for a parameter's value, you specify a pointer
  302. // to that data type. Specify NULL for a parameter that you are not interested
  303. // as this can save work in the host.
  304. OSStatus CallHostBeatAndTempo(Float64* outCurrentBeat, Float64* outCurrentTempo) const
  305. {
  306. return (mHostCallbackInfo.beatAndTempoProc != nullptr
  307. ? (*mHostCallbackInfo.beatAndTempoProc)(
  308. mHostCallbackInfo.hostUserData, outCurrentBeat, outCurrentTempo)
  309. : -1);
  310. }
  311. OSStatus CallHostMusicalTimeLocation(UInt32* outDeltaSampleOffsetToNextBeat,
  312. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  313. Float64* outCurrentMeasureDownBeat) const
  314. {
  315. return (mHostCallbackInfo.musicalTimeLocationProc != nullptr
  316. ? (*mHostCallbackInfo.musicalTimeLocationProc)(mHostCallbackInfo.hostUserData,
  317. outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  318. outTimeSig_Denominator, outCurrentMeasureDownBeat)
  319. : -1);
  320. }
  321. OSStatus CallHostTransportState(Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  322. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling, Float64* outCycleStartBeat,
  323. Float64* outCycleEndBeat) const
  324. {
  325. return (mHostCallbackInfo.transportStateProc != nullptr
  326. ? (*mHostCallbackInfo.transportStateProc)(mHostCallbackInfo.hostUserData,
  327. outIsPlaying, outTransportStateChanged, outCurrentSampleInTimeLine,
  328. outIsCycling, outCycleStartBeat, outCycleEndBeat)
  329. : -1);
  330. }
  331. [[nodiscard]] const char* GetLoggingString() const noexcept;
  332. AUMutex* GetMutex() noexcept { return mAUMutex; }
  333. // The caller of SetMutex is responsible for the managing the lifetime of the
  334. // mutex object and, if deleted before the AUBase instance, is responsible
  335. // for calling SetMutex(nullptr)
  336. void SetMutex(AUMutex* mutex) noexcept { mAUMutex = mutex; }
  337. #pragma mark -
  338. #pragma mark AU Output Base Dispatch
  339. // ________________________________________________________________________
  340. // ________________________________________________________________________
  341. // ________________________________________________________________________
  342. // output unit methods
  343. virtual OSStatus Start() { return kAudio_UnimplementedError; }
  344. virtual OSStatus Stop() { return kAudio_UnimplementedError; }
  345. #pragma mark -
  346. #pragma mark AU Music Base Dispatch
  347. // ________________________________________________________________________
  348. // ________________________________________________________________________
  349. // ________________________________________________________________________
  350. // music device/music effect methods
  351. virtual OSStatus MIDIEvent(
  352. UInt32 /*inStatus*/, UInt32 /*inData1*/, UInt32 /*inData2*/, UInt32 /*inOffsetSampleFrame*/)
  353. {
  354. return kAudio_UnimplementedError;
  355. }
  356. virtual OSStatus SysEx(const UInt8* /*inData*/, UInt32 /*inLength*/)
  357. {
  358. return kAudio_UnimplementedError;
  359. }
  360. #if AUSDK_MIDI2_AVAILABLE
  361. virtual OSStatus MIDIEventList(
  362. UInt32 /*inOffsetSampleFrame*/, const MIDIEventList* /*eventList*/)
  363. {
  364. return kAudio_UnimplementedError;
  365. }
  366. #endif
  367. virtual OSStatus StartNote(MusicDeviceInstrumentID /*inInstrument*/,
  368. MusicDeviceGroupID /*inGroupID*/, NoteInstanceID* /*outNoteInstanceID*/,
  369. UInt32 /*inOffsetSampleFrame*/, const MusicDeviceNoteParams& /*inParams*/)
  370. {
  371. return kAudio_UnimplementedError;
  372. }
  373. virtual OSStatus StopNote(MusicDeviceGroupID /*inGroupID*/, NoteInstanceID /*inNoteInstanceID*/,
  374. UInt32 /*inOffsetSampleFrame*/)
  375. {
  376. return kAudio_UnimplementedError;
  377. }
  378. /// Obsolete
  379. static OSStatus PrepareInstrument(MusicDeviceInstrumentID /*inInstrument*/)
  380. {
  381. return kAudio_UnimplementedError;
  382. }
  383. /// Obsolete
  384. static OSStatus ReleaseInstrument(MusicDeviceInstrumentID /*inInstrument*/)
  385. {
  386. return kAudio_UnimplementedError;
  387. }
  388. // ________________________________________________________________________
  389. // ________________________________________________________________________
  390. // ________________________________________________________________________
  391. protected:
  392. #pragma mark -
  393. #pragma mark Implementation methods
  394. void PostConstructorInternal() final;
  395. void PreDestructorInternal() final;
  396. /// needs to be called when mMaxFramesPerSlice changes
  397. virtual void ReallocateBuffers();
  398. virtual void DeallocateIOBuffers();
  399. static void FillInParameterName(
  400. AudioUnitParameterInfo& ioInfo, CFStringRef inName, bool inShouldRelease)
  401. {
  402. ioInfo.cfNameString = inName;
  403. ioInfo.flags |= kAudioUnitParameterFlag_HasCFNameString;
  404. if (inShouldRelease) {
  405. ioInfo.flags |= kAudioUnitParameterFlag_CFNameRelease;
  406. }
  407. CFStringGetCString(inName, &ioInfo.name[0], offsetof(AudioUnitParameterInfo, clumpID),
  408. kCFStringEncodingUTF8);
  409. }
  410. static void HasClump(AudioUnitParameterInfo& ioInfo, UInt32 inClumpID) noexcept
  411. {
  412. ioInfo.clumpID = inClumpID;
  413. ioInfo.flags |= kAudioUnitParameterFlag_HasClump;
  414. }
  415. virtual void SetMaxFramesPerSlice(UInt32 nFrames);
  416. [[nodiscard]] virtual OSStatus CanSetMaxFrames() const;
  417. [[nodiscard]] bool WantsRenderThreadID() const noexcept { return mWantsRenderThreadID; }
  418. void SetWantsRenderThreadID(bool inFlag);
  419. OSStatus SetRenderError(OSStatus inErr)
  420. {
  421. if (inErr != noErr && mLastRenderError == 0) {
  422. mLastRenderError = inErr;
  423. PropertyChanged(kAudioUnitProperty_LastRenderError, kAudioUnitScope_Global, 0);
  424. }
  425. return inErr;
  426. }
  427. struct PropertyListener {
  428. AudioUnitPropertyID propertyID{ 0 };
  429. AudioUnitPropertyListenerProc listenerProc{ nullptr };
  430. void* listenerRefCon{ nullptr };
  431. };
  432. using PropertyListeners = std::vector<PropertyListener>;
  433. [[nodiscard]] const PropertyListeners& GetPropertyListeners() const noexcept
  434. {
  435. return mPropertyListeners;
  436. }
  437. HostCallbackInfo& GetHostCallbackInfo() noexcept { return mHostCallbackInfo; }
  438. private:
  439. // shared between Render and RenderSlice, inlined to minimize function call overhead
  440. OSStatus DoRenderBus(AudioUnitRenderActionFlags& ioActionFlags,
  441. const AudioTimeStamp& inTimeStamp, UInt32 inBusNumber, AUOutputElement& theOutput,
  442. UInt32 inNumberFrames, AudioBufferList& ioData)
  443. {
  444. if (ioData.mBuffers[0].mData == nullptr ||
  445. (theOutput.WillAllocateBuffer() && Outputs().GetNumberOfElements() > 1)) {
  446. // will render into cache buffer
  447. theOutput.PrepareBuffer(inNumberFrames);
  448. } else {
  449. // will render into caller's buffer
  450. theOutput.SetBufferList(ioData);
  451. }
  452. const OSStatus result = RenderBus(ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames);
  453. if (result == noErr) {
  454. if (ioData.mBuffers[0].mData == nullptr) {
  455. theOutput.CopyBufferListTo(ioData);
  456. } else {
  457. theOutput.CopyBufferContentsTo(ioData);
  458. theOutput.InvalidateBufferList();
  459. }
  460. }
  461. return result;
  462. }
  463. bool HasIcon();
  464. [[nodiscard]] std::string CreateLoggingString() const;
  465. protected:
  466. //. Returns size. outLayoutPtr may be null if querying only for size.
  467. virtual UInt32 GetAudioChannelLayout(AudioUnitScope scope, AudioUnitElement element,
  468. AudioChannelLayout* outLayoutPtr, bool& outWritable);
  469. /// Layout is non-null.
  470. virtual OSStatus SetAudioChannelLayout(
  471. AudioUnitScope scope, AudioUnitElement element, const AudioChannelLayout* inLayout);
  472. virtual OSStatus RemoveAudioChannelLayout(AudioUnitScope scope, AudioUnitElement element);
  473. virtual std::vector<AudioChannelLayoutTag> GetChannelLayoutTags(
  474. AudioUnitScope scope, AudioUnitElement element);
  475. bool NeedsToRender(const AudioTimeStamp& inTimeStamp)
  476. {
  477. const bool needsToRender = (inTimeStamp.mSampleTime != mCurrentRenderTime.mSampleTime);
  478. if (needsToRender) { // only copy this if we need to render
  479. mCurrentRenderTime = inTimeStamp;
  480. }
  481. return needsToRender;
  482. }
  483. // Scheduled parameter implementation:
  484. using ParameterEventList = std::vector<AudioUnitParameterEvent>;
  485. // Usually, you won't override this method. You only need to call this if your DSP code
  486. // is prepared to handle scheduled immediate and ramped parameter changes.
  487. // Before calling this method, it is assumed you have already called PullInput() on the input
  488. // busses for which the DSP code depends. ProcessForScheduledParams() will call (potentially
  489. // repeatedly) virtual method ProcessScheduledSlice() to perform the actual DSP for a given
  490. // sub-division of the buffer. The job of ProcessForScheduledParams() is to sub-divide the
  491. // buffer into smaller pieces according to the scheduled times found in the ParameterEventList
  492. // (usually coming directly from a previous call to ScheduleParameter() ), setting the
  493. // appropriate immediate or ramped parameter values for the corresponding scopes and elements,
  494. // then calling ProcessScheduledSlice() to do the actual DSP for each of these divisions.
  495. virtual OSStatus ProcessForScheduledParams(
  496. ParameterEventList& inParamList, UInt32 inFramesToProcess, void* inUserData);
  497. // This method is called (potentially repeatedly) by ProcessForScheduledParams()
  498. // in order to perform the actual DSP required for this portion of the entire buffer
  499. // being processed. The entire buffer can be divided up into smaller "slices"
  500. // according to the timestamps on the scheduled parameters...
  501. //
  502. // sub-classes wishing to handle scheduled parameter changes should override this method
  503. // in order to do the appropriate DSP. AUEffectBase already overrides this for standard
  504. // effect AudioUnits.
  505. virtual OSStatus ProcessScheduledSlice(void* /*inUserData*/, UInt32 /*inStartFrameInBuffer*/,
  506. UInt32 /*inSliceFramesToProcess*/, UInt32 /*inTotalBufferFrames*/)
  507. {
  508. // default implementation does nothing.
  509. return noErr;
  510. }
  511. [[nodiscard]] const AudioTimeStamp& CurrentRenderTime() const noexcept
  512. {
  513. return mCurrentRenderTime;
  514. }
  515. void ResetRenderTime();
  516. // ________________________________________________________________________
  517. // Private data members to discourage hacking in subclasses
  518. private:
  519. struct RenderCallback {
  520. RenderCallback() = default;
  521. RenderCallback(AURenderCallback proc, void* ref)
  522. : mRenderNotify(proc), mRenderNotifyRefCon(ref)
  523. {
  524. }
  525. AURenderCallback mRenderNotify = nullptr;
  526. void* mRenderNotifyRefCon = nullptr;
  527. bool operator==(const RenderCallback& other) const
  528. {
  529. return this->mRenderNotify == other.mRenderNotify &&
  530. this->mRenderNotifyRefCon == other.mRenderNotifyRefCon;
  531. }
  532. };
  533. class RenderCallbackList {
  534. public:
  535. void add(const RenderCallback& rc)
  536. {
  537. const std::lock_guard guard{ mLock };
  538. const auto iter = std::find(mImpl.begin(), mImpl.end(), rc);
  539. if (iter != mImpl.end()) {
  540. return;
  541. }
  542. mImpl.emplace_back(rc);
  543. }
  544. void remove(const RenderCallback& rc)
  545. {
  546. const std::lock_guard guard{ mLock };
  547. const auto iter = std::find(mImpl.begin(), mImpl.end(), rc);
  548. if (iter != mImpl.end()) {
  549. mImpl.erase(iter);
  550. }
  551. }
  552. template <typename F>
  553. void foreach (F&& func)
  554. {
  555. const std::lock_guard guard{ mLock };
  556. for (const auto& cb : mImpl) {
  557. func(cb);
  558. }
  559. }
  560. private:
  561. AUMutex mLock;
  562. std::vector<RenderCallback> mImpl;
  563. };
  564. protected:
  565. static constexpr AudioUnitScope kNumScopes = 4;
  566. ParameterEventList& GetParamEventList() noexcept { return mParamEventList; }
  567. void SetBuffersAllocated(bool b) noexcept { mBuffersAllocated = b; }
  568. [[nodiscard]] CFStringRef GetContextName() const { return *mContextName; }
  569. void SetContextName(CFStringRef str) { mContextName = str; }
  570. [[nodiscard]] CFStringRef GetNickName() const { return *mNickName; }
  571. private:
  572. bool mElementsCreated{ false };
  573. bool mInitialized{ false };
  574. bool mHasBegunInitializing{ false };
  575. const UInt32 mInitNumInputEls;
  576. const UInt32 mInitNumOutputEls;
  577. const UInt32 mInitNumGroupEls;
  578. std::array<AUScope, kNumScopes> mScopes;
  579. RenderCallbackList mRenderCallbacks;
  580. bool mRenderCallbacksTouched{ false };
  581. std::thread::id mRenderThreadID{};
  582. bool mWantsRenderThreadID{ false };
  583. AudioTimeStamp mCurrentRenderTime{};
  584. UInt32 mMaxFramesPerSlice{ 0 };
  585. OSStatus mLastRenderError{ noErr };
  586. #ifndef AUSDK_NO_LOGGING
  587. const double mHostTimeFrequency{
  588. HostTime::Frequency()
  589. }; // cache because there is calculation cost
  590. #endif
  591. AUPreset mCurrentPreset{ -1, nullptr };
  592. bool mUsesFixedBlockSize{ false };
  593. ParameterEventList mParamEventList;
  594. PropertyListeners mPropertyListeners;
  595. bool mBuffersAllocated{ false };
  596. const std::string mLogString;
  597. Owned<CFStringRef> mNickName;
  598. /*! @var mAUMutex
  599. If non-null, guards all non-realtime entry points into the AudioUnit. Most AudioUnits
  600. do not need to use this. It's useful for the case of an AU which must synchronize
  601. an external source of callbacks against entry from the host.
  602. */
  603. AUMutex* mAUMutex{ nullptr };
  604. HostCallbackInfo mHostCallbackInfo{};
  605. Owned<CFStringRef> mContextName;
  606. };
  607. } // namespace ausdk
  608. #endif // AudioUnitSDK_AUBase_h