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.

2246 lines
85KB

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