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.

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