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.

2404 lines
92KB

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