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.

1051 lines
37KB

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