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.

1065 lines
38KB

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