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.

2657 lines
101KB

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