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.

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