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.

1162 lines
45KB

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