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.

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