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.

2494 lines
95KB

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