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.

1606 lines
69KB

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