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.

1055 lines
38KB

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