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.

1474 lines
61KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #include "../../juce_core/system/juce_TargetPlatform.h"
  18. #include "../utility/juce_CheckSettingMacros.h"
  19. #if JucePlugin_Build_AAX && (JUCE_INCLUDED_AAX_IN_MM || defined (_WIN32) || defined (_WIN64))
  20. #include "../utility/juce_IncludeSystemHeaders.h"
  21. #include "../utility/juce_IncludeModuleHeaders.h"
  22. #include "../utility/juce_WindowsHooks.h"
  23. #include "../utility/juce_PluginBusUtilities.h"
  24. #ifdef __clang__
  25. #pragma clang diagnostic push
  26. #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  27. #pragma clang diagnostic ignored "-Wsign-conversion"
  28. #endif
  29. #ifdef _MSC_VER
  30. #pragma warning (push)
  31. #pragma warning (disable : 4127 4512)
  32. #endif
  33. #include "AAX_Exports.cpp"
  34. #include "AAX_ICollection.h"
  35. #include "AAX_IComponentDescriptor.h"
  36. #include "AAX_IEffectDescriptor.h"
  37. #include "AAX_IPropertyMap.h"
  38. #include "AAX_CEffectParameters.h"
  39. #include "AAX_Errors.h"
  40. #include "AAX_CBinaryTaperDelegate.h"
  41. #include "AAX_CBinaryDisplayDelegate.h"
  42. #include "AAX_CLinearTaperDelegate.h"
  43. #include "AAX_CNumberDisplayDelegate.h"
  44. #include "AAX_CEffectGUI.h"
  45. #include "AAX_IViewContainer.h"
  46. #include "AAX_ITransport.h"
  47. #include "AAX_IMIDINode.h"
  48. #include "AAX_UtilsNative.h"
  49. #include "AAX_Enums.h"
  50. #ifdef _MSC_VER
  51. #pragma warning (pop)
  52. #endif
  53. #ifdef __clang__
  54. #pragma clang diagnostic pop
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifndef JucePlugin_AAXLibs_path
  58. #error "You need to define the JucePlugin_AAXLibs_path macro. (This is best done via the introjucer)"
  59. #endif
  60. #if JUCE_64BIT
  61. #define JUCE_AAX_LIB "AAXLibrary_x64"
  62. #else
  63. #define JUCE_AAX_LIB "AAXLibrary"
  64. #endif
  65. #if JUCE_DEBUG
  66. #define JUCE_AAX_LIB_PATH "\\Debug\\"
  67. #define JUCE_AAX_LIB_SUFFIX "_D"
  68. #else
  69. #define JUCE_AAX_LIB_PATH "\\Release\\"
  70. #define JUCE_AAX_LIB_SUFFIX ""
  71. #endif
  72. #pragma comment(lib, JucePlugin_AAXLibs_path JUCE_AAX_LIB_PATH JUCE_AAX_LIB JUCE_AAX_LIB_SUFFIX ".lib")
  73. #endif
  74. #undef check
  75. const int32_t juceChunkType = 'juce';
  76. //==============================================================================
  77. struct AAXClasses
  78. {
  79. static void check (AAX_Result result)
  80. {
  81. jassert (result == AAX_SUCCESS); ignoreUnused (result);
  82. }
  83. static int getParamIndexFromID (AAX_CParamID paramID) noexcept
  84. {
  85. return atoi (paramID);
  86. }
  87. static bool isBypassParam (AAX_CParamID paramID) noexcept
  88. {
  89. return AAX::IsParameterIDEqual (paramID, cDefaultMasterBypassID) != 0;
  90. }
  91. static AAX_EStemFormat getFormatForAudioChannelSet (const AudioChannelSet& set, bool ignoreLayout) noexcept
  92. {
  93. // if the plug-in ignores layout, it is ok to convert between formats only by their numchannnels
  94. if (ignoreLayout)
  95. {
  96. switch (set.size())
  97. {
  98. case 0: return AAX_eStemFormat_None;
  99. case 1: return AAX_eStemFormat_Mono;
  100. case 2: return AAX_eStemFormat_Stereo;
  101. case 3: return AAX_eStemFormat_LCR;
  102. case 4: return AAX_eStemFormat_Quad;
  103. case 5: return AAX_eStemFormat_5_0;
  104. case 6: return AAX_eStemFormat_5_1;
  105. case 7: return AAX_eStemFormat_7_0_DTS;
  106. case 8: return AAX_eStemFormat_7_1_DTS;
  107. default:
  108. break;
  109. }
  110. return AAX_eStemFormat_INT32_MAX;
  111. }
  112. if (set == AudioChannelSet::disabled()) return AAX_eStemFormat_None;
  113. if (set == AudioChannelSet::mono()) return AAX_eStemFormat_Mono;
  114. if (set == AudioChannelSet::stereo()) return AAX_eStemFormat_Stereo;
  115. if (set == AudioChannelSet::createLCR()) return AAX_eStemFormat_LCR;
  116. if (set == AudioChannelSet::createLCRS()) return AAX_eStemFormat_LCRS;
  117. if (set == AudioChannelSet::quadraphonic()) return AAX_eStemFormat_Quad;
  118. if (set == AudioChannelSet::create5point0()) return AAX_eStemFormat_5_0;
  119. if (set == AudioChannelSet::create5point1()) return AAX_eStemFormat_5_1;
  120. if (set == AudioChannelSet::create6point0()) return AAX_eStemFormat_6_0;
  121. if (set == AudioChannelSet::create6point1()) return AAX_eStemFormat_6_1;
  122. if (set == AudioChannelSet::create7point0()) return AAX_eStemFormat_7_0_DTS;
  123. if (set == AudioChannelSet::create7point1()) return AAX_eStemFormat_7_1_DTS;
  124. if (set == AudioChannelSet::createFront7point0()) return AAX_eStemFormat_7_0_SDDS;
  125. if (set == AudioChannelSet::createFront7point1()) return AAX_eStemFormat_7_1_SDDS;
  126. return AAX_eStemFormat_INT32_MAX;
  127. }
  128. static AudioChannelSet channelSetFromStemFormat (AAX_EStemFormat format, bool ignoreLayout) noexcept
  129. {
  130. if (! ignoreLayout)
  131. {
  132. switch (format)
  133. {
  134. case AAX_eStemFormat_None: return AudioChannelSet::disabled();
  135. case AAX_eStemFormat_Mono: return AudioChannelSet::mono();
  136. case AAX_eStemFormat_Stereo: return AudioChannelSet::stereo();
  137. case AAX_eStemFormat_LCR: return AudioChannelSet::createLCR();
  138. case AAX_eStemFormat_LCRS: return AudioChannelSet::createLCRS();
  139. case AAX_eStemFormat_Quad: return AudioChannelSet::quadraphonic();
  140. case AAX_eStemFormat_5_0: return AudioChannelSet::create5point0();
  141. case AAX_eStemFormat_5_1: return AudioChannelSet::create5point1();
  142. case AAX_eStemFormat_6_0: return AudioChannelSet::create6point0();
  143. case AAX_eStemFormat_6_1: return AudioChannelSet::create6point1();
  144. case AAX_eStemFormat_7_0_SDDS: return AudioChannelSet::createFront7point0();
  145. case AAX_eStemFormat_7_0_DTS: return AudioChannelSet::create7point0();
  146. case AAX_eStemFormat_7_1_SDDS: return AudioChannelSet::createFront7point1();
  147. case AAX_eStemFormat_7_1_DTS: return AudioChannelSet::create7point1();
  148. default:
  149. break;
  150. }
  151. return AudioChannelSet::disabled();
  152. }
  153. return AudioChannelSet::discreteChannels (jmax (0, static_cast<int> (AAX_STEM_FORMAT_CHANNEL_COUNT (format))));
  154. }
  155. static const char* getSpeakerArrangementString (AAX_EStemFormat format) noexcept
  156. {
  157. switch (format)
  158. {
  159. case AAX_eStemFormat_Mono: return "M";
  160. case AAX_eStemFormat_Stereo: return "L R";
  161. case AAX_eStemFormat_LCR: return "L C R";
  162. case AAX_eStemFormat_LCRS: return "L C R S";
  163. case AAX_eStemFormat_Quad: return "L R Ls Rs";
  164. case AAX_eStemFormat_5_0: return "L C R Ls Rs";
  165. case AAX_eStemFormat_5_1: return "L C R Ls Rs LFE";
  166. case AAX_eStemFormat_6_0: return "L C R Ls Cs Rs";
  167. case AAX_eStemFormat_6_1: return "L C R Ls Cs Rs LFE";
  168. case AAX_eStemFormat_7_0_SDDS: return "L Lc C Rc R Ls Rs";
  169. case AAX_eStemFormat_7_1_SDDS: return "L Lc C Rc R Ls Rs LFE";
  170. case AAX_eStemFormat_7_0_DTS: return "L C R Lss Rss Lsr Rsr";
  171. case AAX_eStemFormat_7_1_DTS: return "L C R Lss Rss Lsr Rsr LFE";
  172. default: break;
  173. }
  174. return nullptr;
  175. }
  176. static Colour getColourFromHighlightEnum (AAX_EHighlightColor colour) noexcept
  177. {
  178. switch (colour)
  179. {
  180. case AAX_eHighlightColor_Red: return Colours::red;
  181. case AAX_eHighlightColor_Blue: return Colours::blue;
  182. case AAX_eHighlightColor_Green: return Colours::green;
  183. case AAX_eHighlightColor_Yellow: return Colours::yellow;
  184. default: jassertfalse; break;
  185. }
  186. return Colours::black;
  187. }
  188. //==============================================================================
  189. class JuceAAX_Processor;
  190. struct PluginInstanceInfo
  191. {
  192. PluginInstanceInfo (JuceAAX_Processor& p) : parameters (p) {}
  193. JuceAAX_Processor& parameters;
  194. JUCE_DECLARE_NON_COPYABLE (PluginInstanceInfo)
  195. };
  196. //==============================================================================
  197. struct JUCEAlgorithmContext
  198. {
  199. float** inputChannels;
  200. float** outputChannels;
  201. int32_t* bufferSize;
  202. int32_t* bypass;
  203. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  204. AAX_IMIDINode* midiNodeIn;
  205. #endif
  206. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsSynth || JucePlugin_IsMidiEffect
  207. AAX_IMIDINode* midiNodeOut;
  208. #endif
  209. PluginInstanceInfo* pluginInstance;
  210. int32_t* isPrepared;
  211. int32_t* sideChainBuffers;
  212. };
  213. struct JUCEAlgorithmIDs
  214. {
  215. enum
  216. {
  217. inputChannels = AAX_FIELD_INDEX (JUCEAlgorithmContext, inputChannels),
  218. outputChannels = AAX_FIELD_INDEX (JUCEAlgorithmContext, outputChannels),
  219. bufferSize = AAX_FIELD_INDEX (JUCEAlgorithmContext, bufferSize),
  220. bypass = AAX_FIELD_INDEX (JUCEAlgorithmContext, bypass),
  221. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  222. midiNodeIn = AAX_FIELD_INDEX (JUCEAlgorithmContext, midiNodeIn),
  223. #endif
  224. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsSynth || JucePlugin_IsMidiEffect
  225. midiNodeOut = AAX_FIELD_INDEX (JUCEAlgorithmContext, midiNodeOut),
  226. #endif
  227. pluginInstance = AAX_FIELD_INDEX (JUCEAlgorithmContext, pluginInstance),
  228. preparedFlag = AAX_FIELD_INDEX (JUCEAlgorithmContext, isPrepared),
  229. sideChainBuffers = AAX_FIELD_INDEX (JUCEAlgorithmContext, sideChainBuffers)
  230. };
  231. };
  232. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  233. static AAX_IMIDINode* getMidiNodeIn (const JUCEAlgorithmContext& c) noexcept { return c.midiNodeIn; }
  234. #else
  235. static AAX_IMIDINode* getMidiNodeIn (const JUCEAlgorithmContext&) noexcept { return nullptr; }
  236. #endif
  237. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsSynth || JucePlugin_IsMidiEffect
  238. AAX_IMIDINode* midiNodeOut;
  239. static AAX_IMIDINode* getMidiNodeOut (const JUCEAlgorithmContext& c) noexcept { return c.midiNodeOut; }
  240. #else
  241. static AAX_IMIDINode* getMidiNodeOut (const JUCEAlgorithmContext&) noexcept { return nullptr; }
  242. #endif
  243. //==============================================================================
  244. class JuceAAX_GUI : public AAX_CEffectGUI
  245. {
  246. public:
  247. JuceAAX_GUI() {}
  248. ~JuceAAX_GUI() { DeleteViewContainer(); }
  249. static AAX_IEffectGUI* AAX_CALLBACK Create() { return new JuceAAX_GUI(); }
  250. void CreateViewContents() override
  251. {
  252. if (component == nullptr)
  253. {
  254. if (JuceAAX_Processor* params = dynamic_cast<JuceAAX_Processor*> (GetEffectParameters()))
  255. component = new ContentWrapperComponent (*this, params->getPluginInstance());
  256. else
  257. jassertfalse;
  258. }
  259. }
  260. void CreateViewContainer() override
  261. {
  262. CreateViewContents();
  263. if (void* nativeViewToAttachTo = GetViewContainerPtr())
  264. {
  265. #if JUCE_MAC
  266. if (GetViewContainerType() == AAX_eViewContainer_Type_NSView)
  267. #else
  268. if (GetViewContainerType() == AAX_eViewContainer_Type_HWND)
  269. #endif
  270. {
  271. component->setVisible (true);
  272. component->addToDesktop (0, nativeViewToAttachTo);
  273. }
  274. }
  275. }
  276. void DeleteViewContainer() override
  277. {
  278. if (component != nullptr)
  279. {
  280. JUCE_AUTORELEASEPOOL
  281. {
  282. component->removeFromDesktop();
  283. component = nullptr;
  284. }
  285. }
  286. }
  287. AAX_Result GetViewSize (AAX_Point* viewSize) const override
  288. {
  289. if (component != nullptr)
  290. {
  291. viewSize->horz = (float) component->getWidth();
  292. viewSize->vert = (float) component->getHeight();
  293. return AAX_SUCCESS;
  294. }
  295. return AAX_ERROR_NULL_OBJECT;
  296. }
  297. AAX_Result ParameterUpdated (AAX_CParamID) override
  298. {
  299. return AAX_SUCCESS;
  300. }
  301. AAX_Result SetControlHighlightInfo (AAX_CParamID paramID, AAX_CBoolean isHighlighted, AAX_EHighlightColor colour) override
  302. {
  303. if (component != nullptr && component->pluginEditor != nullptr)
  304. {
  305. if (! isBypassParam (paramID))
  306. {
  307. AudioProcessorEditor::ParameterControlHighlightInfo info;
  308. info.parameterIndex = getParamIndexFromID (paramID);
  309. info.isHighlighted = (isHighlighted != 0);
  310. info.suggestedColour = getColourFromHighlightEnum (colour);
  311. component->pluginEditor->setControlHighlight (info);
  312. }
  313. return AAX_SUCCESS;
  314. }
  315. return AAX_ERROR_NULL_OBJECT;
  316. }
  317. private:
  318. struct ContentWrapperComponent : public Component
  319. {
  320. ContentWrapperComponent (JuceAAX_GUI& gui, AudioProcessor& plugin)
  321. : owner (gui)
  322. {
  323. setOpaque (true);
  324. setBroughtToFrontOnMouseClick (true);
  325. addAndMakeVisible (pluginEditor = plugin.createEditorIfNeeded());
  326. if (pluginEditor != nullptr)
  327. {
  328. setBounds (pluginEditor->getLocalBounds());
  329. pluginEditor->addMouseListener (this, true);
  330. }
  331. }
  332. ~ContentWrapperComponent()
  333. {
  334. if (pluginEditor != nullptr)
  335. {
  336. PopupMenu::dismissAllActiveMenus();
  337. pluginEditor->removeMouseListener (this);
  338. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  339. }
  340. }
  341. void paint (Graphics& g) override
  342. {
  343. g.fillAll (Colours::black);
  344. }
  345. template <typename MethodType>
  346. void callMouseMethod (const MouseEvent& e, MethodType method)
  347. {
  348. if (AAX_IViewContainer* vc = owner.GetViewContainer())
  349. {
  350. const int parameterIndex = pluginEditor->getControlParameterIndex (*e.eventComponent);
  351. if (parameterIndex >= 0)
  352. {
  353. uint32_t mods = 0;
  354. vc->GetModifiers (&mods);
  355. (vc->*method) (IndexAsParamID (parameterIndex), mods);
  356. }
  357. }
  358. }
  359. void mouseDown (const MouseEvent& e) override { callMouseMethod (e, &AAX_IViewContainer::HandleParameterMouseDown); }
  360. void mouseUp (const MouseEvent& e) override { callMouseMethod (e, &AAX_IViewContainer::HandleParameterMouseUp); }
  361. void mouseDrag (const MouseEvent& e) override { callMouseMethod (e, &AAX_IViewContainer::HandleParameterMouseDrag); }
  362. void childBoundsChanged (Component*) override
  363. {
  364. if (pluginEditor != nullptr)
  365. {
  366. const int w = pluginEditor->getWidth();
  367. const int h = pluginEditor->getHeight();
  368. setSize (w, h);
  369. AAX_Point newSize ((float) h, (float) w);
  370. owner.GetViewContainer()->SetViewSize (newSize);
  371. }
  372. }
  373. ScopedPointer<AudioProcessorEditor> pluginEditor;
  374. JuceAAX_GUI& owner;
  375. #if JUCE_WINDOWS
  376. WindowsHooks hooks;
  377. #endif
  378. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  379. };
  380. ScopedPointer<ContentWrapperComponent> component;
  381. ScopedJuceInitialiser_GUI libraryInitialiser;
  382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAAX_GUI)
  383. };
  384. //==============================================================================
  385. class JuceAAX_Processor : public AAX_CEffectParameters,
  386. public juce::AudioPlayHead,
  387. public AudioProcessorListener
  388. {
  389. public:
  390. JuceAAX_Processor() : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_AAX)),
  391. busUtils (*pluginInstance, false),
  392. sampleRate (0), lastBufferSize (1024), maxBufferSize (1024),
  393. hasSidechain (false)
  394. {
  395. pluginInstance->setPlayHead (this);
  396. pluginInstance->addListener (this);
  397. busUtils.findAllCompatibleLayouts();
  398. AAX_CEffectParameters::GetNumberOfChunks (&juceChunkIndex);
  399. }
  400. static AAX_CEffectParameters* AAX_CALLBACK Create() { return new JuceAAX_Processor(); }
  401. AAX_Result EffectInit() override
  402. {
  403. AAX_Result err;
  404. check (Controller()->GetSampleRate (&sampleRate));
  405. if ((err = preparePlugin()) != AAX_SUCCESS)
  406. return err;
  407. addBypassParameter();
  408. addAudioProcessorParameters();
  409. return AAX_SUCCESS;
  410. }
  411. AAX_Result GetNumberOfChunks (int32_t* numChunks) const override
  412. {
  413. // The juceChunk is the last chunk.
  414. *numChunks = juceChunkIndex + 1;
  415. return AAX_SUCCESS;
  416. }
  417. AAX_Result GetChunkIDFromIndex (int32_t index, AAX_CTypeID* chunkID) const override
  418. {
  419. if (index != juceChunkIndex)
  420. return AAX_CEffectParameters::GetChunkIDFromIndex (index, chunkID);
  421. *chunkID = juceChunkType;
  422. return AAX_SUCCESS;
  423. }
  424. juce::MemoryBlock& getTemporaryChunkMemory() const
  425. {
  426. ScopedLock sl (perThreadDataLock);
  427. const Thread::ThreadID currentThread = Thread::getCurrentThreadId();
  428. if (ChunkMemoryBlock::Ptr m = perThreadFilterData [currentThread])
  429. return m->data;
  430. ChunkMemoryBlock::Ptr m (new ChunkMemoryBlock());
  431. perThreadFilterData.set (currentThread, m);
  432. return m->data;
  433. }
  434. AAX_Result GetChunkSize (AAX_CTypeID chunkID, uint32_t* oSize) const override
  435. {
  436. if (chunkID != juceChunkType)
  437. return AAX_CEffectParameters::GetChunkSize (chunkID, oSize);
  438. juce::MemoryBlock& tempFilterData = getTemporaryChunkMemory();
  439. tempFilterData.reset();
  440. pluginInstance->getStateInformation (tempFilterData);
  441. *oSize = (uint32_t) tempFilterData.getSize();
  442. return AAX_SUCCESS;
  443. }
  444. AAX_Result GetChunk (AAX_CTypeID chunkID, AAX_SPlugInChunk* oChunk) const override
  445. {
  446. if (chunkID != juceChunkType)
  447. return AAX_CEffectParameters::GetChunk (chunkID, oChunk);
  448. juce::MemoryBlock& tempFilterData = getTemporaryChunkMemory();
  449. if (tempFilterData.getSize() == 0)
  450. return 20700 /*AAX_ERROR_PLUGIN_API_INVALID_THREAD*/;
  451. oChunk->fSize = (int32_t) tempFilterData.getSize();
  452. tempFilterData.copyTo (oChunk->fData, 0, tempFilterData.getSize());
  453. tempFilterData.reset();
  454. return AAX_SUCCESS;
  455. }
  456. AAX_Result SetChunk (AAX_CTypeID chunkID, const AAX_SPlugInChunk* chunk) override
  457. {
  458. if (chunkID != juceChunkType)
  459. return AAX_CEffectParameters::SetChunk (chunkID, chunk);
  460. pluginInstance->setStateInformation ((void*) chunk->fData, chunk->fSize);
  461. // Notify Pro Tools that the parameters were updated.
  462. // Without it a bug happens in these circumstances:
  463. // * A preset is saved with the RTAS version of the plugin (".tfx" preset format).
  464. // * The preset is loaded in PT 10 using the AAX version.
  465. // * The session is then saved, and closed.
  466. // * The saved session is loaded, but acting as if the preset was never loaded.
  467. const int numParameters = pluginInstance->getNumParameters();
  468. for (int i = 0; i < numParameters; ++i)
  469. SetParameterNormalizedValue (IndexAsParamID (i), (double) pluginInstance->getParameter(i));
  470. return AAX_SUCCESS;
  471. }
  472. AAX_Result ResetFieldData (AAX_CFieldIndex fieldIndex, void* data, uint32_t dataSize) const override
  473. {
  474. switch (fieldIndex)
  475. {
  476. case JUCEAlgorithmIDs::pluginInstance:
  477. {
  478. const size_t numObjects = dataSize / sizeof (PluginInstanceInfo);
  479. PluginInstanceInfo* const objects = static_cast<PluginInstanceInfo*> (data);
  480. jassert (numObjects == 1); // not sure how to handle more than one..
  481. for (size_t i = 0; i < numObjects; ++i)
  482. new (objects + i) PluginInstanceInfo (const_cast<JuceAAX_Processor&> (*this));
  483. break;
  484. }
  485. case JUCEAlgorithmIDs::preparedFlag:
  486. {
  487. const_cast<JuceAAX_Processor*>(this)->preparePlugin();
  488. const size_t numObjects = dataSize / sizeof (uint32_t);
  489. uint32_t* const objects = static_cast<uint32_t*> (data);
  490. for (size_t i = 0; i < numObjects; ++i)
  491. new (objects + i) uint32_t (1);
  492. break;
  493. }
  494. }
  495. return AAX_SUCCESS;
  496. }
  497. AAX_Result UpdateParameterNormalizedValue (AAX_CParamID paramID, double value, AAX_EUpdateSource source) override
  498. {
  499. AAX_Result result = AAX_CEffectParameters::UpdateParameterNormalizedValue (paramID, value, source);
  500. if (! isBypassParam (paramID))
  501. pluginInstance->setParameter (getParamIndexFromID (paramID), (float) value);
  502. return result;
  503. }
  504. AAX_Result GetParameterValueFromString (AAX_CParamID paramID, double* result, const AAX_IString& text) const override
  505. {
  506. if (isBypassParam (paramID))
  507. {
  508. *result = (text.Get()[0] == 'B') ? 1 : 0;
  509. return AAX_SUCCESS;
  510. }
  511. if (AudioProcessorParameter* param = pluginInstance->getParameters() [getParamIndexFromID (paramID)])
  512. {
  513. *result = param->getValueForText (text.Get());
  514. return AAX_SUCCESS;
  515. }
  516. return AAX_CEffectParameters::GetParameterValueFromString (paramID, result, text);
  517. }
  518. AAX_Result GetParameterStringFromValue (AAX_CParamID paramID, double value, AAX_IString* result, int32_t maxLen) const override
  519. {
  520. if (isBypassParam (paramID))
  521. {
  522. result->Set (value == 0 ? "Off" : (maxLen >= 8 ? "Bypassed" : "Byp"));
  523. }
  524. else
  525. {
  526. const int paramIndex = getParamIndexFromID (paramID);
  527. juce::String text;
  528. if (AudioProcessorParameter* param = pluginInstance->getParameters() [paramIndex])
  529. text = param->getText ((float) value, maxLen);
  530. else
  531. text = pluginInstance->getParameterText (paramIndex, maxLen);
  532. result->Set (text.toRawUTF8());
  533. }
  534. return AAX_SUCCESS;
  535. }
  536. AAX_Result GetParameterNumberofSteps (AAX_CParamID paramID, int32_t* result) const
  537. {
  538. if (isBypassParam (paramID))
  539. *result = 2;
  540. else
  541. *result = pluginInstance->getParameterNumSteps (getParamIndexFromID (paramID));
  542. return AAX_SUCCESS;
  543. }
  544. AAX_Result GetParameterNormalizedValue (AAX_CParamID paramID, double* result) const override
  545. {
  546. if (isBypassParam (paramID))
  547. return AAX_CEffectParameters::GetParameterNormalizedValue (paramID, result);
  548. *result = pluginInstance->getParameter (getParamIndexFromID (paramID));
  549. return AAX_SUCCESS;
  550. }
  551. AAX_Result SetParameterNormalizedValue (AAX_CParamID paramID, double newValue) override
  552. {
  553. if (isBypassParam (paramID))
  554. return AAX_CEffectParameters::SetParameterNormalizedValue (paramID, newValue);
  555. if (AAX_IParameter* p = const_cast<AAX_IParameter*> (mParameterManager.GetParameterByID (paramID)))
  556. p->SetValueWithFloat ((float) newValue);
  557. pluginInstance->setParameter (getParamIndexFromID (paramID), (float) newValue);
  558. return AAX_SUCCESS;
  559. }
  560. AAX_Result SetParameterNormalizedRelative (AAX_CParamID paramID, double newDeltaValue) override
  561. {
  562. if (isBypassParam (paramID))
  563. return AAX_CEffectParameters::SetParameterNormalizedRelative (paramID, newDeltaValue);
  564. const int paramIndex = getParamIndexFromID (paramID);
  565. const float newValue = pluginInstance->getParameter (paramIndex) + (float) newDeltaValue;
  566. pluginInstance->setParameter (paramIndex, jlimit (0.0f, 1.0f, newValue));
  567. if (AAX_IParameter* p = const_cast<AAX_IParameter*> (mParameterManager.GetParameterByID (paramID)))
  568. p->SetValueWithFloat (newValue);
  569. return AAX_SUCCESS;
  570. }
  571. AAX_Result GetParameterNameOfLength (AAX_CParamID paramID, AAX_IString* result, int32_t maxLen) const override
  572. {
  573. if (isBypassParam (paramID))
  574. result->Set (maxLen >= 13 ? "Master Bypass"
  575. : (maxLen >= 8 ? "Mast Byp"
  576. : (maxLen >= 6 ? "MstByp" : "MByp")));
  577. else
  578. result->Set (pluginInstance->getParameterName (getParamIndexFromID (paramID), maxLen).toRawUTF8());
  579. return AAX_SUCCESS;
  580. }
  581. AAX_Result GetParameterName (AAX_CParamID paramID, AAX_IString* result) const override
  582. {
  583. if (isBypassParam (paramID))
  584. result->Set ("Master Bypass");
  585. else
  586. result->Set (pluginInstance->getParameterName (getParamIndexFromID (paramID), 31).toRawUTF8());
  587. return AAX_SUCCESS;
  588. }
  589. AAX_Result GetParameterDefaultNormalizedValue (AAX_CParamID paramID, double* result) const override
  590. {
  591. if (! isBypassParam (paramID))
  592. {
  593. *result = (double) pluginInstance->getParameterDefaultValue (getParamIndexFromID (paramID));
  594. jassert (*result >= 0 && *result <= 1.0f);
  595. }
  596. return AAX_SUCCESS;
  597. }
  598. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  599. bool getCurrentPosition (juce::AudioPlayHead::CurrentPositionInfo& info) override
  600. {
  601. const AAX_ITransport& transport = *Transport();
  602. info.bpm = 0.0;
  603. check (transport.GetCurrentTempo (&info.bpm));
  604. int32_t num = 4, den = 4;
  605. transport.GetCurrentMeter (&num, &den);
  606. info.timeSigNumerator = (int) num;
  607. info.timeSigDenominator = (int) den;
  608. info.timeInSamples = 0;
  609. if (transport.IsTransportPlaying (&info.isPlaying) != AAX_SUCCESS)
  610. info.isPlaying = false;
  611. if (info.isPlaying
  612. || transport.GetTimelineSelectionStartPosition (&info.timeInSamples) != AAX_SUCCESS)
  613. check (transport.GetCurrentNativeSampleLocation (&info.timeInSamples));
  614. info.timeInSeconds = info.timeInSamples / sampleRate;
  615. int64_t ticks = 0;
  616. check (transport.GetCurrentTickPosition (&ticks));
  617. info.ppqPosition = ticks / 960000.0;
  618. info.isLooping = false;
  619. int64_t loopStartTick = 0, loopEndTick = 0;
  620. check (transport.GetCurrentLoopPosition (&info.isLooping, &loopStartTick, &loopEndTick));
  621. info.ppqLoopStart = loopStartTick / 960000.0;
  622. info.ppqLoopEnd = loopEndTick / 960000.0;
  623. info.editOriginTime = 0;
  624. info.frameRate = AudioPlayHead::fpsUnknown;
  625. AAX_EFrameRate frameRate;
  626. int32_t offset;
  627. if (transport.GetTimeCodeInfo (&frameRate, &offset) == AAX_SUCCESS)
  628. {
  629. double framesPerSec = 24.0;
  630. switch (frameRate)
  631. {
  632. case AAX_eFrameRate_Undeclared: break;
  633. case AAX_eFrameRate_24Frame: info.frameRate = AudioPlayHead::fps24; break;
  634. case AAX_eFrameRate_25Frame: info.frameRate = AudioPlayHead::fps25; framesPerSec = 25.0; break;
  635. case AAX_eFrameRate_2997NonDrop: info.frameRate = AudioPlayHead::fps2997; framesPerSec = 29.97002997; break;
  636. case AAX_eFrameRate_2997DropFrame: info.frameRate = AudioPlayHead::fps2997drop; framesPerSec = 29.97002997; break;
  637. case AAX_eFrameRate_30NonDrop: info.frameRate = AudioPlayHead::fps30; framesPerSec = 30.0; break;
  638. case AAX_eFrameRate_30DropFrame: info.frameRate = AudioPlayHead::fps30drop; framesPerSec = 30.0; break;
  639. case AAX_eFrameRate_23976: info.frameRate = AudioPlayHead::fps24; framesPerSec = 23.976; break;
  640. default: break;
  641. }
  642. info.editOriginTime = offset / framesPerSec;
  643. }
  644. // No way to get these: (?)
  645. info.isRecording = false;
  646. info.ppqPositionOfLastBarStart = 0;
  647. return true;
  648. }
  649. void audioProcessorParameterChanged (AudioProcessor* /*processor*/, int parameterIndex, float newValue) override
  650. {
  651. SetParameterNormalizedValue (IndexAsParamID (parameterIndex), (double) newValue);
  652. }
  653. void audioProcessorChanged (AudioProcessor* processor) override
  654. {
  655. ++mNumPlugInChanges;
  656. check (Controller()->SetSignalLatency (processor->getLatencySamples()));
  657. }
  658. void audioProcessorParameterChangeGestureBegin (AudioProcessor* /*processor*/, int parameterIndex) override
  659. {
  660. TouchParameter (IndexAsParamID (parameterIndex));
  661. }
  662. void audioProcessorParameterChangeGestureEnd (AudioProcessor* /*processor*/, int parameterIndex) override
  663. {
  664. ReleaseParameter (IndexAsParamID (parameterIndex));
  665. }
  666. AAX_Result NotificationReceived (AAX_CTypeID type, const void* data, uint32_t size) override
  667. {
  668. if (type == AAX_eNotificationEvent_EnteringOfflineMode) pluginInstance->setNonRealtime (true);
  669. if (type == AAX_eNotificationEvent_ExitingOfflineMode) pluginInstance->setNonRealtime (false);
  670. return AAX_CEffectParameters::NotificationReceived (type, data, size);
  671. }
  672. const float* getAudioBufferForInput (const float* const* inputs, const int sidechain, const int mainNumIns, int idx) const noexcept
  673. {
  674. jassert (idx < (mainNumIns + 1));
  675. if (idx < mainNumIns)
  676. return inputs[idx];
  677. return (sidechain != -1 ? inputs[sidechain] : sideChainBuffer.getData());
  678. }
  679. void process (const float* const* inputs, float* const* outputs, const int sideChainBufferIdx,
  680. const int bufferSize, const bool bypass,
  681. AAX_IMIDINode* midiNodeIn, AAX_IMIDINode* midiNodesOut)
  682. {
  683. const int numIns = pluginInstance->getTotalNumInputChannels();
  684. const int numOuts = pluginInstance->getTotalNumOutputChannels();
  685. if (pluginInstance->isSuspended())
  686. {
  687. for (int i = 0; i < numOuts; ++i)
  688. FloatVectorOperations::clear (outputs[i], bufferSize);
  689. }
  690. else
  691. {
  692. const int mainNumIns = numIns > 0 ? pluginInstance->busArrangement.inputBuses.getReference (0).channels.size() : 0;
  693. const int sidechain = busUtils.getNumEnabledBuses (true) >= 2 ? sideChainBufferIdx : -1;
  694. if (numOuts >= numIns)
  695. {
  696. for (int i = 0; i < numIns; ++i)
  697. memcpy (outputs[i], getAudioBufferForInput (inputs, sidechain, mainNumIns, i), (size_t) bufferSize * sizeof (float));
  698. process (outputs, numOuts, bufferSize, bypass, midiNodeIn, midiNodesOut);
  699. }
  700. else
  701. {
  702. if (channelList.size() <= numIns)
  703. channelList.insertMultiple (-1, nullptr, 1 + numIns - channelList.size());
  704. float** channels = channelList.getRawDataPointer();
  705. for (int i = 0; i < numOuts; ++i)
  706. {
  707. memcpy (outputs[i], getAudioBufferForInput (inputs, sidechain, mainNumIns, i), (size_t) bufferSize * sizeof (float));
  708. channels[i] = outputs[i];
  709. }
  710. for (int i = numOuts; i < numIns; ++i)
  711. channels[i] = const_cast<float*> (getAudioBufferForInput (inputs, sidechain, mainNumIns, i));
  712. process (channels, numIns, bufferSize, bypass, midiNodeIn, midiNodesOut);
  713. }
  714. }
  715. }
  716. bool supportsSidechain() const noexcept { return hasSidechain; };
  717. private:
  718. void process (float* const* channels, const int numChans, const int bufferSize,
  719. const bool bypass, AAX_IMIDINode* midiNodeIn, AAX_IMIDINode* midiNodesOut)
  720. {
  721. AudioSampleBuffer buffer (channels, numChans, bufferSize);
  722. midiBuffer.clear();
  723. ignoreUnused (midiNodeIn, midiNodesOut);
  724. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  725. {
  726. AAX_CMidiStream* const midiStream = midiNodeIn->GetNodeBuffer();
  727. const uint32_t numMidiEvents = midiStream->mBufferSize;
  728. for (uint32_t i = 0; i < numMidiEvents; ++i)
  729. {
  730. const AAX_CMidiPacket& m = midiStream->mBuffer[i];
  731. jassert ((int) m.mTimestamp < bufferSize);
  732. midiBuffer.addEvent (m.mData, (int) m.mLength,
  733. jlimit (0, (int) bufferSize - 1, (int) m.mTimestamp));
  734. }
  735. }
  736. #endif
  737. {
  738. if (lastBufferSize != bufferSize)
  739. {
  740. lastBufferSize = bufferSize;
  741. pluginInstance->setRateAndBufferSizeDetails (sampleRate, bufferSize);
  742. if (bufferSize > maxBufferSize)
  743. {
  744. // we only call prepareToPlay here if the new buffer size is larger than
  745. // the one used last time prepareToPlay was called.
  746. // currently, this should never actually happen, because as of Pro Tools 12,
  747. // the maximum possible value is 1024, and we call prepareToPlay with that
  748. // value during initialisation.
  749. pluginInstance->prepareToPlay (sampleRate, bufferSize);
  750. maxBufferSize = bufferSize;
  751. sideChainBuffer.realloc (static_cast<size_t> (maxBufferSize));
  752. }
  753. }
  754. const ScopedLock sl (pluginInstance->getCallbackLock());
  755. if (bypass)
  756. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  757. else
  758. pluginInstance->processBlock (buffer, midiBuffer);
  759. }
  760. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  761. {
  762. const juce::uint8* midiEventData;
  763. int midiEventSize, midiEventPosition;
  764. MidiBuffer::Iterator i (midiBuffer);
  765. AAX_CMidiPacket packet;
  766. packet.mIsImmediate = false;
  767. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  768. {
  769. jassert (isPositiveAndBelow (midiEventPosition, bufferSize));
  770. if (midiEventSize <= 4)
  771. {
  772. packet.mTimestamp = (uint32_t) midiEventPosition;
  773. packet.mLength = (uint32_t) midiEventSize;
  774. memcpy (packet.mData, midiEventData, (size_t) midiEventSize);
  775. check (midiNodesOut->PostMIDIPacket (&packet));
  776. }
  777. }
  778. }
  779. #endif
  780. }
  781. void addBypassParameter()
  782. {
  783. AAX_IParameter* masterBypass = new AAX_CParameter<bool> (cDefaultMasterBypassID,
  784. AAX_CString ("Master Bypass"),
  785. false,
  786. AAX_CBinaryTaperDelegate<bool>(),
  787. AAX_CBinaryDisplayDelegate<bool> ("bypass", "on"),
  788. true);
  789. masterBypass->SetNumberOfSteps (2);
  790. masterBypass->SetType (AAX_eParameterType_Discrete);
  791. mParameterManager.AddParameter (masterBypass);
  792. mPacketDispatcher.RegisterPacket (cDefaultMasterBypassID, JUCEAlgorithmIDs::bypass);
  793. }
  794. void addAudioProcessorParameters()
  795. {
  796. AudioProcessor& audioProcessor = getPluginInstance();
  797. const int numParameters = audioProcessor.getNumParameters();
  798. for (int parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex)
  799. {
  800. AAX_CString paramName (audioProcessor.getParameterName (parameterIndex, 31).toRawUTF8());
  801. AAX_IParameter* parameter
  802. = new AAX_CParameter<float> (IndexAsParamID (parameterIndex),
  803. paramName,
  804. audioProcessor.getParameterDefaultValue (parameterIndex),
  805. AAX_CLinearTaperDelegate<float, 0>(),
  806. AAX_CNumberDisplayDelegate<float, 3>(),
  807. audioProcessor.isParameterAutomatable (parameterIndex));
  808. parameter->AddShortenedName (audioProcessor.getParameterName (parameterIndex, 4).toRawUTF8());
  809. const int parameterNumSteps = audioProcessor.getParameterNumSteps (parameterIndex);
  810. parameter->SetNumberOfSteps ((uint32_t) parameterNumSteps);
  811. parameter->SetType (parameterNumSteps > 1000 ? AAX_eParameterType_Continuous
  812. : AAX_eParameterType_Discrete);
  813. parameter->SetOrientation (audioProcessor.isParameterOrientationInverted (parameterIndex)
  814. ? (AAX_eParameterOrientation_RightMinLeftMax | AAX_eParameterOrientation_TopMinBottomMax
  815. | AAX_eParameterOrientation_RotarySingleDotMode | AAX_eParameterOrientation_RotaryRightMinLeftMax)
  816. : (AAX_eParameterOrientation_LeftMinRightMax | AAX_eParameterOrientation_BottomMinTopMax
  817. | AAX_eParameterOrientation_RotarySingleDotMode | AAX_eParameterOrientation_RotaryLeftMinRightMax));
  818. mParameterManager.AddParameter (parameter);
  819. }
  820. }
  821. AAX_Result preparePlugin()
  822. {
  823. AudioProcessor& audioProcessor = getPluginInstance();
  824. #if JucePlugin_IsMidiEffect
  825. // MIDI effect plug-ins do not support any audio channels
  826. jassert (audioProcessor.busArrangement.getTotalNumInputChannels() == 0
  827. && audioProcessor.busArrangement.getTotalNumOutputChannels() == 0);
  828. #else
  829. AAX_EStemFormat inputStemFormat = AAX_eStemFormat_None;
  830. check (Controller()->GetInputStemFormat (&inputStemFormat));
  831. AAX_EStemFormat outputStemFormat = AAX_eStemFormat_None;
  832. check (Controller()->GetOutputStemFormat (&outputStemFormat));
  833. const AudioChannelSet inputSet = channelSetFromStemFormat (inputStemFormat, busUtils.busIgnoresLayout (true, 0));
  834. const AudioChannelSet outputSet = channelSetFromStemFormat (outputStemFormat, busUtils.busIgnoresLayout (false, 0));
  835. if ( (inputSet == AudioChannelSet::disabled() && inputStemFormat != AAX_eStemFormat_None)
  836. || (outputSet == AudioChannelSet::disabled() && outputStemFormat != AAX_eStemFormat_None))
  837. return AAX_ERROR_UNIMPLEMENTED;
  838. bool success = true;
  839. if (busUtils.getBusCount (true) > 0)
  840. success = audioProcessor.setPreferredBusArrangement (true, 0, inputSet);
  841. if (success && busUtils.getBusCount (false) > 0)
  842. success = audioProcessor.setPreferredBusArrangement (false, 0, outputSet);
  843. // This should never happen as the plugin reported that this layout is supported
  844. jassert (success);
  845. hasSidechain = enableAuxBusesForCurrentFormat (busUtils, inputSet, outputSet);
  846. if (hasSidechain)
  847. sideChainBuffer.realloc (static_cast<size_t> (maxBufferSize));
  848. // recheck the format
  849. if ( (busUtils.getBusCount (true) > 0 && busUtils.getChannelSet (true, 0) != inputSet)
  850. || (busUtils.getBusCount (false) > 0 && busUtils.getChannelSet (false, 0) != outputSet)
  851. || (hasSidechain && busUtils.getNumChannels(true, 1) != 1))
  852. return AAX_ERROR_UNIMPLEMENTED;
  853. #endif
  854. audioProcessor.setRateAndBufferSizeDetails (sampleRate, maxBufferSize);
  855. audioProcessor.prepareToPlay (sampleRate, lastBufferSize);
  856. maxBufferSize = lastBufferSize;
  857. check (Controller()->SetSignalLatency (audioProcessor.getLatencySamples()));
  858. return AAX_SUCCESS;
  859. }
  860. ScopedJuceInitialiser_GUI libraryInitialiser;
  861. ScopedPointer<AudioProcessor> pluginInstance;
  862. PluginBusUtilities busUtils;
  863. MidiBuffer midiBuffer;
  864. Array<float*> channelList;
  865. int32_t juceChunkIndex;
  866. AAX_CSampleRate sampleRate;
  867. int lastBufferSize, maxBufferSize;
  868. bool hasSidechain;
  869. HeapBlock<float> sideChainBuffer;
  870. struct ChunkMemoryBlock : public ReferenceCountedObject
  871. {
  872. juce::MemoryBlock data;
  873. typedef ReferenceCountedObjectPtr<ChunkMemoryBlock> Ptr;
  874. };
  875. // temporary filter data is generated in GetChunkSize
  876. // and the size of the data returned. To avoid generating
  877. // it again in GetChunk, we need to store it somewhere.
  878. // However, as GetChunkSize and GetChunk can be called
  879. // on different threads, we store it in thread dependant storage
  880. // in a hash map with the thread id as a key.
  881. mutable HashMap<Thread::ThreadID, ChunkMemoryBlock::Ptr> perThreadFilterData;
  882. CriticalSection perThreadDataLock;
  883. JUCE_DECLARE_NON_COPYABLE (JuceAAX_Processor)
  884. };
  885. //==============================================================================
  886. struct IndexAsParamID
  887. {
  888. inline explicit IndexAsParamID (int i) noexcept : index (i) {}
  889. operator AAX_CParamID() noexcept
  890. {
  891. jassert (index >= 0);
  892. char* t = name + sizeof (name);
  893. *--t = 0;
  894. int v = index;
  895. do
  896. {
  897. *--t = (char) ('0' + (v % 10));
  898. v /= 10;
  899. } while (v > 0);
  900. return static_cast<AAX_CParamID> (t);
  901. }
  902. private:
  903. int index;
  904. char name[32];
  905. JUCE_DECLARE_NON_COPYABLE (IndexAsParamID)
  906. };
  907. //==============================================================================
  908. struct AAXFormatConfiguration
  909. {
  910. AAXFormatConfiguration() noexcept
  911. : inputFormat (AAX_eStemFormat_None), outputFormat (AAX_eStemFormat_None) {}
  912. AAXFormatConfiguration (AAX_EStemFormat inFormat, AAX_EStemFormat outFormat) noexcept
  913. : inputFormat (inFormat), outputFormat (outFormat) {}
  914. AAX_EStemFormat inputFormat, outputFormat;
  915. bool operator== (const AAXFormatConfiguration other) const noexcept { return (inputFormat == other.inputFormat) && (outputFormat == other.outputFormat); }
  916. bool operator< (const AAXFormatConfiguration other) const noexcept
  917. {
  918. return (inputFormat == other.inputFormat) ? (outputFormat < other.outputFormat) : (inputFormat < other.inputFormat);
  919. }
  920. };
  921. //==============================================================================
  922. static void AAX_CALLBACK algorithmProcessCallback (JUCEAlgorithmContext* const instancesBegin[],
  923. const void* const instancesEnd)
  924. {
  925. for (JUCEAlgorithmContext* const* iter = instancesBegin; iter < instancesEnd; ++iter)
  926. {
  927. const JUCEAlgorithmContext& i = **iter;
  928. int sideChainBufferIdx = i.pluginInstance->parameters.supportsSidechain() && i.sideChainBuffers != nullptr
  929. ? static_cast<int> (*i.sideChainBuffers)
  930. : -1;
  931. i.pluginInstance->parameters.process (i.inputChannels, i.outputChannels, sideChainBufferIdx,
  932. *(i.bufferSize), *(i.bypass) != 0,
  933. getMidiNodeIn(i), getMidiNodeOut(i));
  934. }
  935. }
  936. static bool enableAuxBusesForCurrentFormat (PluginBusUtilities& busUtils, const AudioChannelSet& inputLayout,
  937. const AudioChannelSet& outputLayout)
  938. {
  939. const int numOutBuses = busUtils.getBusCount (false);
  940. const int numInputBuses = busUtils.getBusCount(true);
  941. if (numOutBuses > 1)
  942. {
  943. PluginBusUtilities::ScopedBusRestorer layoutRestorer (busUtils);
  944. // enable all possible output buses
  945. for (int busIdx = 1; busIdx < busUtils.getBusCount (false); ++busIdx)
  946. {
  947. AudioChannelSet layout = busUtils.getChannelSet (false, busIdx);
  948. // bus disabled by default? try to enable it with the default layout
  949. if (layout == AudioChannelSet::disabled())
  950. {
  951. layout = busUtils.getDefaultLayoutForBus (false, busIdx);
  952. busUtils.processor.setPreferredBusArrangement (false, busIdx, layout);
  953. }
  954. }
  955. // changing output buses may have changed main bus layout
  956. bool success = true;
  957. if (numInputBuses > 0)
  958. success = busUtils.processor.setPreferredBusArrangement (true, 0, inputLayout);
  959. if (success)
  960. success = busUtils.processor.setPreferredBusArrangement (false, 0, outputLayout);
  961. // was the above successful
  962. if (success && (numInputBuses == 0 || busUtils.getChannelSet (true, 0) == inputLayout)
  963. && busUtils.getChannelSet (false, 0) == outputLayout)
  964. layoutRestorer.release();
  965. }
  966. // does the plug-in have side-chain support? Check the following:
  967. // 1) does it have an input bus with index = 1 which supports mono
  968. // 2) can all other input buses be disabled
  969. // 3) does the format of the main buses not change when enabling the first bus
  970. if (numInputBuses > 1)
  971. {
  972. bool success = true;
  973. bool hasSidechain = false;
  974. if (const AudioChannelSet* set = busUtils.getSupportedBusLayouts (true, 1).getDefaultLayoutForChannelNum (1))
  975. hasSidechain = busUtils.processor.setPreferredBusArrangement (true, 1, *set);
  976. if (! hasSidechain)
  977. success = busUtils.processor.setPreferredBusArrangement (true, 1, AudioChannelSet::disabled());
  978. // AAX requires your processor's first sidechain to be either mono or that
  979. // it can be disabled
  980. jassert(success);
  981. // disable all other input buses
  982. for (int busIdx = 2; busIdx < numInputBuses; ++busIdx)
  983. {
  984. success = busUtils.processor.setPreferredBusArrangement (true, busIdx, AudioChannelSet::disabled());
  985. // AAX can only have a single side-chain input. Therefore, your processor must either
  986. // only have a single side-chain input or allow disabling all other side-chains
  987. jassert (success);
  988. }
  989. if (hasSidechain)
  990. {
  991. if (busUtils.getBusCount (false) == 0 || busUtils.getBusCount (true) == 0 ||
  992. (busUtils.getChannelSet (true, 0) == inputLayout && busUtils.getChannelSet (false, 0) == outputLayout))
  993. return true;
  994. // restore the old layout
  995. if (busUtils.getBusCount(true) > 0)
  996. busUtils.processor.setPreferredBusArrangement (true, 0, inputLayout);
  997. if (busUtils.getBusCount (false) > 0)
  998. busUtils.processor.setPreferredBusArrangement (false, 0, outputLayout);
  999. }
  1000. }
  1001. return false;
  1002. }
  1003. //==============================================================================
  1004. static void createDescriptor (AAX_IComponentDescriptor& desc, int configIndex, PluginBusUtilities& busUtils,
  1005. const AudioChannelSet& inputLayout, const AudioChannelSet& outputLayout,
  1006. const AAX_EStemFormat aaxInputFormat, const AAX_EStemFormat aaxOutputFormat)
  1007. {
  1008. check (desc.AddAudioIn (JUCEAlgorithmIDs::inputChannels));
  1009. check (desc.AddAudioOut (JUCEAlgorithmIDs::outputChannels));
  1010. check (desc.AddAudioBufferLength (JUCEAlgorithmIDs::bufferSize));
  1011. check (desc.AddDataInPort (JUCEAlgorithmIDs::bypass, sizeof (int32_t)));
  1012. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1013. check (desc.AddMIDINode (JUCEAlgorithmIDs::midiNodeIn, AAX_eMIDINodeType_LocalInput,
  1014. JucePlugin_Name, 0xffff));
  1015. #endif
  1016. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsSynth || JucePlugin_IsMidiEffect
  1017. check (desc.AddMIDINode (JUCEAlgorithmIDs::midiNodeOut, AAX_eMIDINodeType_LocalOutput,
  1018. JucePlugin_Name " Out", 0xffff));
  1019. #endif
  1020. check (desc.AddPrivateData (JUCEAlgorithmIDs::pluginInstance, sizeof (PluginInstanceInfo)));
  1021. check (desc.AddPrivateData (JUCEAlgorithmIDs::preparedFlag, sizeof (int32_t)));
  1022. // Create a property map
  1023. AAX_IPropertyMap* const properties = desc.NewPropertyMap();
  1024. jassert (properties != nullptr);
  1025. properties->AddProperty (AAX_eProperty_ManufacturerID, JucePlugin_AAXManufacturerCode);
  1026. properties->AddProperty (AAX_eProperty_ProductID, JucePlugin_AAXProductId);
  1027. #if JucePlugin_AAXDisableBypass
  1028. properties->AddProperty (AAX_eProperty_CanBypass, false);
  1029. #else
  1030. properties->AddProperty (AAX_eProperty_CanBypass, true);
  1031. #endif
  1032. properties->AddProperty (AAX_eProperty_InputStemFormat, static_cast<AAX_CPropertyValue> (aaxInputFormat));
  1033. properties->AddProperty (AAX_eProperty_OutputStemFormat, static_cast<AAX_CPropertyValue> (aaxOutputFormat));
  1034. // This value needs to match the RTAS wrapper's Type ID, so that
  1035. // the host knows that the RTAS/AAX plugins are equivalent.
  1036. properties->AddProperty (AAX_eProperty_PlugInID_Native, 'jcaa' + configIndex);
  1037. #if ! JucePlugin_AAXDisableAudioSuite
  1038. properties->AddProperty (AAX_eProperty_PlugInID_AudioSuite, 'jyaa' + configIndex);
  1039. #endif
  1040. #if JucePlugin_AAXDisableMultiMono
  1041. properties->AddProperty (AAX_eProperty_Constraint_MultiMonoSupport, false);
  1042. #else
  1043. properties->AddProperty (AAX_eProperty_Constraint_MultiMonoSupport, true);
  1044. #endif
  1045. #if JucePlugin_AAXDisableDynamicProcessing
  1046. properties->AddProperty (AAX_eProperty_Constraint_AlwaysProcess, true);
  1047. #endif
  1048. if (enableAuxBusesForCurrentFormat (busUtils, inputLayout, outputLayout))
  1049. {
  1050. check (desc.AddSideChainIn (JUCEAlgorithmIDs::sideChainBuffers));
  1051. properties->AddProperty (AAX_eProperty_SupportsSideChainInput, true);
  1052. }
  1053. // add the output buses
  1054. // This is incrdibly dumb: the output bus format must be well defined
  1055. // for every main bus in/out format pair. This means that there cannot
  1056. // be two configurations with different aux formats but
  1057. // identical main bus in/out formats.
  1058. for (int busIdx = 1; busIdx < busUtils.getBusCount (false); ++busIdx)
  1059. {
  1060. AudioChannelSet outBusLayout = busUtils.getChannelSet (false, busIdx);
  1061. if (outBusLayout != AudioChannelSet::disabled())
  1062. {
  1063. AAX_EStemFormat auxFormat = getFormatForAudioChannelSet (outBusLayout, busUtils.busIgnoresLayout (false, busIdx));
  1064. if (auxFormat != AAX_eStemFormat_INT32_MAX && auxFormat != AAX_eStemFormat_None)
  1065. {
  1066. const String& name = busUtils.processor.busArrangement.outputBuses.getReference (busIdx).name;
  1067. check (desc.AddAuxOutputStem (0, static_cast<int32_t> (auxFormat), name.toRawUTF8()));
  1068. }
  1069. }
  1070. }
  1071. // this assertion should be covered by the assertions above
  1072. // if not please report a bug
  1073. jassert (busUtils.getNumEnabledBuses (true) <= 2);
  1074. check (desc.AddProcessProc_Native (algorithmProcessCallback, properties));
  1075. }
  1076. static void getPlugInDescription (AAX_IEffectDescriptor& descriptor)
  1077. {
  1078. ScopedPointer<AudioProcessor> plugin = createPluginFilterOfType (AudioProcessor::wrapperType_AAX);
  1079. PluginBusUtilities busUtils (*plugin, false);
  1080. busUtils.findAllCompatibleLayouts();
  1081. descriptor.AddName (JucePlugin_Desc);
  1082. descriptor.AddName (JucePlugin_Name);
  1083. descriptor.AddCategory (JucePlugin_AAXCategory);
  1084. #ifdef JucePlugin_AAXPageTableFile
  1085. // optional page table setting - define this macro in your project if you want
  1086. // to set this value - see Avid documentation for details about its format.
  1087. descriptor.AddResourceInfo (AAX_eResourceType_PageTable, JucePlugin_AAXPageTableFile);
  1088. #endif
  1089. check (descriptor.AddProcPtr ((void*) JuceAAX_GUI::Create, kAAX_ProcPtrID_Create_EffectGUI));
  1090. check (descriptor.AddProcPtr ((void*) JuceAAX_Processor::Create, kAAX_ProcPtrID_Create_EffectParameters));
  1091. SortedSet<AAXFormatConfiguration> aaxFormats;
  1092. SortedSet<AudioChannelSet> inLayouts = busUtils.getBusCount (true) > 0 ? busUtils.getSupportedBusLayouts (true, 0).supportedLayouts : SortedSet<AudioChannelSet>();
  1093. SortedSet<AudioChannelSet> outLayouts = busUtils.getBusCount (false) > 0 ? busUtils.getSupportedBusLayouts (false, 0).supportedLayouts : SortedSet<AudioChannelSet>();
  1094. const int numIns = inLayouts. size();
  1095. const int numOuts = outLayouts.size();
  1096. #if JucePlugin_IsMidiEffect
  1097. // MIDI effect plug-ins do not support any audio channels
  1098. jassert (numIns == 0 && numOuts == 0);
  1099. if (AAX_IComponentDescriptor* const desc = descriptor.NewComponentDescriptor())
  1100. {
  1101. createDescriptor (*desc, 0, busUtils,
  1102. AudioChannelSet::disabled(), AudioChannelSet::disabled(),
  1103. AAX_eStemFormat_Mono, AAX_eStemFormat_Mono);
  1104. check (descriptor.AddComponent (desc));
  1105. }
  1106. #else
  1107. int configIndex = 0;
  1108. for (int inIdx = 0; inIdx < jmax (numIns, 1); ++inIdx)
  1109. {
  1110. for (int outIdx = 0; outIdx < jmax (numOuts, 1); ++outIdx)
  1111. {
  1112. bool success = true;
  1113. if (numIns > 0)
  1114. success = busUtils.processor.setPreferredBusArrangement (true, 0, inLayouts.getReference (inIdx));
  1115. if (numOuts > 0 && success)
  1116. success = busUtils.processor.setPreferredBusArrangement (false, 0, outLayouts.getReference (outIdx));
  1117. // We should never hit this assertion: PluginBusUtilities reported this as supported.
  1118. // Please report this as a bug!
  1119. jassert (success);
  1120. AudioChannelSet inLayout = numIns > 0 ? busUtils.getChannelSet (true, 0) : AudioChannelSet();
  1121. AudioChannelSet outLayout = numOuts > 0 ? busUtils.getChannelSet (false, 0) : AudioChannelSet();
  1122. // if we can't set both in AND out formats simultaneously then ignore this format!
  1123. if (numIns > 0 && numOuts > 0 && (inLayout != inLayouts.getReference (inIdx) || (outLayout != outLayouts.getReference (outIdx))))
  1124. continue;
  1125. AAX_EStemFormat aaxInFormat = getFormatForAudioChannelSet (inLayout, busUtils.busIgnoresLayout (true, 0));
  1126. AAX_EStemFormat aaxOutFormat = getFormatForAudioChannelSet (outLayout, busUtils.busIgnoresLayout (false, 0));
  1127. // does AAX support this layout?
  1128. if (aaxInFormat == AAX_eStemFormat_INT32_MAX || aaxOutFormat == AAX_eStemFormat_INT32_MAX)
  1129. continue;
  1130. // AAX requires a single input if this plug-in is a synth
  1131. #if JucePlugin_IsSynth
  1132. if (numIns == 0)
  1133. aaxInFormat = aaxOutFormat;
  1134. #endif
  1135. if (aaxInFormat == AAX_eStemFormat_None && aaxOutFormat == AAX_eStemFormat_None)
  1136. continue;
  1137. AAXFormatConfiguration aaxFormat (aaxInFormat, aaxOutFormat);
  1138. if (aaxFormats.indexOf (aaxFormat) < 0)
  1139. {
  1140. aaxFormats.add (aaxFormat);
  1141. if (AAX_IComponentDescriptor* const desc = descriptor.NewComponentDescriptor())
  1142. {
  1143. createDescriptor (*desc, configIndex++, busUtils, inLayout, outLayout, aaxInFormat, aaxOutFormat);
  1144. check (descriptor.AddComponent (desc));
  1145. }
  1146. }
  1147. }
  1148. }
  1149. // You don't have any supported layouts
  1150. jassert (configIndex > 0);
  1151. #endif
  1152. }
  1153. };
  1154. //==============================================================================
  1155. AAX_Result JUCE_CDECL GetEffectDescriptions (AAX_ICollection*);
  1156. AAX_Result JUCE_CDECL GetEffectDescriptions (AAX_ICollection* collection)
  1157. {
  1158. ScopedJuceInitialiser_GUI libraryInitialiser;
  1159. if (AAX_IEffectDescriptor* const descriptor = collection->NewDescriptor())
  1160. {
  1161. AAXClasses::getPlugInDescription (*descriptor);
  1162. collection->AddEffect (JUCE_STRINGIFY (JucePlugin_AAXIdentifier), descriptor);
  1163. collection->SetManufacturerName (JucePlugin_Manufacturer);
  1164. collection->AddPackageName (JucePlugin_Desc);
  1165. collection->AddPackageName (JucePlugin_Name);
  1166. collection->SetPackageVersion (JucePlugin_VersionCode);
  1167. return AAX_SUCCESS;
  1168. }
  1169. return AAX_ERROR_NULL_OBJECT;
  1170. }
  1171. #endif