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.

1576 lines
68KB

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