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.

1012 lines
36KB

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