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.

2710 lines
103KB

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