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.

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