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.

1058 lines
38KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #include <juce_core/system/juce_CompilerWarnings.h>
  19. #include <juce_core/system/juce_TargetPlatform.h>
  20. #include "../utility/juce_CheckSettingMacros.h"
  21. #if JucePlugin_Build_RTAS
  22. #ifdef _MSC_VER
  23. // (this is a workaround for a build problem in VC9)
  24. #define _DO_NOT_DECLARE_INTERLOCKED_INTRINSICS_IN_MEMORY
  25. #include <intrin.h>
  26. #ifndef JucePlugin_WinBag_path
  27. #error "You need to define the JucePlugin_WinBag_path value!"
  28. #endif
  29. #endif
  30. #include "juce_RTAS_DigiCode_Header.h"
  31. #ifdef _MSC_VER
  32. #include <Mac2Win.H>
  33. #endif
  34. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Widiomatic-parentheses",
  35. "-Wnon-virtual-dtor",
  36. "-Wcomment")
  37. /* Note about include paths
  38. ------------------------
  39. To be able to include all the Digidesign headers correctly, you'll need to add this
  40. lot to your include path:
  41. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\EffectClasses
  42. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\ProcessClasses
  43. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\ProcessClasses\Interfaces
  44. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Utilities
  45. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\RTASP_Adapt
  46. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\CoreClasses
  47. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Controls
  48. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Meters
  49. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\ViewClasses
  50. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\DSPClasses
  51. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Interfaces
  52. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\common
  53. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\common\Platform
  54. c:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugins\SignalProcessing\Public
  55. C:\yourdirectory\PT_80_SDK\AlturaPorts\TDMPlugIns\DSPManager\Interfaces
  56. c:\yourdirectory\PT_80_SDK\AlturaPorts\SADriver\Interfaces
  57. c:\yourdirectory\PT_80_SDK\AlturaPorts\DigiPublic\Interfaces
  58. c:\yourdirectory\PT_80_SDK\AlturaPorts\Fic\Interfaces\DAEClient
  59. c:\yourdirectory\PT_80_SDK\AlturaPorts\NewFileLibs\Cmn
  60. c:\yourdirectory\PT_80_SDK\AlturaPorts\NewFileLibs\DOA
  61. c:\yourdirectory\PT_80_SDK\AlturaPorts\AlturaSource\PPC_H
  62. c:\yourdirectory\PT_80_SDK\AlturaPorts\AlturaSource\AppSupport
  63. c:\yourdirectory\PT_80_SDK\AlturaPorts\DigiPublic
  64. c:\yourdirectory\PT_80_SDK\AvidCode\AVX2sdk\AVX\avx2\avx2sdk\inc
  65. c:\yourdirectory\PT_80_SDK\xplat\AVX\avx2\avx2sdk\inc
  66. NB. If you hit a huge pile of bugs around here, make sure that you've not got the
  67. Apple QuickTime headers before the PT headers in your path, because there are
  68. some filename clashes between them.
  69. */
  70. #include <CEffectGroupMIDI.h>
  71. #include <CEffectProcessMIDI.h>
  72. #include <CEffectProcessRTAS.h>
  73. #include <CCustomView.h>
  74. #include <CEffectTypeRTAS.h>
  75. #include <CPluginControl.h>
  76. #include <CPluginControl_OnOff.h>
  77. #include <FicProcessTokens.h>
  78. #include <ExternalVersionDefines.h>
  79. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  80. //==============================================================================
  81. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4263 4264 4250)
  82. #include "../utility/juce_IncludeModuleHeaders.h"
  83. #ifdef _MSC_VER
  84. #pragma pack (pop)
  85. // This JUCE_RTAS_LINK_TO_DEBUG_LIB setting can be used to force linkage
  86. // against only the release build of the RTAS lib, since in older SDKs there
  87. // can be problems with the debug build.
  88. #if JUCE_DEBUG && ! defined (JUCE_RTAS_LINK_TO_DEBUG_LIB)
  89. #define JUCE_RTAS_LINK_TO_DEBUG_LIB 1
  90. #endif
  91. #if JUCE_RTAS_LINK_TO_DEBUG_LIB
  92. #define PT_LIB_PATH JucePlugin_WinBag_path "\\Debug\\lib\\"
  93. #else
  94. #define PT_LIB_PATH JucePlugin_WinBag_path "\\Release\\lib\\"
  95. #endif
  96. #pragma comment(lib, PT_LIB_PATH "DAE.lib")
  97. #pragma comment(lib, PT_LIB_PATH "DigiExt.lib")
  98. #pragma comment(lib, PT_LIB_PATH "DSI.lib")
  99. #pragma comment(lib, PT_LIB_PATH "PluginLib.lib")
  100. #pragma comment(lib, PT_LIB_PATH "DSPManager.lib")
  101. #pragma comment(lib, PT_LIB_PATH "DSPManagerClientLib.lib")
  102. #pragma comment(lib, PT_LIB_PATH "RTASClientLib.lib")
  103. #endif
  104. #undef MemoryBlock
  105. //==============================================================================
  106. #if JUCE_WINDOWS
  107. extern void JUCE_CALLTYPE attachSubWindow (void* hostWindow, int& titleW, int& titleH, Component* comp);
  108. extern void JUCE_CALLTYPE resizeHostWindow (void* hostWindow, int& titleW, int& titleH, Component* comp);
  109. #if ! JucePlugin_EditorRequiresKeyboardFocus
  110. extern void JUCE_CALLTYPE passFocusToHostWindow (void* hostWindow);
  111. #endif
  112. #else
  113. extern void* attachSubWindow (void* hostWindowRef, Component* comp);
  114. extern void removeSubWindow (void* nsWindow, Component* comp);
  115. extern void forwardCurrentKeyEventToHostWindow();
  116. #endif
  117. #if ! (JUCE_DEBUG || defined (JUCE_RTAS_PLUGINGESTALT_IS_CACHEABLE))
  118. #define JUCE_RTAS_PLUGINGESTALT_IS_CACHEABLE 1
  119. #endif
  120. const int midiBufferSize = 1024;
  121. const OSType juceChunkType = 'juce';
  122. static const int bypassControlIndex = 1;
  123. static int numInstances = 0;
  124. using namespace juce;
  125. //==============================================================================
  126. class JucePlugInProcess : public CEffectProcessMIDI,
  127. public CEffectProcessRTAS,
  128. public AudioProcessorListener,
  129. public AudioPlayHead
  130. {
  131. public:
  132. //==============================================================================
  133. [[deprecated ("RTAS builds will be removed from JUCE in the next release.")]]
  134. JucePlugInProcess()
  135. {
  136. juceFilter.reset (createPluginFilterOfType (AudioProcessor::wrapperType_RTAS));
  137. AddChunk (juceChunkType, "Juce Audio Plugin Data");
  138. ++numInstances;
  139. }
  140. ~JucePlugInProcess()
  141. {
  142. JUCE_AUTORELEASEPOOL
  143. {
  144. if (mLoggedIn)
  145. MIDILogOut();
  146. midiBufferNode.reset();
  147. midiTransport.reset();
  148. if (juceFilter != nullptr)
  149. {
  150. juceFilter->releaseResources();
  151. juceFilter.reset();
  152. }
  153. if (--numInstances == 0)
  154. {
  155. #if JUCE_MAC
  156. // Hack to allow any NSWindows to clear themselves up before returning to PT..
  157. for (int i = 20; --i >= 0;)
  158. MessageManager::getInstance()->runDispatchLoopUntil (1);
  159. #endif
  160. shutdownJuce_GUI();
  161. }
  162. }
  163. }
  164. //==============================================================================
  165. class JuceCustomUIView : public CCustomView,
  166. public Timer
  167. {
  168. public:
  169. //==============================================================================
  170. JuceCustomUIView (AudioProcessor* ap, JucePlugInProcess* p)
  171. : filter (ap), process (p)
  172. {
  173. // setting the size in here crashes PT for some reason, so keep it simple..
  174. }
  175. ~JuceCustomUIView()
  176. {
  177. deleteEditorComp();
  178. }
  179. //==============================================================================
  180. void updateSize()
  181. {
  182. if (editorComp == nullptr)
  183. {
  184. editorComp.reset (filter->createEditorIfNeeded());
  185. jassert (editorComp != nullptr);
  186. }
  187. if (editorComp->getWidth() != 0 && editorComp->getHeight() != 0)
  188. {
  189. Rect oldRect;
  190. GetRect (&oldRect);
  191. Rect r;
  192. r.left = 0;
  193. r.top = 0;
  194. r.right = editorComp->getWidth();
  195. r.bottom = editorComp->getHeight();
  196. SetRect (&r);
  197. if (oldRect.right != r.right || oldRect.bottom != r.bottom)
  198. startTimer (50);
  199. }
  200. }
  201. void timerCallback() override
  202. {
  203. if (! Component::isMouseButtonDownAnywhere())
  204. {
  205. stopTimer();
  206. // Send a token to the host to tell it about the resize
  207. SSetProcessWindowResizeToken token (process->fRootNameId, process->fRootNameId);
  208. FicSDSDispatchToken (&token);
  209. }
  210. }
  211. void attachToWindow (GrafPtr port)
  212. {
  213. if (port != 0)
  214. {
  215. JUCE_AUTORELEASEPOOL
  216. {
  217. updateSize();
  218. #if JUCE_WINDOWS
  219. auto hostWindow = (void*) ASI_GethWnd ((WindowPtr) port);
  220. #else
  221. auto hostWindow = (void*) GetWindowFromPort (port);
  222. #endif
  223. wrapper.reset();
  224. wrapper.reset (new EditorCompWrapper (hostWindow, editorComp.get(), this));
  225. }
  226. }
  227. else
  228. {
  229. deleteEditorComp();
  230. }
  231. }
  232. void DrawContents (Rect*) override
  233. {
  234. #if JUCE_WINDOWS
  235. if (wrapper != nullptr)
  236. if (auto peer = wrapper->getPeer())
  237. peer->repaint (wrapper->getLocalBounds()); // (seems to be required in PT6.4, but not in 7.x)
  238. #endif
  239. }
  240. void DrawBackground (Rect*) override {}
  241. //==============================================================================
  242. private:
  243. AudioProcessor* const filter;
  244. JucePlugInProcess* const process;
  245. std::unique_ptr<Component> wrapper;
  246. std::unique_ptr<AudioProcessorEditor> editorComp;
  247. void deleteEditorComp()
  248. {
  249. if (editorComp != nullptr || wrapper != nullptr)
  250. {
  251. JUCE_AUTORELEASEPOOL
  252. {
  253. PopupMenu::dismissAllActiveMenus();
  254. if (Component* const modalComponent = Component::getCurrentlyModalComponent())
  255. modalComponent->exitModalState (0);
  256. filter->editorBeingDeleted (editorComp.get());
  257. editorComp.reset();
  258. wrapper.reset();
  259. }
  260. }
  261. }
  262. //==============================================================================
  263. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  264. // chores when it changes or repaints.
  265. class EditorCompWrapper : public Component
  266. #if ! JUCE_MAC
  267. , public FocusChangeListener
  268. #endif
  269. {
  270. public:
  271. EditorCompWrapper (void* hostWindow_,
  272. Component* editorComp,
  273. JuceCustomUIView* owner_)
  274. : hostWindow (hostWindow_),
  275. owner (owner_),
  276. titleW (0),
  277. titleH (0)
  278. {
  279. #if ! JucePlugin_EditorRequiresKeyboardFocus
  280. setMouseClickGrabsKeyboardFocus (false);
  281. setWantsKeyboardFocus (false);
  282. #endif
  283. setOpaque (true);
  284. setBroughtToFrontOnMouseClick (true);
  285. setBounds (editorComp->getBounds());
  286. editorComp->setTopLeftPosition (0, 0);
  287. addAndMakeVisible (*editorComp);
  288. #if JUCE_WINDOWS
  289. attachSubWindow (hostWindow, titleW, titleH, this);
  290. #else
  291. nsWindow = attachSubWindow (hostWindow, this);
  292. #endif
  293. setVisible (true);
  294. #if JUCE_WINDOWS && ! JucePlugin_EditorRequiresKeyboardFocus
  295. Desktop::getInstance().addFocusChangeListener (this);
  296. #endif
  297. }
  298. ~EditorCompWrapper()
  299. {
  300. removeChildComponent (getEditor());
  301. #if JUCE_WINDOWS && ! JucePlugin_EditorRequiresKeyboardFocus
  302. Desktop::getInstance().removeFocusChangeListener (this);
  303. #endif
  304. #if JUCE_MAC
  305. removeSubWindow (nsWindow, this);
  306. #endif
  307. }
  308. void paint (Graphics&) override {}
  309. void resized() override
  310. {
  311. if (Component* const ed = getEditor())
  312. ed->setBounds (getLocalBounds());
  313. repaint();
  314. }
  315. #if JUCE_WINDOWS
  316. void globalFocusChanged (Component*) override
  317. {
  318. #if ! JucePlugin_EditorRequiresKeyboardFocus
  319. if (hasKeyboardFocus (true))
  320. passFocusToHostWindow (hostWindow);
  321. #endif
  322. }
  323. #endif
  324. void childBoundsChanged (Component* child) override
  325. {
  326. setSize (child->getWidth(), child->getHeight());
  327. child->setTopLeftPosition (0, 0);
  328. #if JUCE_WINDOWS
  329. resizeHostWindow (hostWindow, titleW, titleH, this);
  330. #endif
  331. owner->updateSize();
  332. }
  333. void userTriedToCloseWindow() override {}
  334. #if JUCE_MAC && JucePlugin_EditorRequiresKeyboardFocus
  335. bool keyPressed (const KeyPress& kp) override
  336. {
  337. owner->updateSize();
  338. forwardCurrentKeyEventToHostWindow();
  339. return true;
  340. }
  341. #endif
  342. private:
  343. //==============================================================================
  344. void* const hostWindow;
  345. void* nsWindow;
  346. JuceCustomUIView* const owner;
  347. int titleW, titleH;
  348. Component* getEditor() const { return getChildComponent (0); }
  349. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  350. };
  351. };
  352. JuceCustomUIView* getView() const
  353. {
  354. return dynamic_cast<JuceCustomUIView*> (fOurPlugInView);
  355. }
  356. void GetViewRect (Rect* size) override
  357. {
  358. if (JuceCustomUIView* const v = getView())
  359. v->updateSize();
  360. CEffectProcessRTAS::GetViewRect (size);
  361. }
  362. CPlugInView* CreateCPlugInView() override
  363. {
  364. return new JuceCustomUIView (juceFilter.get(), this);
  365. }
  366. void SetViewPort (GrafPtr port) override
  367. {
  368. CEffectProcessRTAS::SetViewPort (port);
  369. if (JuceCustomUIView* const v = getView())
  370. v->attachToWindow (port);
  371. }
  372. //==============================================================================
  373. ComponentResult GetDelaySamplesLong (long* aNumSamples) override
  374. {
  375. if (aNumSamples != nullptr)
  376. *aNumSamples = juceFilter != nullptr ? juceFilter->getLatencySamples() : 0;
  377. return noErr;
  378. }
  379. //==============================================================================
  380. void EffectInit() override
  381. {
  382. sampleRate = (double) GetSampleRate();
  383. jassert (sampleRate > 0);
  384. const int maxBlockSize = (int) CEffectProcessRTAS::GetMaximumRTASQuantum();
  385. jassert (maxBlockSize > 0);
  386. SFicPlugInStemFormats stems;
  387. GetProcessType()->GetStemFormats (&stems);
  388. juceFilter->setPlayConfigDetails (fNumInputs, fNumOutputs, sampleRate, maxBlockSize);
  389. AddControl (new CPluginControl_OnOff ('bypa', "Master Bypass\nMastrByp\nMByp\nByp", false, true));
  390. DefineMasterBypassControlIndex (bypassControlIndex);
  391. const int numParameters = juceFilter->getNumParameters();
  392. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  393. const bool usingManagedParameters = false;
  394. #else
  395. const bool usingManagedParameters = (juceFilter->getParameters().size() == numParameters);
  396. #endif
  397. for (int i = 0; i < numParameters; ++i)
  398. {
  399. OSType rtasParamID = static_cast<OSType> (usingManagedParameters ? juceFilter->getParameterID (i).hashCode() : i);
  400. AddControl (new JucePluginControl (*juceFilter, i, rtasParamID));
  401. }
  402. // we need to do this midi log-in to get timecode, regardless of whether
  403. // the plugin actually uses midi...
  404. if (MIDILogIn() == noErr)
  405. {
  406. #if JucePlugin_WantsMidiInput
  407. if (CEffectType* const type = dynamic_cast<CEffectType*> (this->GetProcessType()))
  408. {
  409. char nodeName[80] = { 0 };
  410. type->GetProcessTypeName (63, nodeName);
  411. nodeName[nodeName[0] + 1] = 0;
  412. midiBufferNode.reset (new CEffectMIDIOtherBufferedNode (&mMIDIWorld,
  413. 8192,
  414. eLocalNode,
  415. nodeName + 1,
  416. midiBuffer));
  417. midiBufferNode->Initialize (0xffff, true);
  418. }
  419. #endif
  420. }
  421. midiTransport.reset (new CEffectMIDITransport (&mMIDIWorld));
  422. midiEvents.ensureSize (2048);
  423. channels.calloc (jmax (juceFilter->getTotalNumInputChannels(),
  424. juceFilter->getTotalNumOutputChannels()));
  425. juceFilter->setPlayHead (this);
  426. juceFilter->addListener (this);
  427. juceFilter->prepareToPlay (sampleRate, maxBlockSize);
  428. }
  429. void RenderAudio (float** inputs, float** outputs, long numSamples) override
  430. {
  431. #if JucePlugin_WantsMidiInput
  432. midiEvents.clear();
  433. const Cmn_UInt32 bufferSize = mRTGlobals->mHWBufferSizeInSamples;
  434. if (midiBufferNode != nullptr)
  435. {
  436. if (midiBufferNode->GetAdvanceScheduleTime() != bufferSize)
  437. midiBufferNode->SetAdvanceScheduleTime (bufferSize);
  438. if (midiBufferNode->FillMIDIBuffer (mRTGlobals->mRunningTime, numSamples) == noErr)
  439. {
  440. jassert (midiBufferNode->GetBufferPtr() != nullptr);
  441. const int numMidiEvents = midiBufferNode->GetBufferSize();
  442. for (int i = 0; i < numMidiEvents; ++i)
  443. {
  444. const DirectMidiPacket& m = midiBuffer[i];
  445. jassert ((int) m.mTimestamp < numSamples);
  446. midiEvents.addEvent (m.mData, m.mLength,
  447. jlimit (0, (int) numSamples - 1, (int) m.mTimestamp));
  448. }
  449. }
  450. }
  451. #endif
  452. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  453. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  454. ignoreUnused (numMidiEventsComingIn);
  455. #endif
  456. {
  457. const ScopedLock sl (juceFilter->getCallbackLock());
  458. const int numIn = juceFilter->getTotalNumInputChannels();
  459. const int numOut = juceFilter->getTotalNumOutputChannels();
  460. const int totalChans = jmax (numIn, numOut);
  461. if (juceFilter->isSuspended())
  462. {
  463. for (int i = 0; i < numOut; ++i)
  464. FloatVectorOperations::clear (outputs [i], numSamples);
  465. }
  466. else
  467. {
  468. {
  469. int i;
  470. for (i = 0; i < numOut; ++i)
  471. {
  472. channels[i] = outputs [i];
  473. if (i < numIn && inputs != outputs)
  474. FloatVectorOperations::copy (outputs [i], inputs[i], numSamples);
  475. }
  476. for (; i < numIn; ++i)
  477. channels [i] = inputs [i];
  478. }
  479. AudioBuffer<float> chans (channels, totalChans, numSamples);
  480. if (mBypassed)
  481. juceFilter->processBlockBypassed (chans, midiEvents);
  482. else
  483. juceFilter->processBlock (chans, midiEvents);
  484. }
  485. }
  486. if (! midiEvents.isEmpty())
  487. {
  488. #if JucePlugin_ProducesMidiOutput
  489. for (const auto metadata : midiEvents)
  490. {
  491. //jassert (metadata.samplePosition >= 0 && metadata.samplePosition < (int) numSamples);
  492. }
  493. #elif JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  494. // if your plugin creates midi messages, you'll need to set
  495. // the JucePlugin_ProducesMidiOutput macro to 1 in your
  496. // JucePluginCharacteristics.h file
  497. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  498. #endif
  499. midiEvents.clear();
  500. }
  501. }
  502. //==============================================================================
  503. ComponentResult GetChunkSize (OSType chunkID, long* size) override
  504. {
  505. if (chunkID == juceChunkType)
  506. {
  507. tempFilterData.reset();
  508. juceFilter->getStateInformation (tempFilterData);
  509. *size = sizeof (SFicPlugInChunkHeader) + tempFilterData.getSize();
  510. return noErr;
  511. }
  512. return CEffectProcessMIDI::GetChunkSize (chunkID, size);
  513. }
  514. ComponentResult GetChunk (OSType chunkID, SFicPlugInChunk* chunk) override
  515. {
  516. if (chunkID == juceChunkType)
  517. {
  518. if (tempFilterData.getSize() == 0)
  519. juceFilter->getStateInformation (tempFilterData);
  520. chunk->fSize = sizeof (SFicPlugInChunkHeader) + tempFilterData.getSize();
  521. tempFilterData.copyTo ((void*) chunk->fData, 0, tempFilterData.getSize());
  522. tempFilterData.reset();
  523. return noErr;
  524. }
  525. return CEffectProcessMIDI::GetChunk (chunkID, chunk);
  526. }
  527. ComponentResult SetChunk (OSType chunkID, SFicPlugInChunk* chunk) override
  528. {
  529. if (chunkID == juceChunkType)
  530. {
  531. tempFilterData.reset();
  532. if (chunk->fSize - sizeof (SFicPlugInChunkHeader) > 0)
  533. {
  534. juceFilter->setStateInformation ((void*) chunk->fData,
  535. chunk->fSize - sizeof (SFicPlugInChunkHeader));
  536. }
  537. return noErr;
  538. }
  539. return CEffectProcessMIDI::SetChunk (chunkID, chunk);
  540. }
  541. //==============================================================================
  542. ComponentResult UpdateControlValue (long controlIndex, long value) override
  543. {
  544. if (controlIndex != bypassControlIndex)
  545. {
  546. auto paramIndex = controlIndex - 2;
  547. auto floatValue = longToFloat (value);
  548. if (auto* param = juceFilter->getParameters()[paramIndex])
  549. {
  550. param->setValue (floatValue);
  551. param->sendValueChangedMessageToListeners (floatValue);
  552. }
  553. else
  554. {
  555. juceFilter->setParameter (paramIndex, floatValue);
  556. }
  557. }
  558. else
  559. {
  560. mBypassed = (value > 0);
  561. }
  562. return CProcess::UpdateControlValue (controlIndex, value);
  563. }
  564. #if JUCE_WINDOWS
  565. Boolean HandleKeystroke (EventRecord* e) override
  566. {
  567. if (Component* modalComp = Component::getCurrentlyModalComponent())
  568. {
  569. if (Component* focused = modalComp->getCurrentlyFocusedComponent())
  570. {
  571. switch (e->message & charCodeMask)
  572. {
  573. case kReturnCharCode:
  574. case kEnterCharCode: focused->keyPressed (KeyPress (KeyPress::returnKey)); break;
  575. case kEscapeCharCode: focused->keyPressed (KeyPress (KeyPress::escapeKey)); break;
  576. default: break;
  577. }
  578. return true;
  579. }
  580. }
  581. return false;
  582. }
  583. #endif
  584. //==============================================================================
  585. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info) override
  586. {
  587. Cmn_Float64 bpm = 120.0;
  588. Cmn_Int32 num = 4, denom = 4;
  589. Cmn_Int64 ticks = 0;
  590. Cmn_Bool isPlaying = false;
  591. if (midiTransport != nullptr)
  592. {
  593. midiTransport->GetCurrentTempo (&bpm);
  594. midiTransport->IsTransportPlaying (&isPlaying);
  595. midiTransport->GetCurrentMeter (&num, &denom);
  596. // (The following is a work-around because GetCurrentTickPosition() doesn't work correctly).
  597. Cmn_Int64 sampleLocation;
  598. if (isPlaying)
  599. midiTransport->GetCurrentRTASSampleLocation (&sampleLocation);
  600. else
  601. midiTransport->GetCurrentTDMSampleLocation (&sampleLocation);
  602. midiTransport->GetCustomTickPosition (&ticks, sampleLocation);
  603. info.timeInSamples = (int64) sampleLocation;
  604. info.timeInSeconds = sampleLocation / sampleRate;
  605. }
  606. else
  607. {
  608. info.timeInSamples = 0;
  609. info.timeInSeconds = 0;
  610. }
  611. info.bpm = bpm;
  612. info.timeSigNumerator = num;
  613. info.timeSigDenominator = denom;
  614. info.isPlaying = isPlaying;
  615. info.isRecording = false;
  616. info.ppqPosition = ticks / 960000.0;
  617. info.ppqPositionOfLastBarStart = 0; //xxx no idea how to get this correctly..
  618. info.isLooping = false;
  619. info.ppqLoopStart = 0;
  620. info.ppqLoopEnd = 0;
  621. info.frameRate = [this]
  622. {
  623. switch (fTimeCodeInfo.mFrameRate)
  624. {
  625. case ficFrameRate_24Frame: return FrameRate().withBaseRate (24);
  626. case ficFrameRate_23976: return FrameRate().withBaseRate (24).withPullDown();
  627. case ficFrameRate_25Frame: return FrameRate().withBaseRate (25);
  628. case ficFrameRate_30NonDrop: return FrameRate().withBaseRate (30);
  629. case ficFrameRate_30DropFrame: return FrameRate().withBaseRate (30).withDrop();
  630. case ficFrameRate_2997NonDrop: return FrameRate().withBaseRate (30).withPullDown();
  631. case ficFrameRate_2997DropFrame: return FrameRate().withBaseRate (30).withPullDown().withDrop();
  632. }
  633. return FrameRate();
  634. }();
  635. const auto effectiveRate = info.frameRate.getEffectiveRate();
  636. info.editOriginTime = effectiveRate != 0.0 ? fTimeCodeInfo.mFrameOffset / effectiveRate : 0.0;
  637. return true;
  638. }
  639. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  640. {
  641. SetControlValue (index + 2, floatToLong (newValue));
  642. }
  643. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override
  644. {
  645. TouchControl (index + 2);
  646. }
  647. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override
  648. {
  649. ReleaseControl (index + 2);
  650. }
  651. void audioProcessorChanged (AudioProcessor*, const ChangeDetails&) override
  652. {
  653. // xxx is there an RTAS equivalent?
  654. }
  655. private:
  656. std::unique_ptr<AudioProcessor> juceFilter;
  657. MidiBuffer midiEvents;
  658. std::unique_ptr<CEffectMIDIOtherBufferedNode> midiBufferNode;
  659. std::unique_ptr<CEffectMIDITransport> midiTransport;
  660. DirectMidiPacket midiBuffer [midiBufferSize];
  661. juce::MemoryBlock tempFilterData;
  662. HeapBlock<float*> channels;
  663. double sampleRate = 44100.0;
  664. static float longToFloat (const long n) noexcept
  665. {
  666. return (float) ((((double) n) + (double) 0x80000000) / (double) 0xffffffff);
  667. }
  668. static long floatToLong (const float n) noexcept
  669. {
  670. return roundToInt (jlimit (-(double) 0x80000000, (double) 0x7fffffff,
  671. n * (double) 0xffffffff - (double) 0x80000000));
  672. }
  673. void bypassBuffers (float** const inputs, float** const outputs, const long numSamples) const
  674. {
  675. for (int i = fNumOutputs; --i >= 0;)
  676. {
  677. if (i < fNumInputs)
  678. FloatVectorOperations::copy (outputs[i], inputs[i], numSamples);
  679. else
  680. FloatVectorOperations::clear (outputs[i], numSamples);
  681. }
  682. }
  683. //==============================================================================
  684. class JucePluginControl : public CPluginControl
  685. {
  686. public:
  687. //==============================================================================
  688. JucePluginControl (AudioProcessor& p, const int i, OSType rtasParamID)
  689. : processor (p), index (i), paramID (rtasParamID)
  690. {
  691. CPluginControl::SetValue (GetDefaultValue());
  692. }
  693. //==============================================================================
  694. OSType GetID() const { return paramID; }
  695. long GetDefaultValue() const { return floatToLong (processor.getParameterDefaultValue (index)); }
  696. void SetDefaultValue (long) {}
  697. long GetNumSteps() const { return processor.getParameterNumSteps (index); }
  698. long ConvertStringToValue (const char* valueString) const
  699. {
  700. return floatToLong (String (valueString).getFloatValue());
  701. }
  702. Cmn_Bool IsKeyValid (long key) const { return true; }
  703. void GetNameOfLength (char* name, int maxLength, OSType inControllerType) const
  704. {
  705. // Pro-tools expects all your parameters to have valid names!
  706. jassert (processor.getParameterName (index, maxLength).isNotEmpty());
  707. processor.getParameterName (index, maxLength).copyToUTF8 (name, (size_t) maxLength + 1);
  708. }
  709. long GetPriority() const { return kFicCooperativeTaskPriority; }
  710. long GetOrientation() const
  711. {
  712. return processor.isParameterOrientationInverted (index)
  713. ? kDAE_RightMinLeftMax | kDAE_TopMinBottomMax | kDAE_RotarySingleDotMode | kDAE_RotaryRightMinLeftMax
  714. : kDAE_LeftMinRightMax | kDAE_BottomMinTopMax | kDAE_RotarySingleDotMode | kDAE_RotaryLeftMinRightMax;
  715. }
  716. long GetControlType() const { return kDAE_ContinuousValues; }
  717. void GetValueString (char* valueString, int maxLength, long value) const
  718. {
  719. processor.getParameterText (index, maxLength).copyToUTF8 (valueString, (size_t) maxLength + 1);
  720. }
  721. Cmn_Bool IsAutomatable() const
  722. {
  723. return processor.isParameterAutomatable (index);
  724. }
  725. private:
  726. //==============================================================================
  727. AudioProcessor& processor;
  728. const int index;
  729. const OSType paramID;
  730. JUCE_DECLARE_NON_COPYABLE (JucePluginControl)
  731. };
  732. };
  733. //==============================================================================
  734. class JucePlugInGroup : public CEffectGroupMIDI
  735. {
  736. public:
  737. //==============================================================================
  738. JucePlugInGroup()
  739. {
  740. DefineManufacturerNamesAndID (JucePlugin_Manufacturer, JucePlugin_RTASManufacturerCode);
  741. DefinePlugInNamesAndVersion (createRTASName().toUTF8(), JucePlugin_VersionCode);
  742. #if JUCE_RTAS_PLUGINGESTALT_IS_CACHEABLE
  743. AddGestalt (pluginGestalt_IsCacheable);
  744. #endif
  745. }
  746. ~JucePlugInGroup()
  747. {
  748. shutdownJuce_GUI();
  749. }
  750. static AudioChannelSet rtasChannelSet (int numChannels)
  751. {
  752. if (numChannels == 0) return AudioChannelSet::disabled();
  753. if (numChannels == 1) return AudioChannelSet::mono();
  754. if (numChannels == 2) return AudioChannelSet::stereo();
  755. if (numChannels == 3) return AudioChannelSet::createLCR();
  756. if (numChannels == 4) return AudioChannelSet::quadraphonic();
  757. if (numChannels == 5) return AudioChannelSet::create5point0();
  758. if (numChannels == 6) return AudioChannelSet::create5point1();
  759. #if PT_VERS_MAJOR >= 9
  760. if (numChannels == 7) return AudioChannelSet::create7point0();
  761. if (numChannels == 8) return AudioChannelSet::create7point1();
  762. #else
  763. if (numChannels == 7) return AudioChannelSet::create7point0SDDS();
  764. if (numChannels == 8) return AudioChannelSet::create7point1SDDS();
  765. #endif
  766. jassertfalse;
  767. return AudioChannelSet::discreteChannels (numChannels);
  768. }
  769. //==============================================================================
  770. void CreateEffectTypes()
  771. {
  772. std::unique_ptr<AudioProcessor> plugin (createPluginFilterOfType (AudioProcessor::wrapperType_RTAS));
  773. #ifndef JucePlugin_PreferredChannelConfigurations
  774. #error You need to set the "Plugin Channel Configurations" field in the Projucer to build RTAS plug-ins
  775. #endif
  776. const short channelConfigs[][2] = { JucePlugin_PreferredChannelConfigurations };
  777. const int numConfigs = numElementsInArray (channelConfigs);
  778. // You need to actually add some configurations to the JucePlugin_PreferredChannelConfigurations
  779. // value in your JucePluginCharacteristics.h file..
  780. jassert (numConfigs > 0);
  781. for (int i = 0; i < numConfigs; ++i)
  782. {
  783. if (channelConfigs[i][0] <= 8 && channelConfigs[i][1] <= 8)
  784. {
  785. const AudioChannelSet inputLayout (rtasChannelSet (channelConfigs[i][0]));
  786. const AudioChannelSet outputLayout (rtasChannelSet (channelConfigs[i][1]));
  787. const int32 pluginId = plugin->getAAXPluginIDForMainBusConfig (inputLayout, outputLayout, false);
  788. CEffectType* const type
  789. = new CEffectTypeRTAS (pluginId,
  790. JucePlugin_RTASProductId,
  791. JucePlugin_RTASCategory);
  792. type->DefineTypeNames (createRTASName().toRawUTF8());
  793. type->DefineSampleRateSupport (eSupports48kAnd96kAnd192k);
  794. type->DefineStemFormats (getFormatForChans (channelConfigs [i][0] != 0 ? channelConfigs [i][0] : channelConfigs [i][1]),
  795. getFormatForChans (channelConfigs [i][1] != 0 ? channelConfigs [i][1] : channelConfigs [i][0]));
  796. #if ! JucePlugin_RTASDisableBypass
  797. type->AddGestalt (pluginGestalt_CanBypass);
  798. #endif
  799. #if JucePlugin_RTASDisableMultiMono
  800. type->AddGestalt (pluginGestalt_DoesntSupportMultiMono);
  801. #endif
  802. type->AddGestalt (pluginGestalt_SupportsVariableQuanta);
  803. type->AttachEffectProcessCreator (createNewProcess);
  804. AddEffectType (type);
  805. }
  806. }
  807. }
  808. void Initialize()
  809. {
  810. CEffectGroupMIDI::Initialize();
  811. }
  812. //==============================================================================
  813. private:
  814. static CEffectProcess* createNewProcess()
  815. {
  816. #if JUCE_WINDOWS
  817. Process::setCurrentModuleInstanceHandle (gThisModule);
  818. #endif
  819. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_RTAS;
  820. initialiseJuce_GUI();
  821. return new JucePlugInProcess();
  822. }
  823. static String createRTASName()
  824. {
  825. return String (JucePlugin_Name) + "\n"
  826. + String (JucePlugin_Desc);
  827. }
  828. static EPlugIn_StemFormat getFormatForChans (const int numChans) noexcept
  829. {
  830. switch (numChans)
  831. {
  832. case 0: return ePlugIn_StemFormat_Generic;
  833. case 1: return ePlugIn_StemFormat_Mono;
  834. case 2: return ePlugIn_StemFormat_Stereo;
  835. case 3: return ePlugIn_StemFormat_LCR;
  836. case 4: return ePlugIn_StemFormat_Quad;
  837. case 5: return ePlugIn_StemFormat_5dot0;
  838. case 6: return ePlugIn_StemFormat_5dot1;
  839. #if PT_VERS_MAJOR >= 9
  840. case 7: return ePlugIn_StemFormat_7dot0DTS;
  841. case 8: return ePlugIn_StemFormat_7dot1DTS;
  842. #else
  843. case 7: return ePlugIn_StemFormat_7dot0;
  844. case 8: return ePlugIn_StemFormat_7dot1;
  845. #endif
  846. default: jassertfalse; break; // hmm - not a valid number of chans for RTAS..
  847. }
  848. return ePlugIn_StemFormat_Generic;
  849. }
  850. };
  851. void initialiseMacRTAS();
  852. CProcessGroupInterface* CProcessGroup::CreateProcessGroup()
  853. {
  854. #if JUCE_MAC
  855. initialiseMacRTAS();
  856. #endif
  857. return new JucePlugInGroup();
  858. }
  859. JUCE_END_IGNORE_WARNINGS_MSVC
  860. #endif