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.

2423 lines
93KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. #include <juce_core/system/juce_TargetPlatform.h>
  14. #include <juce_core/system/juce_CompilerWarnings.h>
  15. #include "../utility/juce_CheckSettingMacros.h"
  16. #if JucePlugin_Build_AU
  17. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wshorten-64-to-32",
  18. "-Wunused-parameter",
  19. "-Wdeprecated-declarations",
  20. "-Wsign-conversion",
  21. "-Wconversion",
  22. "-Woverloaded-virtual",
  23. "-Wextra-semi",
  24. "-Wcast-align",
  25. "-Wshadow",
  26. "-Wswitch-enum",
  27. "-Wzero-as-null-pointer-constant",
  28. "-Wnullable-to-nonnull-conversion",
  29. "-Wgnu-zero-variadic-macro-arguments",
  30. "-Wformat-pedantic",
  31. "-Wdeprecated-anon-enum-enum-conversion")
  32. #include "../utility/juce_IncludeSystemHeaders.h"
  33. #include <AudioUnit/AUCocoaUIView.h>
  34. #include <AudioUnit/AudioUnit.h>
  35. #include <AudioToolbox/AudioUnitUtilities.h>
  36. #include <CoreMIDI/MIDIServices.h>
  37. #include <QuartzCore/QuartzCore.h>
  38. #include "CoreAudioUtilityClasses/MusicDeviceBase.h"
  39. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  40. #define JUCE_CORE_INCLUDE_OBJC_HELPERS 1
  41. #include "../utility/juce_IncludeModuleHeaders.h"
  42. #include <juce_audio_basics/native/juce_mac_CoreAudioLayouts.h>
  43. #include <juce_audio_basics/native/juce_mac_CoreAudioTimeConversions.h>
  44. #include <juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp>
  45. #include <juce_audio_processors/format_types/juce_AU_Shared.h>
  46. //==============================================================================
  47. using namespace juce;
  48. static Array<void*> activePlugins, activeUIs;
  49. static const AudioUnitPropertyID juceFilterObjectPropertyID = 0x1a45ffe9;
  50. template <> struct ContainerDeletePolicy<const __CFString> { static void destroy (const __CFString* o) { if (o != nullptr) CFRelease (o); } };
  51. // make sure the audio processor is initialized before the AUBase class
  52. struct AudioProcessorHolder
  53. {
  54. AudioProcessorHolder (bool initialiseGUI)
  55. {
  56. if (initialiseGUI)
  57. initialiseJuce_GUI();
  58. juceFilter.reset (createPluginFilterOfType (AudioProcessor::wrapperType_AudioUnit));
  59. // audio units do not have a notion of enabled or un-enabled buses
  60. juceFilter->enableAllBuses();
  61. }
  62. std::unique_ptr<AudioProcessor> juceFilter;
  63. };
  64. //==============================================================================
  65. class JuceAU : public AudioProcessorHolder,
  66. public MusicDeviceBase,
  67. public AudioProcessorListener,
  68. public AudioPlayHead,
  69. public AudioProcessorParameter::Listener
  70. {
  71. public:
  72. JuceAU (AudioUnit component)
  73. : AudioProcessorHolder (activePlugins.size() + activeUIs.size() == 0),
  74. MusicDeviceBase (component,
  75. (UInt32) AudioUnitHelpers::getBusCountForWrapper (*juceFilter, true),
  76. (UInt32) AudioUnitHelpers::getBusCountForWrapper (*juceFilter, false))
  77. {
  78. inParameterChangedCallback = false;
  79. #ifdef JucePlugin_PreferredChannelConfigurations
  80. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  81. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  82. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  83. juceFilter->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  84. for (int i = 0; i < numConfigs; ++i)
  85. {
  86. AUChannelInfo info;
  87. info.inChannels = configs[i][0];
  88. info.outChannels = configs[i][1];
  89. channelInfo.add (info);
  90. }
  91. #else
  92. channelInfo = AudioUnitHelpers::getAUChannelInfo (*juceFilter);
  93. #endif
  94. AddPropertyListener (kAudioUnitProperty_ContextName, auPropertyListenerDispatcher, this);
  95. totalInChannels = juceFilter->getTotalNumInputChannels();
  96. totalOutChannels = juceFilter->getTotalNumOutputChannels();
  97. juceFilter->setPlayHead (this);
  98. juceFilter->addListener (this);
  99. addParameters();
  100. activePlugins.add (this);
  101. zerostruct (auEvent);
  102. auEvent.mArgument.mParameter.mAudioUnit = GetComponentInstance();
  103. auEvent.mArgument.mParameter.mScope = kAudioUnitScope_Global;
  104. auEvent.mArgument.mParameter.mElement = 0;
  105. zerostruct (midiCallback);
  106. CreateElements();
  107. if (syncAudioUnitWithProcessor() != noErr)
  108. jassertfalse;
  109. }
  110. ~JuceAU() override
  111. {
  112. if (bypassParam != nullptr)
  113. bypassParam->removeListener (this);
  114. deleteActiveEditors();
  115. juceFilter = nullptr;
  116. clearPresetsArray();
  117. jassert (activePlugins.contains (this));
  118. activePlugins.removeFirstMatchingValue (this);
  119. if (activePlugins.size() + activeUIs.size() == 0)
  120. shutdownJuce_GUI();
  121. }
  122. //==============================================================================
  123. ComponentResult Initialize() override
  124. {
  125. ComponentResult err;
  126. if ((err = syncProcessorWithAudioUnit()) != noErr)
  127. return err;
  128. if ((err = MusicDeviceBase::Initialize()) != noErr)
  129. return err;
  130. mapper.alloc (*juceFilter);
  131. pulledSucceeded.calloc (static_cast<size_t> (AudioUnitHelpers::getBusCountForWrapper (*juceFilter, true)));
  132. prepareToPlay();
  133. return noErr;
  134. }
  135. void Cleanup() override
  136. {
  137. MusicDeviceBase::Cleanup();
  138. pulledSucceeded.free();
  139. mapper.release();
  140. if (juceFilter != nullptr)
  141. juceFilter->releaseResources();
  142. audioBuffer.release();
  143. midiEvents.clear();
  144. incomingEvents.clear();
  145. prepared = false;
  146. }
  147. ComponentResult Reset (AudioUnitScope inScope, AudioUnitElement inElement) override
  148. {
  149. if (! prepared)
  150. prepareToPlay();
  151. if (juceFilter != nullptr)
  152. juceFilter->reset();
  153. return MusicDeviceBase::Reset (inScope, inElement);
  154. }
  155. //==============================================================================
  156. void prepareToPlay()
  157. {
  158. if (juceFilter != nullptr)
  159. {
  160. juceFilter->setRateAndBufferSizeDetails (getSampleRate(), (int) GetMaxFramesPerSlice());
  161. audioBuffer.prepare (AudioUnitHelpers::getBusesLayout (juceFilter.get()), (int) GetMaxFramesPerSlice() + 32);
  162. juceFilter->prepareToPlay (getSampleRate(), (int) GetMaxFramesPerSlice());
  163. midiEvents.ensureSize (2048);
  164. midiEvents.clear();
  165. incomingEvents.ensureSize (2048);
  166. incomingEvents.clear();
  167. prepared = true;
  168. }
  169. }
  170. //==============================================================================
  171. static OSStatus ComponentEntryDispatch (ComponentParameters* params, JuceAU* effect)
  172. {
  173. if (effect == nullptr)
  174. return paramErr;
  175. switch (params->what)
  176. {
  177. case kMusicDeviceMIDIEventSelect:
  178. case kMusicDeviceSysExSelect:
  179. return AUMIDIBase::ComponentEntryDispatch (params, effect);
  180. default:
  181. break;
  182. }
  183. return MusicDeviceBase::ComponentEntryDispatch (params, effect);
  184. }
  185. //==============================================================================
  186. bool BusCountWritable (AudioUnitScope scope) override
  187. {
  188. #ifdef JucePlugin_PreferredChannelConfigurations
  189. ignoreUnused (scope);
  190. return false;
  191. #else
  192. bool isInput;
  193. if (scopeToDirection (scope, isInput) != noErr)
  194. return false;
  195. #if JucePlugin_IsMidiEffect
  196. return false;
  197. #elif JucePlugin_IsSynth
  198. if (isInput) return false;
  199. #endif
  200. const int busCount = AudioUnitHelpers::getBusCount (*juceFilter, isInput);
  201. return (juceFilter->canAddBus (isInput) || (busCount > 0 && juceFilter->canRemoveBus (isInput)));
  202. #endif
  203. }
  204. OSStatus SetBusCount (AudioUnitScope scope, UInt32 count) override
  205. {
  206. OSStatus err = noErr;
  207. bool isInput;
  208. if ((err = scopeToDirection (scope, isInput)) != noErr)
  209. return err;
  210. if (count != (UInt32) AudioUnitHelpers::getBusCount (*juceFilter, isInput))
  211. {
  212. #ifdef JucePlugin_PreferredChannelConfigurations
  213. return kAudioUnitErr_PropertyNotWritable;
  214. #else
  215. const int busCount = AudioUnitHelpers::getBusCount (*juceFilter, isInput);
  216. if ((! juceFilter->canAddBus (isInput)) && ((busCount == 0) || (! juceFilter->canRemoveBus (isInput))))
  217. return kAudioUnitErr_PropertyNotWritable;
  218. // we need to already create the underlying elements so that we can change their formats
  219. err = MusicDeviceBase::SetBusCount (scope, count);
  220. if (err != noErr)
  221. return err;
  222. // however we do need to update the format tag: we need to do the same thing in SetFormat, for example
  223. const int requestedNumBus = static_cast<int> (count);
  224. {
  225. (isInput ? currentInputLayout : currentOutputLayout).resize (requestedNumBus);
  226. int busNr;
  227. for (busNr = (busCount - 1); busNr != (requestedNumBus - 1); busNr += (requestedNumBus > busCount ? 1 : -1))
  228. {
  229. if (requestedNumBus > busCount)
  230. {
  231. if (! juceFilter->addBus (isInput))
  232. break;
  233. err = syncAudioUnitWithChannelSet (isInput, busNr,
  234. juceFilter->getBus (isInput, busNr + 1)->getDefaultLayout());
  235. if (err != noErr)
  236. break;
  237. }
  238. else
  239. {
  240. if (! juceFilter->removeBus (isInput))
  241. break;
  242. }
  243. }
  244. err = (busNr == (requestedNumBus - 1) ? (OSStatus) noErr : (OSStatus) kAudioUnitErr_FormatNotSupported);
  245. }
  246. // was there an error?
  247. if (err != noErr)
  248. {
  249. // restore bus state
  250. const int newBusCount = AudioUnitHelpers::getBusCount (*juceFilter, isInput);
  251. for (int i = newBusCount; i != busCount; i += (busCount > newBusCount ? 1 : -1))
  252. {
  253. if (busCount > newBusCount)
  254. juceFilter->addBus (isInput);
  255. else
  256. juceFilter->removeBus (isInput);
  257. }
  258. (isInput ? currentInputLayout : currentOutputLayout).resize (busCount);
  259. MusicDeviceBase::SetBusCount (scope, static_cast<UInt32> (busCount));
  260. return kAudioUnitErr_FormatNotSupported;
  261. }
  262. // update total channel count
  263. totalInChannels = juceFilter->getTotalNumInputChannels();
  264. totalOutChannels = juceFilter->getTotalNumOutputChannels();
  265. addSupportedLayoutTagsForDirection (isInput);
  266. if (err != noErr)
  267. return err;
  268. #endif
  269. }
  270. return noErr;
  271. }
  272. UInt32 SupportedNumChannels (const AUChannelInfo** outInfo) override
  273. {
  274. if (outInfo != nullptr)
  275. *outInfo = channelInfo.getRawDataPointer();
  276. return (UInt32) channelInfo.size();
  277. }
  278. //==============================================================================
  279. ComponentResult GetPropertyInfo (AudioUnitPropertyID inID,
  280. AudioUnitScope inScope,
  281. AudioUnitElement inElement,
  282. UInt32& outDataSize,
  283. Boolean& outWritable) override
  284. {
  285. if (inScope == kAudioUnitScope_Global)
  286. {
  287. switch (inID)
  288. {
  289. case juceFilterObjectPropertyID:
  290. outWritable = false;
  291. outDataSize = sizeof (void*) * 2;
  292. return noErr;
  293. case kAudioUnitProperty_OfflineRender:
  294. outWritable = true;
  295. outDataSize = sizeof (UInt32);
  296. return noErr;
  297. case kMusicDeviceProperty_InstrumentCount:
  298. outDataSize = sizeof (UInt32);
  299. outWritable = false;
  300. return noErr;
  301. case kAudioUnitProperty_CocoaUI:
  302. outDataSize = sizeof (AudioUnitCocoaViewInfo);
  303. outWritable = true;
  304. return noErr;
  305. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  306. case kAudioUnitProperty_MIDIOutputCallbackInfo:
  307. outDataSize = sizeof (CFArrayRef);
  308. outWritable = false;
  309. return noErr;
  310. case kAudioUnitProperty_MIDIOutputCallback:
  311. outDataSize = sizeof (AUMIDIOutputCallbackStruct);
  312. outWritable = true;
  313. return noErr;
  314. #endif
  315. case kAudioUnitProperty_ParameterStringFromValue:
  316. outDataSize = sizeof (AudioUnitParameterStringFromValue);
  317. outWritable = false;
  318. return noErr;
  319. case kAudioUnitProperty_ParameterValueFromString:
  320. outDataSize = sizeof (AudioUnitParameterValueFromString);
  321. outWritable = false;
  322. return noErr;
  323. case kAudioUnitProperty_BypassEffect:
  324. outDataSize = sizeof (UInt32);
  325. outWritable = true;
  326. return noErr;
  327. case kAudioUnitProperty_SupportsMPE:
  328. outDataSize = sizeof (UInt32);
  329. outWritable = false;
  330. return noErr;
  331. default: break;
  332. }
  333. }
  334. return MusicDeviceBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable);
  335. }
  336. ComponentResult GetProperty (AudioUnitPropertyID inID,
  337. AudioUnitScope inScope,
  338. AudioUnitElement inElement,
  339. void* outData) override
  340. {
  341. if (inScope == kAudioUnitScope_Global)
  342. {
  343. switch (inID)
  344. {
  345. case kAudioUnitProperty_ParameterClumpName:
  346. if (auto* clumpNameInfo = (AudioUnitParameterNameInfo*) outData)
  347. {
  348. if (juceFilter != nullptr)
  349. {
  350. auto clumpIndex = clumpNameInfo->inID - 1;
  351. const auto* group = parameterGroups[(int) clumpIndex];
  352. auto name = group->getName();
  353. while (group->getParent() != &juceFilter->getParameterTree())
  354. {
  355. group = group->getParent();
  356. name = group->getName() + group->getSeparator() + name;
  357. }
  358. clumpNameInfo->outName = name.toCFString();
  359. return noErr;
  360. }
  361. }
  362. // Failed to find a group corresponding to the clump ID.
  363. jassertfalse;
  364. break;
  365. case juceFilterObjectPropertyID:
  366. ((void**) outData)[0] = (void*) static_cast<AudioProcessor*> (juceFilter.get());
  367. ((void**) outData)[1] = (void*) this;
  368. return noErr;
  369. case kAudioUnitProperty_OfflineRender:
  370. *(UInt32*) outData = (juceFilter != nullptr && juceFilter->isNonRealtime()) ? 1 : 0;
  371. return noErr;
  372. case kMusicDeviceProperty_InstrumentCount:
  373. *(UInt32*) outData = 1;
  374. return noErr;
  375. case kAudioUnitProperty_BypassEffect:
  376. if (bypassParam != nullptr)
  377. *(UInt32*) outData = (bypassParam->getValue() != 0.0f ? 1 : 0);
  378. else
  379. *(UInt32*) outData = isBypassed ? 1 : 0;
  380. return noErr;
  381. case kAudioUnitProperty_SupportsMPE:
  382. *(UInt32*) outData = (juceFilter != nullptr && juceFilter->supportsMPE()) ? 1 : 0;
  383. return noErr;
  384. case kAudioUnitProperty_CocoaUI:
  385. {
  386. JUCE_AUTORELEASEPOOL
  387. {
  388. static JuceUICreationClass cls;
  389. // (NB: this may be the host's bundle, not necessarily the component's)
  390. NSBundle* bundle = [NSBundle bundleForClass: cls.cls];
  391. AudioUnitCocoaViewInfo* info = static_cast<AudioUnitCocoaViewInfo*> (outData);
  392. info->mCocoaAUViewClass[0] = (CFStringRef) [juceStringToNS (class_getName (cls.cls)) retain];
  393. info->mCocoaAUViewBundleLocation = (CFURLRef) [[NSURL fileURLWithPath: [bundle bundlePath]] retain];
  394. }
  395. return noErr;
  396. }
  397. break;
  398. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  399. case kAudioUnitProperty_MIDIOutputCallbackInfo:
  400. {
  401. CFStringRef strs[1];
  402. strs[0] = CFSTR ("MIDI Callback");
  403. CFArrayRef callbackArray = CFArrayCreate (nullptr, (const void**) strs, 1, &kCFTypeArrayCallBacks);
  404. *(CFArrayRef*) outData = callbackArray;
  405. return noErr;
  406. }
  407. #endif
  408. case kAudioUnitProperty_ParameterValueFromString:
  409. {
  410. if (AudioUnitParameterValueFromString* pv = (AudioUnitParameterValueFromString*) outData)
  411. {
  412. if (juceFilter != nullptr)
  413. {
  414. if (auto* param = getParameterForAUParameterID (pv->inParamID))
  415. {
  416. const String text (String::fromCFString (pv->inString));
  417. if (LegacyAudioParameter::isLegacy (param))
  418. pv->outValue = text.getFloatValue();
  419. else
  420. pv->outValue = param->getValueForText (text) * getMaximumParameterValue (param);
  421. return noErr;
  422. }
  423. }
  424. }
  425. }
  426. break;
  427. case kAudioUnitProperty_ParameterStringFromValue:
  428. {
  429. if (AudioUnitParameterStringFromValue* pv = (AudioUnitParameterStringFromValue*) outData)
  430. {
  431. if (juceFilter != nullptr)
  432. {
  433. if (auto* param = getParameterForAUParameterID (pv->inParamID))
  434. {
  435. const float value = (float) *(pv->inValue);
  436. String text;
  437. if (LegacyAudioParameter::isLegacy (param))
  438. text = String (value);
  439. else
  440. text = param->getText (value / getMaximumParameterValue (param), 0);
  441. pv->outString = text.toCFString();
  442. return noErr;
  443. }
  444. }
  445. }
  446. }
  447. break;
  448. default:
  449. break;
  450. }
  451. }
  452. return MusicDeviceBase::GetProperty (inID, inScope, inElement, outData);
  453. }
  454. ComponentResult SetProperty (AudioUnitPropertyID inID,
  455. AudioUnitScope inScope,
  456. AudioUnitElement inElement,
  457. const void* inData,
  458. UInt32 inDataSize) override
  459. {
  460. if (inScope == kAudioUnitScope_Global)
  461. {
  462. switch (inID)
  463. {
  464. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  465. case kAudioUnitProperty_MIDIOutputCallback:
  466. if (inDataSize < sizeof (AUMIDIOutputCallbackStruct))
  467. return kAudioUnitErr_InvalidPropertyValue;
  468. if (AUMIDIOutputCallbackStruct* callbackStruct = (AUMIDIOutputCallbackStruct*) inData)
  469. midiCallback = *callbackStruct;
  470. return noErr;
  471. #endif
  472. case kAudioUnitProperty_BypassEffect:
  473. {
  474. if (inDataSize < sizeof (UInt32))
  475. return kAudioUnitErr_InvalidPropertyValue;
  476. const bool newBypass = *((UInt32*) inData) != 0;
  477. const bool currentlyBypassed = (bypassParam != nullptr ? (bypassParam->getValue() != 0.0f) : isBypassed);
  478. if (newBypass != currentlyBypassed)
  479. {
  480. if (bypassParam != nullptr)
  481. bypassParam->setValueNotifyingHost (newBypass ? 1.0f : 0.0f);
  482. else
  483. isBypassed = newBypass;
  484. if (! currentlyBypassed && IsInitialized()) // turning bypass off and we're initialized
  485. Reset (0, 0);
  486. }
  487. return noErr;
  488. }
  489. case kAudioUnitProperty_OfflineRender:
  490. {
  491. const auto shouldBeOffline = (*reinterpret_cast<const UInt32*> (inData) != 0);
  492. if (juceFilter != nullptr)
  493. {
  494. const auto isOffline = juceFilter->isNonRealtime();
  495. if (isOffline != shouldBeOffline)
  496. {
  497. const ScopedLock sl (juceFilter->getCallbackLock());
  498. juceFilter->setNonRealtime (shouldBeOffline);
  499. juceFilter->prepareToPlay (getSampleRate(), (int) GetMaxFramesPerSlice());
  500. }
  501. }
  502. return noErr;
  503. }
  504. #if defined (MAC_OS_X_VERSION_10_12)
  505. case kAudioUnitProperty_AUHostIdentifier:
  506. {
  507. if (inDataSize < sizeof (AUHostVersionIdentifier))
  508. return kAudioUnitErr_InvalidPropertyValue;
  509. const auto* identifier = static_cast<const AUHostVersionIdentifier*> (inData);
  510. PluginHostType::hostIdReportedByWrapper = String::fromCFString (identifier->hostName);
  511. return noErr;
  512. }
  513. #endif
  514. default: break;
  515. }
  516. }
  517. return MusicDeviceBase::SetProperty (inID, inScope, inElement, inData, inDataSize);
  518. }
  519. //==============================================================================
  520. ComponentResult SaveState (CFPropertyListRef* outData) override
  521. {
  522. ComponentResult err = MusicDeviceBase::SaveState (outData);
  523. if (err != noErr)
  524. return err;
  525. jassert (CFGetTypeID (*outData) == CFDictionaryGetTypeID());
  526. CFMutableDictionaryRef dict = (CFMutableDictionaryRef) *outData;
  527. if (juceFilter != nullptr)
  528. {
  529. juce::MemoryBlock state;
  530. #if JUCE_AU_WRAPPERS_SAVE_PROGRAM_STATES
  531. juceFilter->getCurrentProgramStateInformation (state);
  532. #else
  533. juceFilter->getStateInformation (state);
  534. #endif
  535. if (state.getSize() > 0)
  536. {
  537. CFUniquePtr<CFDataRef> ourState (CFDataCreate (kCFAllocatorDefault, (const UInt8*) state.getData(), (CFIndex) state.getSize()));
  538. CFUniquePtr<CFStringRef> key (CFStringCreateWithCString (kCFAllocatorDefault, JUCE_STATE_DICTIONARY_KEY, kCFStringEncodingUTF8));
  539. CFDictionarySetValue (dict, key.get(), ourState.get());
  540. }
  541. }
  542. return noErr;
  543. }
  544. ComponentResult RestoreState (CFPropertyListRef inData) override
  545. {
  546. const ScopedValueSetter<bool> scope { restoringState, true };
  547. {
  548. // Remove the data entry from the state to prevent the superclass loading the parameters
  549. CFUniquePtr<CFMutableDictionaryRef> copyWithoutData (CFDictionaryCreateMutableCopy (nullptr, 0, (CFDictionaryRef) inData));
  550. CFDictionaryRemoveValue (copyWithoutData.get(), CFSTR (kAUPresetDataKey));
  551. ComponentResult err = MusicDeviceBase::RestoreState (copyWithoutData.get());
  552. if (err != noErr)
  553. return err;
  554. }
  555. if (juceFilter != nullptr)
  556. {
  557. CFDictionaryRef dict = (CFDictionaryRef) inData;
  558. CFDataRef data = nullptr;
  559. CFUniquePtr<CFStringRef> key (CFStringCreateWithCString (kCFAllocatorDefault, JUCE_STATE_DICTIONARY_KEY, kCFStringEncodingUTF8));
  560. bool valuePresent = CFDictionaryGetValueIfPresent (dict, key.get(), (const void**) &data);
  561. if (valuePresent)
  562. {
  563. if (data != nullptr)
  564. {
  565. const int numBytes = (int) CFDataGetLength (data);
  566. const juce::uint8* const rawBytes = CFDataGetBytePtr (data);
  567. if (numBytes > 0)
  568. {
  569. #if JUCE_AU_WRAPPERS_SAVE_PROGRAM_STATES
  570. juceFilter->setCurrentProgramStateInformation (rawBytes, numBytes);
  571. #else
  572. juceFilter->setStateInformation (rawBytes, numBytes);
  573. #endif
  574. }
  575. }
  576. }
  577. }
  578. return noErr;
  579. }
  580. //==============================================================================
  581. bool busIgnoresLayout (bool isInput, int busNr) const
  582. {
  583. #ifdef JucePlugin_PreferredChannelConfigurations
  584. ignoreUnused (isInput, busNr);
  585. return true;
  586. #else
  587. if (const AudioProcessor::Bus* bus = juceFilter->getBus (isInput, busNr))
  588. {
  589. AudioChannelSet discreteRangeSet;
  590. const int n = bus->getDefaultLayout().size();
  591. for (int i = 0; i < n; ++i)
  592. discreteRangeSet.addChannel ((AudioChannelSet::ChannelType) (256 + i));
  593. // if the audioprocessor supports this it cannot
  594. // really be interested in the bus layouts
  595. return bus->isLayoutSupported (discreteRangeSet);
  596. }
  597. return true;
  598. #endif
  599. }
  600. UInt32 GetAudioChannelLayout (AudioUnitScope scope, AudioUnitElement element,
  601. AudioChannelLayout* outLayoutPtr, Boolean& outWritable) override
  602. {
  603. outWritable = false;
  604. const auto info = getElementInfo (scope, element);
  605. if (info.error != noErr)
  606. return 0;
  607. if (busIgnoresLayout (info.isInput, info.busNr))
  608. return 0;
  609. outWritable = true;
  610. const size_t sizeInBytes = sizeof (AudioChannelLayout) - sizeof (AudioChannelDescription);
  611. if (outLayoutPtr != nullptr)
  612. {
  613. zeromem (outLayoutPtr, sizeInBytes);
  614. outLayoutPtr->mChannelLayoutTag = getCurrentLayout (info.isInput, info.busNr);
  615. }
  616. return sizeInBytes;
  617. }
  618. UInt32 GetChannelLayoutTags (AudioUnitScope scope, AudioUnitElement element, AudioChannelLayoutTag* outLayoutTags) override
  619. {
  620. const auto info = getElementInfo (scope, element);
  621. if (info.error != noErr)
  622. return 0;
  623. if (busIgnoresLayout (info.isInput, info.busNr))
  624. return 0;
  625. const Array<AudioChannelLayoutTag>& layouts = getSupportedBusLayouts (info.isInput, info.busNr);
  626. if (outLayoutTags != nullptr)
  627. std::copy (layouts.begin(), layouts.end(), outLayoutTags);
  628. return (UInt32) layouts.size();
  629. }
  630. OSStatus SetAudioChannelLayout (AudioUnitScope scope, AudioUnitElement element, const AudioChannelLayout* inLayout) override
  631. {
  632. const auto info = getElementInfo (scope, element);
  633. if (info.error != noErr)
  634. return info.error;
  635. if (busIgnoresLayout (info.isInput, info.busNr))
  636. return kAudioUnitErr_PropertyNotWritable;
  637. if (inLayout == nullptr)
  638. return kAudioUnitErr_InvalidPropertyValue;
  639. if (const AUIOElement* ioElement = GetIOElement (info.isInput ? kAudioUnitScope_Input : kAudioUnitScope_Output, element))
  640. {
  641. const AudioChannelSet newChannelSet = CoreAudioLayouts::fromCoreAudio (*inLayout);
  642. const int currentNumChannels = static_cast<int> (ioElement->GetStreamFormat().NumberChannels());
  643. const int newChannelNum = newChannelSet.size();
  644. if (currentNumChannels != newChannelNum)
  645. return kAudioUnitErr_InvalidPropertyValue;
  646. // check if the new layout could be potentially set
  647. #ifdef JucePlugin_PreferredChannelConfigurations
  648. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  649. if (! AudioUnitHelpers::isLayoutSupported (*juceFilter, info.isInput, info.busNr, newChannelNum, configs))
  650. return kAudioUnitErr_FormatNotSupported;
  651. #else
  652. if (! juceFilter->getBus (info.isInput, info.busNr)->isLayoutSupported (newChannelSet))
  653. return kAudioUnitErr_FormatNotSupported;
  654. #endif
  655. getCurrentLayout (info.isInput, info.busNr) = CoreAudioLayouts::toCoreAudio (newChannelSet);
  656. return noErr;
  657. }
  658. else
  659. jassertfalse;
  660. return kAudioUnitErr_InvalidElement;
  661. }
  662. //==============================================================================
  663. // When parameters are discrete we need to use integer values.
  664. float getMaximumParameterValue (AudioProcessorParameter* juceParam)
  665. {
  666. #if JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE
  667. ignoreUnused (juceParam);
  668. return 1.0f;
  669. #else
  670. return juceParam->isDiscrete() ? (float) (juceParam->getNumSteps() - 1) : 1.0f;
  671. #endif
  672. }
  673. ComponentResult GetParameterInfo (AudioUnitScope inScope,
  674. AudioUnitParameterID inParameterID,
  675. AudioUnitParameterInfo& outParameterInfo) override
  676. {
  677. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  678. {
  679. if (auto* param = getParameterForAUParameterID (inParameterID))
  680. {
  681. outParameterInfo.unit = kAudioUnitParameterUnit_Generic;
  682. outParameterInfo.flags = (UInt32) (kAudioUnitParameterFlag_IsWritable
  683. | kAudioUnitParameterFlag_IsReadable
  684. | kAudioUnitParameterFlag_HasCFNameString
  685. | kAudioUnitParameterFlag_ValuesHaveStrings);
  686. #if ! JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE
  687. outParameterInfo.flags |= (UInt32) kAudioUnitParameterFlag_IsHighResolution;
  688. #endif
  689. const String name = param->getName (1024);
  690. // Set whether the param is automatable (unnamed parameters aren't allowed to be automated)
  691. if (name.isEmpty() || ! param->isAutomatable())
  692. outParameterInfo.flags |= kAudioUnitParameterFlag_NonRealTime;
  693. const bool isParameterDiscrete = param->isDiscrete();
  694. if (! isParameterDiscrete)
  695. outParameterInfo.flags |= kAudioUnitParameterFlag_CanRamp;
  696. if (param->isMetaParameter())
  697. outParameterInfo.flags |= kAudioUnitParameterFlag_IsGlobalMeta;
  698. auto parameterGroupHierarchy = juceFilter->getParameterTree().getGroupsForParameter (param);
  699. if (! parameterGroupHierarchy.isEmpty())
  700. {
  701. outParameterInfo.flags |= kAudioUnitParameterFlag_HasClump;
  702. outParameterInfo.clumpID = (UInt32) parameterGroups.indexOf (parameterGroupHierarchy.getLast()) + 1;
  703. }
  704. // Is this a meter?
  705. if ((((unsigned int) param->getCategory() & 0xffff0000) >> 16) == 2)
  706. {
  707. outParameterInfo.flags &= ~kAudioUnitParameterFlag_IsWritable;
  708. outParameterInfo.flags |= kAudioUnitParameterFlag_MeterReadOnly | kAudioUnitParameterFlag_DisplayLogarithmic;
  709. outParameterInfo.unit = kAudioUnitParameterUnit_LinearGain;
  710. }
  711. else
  712. {
  713. #if ! JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE
  714. if (isParameterDiscrete)
  715. outParameterInfo.unit = param->isBoolean() ? kAudioUnitParameterUnit_Boolean
  716. : kAudioUnitParameterUnit_Indexed;
  717. #endif
  718. }
  719. MusicDeviceBase::FillInParameterName (outParameterInfo, name.toCFString(), true);
  720. outParameterInfo.minValue = 0.0f;
  721. outParameterInfo.maxValue = getMaximumParameterValue (param);
  722. outParameterInfo.defaultValue = param->getDefaultValue() * getMaximumParameterValue (param);
  723. jassert (outParameterInfo.defaultValue >= outParameterInfo.minValue
  724. && outParameterInfo.defaultValue <= outParameterInfo.maxValue);
  725. return noErr;
  726. }
  727. }
  728. return kAudioUnitErr_InvalidParameter;
  729. }
  730. ComponentResult GetParameterValueStrings (AudioUnitScope inScope,
  731. AudioUnitParameterID inParameterID,
  732. CFArrayRef *outStrings) override
  733. {
  734. if (outStrings == nullptr)
  735. return noErr;
  736. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  737. {
  738. if (auto* param = getParameterForAUParameterID (inParameterID))
  739. {
  740. if (param->isDiscrete())
  741. {
  742. auto index = LegacyAudioParameter::getParamIndex (*juceFilter, param);
  743. if (auto* valueStrings = parameterValueStringArrays[index])
  744. {
  745. *outStrings = CFArrayCreate (nullptr,
  746. (const void **) valueStrings->getRawDataPointer(),
  747. valueStrings->size(),
  748. nullptr);
  749. return noErr;
  750. }
  751. }
  752. }
  753. }
  754. return kAudioUnitErr_InvalidParameter;
  755. }
  756. ComponentResult GetParameter (AudioUnitParameterID inID,
  757. AudioUnitScope inScope,
  758. AudioUnitElement inElement,
  759. Float32& outValue) override
  760. {
  761. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  762. {
  763. if (auto* param = getParameterForAUParameterID (inID))
  764. {
  765. const auto normValue = param->getValue();
  766. outValue = normValue * getMaximumParameterValue (param);
  767. return noErr;
  768. }
  769. }
  770. return MusicDeviceBase::GetParameter (inID, inScope, inElement, outValue);
  771. }
  772. ComponentResult SetParameter (AudioUnitParameterID inID,
  773. AudioUnitScope inScope,
  774. AudioUnitElement inElement,
  775. Float32 inValue,
  776. UInt32 inBufferOffsetInFrames) override
  777. {
  778. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  779. {
  780. if (auto* param = getParameterForAUParameterID (inID))
  781. {
  782. auto value = inValue / getMaximumParameterValue (param);
  783. if (value != param->getValue())
  784. {
  785. inParameterChangedCallback = true;
  786. param->setValueNotifyingHost (value);
  787. }
  788. return noErr;
  789. }
  790. }
  791. return MusicDeviceBase::SetParameter (inID, inScope, inElement, inValue, inBufferOffsetInFrames);
  792. }
  793. // No idea what this method actually does or what it should return. Current Apple docs say nothing about it.
  794. // (Note that this isn't marked 'override' in case older versions of the SDK don't include it)
  795. bool CanScheduleParameters() const override { return false; }
  796. //==============================================================================
  797. ComponentResult Version() override { return JucePlugin_VersionCode; }
  798. bool SupportsTail() override { return true; }
  799. Float64 GetTailTime() override { return juceFilter->getTailLengthSeconds(); }
  800. double getSampleRate()
  801. {
  802. if (AudioUnitHelpers::getBusCountForWrapper (*juceFilter, false) > 0)
  803. return GetOutput (0)->GetStreamFormat().mSampleRate;
  804. return 44100.0;
  805. }
  806. Float64 GetLatency() override
  807. {
  808. const double rate = getSampleRate();
  809. jassert (rate > 0);
  810. return rate > 0 ? juceFilter->getLatencySamples() / rate : 0;
  811. }
  812. //==============================================================================
  813. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info) override
  814. {
  815. info.timeSigNumerator = 0;
  816. info.timeSigDenominator = 0;
  817. info.editOriginTime = 0;
  818. info.ppqPositionOfLastBarStart = 0;
  819. info.isRecording = false;
  820. info.frameRate = [this]
  821. {
  822. switch (lastTimeStamp.mSMPTETime.mType)
  823. {
  824. case kSMPTETimeType2398: return FrameRate().withBaseRate (24).withPullDown();
  825. case kSMPTETimeType24: return FrameRate().withBaseRate (24);
  826. case kSMPTETimeType25: return FrameRate().withBaseRate (25);
  827. case kSMPTETimeType30Drop: return FrameRate().withBaseRate (30).withDrop();
  828. case kSMPTETimeType30: return FrameRate().withBaseRate (30);
  829. case kSMPTETimeType2997: return FrameRate().withBaseRate (30).withPullDown();
  830. case kSMPTETimeType2997Drop: return FrameRate().withBaseRate (30).withPullDown().withDrop();
  831. case kSMPTETimeType60: return FrameRate().withBaseRate (60);
  832. case kSMPTETimeType60Drop: return FrameRate().withBaseRate (60).withDrop();
  833. case kSMPTETimeType5994: return FrameRate().withBaseRate (60).withPullDown();
  834. case kSMPTETimeType5994Drop: return FrameRate().withBaseRate (60).withPullDown().withDrop();
  835. case kSMPTETimeType50: return FrameRate().withBaseRate (50);
  836. default: break;
  837. }
  838. return FrameRate();
  839. }();
  840. if (CallHostBeatAndTempo (&info.ppqPosition, &info.bpm) != noErr)
  841. {
  842. info.ppqPosition = 0;
  843. info.bpm = 0;
  844. }
  845. UInt32 outDeltaSampleOffsetToNextBeat;
  846. double outCurrentMeasureDownBeat;
  847. float num;
  848. UInt32 den;
  849. if (CallHostMusicalTimeLocation (&outDeltaSampleOffsetToNextBeat, &num, &den,
  850. &outCurrentMeasureDownBeat) == noErr)
  851. {
  852. info.timeSigNumerator = (int) num;
  853. info.timeSigDenominator = (int) den;
  854. info.ppqPositionOfLastBarStart = outCurrentMeasureDownBeat;
  855. }
  856. double outCurrentSampleInTimeLine, outCycleStartBeat = 0, outCycleEndBeat = 0;
  857. Boolean playing = false, looping = false, playchanged;
  858. if (CallHostTransportState (&playing,
  859. &playchanged,
  860. &outCurrentSampleInTimeLine,
  861. &looping,
  862. &outCycleStartBeat,
  863. &outCycleEndBeat) != noErr)
  864. {
  865. // If the host doesn't support this callback, then use the sample time from lastTimeStamp:
  866. outCurrentSampleInTimeLine = lastTimeStamp.mSampleTime;
  867. }
  868. info.isPlaying = playing;
  869. info.timeInSamples = (int64) (outCurrentSampleInTimeLine + 0.5);
  870. info.timeInSeconds = info.timeInSamples / getSampleRate();
  871. info.isLooping = looping;
  872. info.ppqLoopStart = outCycleStartBeat;
  873. info.ppqLoopEnd = outCycleEndBeat;
  874. return true;
  875. }
  876. void sendAUEvent (const AudioUnitEventType type, const int juceParamIndex)
  877. {
  878. if (restoringState)
  879. return;
  880. auEvent.mEventType = type;
  881. auEvent.mArgument.mParameter.mParameterID = getAUParameterIDForIndex (juceParamIndex);
  882. AUEventListenerNotify (nullptr, nullptr, &auEvent);
  883. }
  884. void audioProcessorParameterChanged (AudioProcessor*, int index, float /*newValue*/) override
  885. {
  886. if (inParameterChangedCallback.get())
  887. {
  888. inParameterChangedCallback = false;
  889. return;
  890. }
  891. sendAUEvent (kAudioUnitEvent_ParameterValueChange, index);
  892. }
  893. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override
  894. {
  895. sendAUEvent (kAudioUnitEvent_BeginParameterChangeGesture, index);
  896. }
  897. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override
  898. {
  899. sendAUEvent (kAudioUnitEvent_EndParameterChangeGesture, index);
  900. }
  901. void audioProcessorChanged (AudioProcessor*, const ChangeDetails& details) override
  902. {
  903. audioProcessorChangedUpdater.update (details);
  904. }
  905. //==============================================================================
  906. // this will only ever be called by the bypass parameter
  907. void parameterValueChanged (int, float) override
  908. {
  909. if (! restoringState)
  910. PropertyChanged (kAudioUnitProperty_BypassEffect, kAudioUnitScope_Global, 0);
  911. }
  912. void parameterGestureChanged (int, bool) override {}
  913. //==============================================================================
  914. bool StreamFormatWritable (AudioUnitScope scope, AudioUnitElement element) override
  915. {
  916. const auto info = getElementInfo (scope, element);
  917. return ((! IsInitialized()) && (info.error == noErr));
  918. }
  919. bool ValidFormat (AudioUnitScope scope, AudioUnitElement element, const CAStreamBasicDescription& format) override
  920. {
  921. // DSP Quattro incorrectly uses global scope for the ValidFormat call
  922. if (scope == kAudioUnitScope_Global)
  923. return ValidFormat (kAudioUnitScope_Input, element, format)
  924. || ValidFormat (kAudioUnitScope_Output, element, format);
  925. const auto info = getElementInfo (scope, element);
  926. if (info.error != noErr)
  927. return false;
  928. if (info.kind == BusKind::wrapperOnly)
  929. return true;
  930. const int newNumChannels = static_cast<int> (format.NumberChannels());
  931. const int oldNumChannels = juceFilter->getChannelCountOfBus (info.isInput, info.busNr);
  932. if (newNumChannels == oldNumChannels)
  933. return true;
  934. if (AudioProcessor::Bus* bus = juceFilter->getBus (info.isInput, info.busNr))
  935. {
  936. if (! MusicDeviceBase::ValidFormat (scope, element, format))
  937. return false;
  938. #ifdef JucePlugin_PreferredChannelConfigurations
  939. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  940. ignoreUnused (bus);
  941. return AudioUnitHelpers::isLayoutSupported (*juceFilter, info.isInput, info.busNr, newNumChannels, configs);
  942. #else
  943. return bus->isNumberOfChannelsSupported (newNumChannels);
  944. #endif
  945. }
  946. return false;
  947. }
  948. // AU requires us to override this for the sole reason that we need to find a default layout tag if the number of channels have changed
  949. OSStatus ChangeStreamFormat (AudioUnitScope scope, AudioUnitElement element, const CAStreamBasicDescription& old, const CAStreamBasicDescription& format) override
  950. {
  951. const auto info = getElementInfo (scope, element);
  952. if (info.error != noErr)
  953. return info.error;
  954. AudioChannelLayoutTag& currentTag = getCurrentLayout (info.isInput, info.busNr);
  955. const int newNumChannels = static_cast<int> (format.NumberChannels());
  956. const int oldNumChannels = juceFilter->getChannelCountOfBus (info.isInput, info.busNr);
  957. #ifdef JucePlugin_PreferredChannelConfigurations
  958. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  959. if (! AudioUnitHelpers::isLayoutSupported (*juceFilter, info.isInput, info.busNr, newNumChannels, configs))
  960. return kAudioUnitErr_FormatNotSupported;
  961. #endif
  962. // predict channel layout
  963. const auto set = [&]
  964. {
  965. if (info.kind == BusKind::wrapperOnly)
  966. return AudioChannelSet::discreteChannels (newNumChannels);
  967. if (newNumChannels != oldNumChannels)
  968. return juceFilter->getBus (info.isInput, info.busNr)->supportedLayoutWithChannels (newNumChannels);
  969. return juceFilter->getChannelLayoutOfBus (info.isInput, info.busNr);
  970. }();
  971. if (set == AudioChannelSet())
  972. return kAudioUnitErr_FormatNotSupported;
  973. const auto err = MusicDeviceBase::ChangeStreamFormat (scope, element, old, format);
  974. if (err == noErr)
  975. currentTag = CoreAudioLayouts::toCoreAudio (set);
  976. return err;
  977. }
  978. //==============================================================================
  979. ComponentResult Render (AudioUnitRenderActionFlags& ioActionFlags,
  980. const AudioTimeStamp& inTimeStamp,
  981. const UInt32 nFrames) override
  982. {
  983. lastTimeStamp = inTimeStamp;
  984. jassert (! juceFilter->getHostTimeNs());
  985. if ((inTimeStamp.mFlags & kAudioTimeStampHostTimeValid) != 0)
  986. {
  987. const auto timestamp = timeConversions.hostTimeToNanos (inTimeStamp.mHostTime);
  988. juceFilter->setHostTimeNanos (&timestamp);
  989. }
  990. struct AtEndOfScope
  991. {
  992. ~AtEndOfScope() { proc.setHostTimeNanos (nullptr); }
  993. AudioProcessor& proc;
  994. };
  995. const AtEndOfScope scope { *juceFilter };
  996. // prepare buffers
  997. {
  998. pullInputAudio (ioActionFlags, inTimeStamp, nFrames);
  999. prepareOutputBuffers (nFrames);
  1000. audioBuffer.reset();
  1001. }
  1002. ioActionFlags &= ~kAudioUnitRenderAction_OutputIsSilence;
  1003. const int numInputBuses = AudioUnitHelpers::getBusCount (*juceFilter, true);
  1004. const int numOutputBuses = AudioUnitHelpers::getBusCount (*juceFilter, false);
  1005. // set buffer pointers to minimize copying
  1006. {
  1007. int chIdx = 0, numChannels = 0;
  1008. bool interleaved = false;
  1009. AudioBufferList* buffer = nullptr;
  1010. // use output pointers
  1011. for (int busIdx = 0; busIdx < numOutputBuses; ++busIdx)
  1012. {
  1013. GetAudioBufferList (false, busIdx, buffer, interleaved, numChannels);
  1014. const int* outLayoutMap = mapper.get (false, busIdx);
  1015. for (int ch = 0; ch < numChannels; ++ch)
  1016. audioBuffer.setBuffer (chIdx++, interleaved ? nullptr : static_cast<float*> (buffer->mBuffers[outLayoutMap[ch]].mData));
  1017. }
  1018. // use input pointers on remaining channels
  1019. for (int busIdx = 0; chIdx < totalInChannels;)
  1020. {
  1021. int channelIndexInBus = juceFilter->getOffsetInBusBufferForAbsoluteChannelIndex (true, chIdx, busIdx);
  1022. const bool badData = ! pulledSucceeded[busIdx];
  1023. if (! badData)
  1024. GetAudioBufferList (true, busIdx, buffer, interleaved, numChannels);
  1025. const int* inLayoutMap = mapper.get (true, busIdx);
  1026. const int n = juceFilter->getChannelCountOfBus (true, busIdx);
  1027. for (int ch = channelIndexInBus; ch < n; ++ch)
  1028. audioBuffer.setBuffer (chIdx++, interleaved || badData ? nullptr : static_cast<float*> (buffer->mBuffers[inLayoutMap[ch]].mData));
  1029. }
  1030. }
  1031. // copy input
  1032. {
  1033. for (int busIdx = 0; busIdx < numInputBuses; ++busIdx)
  1034. {
  1035. if (pulledSucceeded[busIdx])
  1036. audioBuffer.set (busIdx, GetInput ((UInt32) busIdx)->GetBufferList(), mapper.get (true, busIdx));
  1037. else
  1038. audioBuffer.clearInputBus (busIdx, (int) nFrames);
  1039. }
  1040. audioBuffer.clearUnusedChannels ((int) nFrames);
  1041. }
  1042. // swap midi buffers
  1043. {
  1044. const ScopedLock sl (incomingMidiLock);
  1045. midiEvents.clear();
  1046. incomingEvents.swapWith (midiEvents);
  1047. }
  1048. // process audio
  1049. processBlock (audioBuffer.getBuffer (nFrames), midiEvents);
  1050. // copy back
  1051. {
  1052. for (int busIdx = 0; busIdx < numOutputBuses; ++busIdx)
  1053. audioBuffer.get (busIdx, GetOutput ((UInt32) busIdx)->GetBufferList(), mapper.get (false, busIdx));
  1054. }
  1055. // process midi output
  1056. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1057. if (! midiEvents.isEmpty() && midiCallback.midiOutputCallback != nullptr)
  1058. pushMidiOutput (nFrames);
  1059. #endif
  1060. midiEvents.clear();
  1061. return noErr;
  1062. }
  1063. //==============================================================================
  1064. ComponentResult StartNote (MusicDeviceInstrumentID, MusicDeviceGroupID, NoteInstanceID*, UInt32, const MusicDeviceNoteParams&) override { return noErr; }
  1065. ComponentResult StopNote (MusicDeviceGroupID, NoteInstanceID, UInt32) override { return noErr; }
  1066. //==============================================================================
  1067. OSStatus HandleMidiEvent (UInt8 nStatus, UInt8 inChannel, UInt8 inData1, UInt8 inData2, UInt32 inStartFrame) override
  1068. {
  1069. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1070. const juce::uint8 data[] = { (juce::uint8) (nStatus | inChannel),
  1071. (juce::uint8) inData1,
  1072. (juce::uint8) inData2 };
  1073. const ScopedLock sl (incomingMidiLock);
  1074. incomingEvents.addEvent (data, 3, (int) inStartFrame);
  1075. return noErr;
  1076. #else
  1077. ignoreUnused (nStatus, inChannel, inData1);
  1078. ignoreUnused (inData2, inStartFrame);
  1079. return kAudioUnitErr_PropertyNotInUse;
  1080. #endif
  1081. }
  1082. OSStatus HandleSysEx (const UInt8* inData, UInt32 inLength) override
  1083. {
  1084. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1085. const ScopedLock sl (incomingMidiLock);
  1086. incomingEvents.addEvent (inData, (int) inLength, 0);
  1087. return noErr;
  1088. #else
  1089. ignoreUnused (inData, inLength);
  1090. return kAudioUnitErr_PropertyNotInUse;
  1091. #endif
  1092. }
  1093. //==============================================================================
  1094. ComponentResult GetPresets (CFArrayRef* outData) const override
  1095. {
  1096. if (outData != nullptr)
  1097. {
  1098. const int numPrograms = juceFilter->getNumPrograms();
  1099. clearPresetsArray();
  1100. presetsArray.insertMultiple (0, AUPreset(), numPrograms);
  1101. CFMutableArrayRef presetsArrayRef = CFArrayCreateMutable (nullptr, numPrograms, nullptr);
  1102. for (int i = 0; i < numPrograms; ++i)
  1103. {
  1104. String name (juceFilter->getProgramName(i));
  1105. if (name.isEmpty())
  1106. name = "Untitled";
  1107. AUPreset& p = presetsArray.getReference(i);
  1108. p.presetNumber = i;
  1109. p.presetName = name.toCFString();
  1110. CFArrayAppendValue (presetsArrayRef, &p);
  1111. }
  1112. *outData = (CFArrayRef) presetsArrayRef;
  1113. }
  1114. return noErr;
  1115. }
  1116. OSStatus NewFactoryPresetSet (const AUPreset& inNewFactoryPreset) override
  1117. {
  1118. const int numPrograms = juceFilter->getNumPrograms();
  1119. const SInt32 chosenPresetNumber = (int) inNewFactoryPreset.presetNumber;
  1120. if (chosenPresetNumber >= numPrograms)
  1121. return kAudioUnitErr_InvalidProperty;
  1122. AUPreset chosenPreset;
  1123. chosenPreset.presetNumber = chosenPresetNumber;
  1124. chosenPreset.presetName = juceFilter->getProgramName (chosenPresetNumber).toCFString();
  1125. juceFilter->setCurrentProgram (chosenPresetNumber);
  1126. SetAFactoryPresetAsCurrent (chosenPreset);
  1127. return noErr;
  1128. }
  1129. //==============================================================================
  1130. class EditorCompHolder : public Component
  1131. {
  1132. public:
  1133. EditorCompHolder (AudioProcessorEditor* const editor)
  1134. {
  1135. addAndMakeVisible (editor);
  1136. #if ! JucePlugin_EditorRequiresKeyboardFocus
  1137. setWantsKeyboardFocus (false);
  1138. #else
  1139. setWantsKeyboardFocus (true);
  1140. #endif
  1141. setBounds (getSizeToContainChild());
  1142. lastBounds = getBounds();
  1143. }
  1144. ~EditorCompHolder() override
  1145. {
  1146. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  1147. // have been transferred to another parent which takes over ownership.
  1148. }
  1149. Rectangle<int> getSizeToContainChild()
  1150. {
  1151. if (auto* editor = getChildComponent (0))
  1152. return getLocalArea (editor, editor->getLocalBounds());
  1153. return {};
  1154. }
  1155. static NSView* createViewFor (AudioProcessor* filter, JuceAU* au, AudioProcessorEditor* const editor)
  1156. {
  1157. auto* editorCompHolder = new EditorCompHolder (editor);
  1158. auto r = convertToHostBounds (makeNSRect (editorCompHolder->getSizeToContainChild()));
  1159. static JuceUIViewClass cls;
  1160. auto* view = [[cls.createInstance() initWithFrame: r] autorelease];
  1161. JuceUIViewClass::setFilter (view, filter);
  1162. JuceUIViewClass::setAU (view, au);
  1163. JuceUIViewClass::setEditor (view, editorCompHolder);
  1164. [view setHidden: NO];
  1165. [view setPostsFrameChangedNotifications: YES];
  1166. [[NSNotificationCenter defaultCenter] addObserver: view
  1167. selector: @selector (applicationWillTerminate:)
  1168. name: NSApplicationWillTerminateNotification
  1169. object: nil];
  1170. activeUIs.add (view);
  1171. editorCompHolder->addToDesktop (0, (void*) view);
  1172. editorCompHolder->setVisible (view);
  1173. return view;
  1174. }
  1175. void parentSizeChanged() override
  1176. {
  1177. resizeHostWindow();
  1178. if (auto* editor = getChildComponent (0))
  1179. editor->repaint();
  1180. }
  1181. void childBoundsChanged (Component*) override
  1182. {
  1183. auto b = getSizeToContainChild();
  1184. if (lastBounds != b)
  1185. {
  1186. lastBounds = b;
  1187. setSize (jmax (32, b.getWidth()), jmax (32, b.getHeight()));
  1188. resizeHostWindow();
  1189. }
  1190. }
  1191. bool keyPressed (const KeyPress&) override
  1192. {
  1193. if (getHostType().isAbletonLive())
  1194. {
  1195. static NSTimeInterval lastEventTime = 0; // check we're not recursively sending the same event
  1196. NSTimeInterval eventTime = [[NSApp currentEvent] timestamp];
  1197. if (lastEventTime != eventTime)
  1198. {
  1199. lastEventTime = eventTime;
  1200. NSView* view = (NSView*) getWindowHandle();
  1201. NSView* hostView = [view superview];
  1202. NSWindow* hostWindow = [hostView window];
  1203. [hostWindow makeFirstResponder: hostView];
  1204. [hostView keyDown: (NSEvent*) [NSApp currentEvent]];
  1205. [hostWindow makeFirstResponder: view];
  1206. }
  1207. }
  1208. return false;
  1209. }
  1210. void resizeHostWindow()
  1211. {
  1212. [CATransaction begin];
  1213. [CATransaction setValue:(id) kCFBooleanTrue forKey:kCATransactionDisableActions];
  1214. auto rect = convertToHostBounds (makeNSRect (lastBounds));
  1215. auto* view = (NSView*) getWindowHandle();
  1216. auto superRect = [[view superview] frame];
  1217. superRect.size.width = rect.size.width;
  1218. superRect.size.height = rect.size.height;
  1219. [[view superview] setFrame: superRect];
  1220. [view setFrame: rect];
  1221. [CATransaction commit];
  1222. [view setNeedsDisplay: YES];
  1223. }
  1224. private:
  1225. Rectangle<int> lastBounds;
  1226. JUCE_DECLARE_NON_COPYABLE (EditorCompHolder)
  1227. };
  1228. void deleteActiveEditors()
  1229. {
  1230. for (int i = activeUIs.size(); --i >= 0;)
  1231. {
  1232. id ui = (id) activeUIs.getUnchecked(i);
  1233. if (JuceUIViewClass::getAU (ui) == this)
  1234. JuceUIViewClass::deleteEditor (ui);
  1235. }
  1236. }
  1237. //==============================================================================
  1238. struct JuceUIViewClass : public ObjCClass<NSView>
  1239. {
  1240. JuceUIViewClass() : ObjCClass<NSView> ("JUCEAUView_")
  1241. {
  1242. addIvar<AudioProcessor*> ("filter");
  1243. addIvar<JuceAU*> ("au");
  1244. addIvar<EditorCompHolder*> ("editor");
  1245. addMethod (@selector (dealloc), dealloc);
  1246. addMethod (@selector (applicationWillTerminate:), applicationWillTerminate);
  1247. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow);
  1248. addMethod (@selector (mouseDownCanMoveWindow), mouseDownCanMoveWindow);
  1249. registerClass();
  1250. }
  1251. static void deleteEditor (id self)
  1252. {
  1253. std::unique_ptr<EditorCompHolder> editorComp (getEditor (self));
  1254. if (editorComp != nullptr)
  1255. {
  1256. if (editorComp->getChildComponent(0) != nullptr
  1257. && activePlugins.contains (getAU (self))) // plugin may have been deleted before the UI
  1258. {
  1259. AudioProcessor* const filter = getIvar<AudioProcessor*> (self, "filter");
  1260. filter->editorBeingDeleted ((AudioProcessorEditor*) editorComp->getChildComponent(0));
  1261. }
  1262. editorComp = nullptr;
  1263. setEditor (self, nullptr);
  1264. }
  1265. }
  1266. static JuceAU* getAU (id self) { return getIvar<JuceAU*> (self, "au"); }
  1267. static EditorCompHolder* getEditor (id self) { return getIvar<EditorCompHolder*> (self, "editor"); }
  1268. static void setFilter (id self, AudioProcessor* filter) { object_setInstanceVariable (self, "filter", filter); }
  1269. static void setAU (id self, JuceAU* au) { object_setInstanceVariable (self, "au", au); }
  1270. static void setEditor (id self, EditorCompHolder* e) { object_setInstanceVariable (self, "editor", e); }
  1271. private:
  1272. static void dealloc (id self, SEL)
  1273. {
  1274. if (activeUIs.contains (self))
  1275. shutdown (self);
  1276. sendSuperclassMessage<void> (self, @selector (dealloc));
  1277. }
  1278. static void applicationWillTerminate (id self, SEL, NSNotification*)
  1279. {
  1280. shutdown (self);
  1281. }
  1282. static void shutdown (id self)
  1283. {
  1284. [[NSNotificationCenter defaultCenter] removeObserver: self];
  1285. deleteEditor (self);
  1286. jassert (activeUIs.contains (self));
  1287. activeUIs.removeFirstMatchingValue (self);
  1288. if (activePlugins.size() + activeUIs.size() == 0)
  1289. {
  1290. // there's some kind of component currently modal, but the host
  1291. // is trying to delete our plugin..
  1292. jassert (Component::getCurrentlyModalComponent() == nullptr);
  1293. shutdownJuce_GUI();
  1294. }
  1295. }
  1296. static void viewDidMoveToWindow (id self, SEL)
  1297. {
  1298. if (NSWindow* w = [(NSView*) self window])
  1299. {
  1300. [w setAcceptsMouseMovedEvents: YES];
  1301. if (EditorCompHolder* const editorComp = getEditor (self))
  1302. [w makeFirstResponder: (NSView*) editorComp->getWindowHandle()];
  1303. }
  1304. }
  1305. static BOOL mouseDownCanMoveWindow (id, SEL)
  1306. {
  1307. return NO;
  1308. }
  1309. };
  1310. //==============================================================================
  1311. struct JuceUICreationClass : public ObjCClass<NSObject>
  1312. {
  1313. JuceUICreationClass() : ObjCClass<NSObject> ("JUCE_AUCocoaViewClass_")
  1314. {
  1315. addMethod (@selector (interfaceVersion), interfaceVersion);
  1316. addMethod (@selector (description), description);
  1317. addMethod (@selector (uiViewForAudioUnit:withSize:), uiViewForAudioUnit);
  1318. addProtocol (@protocol (AUCocoaUIBase));
  1319. registerClass();
  1320. }
  1321. private:
  1322. static unsigned int interfaceVersion (id, SEL) { return 0; }
  1323. static NSString* description (id, SEL)
  1324. {
  1325. return [NSString stringWithString: nsStringLiteral (JucePlugin_Name)];
  1326. }
  1327. static NSView* uiViewForAudioUnit (id, SEL, AudioUnit inAudioUnit, NSSize)
  1328. {
  1329. void* pointers[2];
  1330. UInt32 propertySize = sizeof (pointers);
  1331. if (AudioUnitGetProperty (inAudioUnit, juceFilterObjectPropertyID,
  1332. kAudioUnitScope_Global, 0, pointers, &propertySize) == noErr)
  1333. {
  1334. if (AudioProcessor* filter = static_cast<AudioProcessor*> (pointers[0]))
  1335. if (AudioProcessorEditor* editorComp = filter->createEditorIfNeeded())
  1336. return EditorCompHolder::createViewFor (filter, static_cast<JuceAU*> (pointers[1]), editorComp);
  1337. }
  1338. return nil;
  1339. }
  1340. };
  1341. private:
  1342. //==============================================================================
  1343. /* The call to AUBase::PropertyChanged may allocate hence the need for this class */
  1344. class AudioProcessorChangedUpdater final : private AsyncUpdater
  1345. {
  1346. public:
  1347. explicit AudioProcessorChangedUpdater (JuceAU& o) : owner (o) {}
  1348. ~AudioProcessorChangedUpdater() override { cancelPendingUpdate(); }
  1349. void update (const ChangeDetails& details)
  1350. {
  1351. int flags = 0;
  1352. if (details.latencyChanged)
  1353. flags |= latencyChangedFlag;
  1354. if (details.parameterInfoChanged)
  1355. flags |= parameterInfoChangedFlag;
  1356. if (details.programChanged)
  1357. flags |= programChangedFlag;
  1358. if (flags != 0)
  1359. {
  1360. callbackFlags.fetch_or (flags);
  1361. if (MessageManager::getInstance()->isThisTheMessageThread())
  1362. handleAsyncUpdate();
  1363. else
  1364. triggerAsyncUpdate();
  1365. }
  1366. }
  1367. private:
  1368. void handleAsyncUpdate() override
  1369. {
  1370. const auto flags = callbackFlags.exchange (0);
  1371. if ((flags & latencyChangedFlag) != 0)
  1372. owner.PropertyChanged (kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0);
  1373. if ((flags & parameterInfoChangedFlag) != 0)
  1374. {
  1375. owner.PropertyChanged (kAudioUnitProperty_ParameterList, kAudioUnitScope_Global, 0);
  1376. owner.PropertyChanged (kAudioUnitProperty_ParameterInfo, kAudioUnitScope_Global, 0);
  1377. }
  1378. owner.PropertyChanged (kAudioUnitProperty_ClassInfo, kAudioUnitScope_Global, 0);
  1379. if ((flags & programChangedFlag) != 0)
  1380. {
  1381. owner.refreshCurrentPreset();
  1382. owner.PropertyChanged (kAudioUnitProperty_PresentPreset, kAudioUnitScope_Global, 0);
  1383. }
  1384. }
  1385. JuceAU& owner;
  1386. static constexpr int latencyChangedFlag = 1 << 0,
  1387. parameterInfoChangedFlag = 1 << 1,
  1388. programChangedFlag = 1 << 2;
  1389. std::atomic<int> callbackFlags { 0 };
  1390. };
  1391. //==============================================================================
  1392. AudioUnitHelpers::CoreAudioBufferList audioBuffer;
  1393. MidiBuffer midiEvents, incomingEvents;
  1394. bool prepared = false, isBypassed = false, restoringState = false;
  1395. //==============================================================================
  1396. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1397. static constexpr bool forceUseLegacyParamIDs = true;
  1398. #else
  1399. static constexpr bool forceUseLegacyParamIDs = false;
  1400. #endif
  1401. //==============================================================================
  1402. LegacyAudioParametersWrapper juceParameters;
  1403. std::unordered_map<int32, AudioProcessorParameter*> paramMap;
  1404. Array<AudioUnitParameterID> auParamIDs;
  1405. Array<const AudioProcessorParameterGroup*> parameterGroups;
  1406. // Stores the parameter IDs in the order that they will be reported to the host.
  1407. std::vector<AudioUnitParameterID> cachedParameterList;
  1408. //==============================================================================
  1409. // According to the docs, this is the maximum size of a MIDIPacketList.
  1410. static constexpr UInt32 packetListBytes = 65536;
  1411. CoreAudioTimeConversions timeConversions;
  1412. AudioUnitEvent auEvent;
  1413. mutable Array<AUPreset> presetsArray;
  1414. CriticalSection incomingMidiLock;
  1415. AUMIDIOutputCallbackStruct midiCallback;
  1416. AudioTimeStamp lastTimeStamp;
  1417. int totalInChannels, totalOutChannels;
  1418. HeapBlock<bool> pulledSucceeded;
  1419. HeapBlock<MIDIPacketList> packetList { packetListBytes, 1 };
  1420. ThreadLocalValue<bool> inParameterChangedCallback;
  1421. AudioProcessorChangedUpdater audioProcessorChangedUpdater { *this };
  1422. //==============================================================================
  1423. Array<AUChannelInfo> channelInfo;
  1424. Array<Array<AudioChannelLayoutTag>> supportedInputLayouts, supportedOutputLayouts;
  1425. Array<AudioChannelLayoutTag> currentInputLayout, currentOutputLayout;
  1426. //==============================================================================
  1427. AudioUnitHelpers::ChannelRemapper mapper;
  1428. //==============================================================================
  1429. OwnedArray<OwnedArray<const __CFString>> parameterValueStringArrays;
  1430. //==============================================================================
  1431. AudioProcessorParameter* bypassParam = nullptr;
  1432. //==============================================================================
  1433. static NSRect convertToHostBounds (NSRect pluginRect)
  1434. {
  1435. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1436. if (approximatelyEqual (desktopScale, 1.0f))
  1437. return pluginRect;
  1438. return NSMakeRect (static_cast<CGFloat> (pluginRect.origin.x * desktopScale),
  1439. static_cast<CGFloat> (pluginRect.origin.y * desktopScale),
  1440. static_cast<CGFloat> (pluginRect.size.width * desktopScale),
  1441. static_cast<CGFloat> (pluginRect.size.height * desktopScale));
  1442. }
  1443. static NSRect convertFromHostBounds (NSRect hostRect)
  1444. {
  1445. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1446. if (approximatelyEqual (desktopScale, 1.0f))
  1447. return hostRect;
  1448. return NSMakeRect (static_cast<CGFloat> (hostRect.origin.x / desktopScale),
  1449. static_cast<CGFloat> (hostRect.origin.y / desktopScale),
  1450. static_cast<CGFloat> (hostRect.size.width / desktopScale),
  1451. static_cast<CGFloat> (hostRect.size.height / desktopScale));
  1452. }
  1453. //==============================================================================
  1454. void pullInputAudio (AudioUnitRenderActionFlags& flags, const AudioTimeStamp& timestamp, const UInt32 nFrames) noexcept
  1455. {
  1456. const unsigned int numInputBuses = GetScope (kAudioUnitScope_Input).GetNumberOfElements();
  1457. for (unsigned int i = 0; i < numInputBuses; ++i)
  1458. {
  1459. if (AUInputElement* input = GetInput (i))
  1460. {
  1461. const bool succeeded = (input->PullInput (flags, timestamp, i, nFrames) == noErr);
  1462. if ((flags & kAudioUnitRenderAction_OutputIsSilence) != 0 && succeeded)
  1463. AudioUnitHelpers::clearAudioBuffer (input->GetBufferList());
  1464. pulledSucceeded[i] = succeeded;
  1465. }
  1466. }
  1467. }
  1468. void prepareOutputBuffers (const UInt32 nFrames) noexcept
  1469. {
  1470. const auto numProcessorBuses = AudioUnitHelpers::getBusCount (*juceFilter, false);
  1471. const auto numWrapperBuses = GetScope (kAudioUnitScope_Output).GetNumberOfElements();
  1472. for (UInt32 busIdx = 0; busIdx < numWrapperBuses; ++busIdx)
  1473. {
  1474. AUOutputElement* output = GetOutput (busIdx);
  1475. if (output->WillAllocateBuffer())
  1476. output->PrepareBuffer (nFrames);
  1477. if (busIdx >= (UInt32) numProcessorBuses)
  1478. AudioUnitHelpers::clearAudioBuffer (output->GetBufferList());
  1479. }
  1480. }
  1481. void processBlock (juce::AudioBuffer<float>& buffer, MidiBuffer& midiBuffer) noexcept
  1482. {
  1483. const ScopedLock sl (juceFilter->getCallbackLock());
  1484. if (juceFilter->isSuspended())
  1485. {
  1486. buffer.clear();
  1487. }
  1488. else if (bypassParam == nullptr && isBypassed)
  1489. {
  1490. juceFilter->processBlockBypassed (buffer, midiBuffer);
  1491. }
  1492. else
  1493. {
  1494. juceFilter->processBlock (buffer, midiBuffer);
  1495. }
  1496. }
  1497. void pushMidiOutput (UInt32 nFrames) noexcept
  1498. {
  1499. MIDIPacket* end = nullptr;
  1500. const auto init = [&]
  1501. {
  1502. end = MIDIPacketListInit (packetList);
  1503. };
  1504. const auto send = [&]
  1505. {
  1506. midiCallback.midiOutputCallback (midiCallback.userData, &lastTimeStamp, 0, packetList);
  1507. };
  1508. const auto add = [&] (const MidiMessageMetadata& metadata)
  1509. {
  1510. end = MIDIPacketListAdd (packetList,
  1511. packetListBytes,
  1512. end,
  1513. static_cast<MIDITimeStamp> (metadata.samplePosition),
  1514. static_cast<ByteCount> (metadata.numBytes),
  1515. metadata.data);
  1516. };
  1517. init();
  1518. for (const auto metadata : midiEvents)
  1519. {
  1520. jassert (isPositiveAndBelow (metadata.samplePosition, nFrames));
  1521. ignoreUnused (nFrames);
  1522. add (metadata);
  1523. if (end == nullptr)
  1524. {
  1525. send();
  1526. init();
  1527. add (metadata);
  1528. if (end == nullptr)
  1529. {
  1530. // If this is hit, the size of this midi packet exceeds the maximum size of
  1531. // a MIDIPacketList. Large SysEx messages should be broken up into smaller
  1532. // chunks.
  1533. jassertfalse;
  1534. init();
  1535. }
  1536. }
  1537. }
  1538. send();
  1539. }
  1540. void GetAudioBufferList (bool isInput, int busIdx, AudioBufferList*& bufferList, bool& interleaved, int& numChannels)
  1541. {
  1542. AUIOElement* element = GetElement (isInput ? kAudioUnitScope_Input : kAudioUnitScope_Output, static_cast<UInt32> (busIdx))->AsIOElement();
  1543. jassert (element != nullptr);
  1544. bufferList = &element->GetBufferList();
  1545. jassert (bufferList->mNumberBuffers > 0);
  1546. interleaved = AudioUnitHelpers::isAudioBufferInterleaved (*bufferList);
  1547. numChannels = static_cast<int> (interleaved ? bufferList->mBuffers[0].mNumberChannels : bufferList->mNumberBuffers);
  1548. }
  1549. //==============================================================================
  1550. static OSStatus scopeToDirection (AudioUnitScope scope, bool& isInput) noexcept
  1551. {
  1552. isInput = (scope == kAudioUnitScope_Input);
  1553. return (scope != kAudioUnitScope_Input
  1554. && scope != kAudioUnitScope_Output)
  1555. ? (OSStatus) kAudioUnitErr_InvalidScope : (OSStatus) noErr;
  1556. }
  1557. enum class BusKind
  1558. {
  1559. processor,
  1560. wrapperOnly,
  1561. };
  1562. struct ElementInfo
  1563. {
  1564. int busNr;
  1565. BusKind kind;
  1566. bool isInput;
  1567. OSStatus error;
  1568. };
  1569. ElementInfo getElementInfo (AudioUnitScope scope, AudioUnitElement element) noexcept
  1570. {
  1571. bool isInput = false;
  1572. OSStatus err;
  1573. if ((err = scopeToDirection (scope, isInput)) != noErr)
  1574. return { {}, {}, {}, err };
  1575. const auto busIdx = static_cast<int> (element);
  1576. if (isPositiveAndBelow (busIdx, AudioUnitHelpers::getBusCount (*juceFilter, isInput)))
  1577. return { busIdx, BusKind::processor, isInput, noErr };
  1578. if (isPositiveAndBelow (busIdx, AudioUnitHelpers::getBusCountForWrapper (*juceFilter, isInput)))
  1579. return { busIdx, BusKind::wrapperOnly, isInput, noErr };
  1580. return { {}, {}, {}, kAudioUnitErr_InvalidElement };
  1581. }
  1582. OSStatus GetParameterList (AudioUnitScope inScope, AudioUnitParameterID* outParameterList, UInt32& outNumParameters) override
  1583. {
  1584. if (forceUseLegacyParamIDs || inScope != kAudioUnitScope_Global)
  1585. return MusicDeviceBase::GetParameterList (inScope, outParameterList, outNumParameters);
  1586. outNumParameters = (UInt32) juceParameters.size();
  1587. if (outParameterList == nullptr)
  1588. return noErr;
  1589. if (cachedParameterList.empty())
  1590. {
  1591. struct ParamInfo
  1592. {
  1593. AudioUnitParameterID identifier;
  1594. int versionHint;
  1595. };
  1596. std::vector<ParamInfo> vec;
  1597. vec.reserve (juceParameters.size());
  1598. for (const auto* param : juceParameters)
  1599. vec.push_back ({ generateAUParameterID (*param), param->getVersionHint() });
  1600. std::sort (vec.begin(), vec.end(), [] (auto a, auto b) { return a.identifier < b.identifier; });
  1601. std::stable_sort (vec.begin(), vec.end(), [] (auto a, auto b) { return a.versionHint < b.versionHint; });
  1602. std::transform (vec.begin(), vec.end(), std::back_inserter (cachedParameterList), [] (auto x) { return x.identifier; });
  1603. }
  1604. std::copy (cachedParameterList.begin(), cachedParameterList.end(), outParameterList);
  1605. return noErr;
  1606. }
  1607. //==============================================================================
  1608. void addParameters()
  1609. {
  1610. parameterGroups = juceFilter->getParameterTree().getSubgroups (true);
  1611. juceParameters.update (*juceFilter, forceUseLegacyParamIDs);
  1612. const int numParams = juceParameters.getNumParameters();
  1613. if (forceUseLegacyParamIDs)
  1614. {
  1615. Globals()->UseIndexedParameters (numParams);
  1616. }
  1617. else
  1618. {
  1619. for (auto* param : juceParameters)
  1620. {
  1621. const AudioUnitParameterID auParamID = generateAUParameterID (*param);
  1622. // Consider yourself very unlucky if you hit this assertion. The hash codes of your
  1623. // parameter ids are not unique.
  1624. jassert (paramMap.find (static_cast<int32> (auParamID)) == paramMap.end());
  1625. auParamIDs.add (auParamID);
  1626. paramMap.emplace (static_cast<int32> (auParamID), param);
  1627. Globals()->SetParameter (auParamID, param->getValue());
  1628. }
  1629. }
  1630. #if JUCE_DEBUG
  1631. // Some hosts can't handle the huge numbers of discrete parameter values created when
  1632. // using the default number of steps.
  1633. for (auto* param : juceParameters)
  1634. if (param->isDiscrete())
  1635. jassert (param->getNumSteps() != AudioProcessor::getDefaultNumParameterSteps());
  1636. #endif
  1637. parameterValueStringArrays.ensureStorageAllocated (numParams);
  1638. for (auto* param : juceParameters)
  1639. {
  1640. OwnedArray<const __CFString>* stringValues = nullptr;
  1641. auto initialValue = param->getValue();
  1642. bool paramIsLegacy = dynamic_cast<LegacyAudioParameter*> (param) != nullptr;
  1643. if (param->isDiscrete() && (! forceUseLegacyParamIDs))
  1644. {
  1645. const auto numSteps = param->getNumSteps();
  1646. stringValues = new OwnedArray<const __CFString>();
  1647. stringValues->ensureStorageAllocated (numSteps);
  1648. const auto maxValue = getMaximumParameterValue (param);
  1649. auto getTextValue = [param, paramIsLegacy] (float value)
  1650. {
  1651. if (paramIsLegacy)
  1652. {
  1653. param->setValue (value);
  1654. return param->getCurrentValueAsText();
  1655. }
  1656. return param->getText (value, 256);
  1657. };
  1658. for (int i = 0; i < numSteps; ++i)
  1659. {
  1660. auto value = (float) i / maxValue;
  1661. stringValues->add (CFStringCreateCopy (nullptr, (getTextValue (value).toCFString())));
  1662. }
  1663. }
  1664. if (paramIsLegacy)
  1665. param->setValue (initialValue);
  1666. parameterValueStringArrays.add (stringValues);
  1667. }
  1668. if ((bypassParam = juceFilter->getBypassParameter()) != nullptr)
  1669. bypassParam->addListener (this);
  1670. }
  1671. //==============================================================================
  1672. static AudioUnitParameterID generateAUParameterID (const AudioProcessorParameter& param)
  1673. {
  1674. const String& juceParamID = LegacyAudioParameter::getParamID (&param, forceUseLegacyParamIDs);
  1675. AudioUnitParameterID paramHash = static_cast<AudioUnitParameterID> (juceParamID.hashCode());
  1676. #if JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS
  1677. // studio one doesn't like negative parameters
  1678. paramHash &= ~(((AudioUnitParameterID) 1) << (sizeof (AudioUnitParameterID) * 8 - 1));
  1679. #endif
  1680. return forceUseLegacyParamIDs ? static_cast<AudioUnitParameterID> (juceParamID.getIntValue())
  1681. : paramHash;
  1682. }
  1683. inline AudioUnitParameterID getAUParameterIDForIndex (int paramIndex) const noexcept
  1684. {
  1685. return forceUseLegacyParamIDs ? static_cast<AudioUnitParameterID> (paramIndex)
  1686. : auParamIDs.getReference (paramIndex);
  1687. }
  1688. AudioProcessorParameter* getParameterForAUParameterID (AudioUnitParameterID address) const noexcept
  1689. {
  1690. const auto index = static_cast<int32> (address);
  1691. if (forceUseLegacyParamIDs)
  1692. return juceParameters.getParamForIndex (index);
  1693. const auto iter = paramMap.find (index);
  1694. return iter != paramMap.end() ? iter->second : nullptr;
  1695. }
  1696. //==============================================================================
  1697. OSStatus syncAudioUnitWithProcessor()
  1698. {
  1699. OSStatus err = noErr;
  1700. const auto numWrapperInputs = AudioUnitHelpers::getBusCountForWrapper (*juceFilter, true);
  1701. const auto numWrapperOutputs = AudioUnitHelpers::getBusCountForWrapper (*juceFilter, false);
  1702. if ((err = MusicDeviceBase::SetBusCount (kAudioUnitScope_Input, static_cast<UInt32> (numWrapperInputs))) != noErr)
  1703. return err;
  1704. if ((err = MusicDeviceBase::SetBusCount (kAudioUnitScope_Output, static_cast<UInt32> (numWrapperOutputs))) != noErr)
  1705. return err;
  1706. addSupportedLayoutTags();
  1707. const auto numProcessorInputs = AudioUnitHelpers::getBusCount (*juceFilter, true);
  1708. const auto numProcessorOutputs = AudioUnitHelpers::getBusCount (*juceFilter, false);
  1709. for (int i = 0; i < numProcessorInputs; ++i)
  1710. if ((err = syncAudioUnitWithChannelSet (true, i, juceFilter->getChannelLayoutOfBus (true, i))) != noErr)
  1711. return err;
  1712. for (int i = 0; i < numProcessorOutputs; ++i)
  1713. if ((err = syncAudioUnitWithChannelSet (false, i, juceFilter->getChannelLayoutOfBus (false, i))) != noErr)
  1714. return err;
  1715. return noErr;
  1716. }
  1717. OSStatus syncProcessorWithAudioUnit()
  1718. {
  1719. const int numInputBuses = AudioUnitHelpers::getBusCount (*juceFilter, true);
  1720. const int numOutputBuses = AudioUnitHelpers::getBusCount (*juceFilter, false);
  1721. const int numInputElements = static_cast<int> (GetScope(kAudioUnitScope_Input). GetNumberOfElements());
  1722. const int numOutputElements = static_cast<int> (GetScope(kAudioUnitScope_Output).GetNumberOfElements());
  1723. AudioProcessor::BusesLayout requestedLayouts;
  1724. for (int dir = 0; dir < 2; ++dir)
  1725. {
  1726. const bool isInput = (dir == 0);
  1727. const int n = (isInput ? numInputBuses : numOutputBuses);
  1728. const int numAUElements = (isInput ? numInputElements : numOutputElements);
  1729. Array<AudioChannelSet>& requestedBuses = (isInput ? requestedLayouts.inputBuses : requestedLayouts.outputBuses);
  1730. for (int busIdx = 0; busIdx < n; ++busIdx)
  1731. {
  1732. const AUIOElement* element = (busIdx < numAUElements ? GetIOElement (isInput ? kAudioUnitScope_Input : kAudioUnitScope_Output, (UInt32) busIdx) : nullptr);
  1733. const int numChannels = (element != nullptr ? static_cast<int> (element->GetStreamFormat().NumberChannels()) : 0);
  1734. AudioChannelLayoutTag currentLayoutTag = isInput ? currentInputLayout[busIdx] : currentOutputLayout[busIdx];
  1735. const int tagNumChannels = currentLayoutTag & 0xffff;
  1736. if (numChannels != tagNumChannels)
  1737. return kAudioUnitErr_FormatNotSupported;
  1738. requestedBuses.add (CoreAudioLayouts::fromCoreAudio (currentLayoutTag));
  1739. }
  1740. }
  1741. #ifdef JucePlugin_PreferredChannelConfigurations
  1742. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1743. if (! AudioProcessor::containsLayout (requestedLayouts, configs))
  1744. return kAudioUnitErr_FormatNotSupported;
  1745. #endif
  1746. if (! AudioUnitHelpers::setBusesLayout (juceFilter.get(), requestedLayouts))
  1747. return kAudioUnitErr_FormatNotSupported;
  1748. // update total channel count
  1749. totalInChannels = juceFilter->getTotalNumInputChannels();
  1750. totalOutChannels = juceFilter->getTotalNumOutputChannels();
  1751. return noErr;
  1752. }
  1753. OSStatus syncAudioUnitWithChannelSet (bool isInput, int busNr, const AudioChannelSet& channelSet)
  1754. {
  1755. const int numChannels = channelSet.size();
  1756. getCurrentLayout (isInput, busNr) = CoreAudioLayouts::toCoreAudio (channelSet);
  1757. // is this bus activated?
  1758. if (numChannels == 0)
  1759. return noErr;
  1760. if (AUIOElement* element = GetIOElement (isInput ? kAudioUnitScope_Input : kAudioUnitScope_Output, (UInt32) busNr))
  1761. {
  1762. element->SetName ((CFStringRef) juceStringToNS (juceFilter->getBus (isInput, busNr)->getName()));
  1763. CAStreamBasicDescription streamDescription;
  1764. streamDescription.mSampleRate = getSampleRate();
  1765. streamDescription.SetCanonical ((UInt32) numChannels, false);
  1766. return element->SetStreamFormat (streamDescription);
  1767. }
  1768. else
  1769. jassertfalse;
  1770. return kAudioUnitErr_InvalidElement;
  1771. }
  1772. //==============================================================================
  1773. void clearPresetsArray() const
  1774. {
  1775. for (int i = presetsArray.size(); --i >= 0;)
  1776. CFRelease (presetsArray.getReference(i).presetName);
  1777. presetsArray.clear();
  1778. }
  1779. void refreshCurrentPreset()
  1780. {
  1781. // this will make the AU host re-read and update the current preset name
  1782. // in case it was changed here in the plug-in:
  1783. const int currentProgramNumber = juceFilter->getCurrentProgram();
  1784. const String currentProgramName = juceFilter->getProgramName (currentProgramNumber);
  1785. AUPreset currentPreset;
  1786. currentPreset.presetNumber = currentProgramNumber;
  1787. currentPreset.presetName = currentProgramName.toCFString();
  1788. SetAFactoryPresetAsCurrent (currentPreset);
  1789. }
  1790. //==============================================================================
  1791. Array<AudioChannelLayoutTag>& getSupportedBusLayouts (bool isInput, int bus) noexcept { return (isInput ? supportedInputLayouts : supportedOutputLayouts).getReference (bus); }
  1792. const Array<AudioChannelLayoutTag>& getSupportedBusLayouts (bool isInput, int bus) const noexcept { return (isInput ? supportedInputLayouts : supportedOutputLayouts).getReference (bus); }
  1793. AudioChannelLayoutTag& getCurrentLayout (bool isInput, int bus) noexcept { return (isInput ? currentInputLayout : currentOutputLayout).getReference (bus); }
  1794. AudioChannelLayoutTag getCurrentLayout (bool isInput, int bus) const noexcept { return (isInput ? currentInputLayout : currentOutputLayout)[bus]; }
  1795. //==============================================================================
  1796. void addSupportedLayoutTagsForBus (bool isInput, int busNum, Array<AudioChannelLayoutTag>& tags)
  1797. {
  1798. if (AudioProcessor::Bus* bus = juceFilter->getBus (isInput, busNum))
  1799. {
  1800. #ifndef JucePlugin_PreferredChannelConfigurations
  1801. auto& knownTags = CoreAudioLayouts::getKnownCoreAudioTags();
  1802. for (auto tag : knownTags)
  1803. if (bus->isLayoutSupported (CoreAudioLayouts::fromCoreAudio (tag)))
  1804. tags.addIfNotAlreadyThere (tag);
  1805. #endif
  1806. // add discrete layout tags
  1807. int n = bus->getMaxSupportedChannels (maxChannelsToProbeFor());
  1808. for (int ch = 0; ch < n; ++ch)
  1809. {
  1810. #ifdef JucePlugin_PreferredChannelConfigurations
  1811. const short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1812. if (AudioUnitHelpers::isLayoutSupported (*juceFilter, isInput, busNum, ch, configs))
  1813. tags.addIfNotAlreadyThere (static_cast<AudioChannelLayoutTag> ((int) kAudioChannelLayoutTag_DiscreteInOrder | ch));
  1814. #else
  1815. if (bus->isLayoutSupported (AudioChannelSet::discreteChannels (ch)))
  1816. tags.addIfNotAlreadyThere (static_cast<AudioChannelLayoutTag> ((int) kAudioChannelLayoutTag_DiscreteInOrder | ch));
  1817. #endif
  1818. }
  1819. }
  1820. }
  1821. void addSupportedLayoutTagsForDirection (bool isInput)
  1822. {
  1823. auto& layouts = isInput ? supportedInputLayouts : supportedOutputLayouts;
  1824. layouts.clearQuick();
  1825. auto numBuses = AudioUnitHelpers::getBusCount (*juceFilter, isInput);
  1826. for (int busNr = 0; busNr < numBuses; ++busNr)
  1827. {
  1828. Array<AudioChannelLayoutTag> busLayouts;
  1829. addSupportedLayoutTagsForBus (isInput, busNr, busLayouts);
  1830. layouts.add (busLayouts);
  1831. }
  1832. }
  1833. void addSupportedLayoutTags()
  1834. {
  1835. currentInputLayout.clear(); currentOutputLayout.clear();
  1836. currentInputLayout. resize (AudioUnitHelpers::getBusCountForWrapper (*juceFilter, true));
  1837. currentOutputLayout.resize (AudioUnitHelpers::getBusCountForWrapper (*juceFilter, false));
  1838. addSupportedLayoutTagsForDirection (true);
  1839. addSupportedLayoutTagsForDirection (false);
  1840. }
  1841. static int maxChannelsToProbeFor()
  1842. {
  1843. return (getHostType().isLogic() ? 8 : 64);
  1844. }
  1845. //==============================================================================
  1846. void auPropertyListener (AudioUnitPropertyID propId, AudioUnitScope scope, AudioUnitElement)
  1847. {
  1848. if (scope == kAudioUnitScope_Global && propId == kAudioUnitProperty_ContextName
  1849. && juceFilter != nullptr && mContextName != nullptr)
  1850. {
  1851. AudioProcessor::TrackProperties props;
  1852. props.name = String::fromCFString (mContextName);
  1853. juceFilter->updateTrackProperties (props);
  1854. }
  1855. }
  1856. static void auPropertyListenerDispatcher (void* inRefCon, AudioUnit, AudioUnitPropertyID propId,
  1857. AudioUnitScope scope, AudioUnitElement element)
  1858. {
  1859. static_cast<JuceAU*> (inRefCon)->auPropertyListener (propId, scope, element);
  1860. }
  1861. JUCE_DECLARE_NON_COPYABLE (JuceAU)
  1862. };
  1863. //==============================================================================
  1864. #define JUCE_COMPONENT_ENTRYX(Class, Name, Suffix) \
  1865. extern "C" __attribute__((visibility("default"))) ComponentResult Name ## Suffix (ComponentParameters* params, Class* obj); \
  1866. extern "C" __attribute__((visibility("default"))) ComponentResult Name ## Suffix (ComponentParameters* params, Class* obj) \
  1867. { \
  1868. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_AudioUnit; \
  1869. return ComponentEntryPoint<Class>::Dispatch (params, obj); \
  1870. }
  1871. #if JucePlugin_ProducesMidiOutput || JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1872. #define FACTORY_BASE_CLASS AUMIDIEffectFactory
  1873. #else
  1874. #define FACTORY_BASE_CLASS AUBaseFactory
  1875. #endif
  1876. #define JUCE_FACTORY_ENTRYX(Class, Name) \
  1877. extern "C" __attribute__((visibility("default"))) void* Name ## Factory (const AudioComponentDescription* desc); \
  1878. extern "C" __attribute__((visibility("default"))) void* Name ## Factory (const AudioComponentDescription* desc) \
  1879. { \
  1880. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_AudioUnit; \
  1881. return FACTORY_BASE_CLASS<Class>::Factory (desc); \
  1882. }
  1883. #define JUCE_COMPONENT_ENTRY(Class, Name, Suffix) JUCE_COMPONENT_ENTRYX(Class, Name, Suffix)
  1884. #define JUCE_FACTORY_ENTRY(Class, Name) JUCE_FACTORY_ENTRYX(Class, Name)
  1885. //==============================================================================
  1886. JUCE_COMPONENT_ENTRY (JuceAU, JucePlugin_AUExportPrefix, Entry)
  1887. #ifndef AUDIOCOMPONENT_ENTRY
  1888. #define JUCE_DISABLE_AU_FACTORY_ENTRY 1
  1889. #endif
  1890. #if ! JUCE_DISABLE_AU_FACTORY_ENTRY // (You might need to disable this for old Xcode 3 builds)
  1891. JUCE_FACTORY_ENTRY (JuceAU, JucePlugin_AUExportPrefix)
  1892. #endif
  1893. #if ! JUCE_DISABLE_AU_FACTORY_ENTRY
  1894. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wcast-align", "-Wzero-as-null-pointer-constant")
  1895. #include "CoreAudioUtilityClasses/AUPlugInDispatch.cpp"
  1896. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1897. #endif
  1898. #endif