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
38KB

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