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.

2489 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* param)
  679. {
  680. return param->isDiscrete() && (! forceUseLegacyParamIDs) ? (float) (param->getNumSteps() - 1) : 1.0f;
  681. }
  682. ComponentResult GetParameterInfo (AudioUnitScope inScope,
  683. AudioUnitParameterID inParameterID,
  684. AudioUnitParameterInfo& outParameterInfo) override
  685. {
  686. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  687. {
  688. if (auto* param = getParameterForAUParameterID (inParameterID))
  689. {
  690. outParameterInfo.unit = kAudioUnitParameterUnit_Generic;
  691. outParameterInfo.flags = (UInt32) (kAudioUnitParameterFlag_IsWritable
  692. | kAudioUnitParameterFlag_IsReadable
  693. | kAudioUnitParameterFlag_HasCFNameString
  694. | kAudioUnitParameterFlag_ValuesHaveStrings);
  695. #if ! JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE
  696. outParameterInfo.flags |= (UInt32) kAudioUnitParameterFlag_IsHighResolution;
  697. #endif
  698. const String name = param->getName (1024);
  699. // Set whether the param is automatable (unnamed parameters aren't allowed to be automated)
  700. if (name.isEmpty() || ! param->isAutomatable())
  701. outParameterInfo.flags |= kAudioUnitParameterFlag_NonRealTime;
  702. const bool isParameterDiscrete = param->isDiscrete();
  703. if (! isParameterDiscrete)
  704. outParameterInfo.flags |= kAudioUnitParameterFlag_CanRamp;
  705. if (param->isMetaParameter())
  706. outParameterInfo.flags |= kAudioUnitParameterFlag_IsGlobalMeta;
  707. auto parameterGroupHierarchy = juceFilter->getParameterTree().getGroupsForParameter (param);
  708. if (! parameterGroupHierarchy.isEmpty())
  709. {
  710. outParameterInfo.flags |= kAudioUnitParameterFlag_HasClump;
  711. outParameterInfo.clumpID = (UInt32) parameterGroups.indexOf (parameterGroupHierarchy.getLast()) + 1;
  712. }
  713. // Is this a meter?
  714. if (((param->getCategory() & 0xffff0000) >> 16) == 2)
  715. {
  716. outParameterInfo.flags &= ~kAudioUnitParameterFlag_IsWritable;
  717. outParameterInfo.flags |= kAudioUnitParameterFlag_MeterReadOnly | kAudioUnitParameterFlag_DisplayLogarithmic;
  718. outParameterInfo.unit = kAudioUnitParameterUnit_LinearGain;
  719. }
  720. else
  721. {
  722. #if ! JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE
  723. if (isParameterDiscrete)
  724. {
  725. outParameterInfo.unit = kAudioUnitParameterUnit_Indexed;
  726. if (param->isBoolean())
  727. outParameterInfo.unit = kAudioUnitParameterUnit_Boolean;
  728. }
  729. #endif
  730. }
  731. MusicDeviceBase::FillInParameterName (outParameterInfo, name.toCFString(), true);
  732. outParameterInfo.minValue = 0.0f;
  733. outParameterInfo.maxValue = getMaximumParameterValue (param);
  734. outParameterInfo.defaultValue = param->getDefaultValue() * getMaximumParameterValue (param);
  735. jassert (outParameterInfo.defaultValue >= outParameterInfo.minValue
  736. && outParameterInfo.defaultValue <= outParameterInfo.maxValue);
  737. return noErr;
  738. }
  739. }
  740. return kAudioUnitErr_InvalidParameter;
  741. }
  742. ComponentResult GetParameterValueStrings (AudioUnitScope inScope,
  743. AudioUnitParameterID inParameterID,
  744. CFArrayRef *outStrings) override
  745. {
  746. if (outStrings == nullptr)
  747. return noErr;
  748. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  749. {
  750. if (auto* param = getParameterForAUParameterID (inParameterID))
  751. {
  752. if (param->isDiscrete())
  753. {
  754. auto index = LegacyAudioParameter::getParamIndex (*juceFilter, param);
  755. if (auto* valueStrings = parameterValueStringArrays[index])
  756. {
  757. *outStrings = CFArrayCreate (NULL,
  758. (const void **) valueStrings->getRawDataPointer(),
  759. valueStrings->size(),
  760. NULL);
  761. return noErr;
  762. }
  763. }
  764. }
  765. }
  766. return kAudioUnitErr_InvalidParameter;
  767. }
  768. ComponentResult GetParameter (AudioUnitParameterID inID,
  769. AudioUnitScope inScope,
  770. AudioUnitElement inElement,
  771. Float32& outValue) override
  772. {
  773. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  774. {
  775. if (auto* param = getParameterForAUParameterID (inID))
  776. {
  777. const auto normValue = param->getValue();
  778. outValue = normValue * getMaximumParameterValue (param);
  779. return noErr;
  780. }
  781. }
  782. return MusicDeviceBase::GetParameter (inID, inScope, inElement, outValue);
  783. }
  784. ComponentResult SetParameter (AudioUnitParameterID inID,
  785. AudioUnitScope inScope,
  786. AudioUnitElement inElement,
  787. Float32 inValue,
  788. UInt32 inBufferOffsetInFrames) override
  789. {
  790. if (inScope == kAudioUnitScope_Global && juceFilter != nullptr)
  791. {
  792. if (auto* param = getParameterForAUParameterID (inID))
  793. {
  794. auto value = inValue / getMaximumParameterValue (param);
  795. param->setValue (value);
  796. inParameterChangedCallback = true;
  797. param->sendValueChangedMessageToListeners (value);
  798. return noErr;
  799. }
  800. }
  801. return MusicDeviceBase::SetParameter (inID, inScope, inElement, inValue, inBufferOffsetInFrames);
  802. }
  803. // No idea what this method actually does or what it should return. Current Apple docs say nothing about it.
  804. // (Note that this isn't marked 'override' in case older versions of the SDK don't include it)
  805. bool CanScheduleParameters() const override { return false; }
  806. //==============================================================================
  807. ComponentResult Version() override { return JucePlugin_VersionCode; }
  808. bool SupportsTail() override { return true; }
  809. Float64 GetTailTime() override { return juceFilter->getTailLengthSeconds(); }
  810. double getSampleRate() { return AudioUnitHelpers::getBusCount (juceFilter.get(), false) > 0 ? GetOutput (0)->GetStreamFormat().mSampleRate : 44100.0; }
  811. Float64 GetLatency() override
  812. {
  813. const double rate = getSampleRate();
  814. jassert (rate > 0);
  815. return rate > 0 ? juceFilter->getLatencySamples() / rate : 0;
  816. }
  817. //==============================================================================
  818. #if BUILD_AU_CARBON_UI
  819. int GetNumCustomUIComponents() override
  820. {
  821. return getHostType().isDigitalPerformer() ? 0 : 1;
  822. }
  823. void GetUIComponentDescs (ComponentDescription* inDescArray) override
  824. {
  825. inDescArray[0].componentType = kAudioUnitCarbonViewComponentType;
  826. inDescArray[0].componentSubType = JucePlugin_AUSubType;
  827. inDescArray[0].componentManufacturer = JucePlugin_AUManufacturerCode;
  828. inDescArray[0].componentFlags = 0;
  829. inDescArray[0].componentFlagsMask = 0;
  830. }
  831. #endif
  832. //==============================================================================
  833. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info) override
  834. {
  835. info.timeSigNumerator = 0;
  836. info.timeSigDenominator = 0;
  837. info.editOriginTime = 0;
  838. info.ppqPositionOfLastBarStart = 0;
  839. info.isRecording = false;
  840. switch (lastTimeStamp.mSMPTETime.mType)
  841. {
  842. case kSMPTETimeType2398: info.frameRate = AudioPlayHead::fps23976; break;
  843. case kSMPTETimeType24: info.frameRate = AudioPlayHead::fps24; break;
  844. case kSMPTETimeType25: info.frameRate = AudioPlayHead::fps25; break;
  845. case kSMPTETimeType30Drop: info.frameRate = AudioPlayHead::fps30drop; break;
  846. case kSMPTETimeType30: info.frameRate = AudioPlayHead::fps30; break;
  847. case kSMPTETimeType2997: info.frameRate = AudioPlayHead::fps2997; break;
  848. case kSMPTETimeType2997Drop: info.frameRate = AudioPlayHead::fps2997drop; break;
  849. case kSMPTETimeType60: info.frameRate = AudioPlayHead::fps60; break;
  850. case kSMPTETimeType60Drop: info.frameRate = AudioPlayHead::fps60drop; break;
  851. default: info.frameRate = AudioPlayHead::fpsUnknown; break;
  852. }
  853. if (CallHostBeatAndTempo (&info.ppqPosition, &info.bpm) != noErr)
  854. {
  855. info.ppqPosition = 0;
  856. info.bpm = 0;
  857. }
  858. UInt32 outDeltaSampleOffsetToNextBeat;
  859. double outCurrentMeasureDownBeat;
  860. float num;
  861. UInt32 den;
  862. if (CallHostMusicalTimeLocation (&outDeltaSampleOffsetToNextBeat, &num, &den,
  863. &outCurrentMeasureDownBeat) == noErr)
  864. {
  865. info.timeSigNumerator = (int) num;
  866. info.timeSigDenominator = (int) den;
  867. info.ppqPositionOfLastBarStart = outCurrentMeasureDownBeat;
  868. }
  869. double outCurrentSampleInTimeLine, outCycleStartBeat = 0, outCycleEndBeat = 0;
  870. Boolean playing = false, looping = false, playchanged;
  871. if (CallHostTransportState (&playing,
  872. &playchanged,
  873. &outCurrentSampleInTimeLine,
  874. &looping,
  875. &outCycleStartBeat,
  876. &outCycleEndBeat) != noErr)
  877. {
  878. // If the host doesn't support this callback, then use the sample time from lastTimeStamp:
  879. outCurrentSampleInTimeLine = lastTimeStamp.mSampleTime;
  880. }
  881. info.isPlaying = playing;
  882. info.timeInSamples = (int64) (outCurrentSampleInTimeLine + 0.5);
  883. info.timeInSeconds = info.timeInSamples / getSampleRate();
  884. info.isLooping = looping;
  885. info.ppqLoopStart = outCycleStartBeat;
  886. info.ppqLoopEnd = outCycleEndBeat;
  887. return true;
  888. }
  889. void sendAUEvent (const AudioUnitEventType type, const int juceParamIndex)
  890. {
  891. auEvent.mEventType = type;
  892. auEvent.mArgument.mParameter.mParameterID = getAUParameterIDForIndex (juceParamIndex);
  893. AUEventListenerNotify (0, 0, &auEvent);
  894. }
  895. void audioProcessorParameterChanged (AudioProcessor*, int index, float /*newValue*/) override
  896. {
  897. if (inParameterChangedCallback.get())
  898. {
  899. inParameterChangedCallback = false;
  900. return;
  901. }
  902. sendAUEvent (kAudioUnitEvent_ParameterValueChange, index);
  903. }
  904. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override
  905. {
  906. sendAUEvent (kAudioUnitEvent_BeginParameterChangeGesture, index);
  907. }
  908. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override
  909. {
  910. sendAUEvent (kAudioUnitEvent_EndParameterChangeGesture, index);
  911. }
  912. void audioProcessorChanged (AudioProcessor*) override
  913. {
  914. PropertyChanged (kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0);
  915. PropertyChanged (kAudioUnitProperty_ParameterList, kAudioUnitScope_Global, 0);
  916. PropertyChanged (kAudioUnitProperty_ParameterInfo, kAudioUnitScope_Global, 0);
  917. PropertyChanged (kAudioUnitProperty_ClassInfo, kAudioUnitScope_Global, 0);
  918. refreshCurrentPreset();
  919. PropertyChanged (kAudioUnitProperty_PresentPreset, kAudioUnitScope_Global, 0);
  920. }
  921. //==============================================================================
  922. // this will only ever be called by the bypass parameter
  923. void parameterValueChanged (int, float) override
  924. {
  925. PropertyChanged (kAudioUnitProperty_BypassEffect, kAudioUnitScope_Global, 0);
  926. }
  927. void parameterGestureChanged (int, bool) override {}
  928. //==============================================================================
  929. bool StreamFormatWritable (AudioUnitScope scope, AudioUnitElement element) override
  930. {
  931. bool ignore;
  932. int busIdx;
  933. return ((! IsInitialized()) && (elementToBusIdx (scope, element, ignore, busIdx) == noErr));
  934. }
  935. bool ValidFormat (AudioUnitScope scope, AudioUnitElement element, const CAStreamBasicDescription& format) override
  936. {
  937. bool isInput;
  938. int busNr;
  939. // DSP Quattro incorrectly uses global scope for the ValidFormat call
  940. if (scope == kAudioUnitScope_Global)
  941. return ValidFormat (kAudioUnitScope_Input, element, format)
  942. || ValidFormat (kAudioUnitScope_Output, element, format);
  943. if (elementToBusIdx (scope, element, isInput, busNr) != noErr)
  944. return false;
  945. const int newNumChannels = static_cast<int> (format.NumberChannels());
  946. const int oldNumChannels = juceFilter->getChannelCountOfBus (isInput, busNr);
  947. if (newNumChannels == oldNumChannels)
  948. return true;
  949. if (AudioProcessor::Bus* bus = juceFilter->getBus (isInput, busNr))
  950. {
  951. if (! MusicDeviceBase::ValidFormat (scope, element, format))
  952. return false;
  953. #ifdef JucePlugin_PreferredChannelConfigurations
  954. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  955. ignoreUnused (bus);
  956. return AudioUnitHelpers::isLayoutSupported (*juceFilter, isInput, busNr, newNumChannels, configs);
  957. #else
  958. return bus->isNumberOfChannelsSupported (newNumChannels);
  959. #endif
  960. }
  961. return false;
  962. }
  963. // 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
  964. OSStatus ChangeStreamFormat (AudioUnitScope scope, AudioUnitElement element, const CAStreamBasicDescription& old, const CAStreamBasicDescription& format) override
  965. {
  966. bool isInput;
  967. int busNr;
  968. OSStatus err = elementToBusIdx (scope, element, isInput, busNr);
  969. if (err != noErr)
  970. return err;
  971. AudioChannelLayoutTag& currentTag = getCurrentLayout (isInput, busNr);
  972. const int newNumChannels = static_cast<int> (format.NumberChannels());
  973. const int oldNumChannels = juceFilter->getChannelCountOfBus (isInput, busNr);
  974. #ifdef JucePlugin_PreferredChannelConfigurations
  975. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  976. if (! AudioUnitHelpers::isLayoutSupported (*juceFilter, isInput, busNr, newNumChannels, configs))
  977. return kAudioUnitErr_FormatNotSupported;
  978. #endif
  979. // predict channel layout
  980. AudioChannelSet set = (newNumChannels != oldNumChannels) ? juceFilter->getBus (isInput, busNr)->supportedLayoutWithChannels (newNumChannels)
  981. : juceFilter->getChannelLayoutOfBus (isInput, busNr);
  982. if (set == AudioChannelSet())
  983. return kAudioUnitErr_FormatNotSupported;
  984. err = MusicDeviceBase::ChangeStreamFormat (scope, element, old, format);
  985. if (err == noErr)
  986. currentTag = CoreAudioLayouts::toCoreAudio (set);
  987. return err;
  988. }
  989. //==============================================================================
  990. ComponentResult Render (AudioUnitRenderActionFlags& ioActionFlags,
  991. const AudioTimeStamp& inTimeStamp,
  992. const UInt32 nFrames) override
  993. {
  994. lastTimeStamp = inTimeStamp;
  995. // prepare buffers
  996. {
  997. pullInputAudio (ioActionFlags, inTimeStamp, nFrames);
  998. prepareOutputBuffers (nFrames);
  999. audioBuffer.reset();
  1000. }
  1001. ioActionFlags &= ~kAudioUnitRenderAction_OutputIsSilence;
  1002. const int numInputBuses = static_cast<int> (GetScope (kAudioUnitScope_Input) .GetNumberOfElements());
  1003. const int numOutputBuses = static_cast<int> (GetScope (kAudioUnitScope_Output).GetNumberOfElements());
  1004. // set buffer pointers to minimize copying
  1005. {
  1006. int chIdx = 0, numChannels = 0;
  1007. bool interleaved = false;
  1008. AudioBufferList* buffer = nullptr;
  1009. // use output pointers
  1010. for (int busIdx = 0; busIdx < numOutputBuses; ++busIdx)
  1011. {
  1012. GetAudioBufferList (false, busIdx, buffer, interleaved, numChannels);
  1013. const int* outLayoutMap = mapper.get (false, busIdx);
  1014. for (int ch = 0; ch < numChannels; ++ch)
  1015. audioBuffer.setBuffer (chIdx++, interleaved ? nullptr : static_cast<float*> (buffer->mBuffers[outLayoutMap[ch]].mData));
  1016. }
  1017. // use input pointers on remaining channels
  1018. for (int busIdx = 0; chIdx < totalInChannels;)
  1019. {
  1020. int channelIndexInBus = juceFilter->getOffsetInBusBufferForAbsoluteChannelIndex (true, chIdx, busIdx);
  1021. const bool badData = ! pulledSucceeded[busIdx];
  1022. if (! badData)
  1023. GetAudioBufferList (true, busIdx, buffer, interleaved, numChannels);
  1024. const int* inLayoutMap = mapper.get (true, busIdx);
  1025. const int n = juceFilter->getChannelCountOfBus (true, busIdx);
  1026. for (int ch = channelIndexInBus; ch < n; ++ch)
  1027. audioBuffer.setBuffer (chIdx++, interleaved || badData ? nullptr : static_cast<float*> (buffer->mBuffers[inLayoutMap[ch]].mData));
  1028. }
  1029. }
  1030. // copy input
  1031. {
  1032. for (int busIdx = 0; busIdx < numInputBuses; ++busIdx)
  1033. {
  1034. if (pulledSucceeded[busIdx])
  1035. {
  1036. audioBuffer.push (GetInput ((UInt32) busIdx)->GetBufferList(), mapper.get (true, busIdx));
  1037. }
  1038. else
  1039. {
  1040. const int n = juceFilter->getChannelCountOfBus (true, busIdx);
  1041. for (int ch = 0; ch < n; ++ch)
  1042. zeromem (audioBuffer.push(), sizeof (float) * nFrames);
  1043. }
  1044. }
  1045. // clear remaining channels
  1046. for (int i = totalInChannels; i < totalOutChannels; ++i)
  1047. zeromem (audioBuffer.push(), sizeof (float) * nFrames);
  1048. }
  1049. // swap midi buffers
  1050. {
  1051. const ScopedLock sl (incomingMidiLock);
  1052. midiEvents.clear();
  1053. incomingEvents.swapWith (midiEvents);
  1054. }
  1055. // process audio
  1056. processBlock (audioBuffer.getBuffer (nFrames), midiEvents);
  1057. // copy back
  1058. {
  1059. for (int busIdx = 0; busIdx < numOutputBuses; ++busIdx)
  1060. audioBuffer.pop (GetOutput ((UInt32) busIdx)->GetBufferList(), mapper.get (false, busIdx));
  1061. }
  1062. // process midi output
  1063. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1064. if (! midiEvents.isEmpty() && midiCallback.midiOutputCallback != nullptr)
  1065. pushMidiOutput (nFrames);
  1066. #endif
  1067. midiEvents.clear();
  1068. return noErr;
  1069. }
  1070. //==============================================================================
  1071. ComponentResult StartNote (MusicDeviceInstrumentID, MusicDeviceGroupID, NoteInstanceID*, UInt32, const MusicDeviceNoteParams&) override { return noErr; }
  1072. ComponentResult StopNote (MusicDeviceGroupID, NoteInstanceID, UInt32) override { return noErr; }
  1073. //==============================================================================
  1074. OSStatus HandleMidiEvent (UInt8 nStatus, UInt8 inChannel, UInt8 inData1, UInt8 inData2, UInt32 inStartFrame) override
  1075. {
  1076. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1077. const juce::uint8 data[] = { (juce::uint8) (nStatus | inChannel),
  1078. (juce::uint8) inData1,
  1079. (juce::uint8) inData2 };
  1080. const ScopedLock sl (incomingMidiLock);
  1081. incomingEvents.addEvent (data, 3, (int) inStartFrame);
  1082. return noErr;
  1083. #else
  1084. ignoreUnused (nStatus, inChannel, inData1);
  1085. ignoreUnused (inData2, inStartFrame);
  1086. return kAudioUnitErr_PropertyNotInUse;
  1087. #endif
  1088. }
  1089. OSStatus HandleSysEx (const UInt8* inData, UInt32 inLength) override
  1090. {
  1091. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1092. const ScopedLock sl (incomingMidiLock);
  1093. incomingEvents.addEvent (inData, (int) inLength, 0);
  1094. return noErr;
  1095. #else
  1096. ignoreUnused (inData, inLength);
  1097. return kAudioUnitErr_PropertyNotInUse;
  1098. #endif
  1099. }
  1100. //==============================================================================
  1101. ComponentResult GetPresets (CFArrayRef* outData) const override
  1102. {
  1103. if (outData != nullptr)
  1104. {
  1105. const int numPrograms = juceFilter->getNumPrograms();
  1106. clearPresetsArray();
  1107. presetsArray.insertMultiple (0, AUPreset(), numPrograms);
  1108. CFMutableArrayRef presetsArrayRef = CFArrayCreateMutable (0, numPrograms, 0);
  1109. for (int i = 0; i < numPrograms; ++i)
  1110. {
  1111. String name (juceFilter->getProgramName(i));
  1112. if (name.isEmpty())
  1113. name = "Untitled";
  1114. AUPreset& p = presetsArray.getReference(i);
  1115. p.presetNumber = i;
  1116. p.presetName = name.toCFString();
  1117. CFArrayAppendValue (presetsArrayRef, &p);
  1118. }
  1119. *outData = (CFArrayRef) presetsArrayRef;
  1120. }
  1121. return noErr;
  1122. }
  1123. OSStatus NewFactoryPresetSet (const AUPreset& inNewFactoryPreset) override
  1124. {
  1125. const int numPrograms = juceFilter->getNumPrograms();
  1126. const SInt32 chosenPresetNumber = (int) inNewFactoryPreset.presetNumber;
  1127. if (chosenPresetNumber >= numPrograms)
  1128. return kAudioUnitErr_InvalidProperty;
  1129. AUPreset chosenPreset;
  1130. chosenPreset.presetNumber = chosenPresetNumber;
  1131. chosenPreset.presetName = juceFilter->getProgramName (chosenPresetNumber).toCFString();
  1132. juceFilter->setCurrentProgram (chosenPresetNumber);
  1133. SetAFactoryPresetAsCurrent (chosenPreset);
  1134. return noErr;
  1135. }
  1136. void componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/) override
  1137. {
  1138. NSView* view = (NSView*) component.getWindowHandle();
  1139. NSRect r = [[view superview] frame];
  1140. r.origin.y = r.origin.y + r.size.height - component.getHeight();
  1141. r.size.width = component.getWidth();
  1142. r.size.height = component.getHeight();
  1143. [CATransaction begin];
  1144. [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
  1145. [[view superview] setFrame: r];
  1146. [view setFrame: makeNSRect (component.getLocalBounds())];
  1147. [CATransaction commit];
  1148. [view setNeedsDisplay: YES];
  1149. }
  1150. //==============================================================================
  1151. class EditorCompHolder : public Component
  1152. {
  1153. public:
  1154. EditorCompHolder (AudioProcessorEditor* const editor)
  1155. {
  1156. addAndMakeVisible (editor);
  1157. #if ! JucePlugin_EditorRequiresKeyboardFocus
  1158. setWantsKeyboardFocus (false);
  1159. #else
  1160. setWantsKeyboardFocus (true);
  1161. #endif
  1162. ignoreUnused (fakeMouseGenerator);
  1163. setBounds (getSizeToContainChild());
  1164. }
  1165. ~EditorCompHolder()
  1166. {
  1167. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  1168. // have been transferred to another parent which takes over ownership.
  1169. }
  1170. Rectangle<int> getSizeToContainChild()
  1171. {
  1172. if (auto* editor = getChildComponent (0))
  1173. return getLocalArea (editor, editor->getLocalBounds());
  1174. return {};
  1175. }
  1176. static NSView* createViewFor (AudioProcessor* filter, JuceAU* au, AudioProcessorEditor* const editor)
  1177. {
  1178. auto* editorCompHolder = new EditorCompHolder (editor);
  1179. auto r = makeNSRect (editorCompHolder->getSizeToContainChild());
  1180. static JuceUIViewClass cls;
  1181. auto* view = [[cls.createInstance() initWithFrame: r] autorelease];
  1182. JuceUIViewClass::setFilter (view, filter);
  1183. JuceUIViewClass::setAU (view, au);
  1184. JuceUIViewClass::setEditor (view, editorCompHolder);
  1185. [view setHidden: NO];
  1186. [view setPostsFrameChangedNotifications: YES];
  1187. [[NSNotificationCenter defaultCenter] addObserver: view
  1188. selector: @selector (applicationWillTerminate:)
  1189. name: NSApplicationWillTerminateNotification
  1190. object: nil];
  1191. activeUIs.add (view);
  1192. editorCompHolder->addToDesktop (0, (void*) view);
  1193. editorCompHolder->setVisible (view);
  1194. return view;
  1195. }
  1196. void childBoundsChanged (Component*) override
  1197. {
  1198. auto b = getSizeToContainChild();
  1199. if (lastBounds != b)
  1200. {
  1201. lastBounds = b;
  1202. auto w = jmax (32, b.getWidth());
  1203. auto h = jmax (32, b.getHeight());
  1204. setSize (w, h);
  1205. auto* view = (NSView*) getWindowHandle();
  1206. auto r = [[view superview] frame];
  1207. r.size.width = w;
  1208. r.size.height = h;
  1209. [CATransaction begin];
  1210. [CATransaction setValue:(id) kCFBooleanTrue forKey:kCATransactionDisableActions];
  1211. [[view superview] setFrame: r];
  1212. [view setFrame: makeNSRect (b)];
  1213. [CATransaction commit];
  1214. [view setNeedsDisplay: YES];
  1215. }
  1216. }
  1217. bool keyPressed (const KeyPress&) override
  1218. {
  1219. if (getHostType().isAbletonLive())
  1220. {
  1221. static NSTimeInterval lastEventTime = 0; // check we're not recursively sending the same event
  1222. NSTimeInterval eventTime = [[NSApp currentEvent] timestamp];
  1223. if (lastEventTime != eventTime)
  1224. {
  1225. lastEventTime = eventTime;
  1226. NSView* view = (NSView*) getWindowHandle();
  1227. NSView* hostView = [view superview];
  1228. NSWindow* hostWindow = [hostView window];
  1229. [hostWindow makeFirstResponder: hostView];
  1230. [hostView keyDown: [NSApp currentEvent]];
  1231. [hostWindow makeFirstResponder: view];
  1232. }
  1233. }
  1234. return false;
  1235. }
  1236. private:
  1237. FakeMouseMoveGenerator fakeMouseGenerator;
  1238. Rectangle<int> lastBounds;
  1239. JUCE_DECLARE_NON_COPYABLE (EditorCompHolder)
  1240. };
  1241. void deleteActiveEditors()
  1242. {
  1243. for (int i = activeUIs.size(); --i >= 0;)
  1244. {
  1245. id ui = (id) activeUIs.getUnchecked(i);
  1246. if (JuceUIViewClass::getAU (ui) == this)
  1247. JuceUIViewClass::deleteEditor (ui);
  1248. }
  1249. }
  1250. //==============================================================================
  1251. struct JuceUIViewClass : public ObjCClass<NSView>
  1252. {
  1253. JuceUIViewClass() : ObjCClass<NSView> ("JUCEAUView_")
  1254. {
  1255. addIvar<AudioProcessor*> ("filter");
  1256. addIvar<JuceAU*> ("au");
  1257. addIvar<EditorCompHolder*> ("editor");
  1258. addMethod (@selector (dealloc), dealloc, "v@:");
  1259. addMethod (@selector (applicationWillTerminate:), applicationWillTerminate, "v@:@");
  1260. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1261. addMethod (@selector (mouseDownCanMoveWindow), mouseDownCanMoveWindow, "c@:");
  1262. registerClass();
  1263. }
  1264. static void deleteEditor (id self)
  1265. {
  1266. std::unique_ptr<EditorCompHolder> editorComp (getEditor (self));
  1267. if (editorComp != nullptr)
  1268. {
  1269. if (editorComp->getChildComponent(0) != nullptr
  1270. && activePlugins.contains (getAU (self))) // plugin may have been deleted before the UI
  1271. {
  1272. AudioProcessor* const filter = getIvar<AudioProcessor*> (self, "filter");
  1273. filter->editorBeingDeleted ((AudioProcessorEditor*) editorComp->getChildComponent(0));
  1274. }
  1275. editorComp = nullptr;
  1276. setEditor (self, nullptr);
  1277. }
  1278. }
  1279. static JuceAU* getAU (id self) { return getIvar<JuceAU*> (self, "au"); }
  1280. static EditorCompHolder* getEditor (id self) { return getIvar<EditorCompHolder*> (self, "editor"); }
  1281. static void setFilter (id self, AudioProcessor* filter) { object_setInstanceVariable (self, "filter", filter); }
  1282. static void setAU (id self, JuceAU* au) { object_setInstanceVariable (self, "au", au); }
  1283. static void setEditor (id self, EditorCompHolder* e) { object_setInstanceVariable (self, "editor", e); }
  1284. private:
  1285. static void dealloc (id self, SEL)
  1286. {
  1287. if (activeUIs.contains (self))
  1288. shutdown (self);
  1289. sendSuperclassMessage (self, @selector (dealloc));
  1290. }
  1291. static void applicationWillTerminate (id self, SEL, NSNotification*)
  1292. {
  1293. shutdown (self);
  1294. }
  1295. static void shutdown (id self)
  1296. {
  1297. [[NSNotificationCenter defaultCenter] removeObserver: self];
  1298. deleteEditor (self);
  1299. jassert (activeUIs.contains (self));
  1300. activeUIs.removeFirstMatchingValue (self);
  1301. if (activePlugins.size() + activeUIs.size() == 0)
  1302. {
  1303. // there's some kind of component currently modal, but the host
  1304. // is trying to delete our plugin..
  1305. jassert (Component::getCurrentlyModalComponent() == nullptr);
  1306. shutdownJuce_GUI();
  1307. }
  1308. }
  1309. static void viewDidMoveToWindow (id self, SEL)
  1310. {
  1311. if (NSWindow* w = [(NSView*) self window])
  1312. {
  1313. [w setAcceptsMouseMovedEvents: YES];
  1314. if (EditorCompHolder* const editorComp = getEditor (self))
  1315. [w makeFirstResponder: (NSView*) editorComp->getWindowHandle()];
  1316. }
  1317. }
  1318. static BOOL mouseDownCanMoveWindow (id, SEL)
  1319. {
  1320. return NO;
  1321. }
  1322. };
  1323. //==============================================================================
  1324. struct JuceUICreationClass : public ObjCClass<NSObject>
  1325. {
  1326. JuceUICreationClass() : ObjCClass<NSObject> ("JUCE_AUCocoaViewClass_")
  1327. {
  1328. addMethod (@selector (interfaceVersion), interfaceVersion, @encode (unsigned int), "@:");
  1329. addMethod (@selector (description), description, @encode (NSString*), "@:");
  1330. addMethod (@selector (uiViewForAudioUnit:withSize:), uiViewForAudioUnit, @encode (NSView*), "@:", @encode (AudioUnit), @encode (NSSize));
  1331. addProtocol (@protocol (AUCocoaUIBase));
  1332. registerClass();
  1333. }
  1334. private:
  1335. static unsigned int interfaceVersion (id, SEL) { return 0; }
  1336. static NSString* description (id, SEL)
  1337. {
  1338. return [NSString stringWithString: nsStringLiteral (JucePlugin_Name)];
  1339. }
  1340. static NSView* uiViewForAudioUnit (id, SEL, AudioUnit inAudioUnit, NSSize)
  1341. {
  1342. void* pointers[2];
  1343. UInt32 propertySize = sizeof (pointers);
  1344. if (AudioUnitGetProperty (inAudioUnit, juceFilterObjectPropertyID,
  1345. kAudioUnitScope_Global, 0, pointers, &propertySize) == noErr)
  1346. {
  1347. if (AudioProcessor* filter = static_cast<AudioProcessor*> (pointers[0]))
  1348. if (AudioProcessorEditor* editorComp = filter->createEditorIfNeeded())
  1349. return EditorCompHolder::createViewFor (filter, static_cast<JuceAU*> (pointers[1]), editorComp);
  1350. }
  1351. return nil;
  1352. }
  1353. };
  1354. private:
  1355. //==============================================================================
  1356. AudioUnitHelpers::CoreAudioBufferList audioBuffer;
  1357. MidiBuffer midiEvents, incomingEvents;
  1358. bool prepared = false, isBypassed = false;
  1359. //==============================================================================
  1360. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1361. static constexpr bool forceUseLegacyParamIDs = true;
  1362. #else
  1363. static constexpr bool forceUseLegacyParamIDs = false;
  1364. #endif
  1365. //==============================================================================
  1366. LegacyAudioParametersWrapper juceParameters;
  1367. HashMap<int32, AudioProcessorParameter*> paramMap;
  1368. Array<AudioUnitParameterID> auParamIDs;
  1369. Array<const AudioProcessorParameterGroup*> parameterGroups;
  1370. //==============================================================================
  1371. AudioUnitEvent auEvent;
  1372. mutable Array<AUPreset> presetsArray;
  1373. CriticalSection incomingMidiLock;
  1374. AUMIDIOutputCallbackStruct midiCallback;
  1375. AudioTimeStamp lastTimeStamp;
  1376. int totalInChannels, totalOutChannels;
  1377. HeapBlock<bool> pulledSucceeded;
  1378. ThreadLocalValue<bool> inParameterChangedCallback;
  1379. //==============================================================================
  1380. Array<AUChannelInfo> channelInfo;
  1381. Array<Array<AudioChannelLayoutTag>> supportedInputLayouts, supportedOutputLayouts;
  1382. Array<AudioChannelLayoutTag> currentInputLayout, currentOutputLayout;
  1383. //==============================================================================
  1384. AudioUnitHelpers::ChannelRemapper mapper;
  1385. //==============================================================================
  1386. OwnedArray<OwnedArray<const __CFString>> parameterValueStringArrays;
  1387. //==============================================================================
  1388. AudioProcessorParameter* bypassParam = nullptr;
  1389. //==============================================================================
  1390. void pullInputAudio (AudioUnitRenderActionFlags& flags, const AudioTimeStamp& timestamp, const UInt32 nFrames) noexcept
  1391. {
  1392. const unsigned int numInputBuses = GetScope (kAudioUnitScope_Input).GetNumberOfElements();
  1393. for (unsigned int i = 0; i < numInputBuses; ++i)
  1394. {
  1395. if (AUInputElement* input = GetInput (i))
  1396. {
  1397. const bool succeeded = (input->PullInput (flags, timestamp, i, nFrames) == noErr);
  1398. if ((flags & kAudioUnitRenderAction_OutputIsSilence) != 0 && succeeded)
  1399. AudioUnitHelpers::clearAudioBuffer (input->GetBufferList());
  1400. pulledSucceeded[i] = succeeded;
  1401. }
  1402. }
  1403. }
  1404. void prepareOutputBuffers (const UInt32 nFrames) noexcept
  1405. {
  1406. const unsigned int numOutputBuses = GetScope (kAudioUnitScope_Output).GetNumberOfElements();
  1407. for (unsigned int busIdx = 0; busIdx < numOutputBuses; ++busIdx)
  1408. {
  1409. AUOutputElement* output = GetOutput (busIdx);
  1410. if (output->WillAllocateBuffer())
  1411. output->PrepareBuffer (nFrames);
  1412. }
  1413. }
  1414. void processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiBuffer) noexcept
  1415. {
  1416. const ScopedLock sl (juceFilter->getCallbackLock());
  1417. if (juceFilter->isSuspended())
  1418. {
  1419. buffer.clear();
  1420. }
  1421. else if (bypassParam == nullptr && isBypassed)
  1422. {
  1423. juceFilter->processBlockBypassed (buffer, midiBuffer);
  1424. }
  1425. else
  1426. {
  1427. juceFilter->processBlock (buffer, midiBuffer);
  1428. }
  1429. }
  1430. void pushMidiOutput (UInt32 nFrames) noexcept
  1431. {
  1432. UInt32 numPackets = 0;
  1433. size_t dataSize = 0;
  1434. const juce::uint8* midiEventData;
  1435. int midiEventSize, midiEventPosition;
  1436. for (MidiBuffer::Iterator i (midiEvents); i.getNextEvent (midiEventData, midiEventSize, midiEventPosition);)
  1437. {
  1438. jassert (isPositiveAndBelow (midiEventPosition, nFrames));
  1439. ignoreUnused (nFrames);
  1440. dataSize += (size_t) midiEventSize;
  1441. ++numPackets;
  1442. }
  1443. MIDIPacket* p;
  1444. const size_t packetMembersSize = sizeof (MIDIPacket) - sizeof (p->data); // NB: GCC chokes on "sizeof (MidiMessage::data)"
  1445. const size_t packetListMembersSize = sizeof (MIDIPacketList) - sizeof (p->data);
  1446. HeapBlock<MIDIPacketList> packetList;
  1447. packetList.malloc (packetListMembersSize + packetMembersSize * numPackets + dataSize, 1);
  1448. packetList->numPackets = numPackets;
  1449. p = packetList->packet;
  1450. for (MidiBuffer::Iterator i (midiEvents); i.getNextEvent (midiEventData, midiEventSize, midiEventPosition);)
  1451. {
  1452. p->timeStamp = (MIDITimeStamp) midiEventPosition;
  1453. p->length = (UInt16) midiEventSize;
  1454. memcpy (p->data, midiEventData, (size_t) midiEventSize);
  1455. p = MIDIPacketNext (p);
  1456. }
  1457. midiCallback.midiOutputCallback (midiCallback.userData, &lastTimeStamp, 0, packetList);
  1458. }
  1459. void GetAudioBufferList (bool isInput, int busIdx, AudioBufferList*& bufferList, bool& interleaved, int& numChannels)
  1460. {
  1461. AUIOElement* element = GetElement (isInput ? kAudioUnitScope_Input : kAudioUnitScope_Output, static_cast<UInt32> (busIdx))->AsIOElement();
  1462. jassert (element != nullptr);
  1463. bufferList = &element->GetBufferList();
  1464. jassert (bufferList->mNumberBuffers > 0);
  1465. interleaved = AudioUnitHelpers::isAudioBufferInterleaved (*bufferList);
  1466. numChannels = static_cast<int> (interleaved ? bufferList->mBuffers[0].mNumberChannels : bufferList->mNumberBuffers);
  1467. }
  1468. //==============================================================================
  1469. static OSStatus scopeToDirection (AudioUnitScope scope, bool& isInput) noexcept
  1470. {
  1471. isInput = (scope == kAudioUnitScope_Input);
  1472. return (scope != kAudioUnitScope_Input
  1473. && scope != kAudioUnitScope_Output)
  1474. ? kAudioUnitErr_InvalidScope : noErr;
  1475. }
  1476. OSStatus elementToBusIdx (AudioUnitScope scope, AudioUnitElement element, bool& isInput, int& busIdx) noexcept
  1477. {
  1478. OSStatus err;
  1479. busIdx = static_cast<int> (element);
  1480. if ((err = scopeToDirection (scope, isInput)) != noErr) return err;
  1481. if (isPositiveAndBelow (busIdx, AudioUnitHelpers::getBusCount (juceFilter.get(), isInput))) return noErr;
  1482. return kAudioUnitErr_InvalidElement;
  1483. }
  1484. //==============================================================================
  1485. void addParameters()
  1486. {
  1487. parameterGroups = juceFilter->getParameterTree().getSubgroups (true);
  1488. juceParameters.update (*juceFilter, forceUseLegacyParamIDs);
  1489. const int numParams = juceParameters.getNumParameters();
  1490. if (forceUseLegacyParamIDs)
  1491. {
  1492. Globals()->UseIndexedParameters (numParams);
  1493. }
  1494. else
  1495. {
  1496. for (auto* param : juceParameters.params)
  1497. {
  1498. const AudioUnitParameterID auParamID = generateAUParameterID (param);
  1499. // Consider yourself very unlucky if you hit this assertion. The hash code of your
  1500. // parameter ids are not unique.
  1501. jassert (! paramMap.contains (static_cast<int32> (auParamID)));
  1502. auParamIDs.add (auParamID);
  1503. paramMap.set (static_cast<int32> (auParamID), param);
  1504. Globals()->SetParameter (auParamID, param->getValue());
  1505. }
  1506. }
  1507. #if JUCE_DEBUG
  1508. // Some hosts can't handle the huge numbers of discrete parameter values created when
  1509. // using the default number of steps.
  1510. for (auto* param : juceParameters.params)
  1511. if (param->isDiscrete())
  1512. jassert (param->getNumSteps() != AudioProcessor::getDefaultNumParameterSteps());
  1513. #endif
  1514. parameterValueStringArrays.ensureStorageAllocated (numParams);
  1515. for (auto* param : juceParameters.params)
  1516. {
  1517. OwnedArray<const __CFString>* stringValues = nullptr;
  1518. auto initialValue = param->getValue();
  1519. bool paramIsLegacy = dynamic_cast<LegacyAudioParameter*> (param) != nullptr;
  1520. if (param->isDiscrete() && (! forceUseLegacyParamIDs))
  1521. {
  1522. const auto numSteps = param->getNumSteps();
  1523. stringValues = new OwnedArray<const __CFString>();
  1524. stringValues->ensureStorageAllocated (numSteps);
  1525. const auto maxValue = getMaximumParameterValue (param);
  1526. auto getTextValue = [param, paramIsLegacy] (float value)
  1527. {
  1528. if (paramIsLegacy)
  1529. {
  1530. param->setValue (value);
  1531. return param->getCurrentValueAsText();
  1532. }
  1533. return param->getText (value, 256);
  1534. };
  1535. for (int i = 0; i < numSteps; ++i)
  1536. {
  1537. auto value = (float) i / maxValue;
  1538. stringValues->add (CFStringCreateCopy (nullptr, (getTextValue (value).toCFString())));
  1539. }
  1540. }
  1541. if (paramIsLegacy)
  1542. param->setValue (initialValue);
  1543. parameterValueStringArrays.add (stringValues);
  1544. }
  1545. if ((bypassParam = juceFilter->getBypassParameter()) != nullptr)
  1546. bypassParam->addListener (this);
  1547. }
  1548. //==============================================================================
  1549. AudioUnitParameterID generateAUParameterID (AudioProcessorParameter* param) const
  1550. {
  1551. const String& juceParamID = LegacyAudioParameter::getParamID (param, forceUseLegacyParamIDs);
  1552. AudioUnitParameterID paramHash = static_cast<AudioUnitParameterID> (juceParamID.hashCode());
  1553. #if JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS
  1554. // studio one doesn't like negative parameters
  1555. paramHash &= ~(1 << (sizeof (AudioUnitParameterID) * 8 - 1));
  1556. #endif
  1557. return forceUseLegacyParamIDs ? static_cast<AudioUnitParameterID> (juceParamID.getIntValue())
  1558. : paramHash;
  1559. }
  1560. inline AudioUnitParameterID getAUParameterIDForIndex (int paramIndex) const noexcept
  1561. {
  1562. return forceUseLegacyParamIDs ? static_cast<AudioUnitParameterID> (paramIndex)
  1563. : auParamIDs.getReference (paramIndex);
  1564. }
  1565. AudioProcessorParameter* getParameterForAUParameterID (AudioUnitParameterID address) const noexcept
  1566. {
  1567. auto index = static_cast<int32> (address);
  1568. return forceUseLegacyParamIDs ? juceParameters.getParamForIndex (index)
  1569. : paramMap[index];
  1570. }
  1571. //==============================================================================
  1572. OSStatus syncAudioUnitWithProcessor()
  1573. {
  1574. OSStatus err = noErr;
  1575. const int enabledInputs = AudioUnitHelpers::getBusCount (juceFilter.get(), true);
  1576. const int enabledOutputs = AudioUnitHelpers::getBusCount (juceFilter.get(), false);
  1577. if ((err = MusicDeviceBase::SetBusCount (kAudioUnitScope_Input, static_cast<UInt32> (enabledInputs))) != noErr)
  1578. return err;
  1579. if ((err = MusicDeviceBase::SetBusCount (kAudioUnitScope_Output, static_cast<UInt32> (enabledOutputs))) != noErr)
  1580. return err;
  1581. addSupportedLayoutTags();
  1582. for (int i = 0; i < enabledInputs; ++i)
  1583. if ((err = syncAudioUnitWithChannelSet (true, i, juceFilter->getChannelLayoutOfBus (true, i))) != noErr) return err;
  1584. for (int i = 0; i < enabledOutputs; ++i)
  1585. if ((err = syncAudioUnitWithChannelSet (false, i, juceFilter->getChannelLayoutOfBus (false, i))) != noErr) return err;
  1586. return noErr;
  1587. }
  1588. OSStatus syncProcessorWithAudioUnit()
  1589. {
  1590. const int numInputBuses = AudioUnitHelpers::getBusCount (juceFilter.get(), true);
  1591. const int numOutputBuses = AudioUnitHelpers::getBusCount (juceFilter.get(), false);
  1592. const int numInputElements = static_cast<int> (GetScope(kAudioUnitScope_Input). GetNumberOfElements());
  1593. const int numOutputElements = static_cast<int> (GetScope(kAudioUnitScope_Output).GetNumberOfElements());
  1594. AudioProcessor::BusesLayout requestedLayouts;
  1595. for (int dir = 0; dir < 2; ++dir)
  1596. {
  1597. const bool isInput = (dir == 0);
  1598. const int n = (isInput ? numInputBuses : numOutputBuses);
  1599. const int numAUElements = (isInput ? numInputElements : numOutputElements);
  1600. Array<AudioChannelSet>& requestedBuses = (isInput ? requestedLayouts.inputBuses : requestedLayouts.outputBuses);
  1601. for (int busIdx = 0; busIdx < n; ++busIdx)
  1602. {
  1603. const AUIOElement* element = (busIdx < numAUElements ? GetIOElement (isInput ? kAudioUnitScope_Input : kAudioUnitScope_Output, (UInt32) busIdx) : nullptr);
  1604. const int numChannels = (element != nullptr ? static_cast<int> (element->GetStreamFormat().NumberChannels()) : 0);
  1605. AudioChannelLayoutTag currentLayoutTag = isInput ? currentInputLayout[busIdx] : currentOutputLayout[busIdx];
  1606. const int tagNumChannels = currentLayoutTag & 0xffff;
  1607. if (numChannels != tagNumChannels)
  1608. return kAudioUnitErr_FormatNotSupported;
  1609. requestedBuses.add (CoreAudioLayouts::fromCoreAudio (currentLayoutTag));
  1610. }
  1611. }
  1612. #ifdef JucePlugin_PreferredChannelConfigurations
  1613. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1614. if (! AudioProcessor::containsLayout (requestedLayouts, configs))
  1615. return kAudioUnitErr_FormatNotSupported;
  1616. #endif
  1617. if (! AudioUnitHelpers::setBusesLayout (juceFilter.get(), requestedLayouts))
  1618. return kAudioUnitErr_FormatNotSupported;
  1619. // update total channel count
  1620. totalInChannels = juceFilter->getTotalNumInputChannels();
  1621. totalOutChannels = juceFilter->getTotalNumOutputChannels();
  1622. return noErr;
  1623. }
  1624. OSStatus syncAudioUnitWithChannelSet (bool isInput, int busNr, const AudioChannelSet& channelSet)
  1625. {
  1626. const int numChannels = channelSet.size();
  1627. getCurrentLayout (isInput, busNr) = CoreAudioLayouts::toCoreAudio (channelSet);
  1628. // is this bus activated?
  1629. if (numChannels == 0)
  1630. return noErr;
  1631. if (AUIOElement* element = GetIOElement (isInput ? kAudioUnitScope_Input : kAudioUnitScope_Output, (UInt32) busNr))
  1632. {
  1633. element->SetName ((CFStringRef) juceStringToNS (juceFilter->getBus (isInput, busNr)->getName()));
  1634. CAStreamBasicDescription streamDescription;
  1635. streamDescription.mSampleRate = getSampleRate();
  1636. streamDescription.SetCanonical ((UInt32) numChannels, false);
  1637. return element->SetStreamFormat (streamDescription);
  1638. }
  1639. else
  1640. jassertfalse;
  1641. return kAudioUnitErr_InvalidElement;
  1642. }
  1643. //==============================================================================
  1644. void clearPresetsArray() const
  1645. {
  1646. for (int i = presetsArray.size(); --i >= 0;)
  1647. CFRelease (presetsArray.getReference(i).presetName);
  1648. presetsArray.clear();
  1649. }
  1650. void refreshCurrentPreset()
  1651. {
  1652. // this will make the AU host re-read and update the current preset name
  1653. // in case it was changed here in the plug-in:
  1654. const int currentProgramNumber = juceFilter->getCurrentProgram();
  1655. const String currentProgramName = juceFilter->getProgramName (currentProgramNumber);
  1656. AUPreset currentPreset;
  1657. currentPreset.presetNumber = currentProgramNumber;
  1658. currentPreset.presetName = currentProgramName.toCFString();
  1659. SetAFactoryPresetAsCurrent (currentPreset);
  1660. }
  1661. //==============================================================================
  1662. Array<AudioChannelLayoutTag>& getSupportedBusLayouts (bool isInput, int bus) noexcept { return (isInput ? supportedInputLayouts : supportedOutputLayouts).getReference (bus); }
  1663. const Array<AudioChannelLayoutTag>& getSupportedBusLayouts (bool isInput, int bus) const noexcept { return (isInput ? supportedInputLayouts : supportedOutputLayouts).getReference (bus); }
  1664. AudioChannelLayoutTag& getCurrentLayout (bool isInput, int bus) noexcept { return (isInput ? currentInputLayout : currentOutputLayout).getReference (bus); }
  1665. AudioChannelLayoutTag getCurrentLayout (bool isInput, int bus) const noexcept { return (isInput ? currentInputLayout : currentOutputLayout)[bus]; }
  1666. //==============================================================================
  1667. void addSupportedLayoutTagsForBus (bool isInput, int busNum, Array<AudioChannelLayoutTag>& tags)
  1668. {
  1669. if (AudioProcessor::Bus* bus = juceFilter->getBus (isInput, busNum))
  1670. {
  1671. #ifndef JucePlugin_PreferredChannelConfigurations
  1672. auto& knownTags = CoreAudioLayouts::getKnownCoreAudioTags();
  1673. for (auto tag : knownTags)
  1674. if (bus->isLayoutSupported (CoreAudioLayouts::fromCoreAudio (tag)))
  1675. tags.addIfNotAlreadyThere (tag);
  1676. #endif
  1677. // add discrete layout tags
  1678. int n = bus->getMaxSupportedChannels(maxChannelsToProbeFor());
  1679. for (int ch = 0; ch < n; ++ch)
  1680. {
  1681. #ifdef JucePlugin_PreferredChannelConfigurations
  1682. const short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1683. if (AudioUnitHelpers::isLayoutSupported (*juceFilter, isInput, busNum, ch, configs))
  1684. tags.addIfNotAlreadyThere (static_cast<AudioChannelLayoutTag> ((int) kAudioChannelLayoutTag_DiscreteInOrder | ch));
  1685. #else
  1686. if (bus->isLayoutSupported (AudioChannelSet::discreteChannels (ch)))
  1687. tags.addIfNotAlreadyThere (static_cast<AudioChannelLayoutTag> ((int) kAudioChannelLayoutTag_DiscreteInOrder | ch));
  1688. #endif
  1689. }
  1690. }
  1691. }
  1692. void addSupportedLayoutTagsForDirection (bool isInput)
  1693. {
  1694. auto& layouts = isInput ? supportedInputLayouts : supportedOutputLayouts;
  1695. layouts.clear();
  1696. auto numBuses = AudioUnitHelpers::getBusCount (juceFilter.get(), isInput);
  1697. for (int busNr = 0; busNr < numBuses; ++busNr)
  1698. {
  1699. Array<AudioChannelLayoutTag> busLayouts;
  1700. addSupportedLayoutTagsForBus (isInput, busNr, busLayouts);
  1701. layouts.add (busLayouts);
  1702. }
  1703. }
  1704. void addSupportedLayoutTags()
  1705. {
  1706. currentInputLayout.clear(); currentOutputLayout.clear();
  1707. currentInputLayout. resize (AudioUnitHelpers::getBusCount (juceFilter.get(), true));
  1708. currentOutputLayout.resize (AudioUnitHelpers::getBusCount (juceFilter.get(), false));
  1709. addSupportedLayoutTagsForDirection (true);
  1710. addSupportedLayoutTagsForDirection (false);
  1711. }
  1712. static int maxChannelsToProbeFor()
  1713. {
  1714. return (getHostType().isLogic() ? 8 : 64);
  1715. }
  1716. //==============================================================================
  1717. void auPropertyListener (AudioUnitPropertyID propId, AudioUnitScope scope, AudioUnitElement)
  1718. {
  1719. if (scope == kAudioUnitScope_Global && propId == kAudioUnitProperty_ContextName
  1720. && juceFilter != nullptr && mContextName != nullptr)
  1721. {
  1722. AudioProcessor::TrackProperties props;
  1723. props.name = String::fromCFString (mContextName);
  1724. juceFilter->updateTrackProperties (props);
  1725. }
  1726. }
  1727. static void auPropertyListenerDispatcher (void* inRefCon, AudioUnit, AudioUnitPropertyID propId,
  1728. AudioUnitScope scope, AudioUnitElement element)
  1729. {
  1730. static_cast<JuceAU*> (inRefCon)->auPropertyListener (propId, scope, element);
  1731. }
  1732. JUCE_DECLARE_NON_COPYABLE (JuceAU)
  1733. };
  1734. //==============================================================================
  1735. #if BUILD_AU_CARBON_UI
  1736. class JuceAUView : public AUCarbonViewBase
  1737. {
  1738. public:
  1739. JuceAUView (AudioUnitCarbonView auview)
  1740. : AUCarbonViewBase (auview),
  1741. juceFilter (nullptr)
  1742. {
  1743. }
  1744. ~JuceAUView()
  1745. {
  1746. deleteUI();
  1747. }
  1748. ComponentResult CreateUI (Float32 /*inXOffset*/, Float32 /*inYOffset*/) override
  1749. {
  1750. JUCE_AUTORELEASEPOOL
  1751. {
  1752. if (juceFilter == nullptr)
  1753. {
  1754. void* pointers[2];
  1755. UInt32 propertySize = sizeof (pointers);
  1756. AudioUnitGetProperty (GetEditAudioUnit(),
  1757. juceFilterObjectPropertyID,
  1758. kAudioUnitScope_Global,
  1759. 0,
  1760. pointers,
  1761. &propertySize);
  1762. juceFilter = (AudioProcessor*) pointers[0];
  1763. }
  1764. if (juceFilter != nullptr)
  1765. {
  1766. deleteUI();
  1767. if (AudioProcessorEditor* editorComp = juceFilter->createEditorIfNeeded())
  1768. {
  1769. editorComp->setOpaque (true);
  1770. windowComp.reset (new ComponentInHIView (editorComp, mCarbonPane));
  1771. }
  1772. }
  1773. else
  1774. {
  1775. jassertfalse; // can't get a pointer to our effect
  1776. }
  1777. }
  1778. return noErr;
  1779. }
  1780. AudioUnitCarbonViewEventListener getEventListener() const { return mEventListener; }
  1781. void* getEventListenerUserData() const { return mEventListenerUserData; }
  1782. private:
  1783. //==============================================================================
  1784. AudioProcessor* juceFilter;
  1785. std::unique_ptr<Component> windowComp;
  1786. FakeMouseMoveGenerator fakeMouseGenerator;
  1787. void deleteUI()
  1788. {
  1789. if (windowComp != nullptr)
  1790. {
  1791. PopupMenu::dismissAllActiveMenus();
  1792. /* This assertion is triggered when there's some kind of modal component active, and the
  1793. host is trying to delete our plugin.
  1794. If you must use modal components, always use them in a non-blocking way, by never
  1795. calling runModalLoop(), but instead using enterModalState() with a callback that
  1796. will be performed on completion. (Note that this assertion could actually trigger
  1797. a false alarm even if you're doing it correctly, but is here to catch people who
  1798. aren't so careful) */
  1799. jassert (Component::getCurrentlyModalComponent() == nullptr);
  1800. if (JuceAU::EditorCompHolder* editorCompHolder = dynamic_cast<JuceAU::EditorCompHolder*> (windowComp->getChildComponent(0)))
  1801. if (AudioProcessorEditor* audioProcessEditor = dynamic_cast<AudioProcessorEditor*> (editorCompHolder->getChildComponent(0)))
  1802. juceFilter->editorBeingDeleted (audioProcessEditor);
  1803. windowComp = nullptr;
  1804. }
  1805. }
  1806. //==============================================================================
  1807. // Uses a child NSWindow to sit in front of a HIView and display our component
  1808. class ComponentInHIView : public Component
  1809. {
  1810. public:
  1811. ComponentInHIView (AudioProcessorEditor* ed, HIViewRef parentHIView)
  1812. : parentView (parentHIView),
  1813. editor (ed),
  1814. recursive (false)
  1815. {
  1816. JUCE_AUTORELEASEPOOL
  1817. {
  1818. jassert (ed != nullptr);
  1819. addAndMakeVisible (editor);
  1820. setOpaque (true);
  1821. setVisible (true);
  1822. setBroughtToFrontOnMouseClick (true);
  1823. setSize (editor.getWidth(), editor.getHeight());
  1824. SizeControl (parentHIView, (SInt16) editor.getWidth(), (SInt16) editor.getHeight());
  1825. WindowRef windowRef = HIViewGetWindow (parentHIView);
  1826. hostWindow = [[NSWindow alloc] initWithWindowRef: windowRef];
  1827. // not really sure why this is needed in older OS X versions
  1828. // but JUCE plug-ins crash without it
  1829. if ((SystemStats::getOperatingSystemType() & 0xff) < 12)
  1830. [hostWindow retain];
  1831. [hostWindow setCanHide: YES];
  1832. [hostWindow setReleasedWhenClosed: YES];
  1833. updateWindowPos();
  1834. #if ! JucePlugin_EditorRequiresKeyboardFocus
  1835. addToDesktop (ComponentPeer::windowIsTemporary | ComponentPeer::windowIgnoresKeyPresses);
  1836. setWantsKeyboardFocus (false);
  1837. #else
  1838. addToDesktop (ComponentPeer::windowIsTemporary);
  1839. setWantsKeyboardFocus (true);
  1840. #endif
  1841. setVisible (true);
  1842. toFront (false);
  1843. addSubWindow();
  1844. NSWindow* pluginWindow = [((NSView*) getWindowHandle()) window];
  1845. [pluginWindow setNextResponder: hostWindow];
  1846. attachWindowHidingHooks (this, (WindowRef) windowRef, hostWindow);
  1847. }
  1848. }
  1849. ~ComponentInHIView()
  1850. {
  1851. JUCE_AUTORELEASEPOOL
  1852. {
  1853. removeWindowHidingHooks (this);
  1854. NSWindow* pluginWindow = [((NSView*) getWindowHandle()) window];
  1855. [hostWindow removeChildWindow: pluginWindow];
  1856. removeFromDesktop();
  1857. [hostWindow release];
  1858. hostWindow = nil;
  1859. }
  1860. }
  1861. void updateWindowPos()
  1862. {
  1863. HIPoint f;
  1864. f.x = f.y = 0;
  1865. HIPointConvert (&f, kHICoordSpaceView, parentView, kHICoordSpaceScreenPixel, 0);
  1866. setTopLeftPosition ((int) f.x, (int) f.y);
  1867. }
  1868. void addSubWindow()
  1869. {
  1870. NSWindow* pluginWindow = [((NSView*) getWindowHandle()) window];
  1871. [pluginWindow setExcludedFromWindowsMenu: YES];
  1872. [pluginWindow setCanHide: YES];
  1873. [hostWindow addChildWindow: pluginWindow
  1874. ordered: NSWindowAbove];
  1875. [hostWindow orderFront: nil];
  1876. [pluginWindow orderFront: nil];
  1877. }
  1878. void resized() override
  1879. {
  1880. if (Component* const child = getChildComponent (0))
  1881. child->setBounds (getLocalBounds());
  1882. }
  1883. void paint (Graphics&) override {}
  1884. void childBoundsChanged (Component*) override
  1885. {
  1886. if (! recursive)
  1887. {
  1888. recursive = true;
  1889. const int w = jmax (32, editor.getWidth());
  1890. const int h = jmax (32, editor.getHeight());
  1891. SizeControl (parentView, (SInt16) w, (SInt16) h);
  1892. if (getWidth() != w || getHeight() != h)
  1893. setSize (w, h);
  1894. editor.repaint();
  1895. updateWindowPos();
  1896. addSubWindow(); // (need this for AULab)
  1897. recursive = false;
  1898. }
  1899. }
  1900. bool keyPressed (const KeyPress& kp) override
  1901. {
  1902. if (! kp.getModifiers().isCommandDown())
  1903. {
  1904. // If we have an unused keypress, move the key-focus to a host window
  1905. // and re-inject the event..
  1906. static NSTimeInterval lastEventTime = 0; // check we're not recursively sending the same event
  1907. NSTimeInterval eventTime = [[NSApp currentEvent] timestamp];
  1908. if (lastEventTime != eventTime)
  1909. {
  1910. lastEventTime = eventTime;
  1911. [[hostWindow parentWindow] makeKeyWindow];
  1912. repostCurrentNSEvent();
  1913. }
  1914. }
  1915. return false;
  1916. }
  1917. private:
  1918. HIViewRef parentView;
  1919. NSWindow* hostWindow;
  1920. JuceAU::EditorCompHolder editor;
  1921. bool recursive;
  1922. };
  1923. };
  1924. #endif
  1925. //==============================================================================
  1926. #define JUCE_COMPONENT_ENTRYX(Class, Name, Suffix) \
  1927. extern "C" __attribute__((visibility("default"))) ComponentResult Name ## Suffix (ComponentParameters* params, Class* obj); \
  1928. extern "C" __attribute__((visibility("default"))) ComponentResult Name ## Suffix (ComponentParameters* params, Class* obj) \
  1929. { \
  1930. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_AudioUnit; \
  1931. return ComponentEntryPoint<Class>::Dispatch (params, obj); \
  1932. }
  1933. #if JucePlugin_ProducesMidiOutput || JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1934. #define FACTORY_BASE_CLASS AUMIDIEffectFactory
  1935. #else
  1936. #define FACTORY_BASE_CLASS AUBaseFactory
  1937. #endif
  1938. #define JUCE_FACTORY_ENTRYX(Class, Name) \
  1939. extern "C" __attribute__((visibility("default"))) void* Name ## Factory (const AudioComponentDescription* desc); \
  1940. extern "C" __attribute__((visibility("default"))) void* Name ## Factory (const AudioComponentDescription* desc) \
  1941. { \
  1942. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_AudioUnit; \
  1943. return FACTORY_BASE_CLASS<Class>::Factory (desc); \
  1944. }
  1945. #define JUCE_COMPONENT_ENTRY(Class, Name, Suffix) JUCE_COMPONENT_ENTRYX(Class, Name, Suffix)
  1946. #define JUCE_FACTORY_ENTRY(Class, Name) JUCE_FACTORY_ENTRYX(Class, Name)
  1947. //==============================================================================
  1948. JUCE_COMPONENT_ENTRY (JuceAU, JucePlugin_AUExportPrefix, Entry)
  1949. #ifndef AUDIOCOMPONENT_ENTRY
  1950. #define JUCE_DISABLE_AU_FACTORY_ENTRY 1
  1951. #endif
  1952. #if ! JUCE_DISABLE_AU_FACTORY_ENTRY // (You might need to disable this for old Xcode 3 builds)
  1953. JUCE_FACTORY_ENTRY (JuceAU, JucePlugin_AUExportPrefix)
  1954. #endif
  1955. #if BUILD_AU_CARBON_UI
  1956. JUCE_COMPONENT_ENTRY (JuceAUView, JucePlugin_AUExportPrefix, ViewEntry)
  1957. #endif
  1958. #if ! JUCE_DISABLE_AU_FACTORY_ENTRY
  1959. #include "CoreAudioUtilityClasses/AUPlugInDispatch.cpp"
  1960. #endif
  1961. #endif