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.

2372 lines
91KB

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