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.

1554 lines
67KB

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