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.

2315 lines
88KB

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