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.

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