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.

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