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.

2497 lines
96KB

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