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.

1046 lines
37KB

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