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.

2513 lines
96KB

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