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.

1184 lines
46KB

  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. // Your project must contain an AppConfig.h file with your project-specific settings in it,
  18. // and your header search path must make it accessible to the module's files.
  19. #include "AppConfig.h"
  20. #include "../utility/juce_CheckSettingMacros.h"
  21. #if JucePlugin_Build_AAX && (JUCE_INCLUDED_AAX_IN_MM || defined (_WIN32) || defined (_WIN64))
  22. #ifdef _MSC_VER
  23. #include <windows.h>
  24. #else
  25. #include <Cocoa/Cocoa.h>
  26. #endif
  27. #include "../utility/juce_IncludeModuleHeaders.h"
  28. #undef Component
  29. #ifdef __clang__
  30. #pragma clang diagnostic push
  31. #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  32. #pragma clang diagnostic ignored "-Wsign-conversion"
  33. #endif
  34. #ifdef _MSC_VER
  35. #pragma warning (push)
  36. #pragma warning (disable : 4127)
  37. #endif
  38. #include "AAX_Exports.cpp"
  39. #include "AAX_ICollection.h"
  40. #include "AAX_IComponentDescriptor.h"
  41. #include "AAX_IEffectDescriptor.h"
  42. #include "AAX_IPropertyMap.h"
  43. #include "AAX_CEffectParameters.h"
  44. #include "AAX_Errors.h"
  45. #include "AAX_CBinaryTaperDelegate.h"
  46. #include "AAX_CBinaryDisplayDelegate.h"
  47. #include "AAX_CLinearTaperDelegate.h"
  48. #include "AAX_CNumberDisplayDelegate.h"
  49. #include "AAX_CEffectGUI.h"
  50. #include "AAX_IViewContainer.h"
  51. #include "AAX_ITransport.h"
  52. #include "AAX_IMIDINode.h"
  53. #include "AAX_UtilsNative.h"
  54. #include "AAX_Enums.h"
  55. #ifdef _MSC_VER
  56. #pragma warning (pop)
  57. #endif
  58. #ifdef __clang__
  59. #pragma clang diagnostic pop
  60. #endif
  61. #if JUCE_WINDOWS
  62. #ifndef JucePlugin_AAXLibs_path
  63. #error "You need to define the JucePlugin_AAXLibs_path macro. (This is best done via the introjucer)"
  64. #endif
  65. #if JUCE_64BIT
  66. #define JUCE_AAX_LIB "AAXLibrary_x64"
  67. #else
  68. #define JUCE_AAX_LIB "AAXLibrary"
  69. #endif
  70. #if JUCE_DEBUG
  71. #define JUCE_AAX_LIB_PATH "\\Debug\\"
  72. #define JUCE_AAX_LIB_SUFFIX "_D"
  73. #else
  74. #define JUCE_AAX_LIB_PATH "\\Release\\"
  75. #define JUCE_AAX_LIB_SUFFIX ""
  76. #endif
  77. #pragma comment(lib, JucePlugin_AAXLibs_path JUCE_AAX_LIB_PATH JUCE_AAX_LIB JUCE_AAX_LIB_SUFFIX ".lib")
  78. #endif
  79. #undef check
  80. using juce::Component;
  81. const int32_t juceChunkType = 'juce';
  82. //==============================================================================
  83. struct AAXClasses
  84. {
  85. static void check (AAX_Result result)
  86. {
  87. jassert (result == AAX_SUCCESS); (void) result;
  88. }
  89. static int getParamIndexFromID (AAX_CParamID paramID) noexcept
  90. {
  91. return atoi (paramID);
  92. }
  93. static bool isBypassParam (AAX_CParamID paramID) noexcept
  94. {
  95. return AAX::IsParameterIDEqual (paramID, cDefaultMasterBypassID) != 0;
  96. }
  97. static AAX_EStemFormat getFormatForChans (const int numChans) noexcept
  98. {
  99. switch (numChans)
  100. {
  101. case 0: return AAX_eStemFormat_None;
  102. case 1: return AAX_eStemFormat_Mono;
  103. case 2: return AAX_eStemFormat_Stereo;
  104. case 3: return AAX_eStemFormat_LCR;
  105. case 4: return AAX_eStemFormat_Quad;
  106. case 5: return AAX_eStemFormat_5_0;
  107. case 6: return AAX_eStemFormat_5_1;
  108. case 7: return AAX_eStemFormat_7_0_DTS;
  109. case 8: return AAX_eStemFormat_7_1_DTS;
  110. default: jassertfalse; break;
  111. }
  112. return AAX_eStemFormat_None;
  113. }
  114. static int getNumChannelsForStemFormat (AAX_EStemFormat format) noexcept
  115. {
  116. switch (format)
  117. {
  118. case AAX_eStemFormat_None: return 0;
  119. case AAX_eStemFormat_Mono: return 1;
  120. case AAX_eStemFormat_Stereo: return 2;
  121. case AAX_eStemFormat_LCR: return 3;
  122. case AAX_eStemFormat_LCRS:
  123. case AAX_eStemFormat_Quad: return 4;
  124. case AAX_eStemFormat_5_0: return 5;
  125. case AAX_eStemFormat_5_1:
  126. case AAX_eStemFormat_6_0: return 6;
  127. case AAX_eStemFormat_6_1:
  128. case AAX_eStemFormat_7_0_SDDS:
  129. case AAX_eStemFormat_7_0_DTS: return 7;
  130. case AAX_eStemFormat_7_1_SDDS:
  131. case AAX_eStemFormat_7_1_DTS: return 8;
  132. default: jassertfalse; break;
  133. }
  134. return 0;
  135. }
  136. static const char* getSpeakerArrangementString (AAX_EStemFormat format) noexcept
  137. {
  138. switch (format)
  139. {
  140. case AAX_eStemFormat_Mono: return "M";
  141. case AAX_eStemFormat_Stereo: return "L R";
  142. case AAX_eStemFormat_LCR: return "L C R";
  143. case AAX_eStemFormat_LCRS: return "L C R S";
  144. case AAX_eStemFormat_Quad: return "L R Ls Rs";
  145. case AAX_eStemFormat_5_0: return "L C R Ls Rs";
  146. case AAX_eStemFormat_5_1: return "L C R Ls Rs LFE";
  147. case AAX_eStemFormat_6_0: return "L C R Ls Cs Rs";
  148. case AAX_eStemFormat_6_1: return "L C R Ls Cs Rs LFE";
  149. case AAX_eStemFormat_7_0_SDDS: return "L Lc C Rc R Ls Rs";
  150. case AAX_eStemFormat_7_1_SDDS: return "L Lc C Rc R Ls Rs LFE";
  151. case AAX_eStemFormat_7_0_DTS: return "L C R Lss Rss Lsr Rsr";
  152. case AAX_eStemFormat_7_1_DTS: return "L C R Lss Rss Lsr Rsr LFE";
  153. default: break;
  154. }
  155. return nullptr;
  156. }
  157. static Colour getColourFromHighlightEnum (AAX_EHighlightColor colour) noexcept
  158. {
  159. switch (colour)
  160. {
  161. case AAX_eHighlightColor_Red: return Colours::red;
  162. case AAX_eHighlightColor_Blue: return Colours::blue;
  163. case AAX_eHighlightColor_Green: return Colours::green;
  164. case AAX_eHighlightColor_Yellow: return Colours::yellow;
  165. default: jassertfalse; break;
  166. }
  167. return Colours::black;
  168. }
  169. //==============================================================================
  170. class JuceAAX_Processor;
  171. struct PluginInstanceInfo
  172. {
  173. PluginInstanceInfo (JuceAAX_Processor& p) : parameters (p) {}
  174. JuceAAX_Processor& parameters;
  175. JUCE_DECLARE_NON_COPYABLE (PluginInstanceInfo)
  176. };
  177. //==============================================================================
  178. struct JUCEAlgorithmContext
  179. {
  180. float** inputChannels;
  181. float** outputChannels;
  182. int32_t* bufferSize;
  183. int32_t* bypass;
  184. #if JucePlugin_WantsMidiInput
  185. AAX_IMIDINode* midiNodeIn;
  186. #endif
  187. #if JucePlugin_ProducesMidiOutput
  188. AAX_IMIDINode* midiNodeOut;
  189. #endif
  190. PluginInstanceInfo* pluginInstance;
  191. int32_t* isPrepared;
  192. };
  193. struct JUCEAlgorithmIDs
  194. {
  195. enum
  196. {
  197. inputChannels = AAX_FIELD_INDEX (JUCEAlgorithmContext, inputChannels),
  198. outputChannels = AAX_FIELD_INDEX (JUCEAlgorithmContext, outputChannels),
  199. bufferSize = AAX_FIELD_INDEX (JUCEAlgorithmContext, bufferSize),
  200. bypass = AAX_FIELD_INDEX (JUCEAlgorithmContext, bypass),
  201. #if JucePlugin_WantsMidiInput
  202. midiNodeIn = AAX_FIELD_INDEX (JUCEAlgorithmContext, midiNodeIn),
  203. #endif
  204. #if JucePlugin_ProducesMidiOutput
  205. midiNodeOut = AAX_FIELD_INDEX (JUCEAlgorithmContext, midiNodeOut),
  206. #endif
  207. pluginInstance = AAX_FIELD_INDEX (JUCEAlgorithmContext, pluginInstance),
  208. preparedFlag = AAX_FIELD_INDEX (JUCEAlgorithmContext, isPrepared)
  209. };
  210. };
  211. #if JucePlugin_WantsMidiInput
  212. static AAX_IMIDINode* getMidiNodeIn (const JUCEAlgorithmContext& c) noexcept { return c.midiNodeIn; }
  213. #else
  214. static AAX_IMIDINode* getMidiNodeIn (const JUCEAlgorithmContext&) noexcept { return nullptr; }
  215. #endif
  216. #if JucePlugin_ProducesMidiOutput
  217. AAX_IMIDINode* midiNodeOut;
  218. static AAX_IMIDINode* getMidiNodeOut (const JUCEAlgorithmContext& c) noexcept { return c.midiNodeOut; }
  219. #else
  220. static AAX_IMIDINode* getMidiNodeOut (const JUCEAlgorithmContext&) noexcept { return nullptr; }
  221. #endif
  222. //==============================================================================
  223. class JuceAAX_GUI : public AAX_CEffectGUI
  224. {
  225. public:
  226. JuceAAX_GUI() {}
  227. ~JuceAAX_GUI() { DeleteViewContainer(); }
  228. static AAX_IEffectGUI* AAX_CALLBACK Create() { return new JuceAAX_GUI(); }
  229. void CreateViewContents() override
  230. {
  231. if (component == nullptr)
  232. {
  233. if (JuceAAX_Processor* params = dynamic_cast<JuceAAX_Processor*> (GetEffectParameters()))
  234. component = new ContentWrapperComponent (*this, params->getPluginInstance());
  235. else
  236. jassertfalse;
  237. }
  238. }
  239. void CreateViewContainer() override
  240. {
  241. CreateViewContents();
  242. if (void* nativeViewToAttachTo = GetViewContainerPtr())
  243. {
  244. #if JUCE_MAC
  245. if (GetViewContainerType() == AAX_eViewContainer_Type_NSView)
  246. #else
  247. if (GetViewContainerType() == AAX_eViewContainer_Type_HWND)
  248. #endif
  249. {
  250. component->setVisible (true);
  251. component->addToDesktop (0, nativeViewToAttachTo);
  252. }
  253. }
  254. }
  255. void DeleteViewContainer() override
  256. {
  257. if (component != nullptr)
  258. {
  259. JUCE_AUTORELEASEPOOL
  260. {
  261. component->removeFromDesktop();
  262. component = nullptr;
  263. }
  264. }
  265. }
  266. AAX_Result GetViewSize (AAX_Point* viewSize) const override
  267. {
  268. if (component != nullptr)
  269. {
  270. viewSize->horz = (float) component->getWidth();
  271. viewSize->vert = (float) component->getHeight();
  272. return AAX_SUCCESS;
  273. }
  274. return AAX_ERROR_NULL_OBJECT;
  275. }
  276. AAX_Result ParameterUpdated (AAX_CParamID) override
  277. {
  278. return AAX_SUCCESS;
  279. }
  280. AAX_Result SetControlHighlightInfo (AAX_CParamID paramID, AAX_CBoolean isHighlighted, AAX_EHighlightColor colour) override
  281. {
  282. if (component != nullptr && component->pluginEditor != nullptr)
  283. {
  284. if (! isBypassParam (paramID))
  285. {
  286. AudioProcessorEditor::ParameterControlHighlightInfo info;
  287. info.parameterIndex = getParamIndexFromID (paramID);
  288. info.isHighlighted = (isHighlighted != 0);
  289. info.suggestedColour = getColourFromHighlightEnum (colour);
  290. component->pluginEditor->setControlHighlight (info);
  291. }
  292. return AAX_SUCCESS;
  293. }
  294. return AAX_ERROR_NULL_OBJECT;
  295. }
  296. private:
  297. struct ContentWrapperComponent : public juce::Component
  298. {
  299. ContentWrapperComponent (JuceAAX_GUI& gui, AudioProcessor& plugin)
  300. : owner (gui)
  301. {
  302. setOpaque (true);
  303. setBroughtToFrontOnMouseClick (true);
  304. addAndMakeVisible (pluginEditor = plugin.createEditorIfNeeded());
  305. if (pluginEditor != nullptr)
  306. {
  307. setBounds (pluginEditor->getLocalBounds());
  308. pluginEditor->addMouseListener (this, true);
  309. }
  310. }
  311. ~ContentWrapperComponent()
  312. {
  313. if (pluginEditor != nullptr)
  314. {
  315. PopupMenu::dismissAllActiveMenus();
  316. pluginEditor->removeMouseListener (this);
  317. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  318. }
  319. }
  320. void paint (Graphics& g) override
  321. {
  322. g.fillAll (Colours::black);
  323. }
  324. template <typename MethodType>
  325. void callMouseMethod (const MouseEvent& e, MethodType method)
  326. {
  327. if (AAX_IViewContainer* vc = owner.GetViewContainer())
  328. {
  329. const int parameterIndex = pluginEditor->getControlParameterIndex (*e.eventComponent);
  330. if (parameterIndex >= 0)
  331. {
  332. uint32_t mods = 0;
  333. vc->GetModifiers (&mods);
  334. (vc->*method) (IndexAsParamID (parameterIndex), mods);
  335. }
  336. }
  337. }
  338. void mouseDown (const MouseEvent& e) override { callMouseMethod (e, &AAX_IViewContainer::HandleParameterMouseDown); }
  339. void mouseUp (const MouseEvent& e) override { callMouseMethod (e, &AAX_IViewContainer::HandleParameterMouseUp); }
  340. void mouseDrag (const MouseEvent& e) override { callMouseMethod (e, &AAX_IViewContainer::HandleParameterMouseDrag); }
  341. void childBoundsChanged (Component*) override
  342. {
  343. if (pluginEditor != nullptr)
  344. {
  345. const int w = pluginEditor->getWidth();
  346. const int h = pluginEditor->getHeight();
  347. setSize (w, h);
  348. AAX_Point newSize ((float) h, (float) w);
  349. owner.GetViewContainer()->SetViewSize (newSize);
  350. }
  351. }
  352. ScopedPointer<AudioProcessorEditor> pluginEditor;
  353. JuceAAX_GUI& owner;
  354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  355. };
  356. ScopedPointer<ContentWrapperComponent> component;
  357. ScopedJuceInitialiser_GUI libraryInitialiser;
  358. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAAX_GUI)
  359. };
  360. //==============================================================================
  361. class JuceAAX_Processor : public AAX_CEffectParameters,
  362. public juce::AudioPlayHead,
  363. public AudioProcessorListener
  364. {
  365. public:
  366. JuceAAX_Processor() : sampleRate (0), lastBufferSize (1024), maxBufferSize (1024)
  367. {
  368. pluginInstance = createPluginFilterOfType (AudioProcessor::wrapperType_AAX);
  369. pluginInstance->setPlayHead (this);
  370. pluginInstance->addListener (this);
  371. AAX_CEffectParameters::GetNumberOfChunks (&juceChunkIndex);
  372. }
  373. static AAX_CEffectParameters* AAX_CALLBACK Create() { return new JuceAAX_Processor(); }
  374. AAX_Result EffectInit() override
  375. {
  376. check (Controller()->GetSampleRate (&sampleRate));
  377. preparePlugin();
  378. addBypassParameter();
  379. addAudioProcessorParameters();
  380. return AAX_SUCCESS;
  381. }
  382. AAX_Result GetNumberOfChunks (int32_t* numChunks) const override
  383. {
  384. // The juceChunk is the last chunk.
  385. *numChunks = juceChunkIndex + 1;
  386. return AAX_SUCCESS;
  387. }
  388. AAX_Result GetChunkIDFromIndex (int32_t index, AAX_CTypeID* chunkID) const override
  389. {
  390. if (index != juceChunkIndex)
  391. return AAX_CEffectParameters::GetChunkIDFromIndex (index, chunkID);
  392. *chunkID = juceChunkType;
  393. return AAX_SUCCESS;
  394. }
  395. juce::MemoryBlock& getTemporaryChunkMemory() const
  396. {
  397. ScopedLock sl (perThreadDataLock);
  398. const Thread::ThreadID currentThread = Thread::getCurrentThreadId();
  399. if (ChunkMemoryBlock::Ptr m = perThreadFilterData [currentThread])
  400. return m->data;
  401. ChunkMemoryBlock::Ptr m (new ChunkMemoryBlock());
  402. perThreadFilterData.set (currentThread, m);
  403. return m->data;
  404. }
  405. AAX_Result GetChunkSize (AAX_CTypeID chunkID, uint32_t* oSize) const override
  406. {
  407. if (chunkID != juceChunkType)
  408. return AAX_CEffectParameters::GetChunkSize (chunkID, oSize);
  409. juce::MemoryBlock& tempFilterData = getTemporaryChunkMemory();
  410. tempFilterData.reset();
  411. pluginInstance->getStateInformation (tempFilterData);
  412. *oSize = (uint32_t) tempFilterData.getSize();
  413. return AAX_SUCCESS;
  414. }
  415. AAX_Result GetChunk (AAX_CTypeID chunkID, AAX_SPlugInChunk* oChunk) const override
  416. {
  417. if (chunkID != juceChunkType)
  418. return AAX_CEffectParameters::GetChunk (chunkID, oChunk);
  419. juce::MemoryBlock& tempFilterData = getTemporaryChunkMemory();
  420. if (tempFilterData.getSize() == 0)
  421. return 20700 /*AAX_ERROR_PLUGIN_API_INVALID_THREAD*/;
  422. oChunk->fSize = (int32_t) tempFilterData.getSize();
  423. tempFilterData.copyTo (oChunk->fData, 0, tempFilterData.getSize());
  424. tempFilterData.reset();
  425. return AAX_SUCCESS;
  426. }
  427. AAX_Result SetChunk (AAX_CTypeID chunkID, const AAX_SPlugInChunk* chunk) override
  428. {
  429. if (chunkID != juceChunkType)
  430. return AAX_CEffectParameters::SetChunk (chunkID, chunk);
  431. pluginInstance->setStateInformation ((void*) chunk->fData, chunk->fSize);
  432. // Notify Pro Tools that the parameters were updated.
  433. // Without it a bug happens in these circumstances:
  434. // * A preset is saved with the RTAS version of the plugin (".tfx" preset format).
  435. // * The preset is loaded in PT 10 using the AAX version.
  436. // * The session is then saved, and closed.
  437. // * The saved session is loaded, but acting as if the preset was never loaded.
  438. const int numParameters = pluginInstance->getNumParameters();
  439. for (int i = 0; i < numParameters; ++i)
  440. SetParameterNormalizedValue (IndexAsParamID (i), (double) pluginInstance->getParameter(i));
  441. return AAX_SUCCESS;
  442. }
  443. AAX_Result ResetFieldData (AAX_CFieldIndex fieldIndex, void* data, uint32_t dataSize) const override
  444. {
  445. switch (fieldIndex)
  446. {
  447. case JUCEAlgorithmIDs::pluginInstance:
  448. {
  449. const size_t numObjects = dataSize / sizeof (PluginInstanceInfo);
  450. PluginInstanceInfo* const objects = static_cast<PluginInstanceInfo*> (data);
  451. jassert (numObjects == 1); // not sure how to handle more than one..
  452. for (size_t i = 0; i < numObjects; ++i)
  453. new (objects + i) PluginInstanceInfo (const_cast<JuceAAX_Processor&> (*this));
  454. break;
  455. }
  456. case JUCEAlgorithmIDs::preparedFlag:
  457. {
  458. const_cast<JuceAAX_Processor*>(this)->preparePlugin();
  459. const size_t numObjects = dataSize / sizeof (uint32_t);
  460. uint32_t* const objects = static_cast<uint32_t*> (data);
  461. for (size_t i = 0; i < numObjects; ++i)
  462. new (objects + i) uint32_t (1);
  463. break;
  464. }
  465. }
  466. return AAX_SUCCESS;
  467. }
  468. AAX_Result UpdateParameterNormalizedValue (AAX_CParamID paramID, double value, AAX_EUpdateSource source) override
  469. {
  470. AAX_Result result = AAX_CEffectParameters::UpdateParameterNormalizedValue (paramID, value, source);
  471. if (! isBypassParam (paramID))
  472. pluginInstance->setParameter (getParamIndexFromID (paramID), (float) value);
  473. return result;
  474. }
  475. AAX_Result GetParameterValueFromString (AAX_CParamID paramID, double* result, const AAX_IString& text) const override
  476. {
  477. if (isBypassParam (paramID))
  478. {
  479. *result = (text.Get()[0] == 'B') ? 1 : 0;
  480. return AAX_SUCCESS;
  481. }
  482. if (AudioProcessorParameter* param = pluginInstance->getParameters() [getParamIndexFromID (paramID)])
  483. {
  484. *result = param->getValueForText (text.Get());
  485. return AAX_SUCCESS;
  486. }
  487. return AAX_CEffectParameters::GetParameterValueFromString (paramID, result, text);
  488. }
  489. AAX_Result GetParameterStringFromValue (AAX_CParamID paramID, double value, AAX_IString* result, int32_t maxLen) const override
  490. {
  491. if (isBypassParam (paramID))
  492. {
  493. result->Set (value == 0 ? "Off" : (maxLen >= 8 ? "Bypassed" : "Byp"));
  494. }
  495. else
  496. {
  497. const int paramIndex = getParamIndexFromID (paramID);
  498. juce::String text;
  499. if (AudioProcessorParameter* param = pluginInstance->getParameters() [paramIndex])
  500. text = param->getText ((float) value, maxLen);
  501. else
  502. text = pluginInstance->getParameterText (paramIndex, maxLen);
  503. result->Set (text.toRawUTF8());
  504. }
  505. return AAX_SUCCESS;
  506. }
  507. AAX_Result GetParameterNumberofSteps (AAX_CParamID paramID, int32_t* result) const
  508. {
  509. if (isBypassParam (paramID))
  510. *result = 2;
  511. else
  512. *result = pluginInstance->getParameterNumSteps (getParamIndexFromID (paramID));
  513. return AAX_SUCCESS;
  514. }
  515. AAX_Result GetParameterNormalizedValue (AAX_CParamID paramID, double* result) const override
  516. {
  517. if (isBypassParam (paramID))
  518. return AAX_CEffectParameters::GetParameterNormalizedValue (paramID, result);
  519. *result = pluginInstance->getParameter (getParamIndexFromID (paramID));
  520. return AAX_SUCCESS;
  521. }
  522. AAX_Result SetParameterNormalizedValue (AAX_CParamID paramID, double newValue) override
  523. {
  524. if (isBypassParam (paramID))
  525. return AAX_CEffectParameters::SetParameterNormalizedValue (paramID, newValue);
  526. if (AAX_IParameter* p = const_cast<AAX_IParameter*> (mParameterManager.GetParameterByID (paramID)))
  527. p->SetValueWithFloat ((float) newValue);
  528. pluginInstance->setParameter (getParamIndexFromID (paramID), (float) newValue);
  529. return AAX_SUCCESS;
  530. }
  531. AAX_Result SetParameterNormalizedRelative (AAX_CParamID paramID, double newDeltaValue) override
  532. {
  533. if (isBypassParam (paramID))
  534. return AAX_CEffectParameters::SetParameterNormalizedRelative (paramID, newDeltaValue);
  535. const int paramIndex = getParamIndexFromID (paramID);
  536. const float newValue = pluginInstance->getParameter (paramIndex) + (float) newDeltaValue;
  537. pluginInstance->setParameter (paramIndex, jlimit (0.0f, 1.0f, newValue));
  538. if (AAX_IParameter* p = const_cast<AAX_IParameter*> (mParameterManager.GetParameterByID (paramID)))
  539. p->SetValueWithFloat (newValue);
  540. return AAX_SUCCESS;
  541. }
  542. AAX_Result GetParameterNameOfLength (AAX_CParamID paramID, AAX_IString* result, int32_t maxLen) const override
  543. {
  544. if (isBypassParam (paramID))
  545. result->Set (maxLen >= 13 ? "Master Bypass"
  546. : (maxLen >= 8 ? "Mast Byp"
  547. : (maxLen >= 6 ? "MstByp" : "MByp")));
  548. else
  549. result->Set (pluginInstance->getParameterName (getParamIndexFromID (paramID), maxLen).toRawUTF8());
  550. return AAX_SUCCESS;
  551. }
  552. AAX_Result GetParameterName (AAX_CParamID paramID, AAX_IString* result) const override
  553. {
  554. if (isBypassParam (paramID))
  555. result->Set ("Master Bypass");
  556. else
  557. result->Set (pluginInstance->getParameterName (getParamIndexFromID (paramID), 31).toRawUTF8());
  558. return AAX_SUCCESS;
  559. }
  560. AAX_Result GetParameterDefaultNormalizedValue (AAX_CParamID paramID, double* result) const override
  561. {
  562. if (! isBypassParam (paramID))
  563. {
  564. *result = (double) pluginInstance->getParameterDefaultValue (getParamIndexFromID (paramID));
  565. jassert (*result >= 0 && *result <= 1.0f);
  566. }
  567. return AAX_SUCCESS;
  568. }
  569. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  570. bool getCurrentPosition (juce::AudioPlayHead::CurrentPositionInfo& info) override
  571. {
  572. const AAX_ITransport& transport = *Transport();
  573. info.bpm = 0.0;
  574. check (transport.GetCurrentTempo (&info.bpm));
  575. int32_t num = 4, den = 4;
  576. transport.GetCurrentMeter (&num, &den);
  577. info.timeSigNumerator = (int) num;
  578. info.timeSigDenominator = (int) den;
  579. info.timeInSamples = 0;
  580. if (transport.IsTransportPlaying (&info.isPlaying) != AAX_SUCCESS)
  581. info.isPlaying = false;
  582. if (info.isPlaying
  583. || transport.GetTimelineSelectionStartPosition (&info.timeInSamples) != AAX_SUCCESS)
  584. check (transport.GetCurrentNativeSampleLocation (&info.timeInSamples));
  585. info.timeInSeconds = info.timeInSamples / sampleRate;
  586. int64_t ticks = 0;
  587. check (transport.GetCurrentTickPosition (&ticks));
  588. info.ppqPosition = ticks / 960000.0;
  589. info.isLooping = false;
  590. int64_t loopStartTick = 0, loopEndTick = 0;
  591. check (transport.GetCurrentLoopPosition (&info.isLooping, &loopStartTick, &loopEndTick));
  592. info.ppqLoopStart = loopStartTick / 960000.0;
  593. info.ppqLoopEnd = loopEndTick / 960000.0;
  594. info.editOriginTime = 0;
  595. info.frameRate = AudioPlayHead::fpsUnknown;
  596. AAX_EFrameRate frameRate;
  597. int32_t offset;
  598. if (transport.GetTimeCodeInfo (&frameRate, &offset) == AAX_SUCCESS)
  599. {
  600. double framesPerSec = 24.0;
  601. switch (frameRate)
  602. {
  603. case AAX_eFrameRate_Undeclared: break;
  604. case AAX_eFrameRate_24Frame: info.frameRate = AudioPlayHead::fps24; break;
  605. case AAX_eFrameRate_25Frame: info.frameRate = AudioPlayHead::fps25; framesPerSec = 25.0; break;
  606. case AAX_eFrameRate_2997NonDrop: info.frameRate = AudioPlayHead::fps2997; framesPerSec = 29.97002997; break;
  607. case AAX_eFrameRate_2997DropFrame: info.frameRate = AudioPlayHead::fps2997drop; framesPerSec = 29.97002997; break;
  608. case AAX_eFrameRate_30NonDrop: info.frameRate = AudioPlayHead::fps30; framesPerSec = 30.0; break;
  609. case AAX_eFrameRate_30DropFrame: info.frameRate = AudioPlayHead::fps30drop; framesPerSec = 30.0; break;
  610. case AAX_eFrameRate_23976: info.frameRate = AudioPlayHead::fps24; framesPerSec = 23.976; break;
  611. default: break;
  612. }
  613. info.editOriginTime = offset / framesPerSec;
  614. }
  615. // No way to get these: (?)
  616. info.isRecording = false;
  617. info.ppqPositionOfLastBarStart = 0;
  618. return true;
  619. }
  620. void audioProcessorParameterChanged (AudioProcessor* /*processor*/, int parameterIndex, float newValue) override
  621. {
  622. SetParameterNormalizedValue (IndexAsParamID (parameterIndex), (double) newValue);
  623. }
  624. void audioProcessorChanged (AudioProcessor* processor) override
  625. {
  626. ++mNumPlugInChanges;
  627. check (Controller()->SetSignalLatency (processor->getLatencySamples()));
  628. }
  629. void audioProcessorParameterChangeGestureBegin (AudioProcessor* /*processor*/, int parameterIndex) override
  630. {
  631. TouchParameter (IndexAsParamID (parameterIndex));
  632. }
  633. void audioProcessorParameterChangeGestureEnd (AudioProcessor* /*processor*/, int parameterIndex) override
  634. {
  635. ReleaseParameter (IndexAsParamID (parameterIndex));
  636. }
  637. AAX_Result NotificationReceived (AAX_CTypeID type, const void* data, uint32_t size) override
  638. {
  639. if (type == AAX_eNotificationEvent_EnteringOfflineMode) pluginInstance->setNonRealtime (true);
  640. if (type == AAX_eNotificationEvent_ExitingOfflineMode) pluginInstance->setNonRealtime (false);
  641. return AAX_CEffectParameters::NotificationReceived (type, data, size);
  642. }
  643. void process (const float* const* inputs, float* const* outputs, const int bufferSize,
  644. const bool bypass, AAX_IMIDINode* midiNodeIn, AAX_IMIDINode* midiNodesOut)
  645. {
  646. const int numIns = pluginInstance->getNumInputChannels();
  647. const int numOuts = pluginInstance->getNumOutputChannels();
  648. if (numOuts >= numIns)
  649. {
  650. for (int i = 0; i < numIns; ++i)
  651. memcpy (outputs[i], inputs[i], (size_t) bufferSize * sizeof (float));
  652. process (outputs, numOuts, bufferSize, bypass, midiNodeIn, midiNodesOut);
  653. }
  654. else
  655. {
  656. if (channelList.size() <= numIns)
  657. channelList.insertMultiple (-1, nullptr, 1 + numIns - channelList.size());
  658. float** channels = channelList.getRawDataPointer();
  659. for (int i = 0; i < numOuts; ++i)
  660. {
  661. memcpy (outputs[i], inputs[i], (size_t) bufferSize * sizeof (float));
  662. channels[i] = outputs[i];
  663. }
  664. for (int i = numOuts; i < numIns; ++i)
  665. channels[i] = const_cast<float*> (inputs[i]);
  666. process (channels, numIns, bufferSize, bypass, midiNodeIn, midiNodesOut);
  667. }
  668. }
  669. private:
  670. void process (float* const* channels, const int numChans, const int bufferSize,
  671. const bool bypass, AAX_IMIDINode* midiNodeIn, AAX_IMIDINode* midiNodesOut)
  672. {
  673. AudioSampleBuffer buffer (channels, numChans, bufferSize);
  674. midiBuffer.clear();
  675. (void) midiNodeIn;
  676. (void) midiNodesOut;
  677. #if JucePlugin_WantsMidiInput
  678. {
  679. AAX_CMidiStream* const midiStream = midiNodeIn->GetNodeBuffer();
  680. const uint32_t numMidiEvents = midiStream->mBufferSize;
  681. for (uint32_t i = 0; i < numMidiEvents; ++i)
  682. {
  683. const AAX_CMidiPacket& m = midiStream->mBuffer[i];
  684. jassert ((int) m.mTimestamp < bufferSize);
  685. midiBuffer.addEvent (m.mData, (int) m.mLength,
  686. jlimit (0, (int) bufferSize - 1, (int) m.mTimestamp));
  687. }
  688. }
  689. #endif
  690. {
  691. if (lastBufferSize != bufferSize)
  692. {
  693. lastBufferSize = bufferSize;
  694. pluginInstance->setPlayConfigDetails (pluginInstance->getNumInputChannels(),
  695. pluginInstance->getNumOutputChannels(),
  696. sampleRate, bufferSize);
  697. if (bufferSize > maxBufferSize)
  698. {
  699. // we only call prepareToPlay here if the new buffer size is larger than
  700. // the one used last time prepareToPlay was called.
  701. // currently, this should never actually happen, because as of Pro Tools 12,
  702. // the maximum possible value is 1024, and we call prepareToPlay with that
  703. // value during initialisation.
  704. pluginInstance->prepareToPlay (sampleRate, bufferSize);
  705. maxBufferSize = bufferSize;
  706. }
  707. }
  708. const ScopedLock sl (pluginInstance->getCallbackLock());
  709. if (bypass)
  710. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  711. else
  712. pluginInstance->processBlock (buffer, midiBuffer);
  713. }
  714. #if JucePlugin_ProducesMidiOutput
  715. {
  716. const juce::uint8* midiEventData;
  717. int midiEventSize, midiEventPosition;
  718. MidiBuffer::Iterator i (midiBuffer);
  719. AAX_CMidiPacket packet;
  720. packet.mIsImmediate = false;
  721. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  722. {
  723. jassert (isPositiveAndBelow (midiEventPosition, bufferSize));
  724. if (midiEventSize <= 4)
  725. {
  726. packet.mTimestamp = (uint32_t) midiEventPosition;
  727. packet.mLength = (uint32_t) midiEventSize;
  728. memcpy (packet.mData, midiEventData, (size_t) midiEventSize);
  729. check (midiNodesOut->PostMIDIPacket (&packet));
  730. }
  731. }
  732. }
  733. #else
  734. (void) midiNodesOut;
  735. #endif
  736. }
  737. void addBypassParameter()
  738. {
  739. AAX_IParameter* masterBypass = new AAX_CParameter<bool> (cDefaultMasterBypassID,
  740. AAX_CString ("Master Bypass"),
  741. false,
  742. AAX_CBinaryTaperDelegate<bool>(),
  743. AAX_CBinaryDisplayDelegate<bool> ("bypass", "on"),
  744. true);
  745. masterBypass->SetNumberOfSteps (2);
  746. masterBypass->SetType (AAX_eParameterType_Discrete);
  747. mParameterManager.AddParameter (masterBypass);
  748. mPacketDispatcher.RegisterPacket (cDefaultMasterBypassID, JUCEAlgorithmIDs::bypass);
  749. }
  750. void addAudioProcessorParameters()
  751. {
  752. AudioProcessor& audioProcessor = getPluginInstance();
  753. const int numParameters = audioProcessor.getNumParameters();
  754. for (int parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex)
  755. {
  756. AAX_CString paramName (audioProcessor.getParameterName (parameterIndex, 31).toRawUTF8());
  757. AAX_IParameter* parameter
  758. = new AAX_CParameter<float> (IndexAsParamID (parameterIndex),
  759. paramName,
  760. audioProcessor.getParameterDefaultValue (parameterIndex),
  761. AAX_CLinearTaperDelegate<float, 0>(),
  762. AAX_CNumberDisplayDelegate<float, 3>(),
  763. audioProcessor.isParameterAutomatable (parameterIndex));
  764. parameter->AddShortenedName (audioProcessor.getParameterName (parameterIndex, 4).toRawUTF8());
  765. const int parameterNumSteps = audioProcessor.getParameterNumSteps (parameterIndex);
  766. parameter->SetNumberOfSteps ((uint32_t) parameterNumSteps);
  767. parameter->SetType (parameterNumSteps > 1000 ? AAX_eParameterType_Continuous
  768. : AAX_eParameterType_Discrete);
  769. parameter->SetOrientation (audioProcessor.isParameterOrientationInverted (parameterIndex)
  770. ? (AAX_eParameterOrientation_RightMinLeftMax | AAX_eParameterOrientation_TopMinBottomMax
  771. | AAX_eParameterOrientation_RotarySingleDotMode | AAX_eParameterOrientation_RotaryRightMinLeftMax)
  772. : (AAX_eParameterOrientation_LeftMinRightMax | AAX_eParameterOrientation_BottomMinTopMax
  773. | AAX_eParameterOrientation_RotarySingleDotMode | AAX_eParameterOrientation_RotaryLeftMinRightMax));
  774. mParameterManager.AddParameter (parameter);
  775. }
  776. }
  777. void preparePlugin()
  778. {
  779. AAX_EStemFormat inputStemFormat = AAX_eStemFormat_None;
  780. check (Controller()->GetInputStemFormat (&inputStemFormat));
  781. const int numberOfInputChannels = getNumChannelsForStemFormat (inputStemFormat);
  782. AAX_EStemFormat outputStemFormat = AAX_eStemFormat_None;
  783. check (Controller()->GetOutputStemFormat (&outputStemFormat));
  784. const int numberOfOutputChannels = getNumChannelsForStemFormat (outputStemFormat);
  785. AudioProcessor& audioProcessor = getPluginInstance();
  786. audioProcessor.setSpeakerArrangement (getSpeakerArrangementString (inputStemFormat),
  787. getSpeakerArrangementString (outputStemFormat));
  788. audioProcessor.setPlayConfigDetails (numberOfInputChannels, numberOfOutputChannels, sampleRate, lastBufferSize);
  789. audioProcessor.prepareToPlay (sampleRate, lastBufferSize);
  790. maxBufferSize = lastBufferSize;
  791. check (Controller()->SetSignalLatency (audioProcessor.getLatencySamples()));
  792. }
  793. ScopedJuceInitialiser_GUI libraryInitialiser;
  794. ScopedPointer<AudioProcessor> pluginInstance;
  795. MidiBuffer midiBuffer;
  796. Array<float*> channelList;
  797. int32_t juceChunkIndex;
  798. AAX_CSampleRate sampleRate;
  799. int lastBufferSize, maxBufferSize;
  800. struct ChunkMemoryBlock : public ReferenceCountedObject
  801. {
  802. juce::MemoryBlock data;
  803. typedef ReferenceCountedObjectPtr<ChunkMemoryBlock> Ptr;
  804. };
  805. // temporary filter data is generated in GetChunkSize
  806. // and the size of the data returned. To avoid generating
  807. // it again in GetChunk, we need to store it somewhere.
  808. // However, as GetChunkSize and GetChunk can be called
  809. // on different threads, we store it in thread dependant storage
  810. // in a hash map with the thread id as a key.
  811. mutable HashMap<Thread::ThreadID, ChunkMemoryBlock::Ptr> perThreadFilterData;
  812. CriticalSection perThreadDataLock;
  813. JUCE_DECLARE_NON_COPYABLE (JuceAAX_Processor)
  814. };
  815. //==============================================================================
  816. struct IndexAsParamID
  817. {
  818. inline explicit IndexAsParamID (int i) noexcept : index (i) {}
  819. operator AAX_CParamID() noexcept
  820. {
  821. jassert (index >= 0);
  822. char* t = name + sizeof (name);
  823. *--t = 0;
  824. int v = index;
  825. do
  826. {
  827. *--t = (char) ('0' + (v % 10));
  828. v /= 10;
  829. } while (v > 0);
  830. return static_cast<AAX_CParamID> (t);
  831. }
  832. private:
  833. int index;
  834. char name[32];
  835. JUCE_DECLARE_NON_COPYABLE (IndexAsParamID)
  836. };
  837. //==============================================================================
  838. static void AAX_CALLBACK algorithmProcessCallback (JUCEAlgorithmContext* const instancesBegin[],
  839. const void* const instancesEnd)
  840. {
  841. for (JUCEAlgorithmContext* const* iter = instancesBegin; iter < instancesEnd; ++iter)
  842. {
  843. const JUCEAlgorithmContext& i = **iter;
  844. i.pluginInstance->parameters.process (i.inputChannels, i.outputChannels,
  845. *(i.bufferSize), *(i.bypass) != 0,
  846. getMidiNodeIn(i), getMidiNodeOut(i));
  847. }
  848. }
  849. //==============================================================================
  850. static void createDescriptor (AAX_IComponentDescriptor& desc, int channelConfigIndex,
  851. int numInputs, int numOutputs)
  852. {
  853. check (desc.AddAudioIn (JUCEAlgorithmIDs::inputChannels));
  854. check (desc.AddAudioOut (JUCEAlgorithmIDs::outputChannels));
  855. check (desc.AddAudioBufferLength (JUCEAlgorithmIDs::bufferSize));
  856. check (desc.AddDataInPort (JUCEAlgorithmIDs::bypass, sizeof (int32_t)));
  857. #if JucePlugin_WantsMidiInput
  858. check (desc.AddMIDINode (JUCEAlgorithmIDs::midiNodeIn, AAX_eMIDINodeType_LocalInput,
  859. JucePlugin_Name, 0xffff));
  860. #endif
  861. #if JucePlugin_ProducesMidiOutput
  862. check (desc.AddMIDINode (JUCEAlgorithmIDs::midiNodeOut, AAX_eMIDINodeType_LocalOutput,
  863. JucePlugin_Name " Out", 0xffff));
  864. #endif
  865. check (desc.AddPrivateData (JUCEAlgorithmIDs::pluginInstance, sizeof (PluginInstanceInfo)));
  866. // Create a property map
  867. AAX_IPropertyMap* const properties = desc.NewPropertyMap();
  868. jassert (properties != nullptr);
  869. properties->AddProperty (AAX_eProperty_ManufacturerID, JucePlugin_AAXManufacturerCode);
  870. properties->AddProperty (AAX_eProperty_ProductID, JucePlugin_AAXProductId);
  871. #if JucePlugin_AAXDisableBypass
  872. properties->AddProperty (AAX_eProperty_CanBypass, false);
  873. #else
  874. properties->AddProperty (AAX_eProperty_CanBypass, true);
  875. #endif
  876. properties->AddProperty (AAX_eProperty_InputStemFormat, getFormatForChans (numInputs));
  877. properties->AddProperty (AAX_eProperty_OutputStemFormat, getFormatForChans (numOutputs));
  878. // This value needs to match the RTAS wrapper's Type ID, so that
  879. // the host knows that the RTAS/AAX plugins are equivalent.
  880. properties->AddProperty (AAX_eProperty_PlugInID_Native, 'jcaa' + channelConfigIndex);
  881. #if ! JucePlugin_AAXDisableAudioSuite
  882. properties->AddProperty (AAX_eProperty_PlugInID_AudioSuite, 'jyaa' + channelConfigIndex);
  883. #endif
  884. #if JucePlugin_AAXDisableMultiMono
  885. properties->AddProperty (AAX_eProperty_Constraint_MultiMonoSupport, false);
  886. #else
  887. properties->AddProperty (AAX_eProperty_Constraint_MultiMonoSupport, true);
  888. #endif
  889. check (desc.AddProcessProc_Native (algorithmProcessCallback, properties));
  890. }
  891. static void getPlugInDescription (AAX_IEffectDescriptor& descriptor)
  892. {
  893. descriptor.AddName (JucePlugin_Desc);
  894. descriptor.AddName (JucePlugin_Name);
  895. descriptor.AddCategory (JucePlugin_AAXCategory);
  896. #ifdef JucePlugin_AAXPageTableFile
  897. // optional page table setting - define this macro in your AppConfig.h if you
  898. // want to set this value - see Avid documentation for details about its format.
  899. descriptor.AddResourceInfo (AAX_eResourceType_PageTable, JucePlugin_AAXPageTableFile);
  900. #endif
  901. check (descriptor.AddProcPtr ((void*) JuceAAX_GUI::Create, kAAX_ProcPtrID_Create_EffectGUI));
  902. check (descriptor.AddProcPtr ((void*) JuceAAX_Processor::Create, kAAX_ProcPtrID_Create_EffectParameters));
  903. #ifdef JucePlugin_PreferredChannelConfigurations_AAX
  904. const short channelConfigs[][2] = { JucePlugin_PreferredChannelConfigurations_AAX };
  905. #else
  906. const short channelConfigs[][2] = { JucePlugin_PreferredChannelConfigurations };
  907. #endif
  908. const int numConfigs = numElementsInArray (channelConfigs);
  909. // You need to actually add some configurations to the JucePlugin_PreferredChannelConfigurations
  910. // value in your JucePluginCharacteristics.h file..
  911. jassert (numConfigs > 0);
  912. for (int i = 0; i < numConfigs; ++i)
  913. {
  914. if (AAX_IComponentDescriptor* const desc = descriptor.NewComponentDescriptor())
  915. {
  916. const int numIns = channelConfigs [i][0];
  917. const int numOuts = channelConfigs [i][1];
  918. if (numIns <= 8 && numOuts <= 8) // AAX doesn't seem to handle more than 8 chans
  919. {
  920. createDescriptor (*desc, i, numIns, numOuts);
  921. check (descriptor.AddComponent (desc));
  922. }
  923. }
  924. }
  925. }
  926. };
  927. //==============================================================================
  928. AAX_Result JUCE_CDECL GetEffectDescriptions (AAX_ICollection*);
  929. AAX_Result JUCE_CDECL GetEffectDescriptions (AAX_ICollection* collection)
  930. {
  931. ScopedJuceInitialiser_GUI libraryInitialiser;
  932. if (AAX_IEffectDescriptor* const descriptor = collection->NewDescriptor())
  933. {
  934. AAXClasses::getPlugInDescription (*descriptor);
  935. collection->AddEffect (JUCE_STRINGIFY (JucePlugin_AAXIdentifier), descriptor);
  936. collection->SetManufacturerName (JucePlugin_Manufacturer);
  937. collection->AddPackageName (JucePlugin_Desc);
  938. collection->AddPackageName (JucePlugin_Name);
  939. collection->SetPackageVersion (JucePlugin_VersionCode);
  940. return AAX_SUCCESS;
  941. }
  942. return AAX_ERROR_NULL_OBJECT;
  943. }
  944. #endif