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.

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