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.

1019 lines
36KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. // Your project must contain an AppConfig.h file with your project-specific settings in it,
  18. // and your header search path must make it accessible to the module's files.
  19. #include "AppConfig.h"
  20. #include "../utility/juce_CheckSettingMacros.h"
  21. #if JucePlugin_Build_RTAS
  22. #ifdef _MSC_VER
  23. // (this is a workaround for a build problem in VC9)
  24. #define _DO_NOT_DECLARE_INTERLOCKED_INTRINSICS_IN_MEMORY
  25. #include <intrin.h>
  26. #endif
  27. #include "juce_RTAS_DigiCode_Header.h"
  28. #ifdef _MSC_VER
  29. #include <Mac2Win.H>
  30. #endif
  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. //==============================================================================
  74. #ifdef _MSC_VER
  75. #pragma pack (push, 8)
  76. #pragma warning (disable: 4263 4264)
  77. #endif
  78. #include "../utility/juce_IncludeModuleHeaders.h"
  79. #ifdef _MSC_VER
  80. #pragma pack (pop)
  81. // This JUCE_RTAS_LINK_TO_DEBUG_LIB setting can be used to force linkage
  82. // against only the release build of the RTAS lib, since in older SDKs there
  83. // can be problems with the debug build.
  84. #if JUCE_DEBUG && ! defined (JUCE_RTAS_LINK_TO_DEBUG_LIB)
  85. #define JUCE_RTAS_LINK_TO_DEBUG_LIB 1
  86. #endif
  87. #if JUCE_RTAS_LINK_TO_DEBUG_LIB
  88. #define PT_LIB_PATH JucePlugin_WinBag_path "\\Debug\\lib\\"
  89. #else
  90. #define PT_LIB_PATH JucePlugin_WinBag_path "\\Release\\lib\\"
  91. #endif
  92. #pragma comment(lib, PT_LIB_PATH "DAE.lib")
  93. #pragma comment(lib, PT_LIB_PATH "DigiExt.lib")
  94. #pragma comment(lib, PT_LIB_PATH "DSI.lib")
  95. #pragma comment(lib, PT_LIB_PATH "PluginLib.lib")
  96. #pragma comment(lib, PT_LIB_PATH "DSPManager.lib")
  97. #pragma comment(lib, PT_LIB_PATH "DSPManagerClientLib.lib")
  98. #pragma comment(lib, PT_LIB_PATH "RTASClientLib.lib")
  99. #endif
  100. #undef Component
  101. #undef MemoryBlock
  102. //==============================================================================
  103. #if JUCE_WINDOWS
  104. extern void JUCE_CALLTYPE attachSubWindow (void* hostWindow, int& titleW, int& titleH, juce::Component* comp);
  105. extern void JUCE_CALLTYPE resizeHostWindow (void* hostWindow, int& titleW, int& titleH, juce::Component* comp);
  106. #if ! JucePlugin_EditorRequiresKeyboardFocus
  107. extern void JUCE_CALLTYPE passFocusToHostWindow (void* hostWindow);
  108. #endif
  109. #else
  110. extern void* attachSubWindow (void* hostWindowRef, juce::Component* comp);
  111. extern void removeSubWindow (void* nsWindow, juce::Component* comp);
  112. extern void forwardCurrentKeyEventToHostWindow();
  113. #endif
  114. #if ! (JUCE_DEBUG || defined (JUCE_RTAS_PLUGINGESTALT_IS_CACHEABLE))
  115. #define JUCE_RTAS_PLUGINGESTALT_IS_CACHEABLE 1
  116. #endif
  117. const int midiBufferSize = 1024;
  118. const OSType juceChunkType = 'juce';
  119. static const int bypassControlIndex = 1;
  120. static int numInstances = 0;
  121. //==============================================================================
  122. class JucePlugInProcess : public CEffectProcessMIDI,
  123. public CEffectProcessRTAS,
  124. public AudioProcessorListener,
  125. public AudioPlayHead
  126. {
  127. public:
  128. //==============================================================================
  129. JucePlugInProcess()
  130. : prepared (false),
  131. sampleRate (44100.0)
  132. {
  133. asyncUpdater = new InternalAsyncUpdater (*this);
  134. juceFilter = createPluginFilterOfType (AudioProcessor::wrapperType_RTAS);
  135. AddChunk (juceChunkType, "Juce Audio Plugin Data");
  136. ++numInstances;
  137. }
  138. ~JucePlugInProcess()
  139. {
  140. JUCE_AUTORELEASEPOOL
  141. {
  142. if (mLoggedIn)
  143. MIDILogOut();
  144. midiBufferNode = nullptr;
  145. midiTransport = nullptr;
  146. if (prepared)
  147. juceFilter->releaseResources();
  148. juceFilter = nullptr;
  149. asyncUpdater = nullptr;
  150. if (--numInstances == 0)
  151. {
  152. #if JUCE_MAC
  153. // Hack to allow any NSWindows to clear themselves up before returning to PT..
  154. for (int i = 20; --i >= 0;)
  155. MessageManager::getInstance()->runDispatchLoopUntil (1);
  156. #endif
  157. shutdownJuce_GUI();
  158. }
  159. }
  160. }
  161. //==============================================================================
  162. class JuceCustomUIView : public CCustomView,
  163. public Timer
  164. {
  165. public:
  166. //==============================================================================
  167. JuceCustomUIView (AudioProcessor* const filter_,
  168. JucePlugInProcess* const process_)
  169. : filter (filter_),
  170. process (process_)
  171. {
  172. // setting the size in here crashes PT for some reason, so keep it simple..
  173. }
  174. ~JuceCustomUIView()
  175. {
  176. deleteEditorComp();
  177. }
  178. //==============================================================================
  179. void updateSize()
  180. {
  181. if (editorComp == nullptr)
  182. {
  183. editorComp = filter->createEditorIfNeeded();
  184. jassert (editorComp != nullptr);
  185. }
  186. if (editorComp->getWidth() != 0 && editorComp->getHeight() != 0)
  187. {
  188. Rect oldRect;
  189. GetRect (&oldRect);
  190. Rect r;
  191. r.left = 0;
  192. r.top = 0;
  193. r.right = editorComp->getWidth();
  194. r.bottom = editorComp->getHeight();
  195. SetRect (&r);
  196. if ((oldRect.right != r.right) || (oldRect.bottom != r.bottom))
  197. startTimer (50);
  198. }
  199. }
  200. void timerCallback() override
  201. {
  202. if (! juce::Component::isMouseButtonDownAnywhere())
  203. {
  204. stopTimer();
  205. // Send a token to the host to tell it about the resize
  206. SSetProcessWindowResizeToken token (process->fRootNameId, process->fRootNameId);
  207. FicSDSDispatchToken (&token);
  208. }
  209. }
  210. void attachToWindow (GrafPtr port)
  211. {
  212. if (port != 0)
  213. {
  214. JUCE_AUTORELEASEPOOL
  215. {
  216. updateSize();
  217. #if JUCE_WINDOWS
  218. void* const hostWindow = (void*) ASI_GethWnd ((WindowPtr) port);
  219. #else
  220. void* const hostWindow = (void*) GetWindowFromPort (port);
  221. #endif
  222. wrapper = nullptr;
  223. wrapper = new EditorCompWrapper (hostWindow, editorComp, this);
  224. process->touchAllParameters();
  225. }
  226. }
  227. else
  228. {
  229. deleteEditorComp();
  230. }
  231. }
  232. void DrawContents (Rect*)
  233. {
  234. #if JUCE_WINDOWS
  235. if (wrapper != nullptr)
  236. {
  237. if (ComponentPeer* const peer = wrapper->getPeer())
  238. peer->repaint (wrapper->getLocalBounds()); // (seems to be required in PT6.4, but not in 7.x)
  239. }
  240. #endif
  241. }
  242. void DrawBackground (Rect*) {}
  243. //==============================================================================
  244. private:
  245. AudioProcessor* const filter;
  246. JucePlugInProcess* const process;
  247. ScopedPointer<juce::Component> wrapper;
  248. ScopedPointer<AudioProcessorEditor> editorComp;
  249. void deleteEditorComp()
  250. {
  251. if (editorComp != nullptr || wrapper != nullptr)
  252. {
  253. JUCE_AUTORELEASEPOOL
  254. {
  255. PopupMenu::dismissAllActiveMenus();
  256. if (juce::Component* const modalComponent = juce::Component::getCurrentlyModalComponent())
  257. modalComponent->exitModalState (0);
  258. filter->editorBeingDeleted (editorComp);
  259. editorComp = nullptr;
  260. wrapper = nullptr;
  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 juce::Component
  268. #if ! JUCE_MAC
  269. , public FocusChangeListener
  270. #endif
  271. {
  272. public:
  273. EditorCompWrapper (void* const hostWindow_,
  274. Component* const editorComp,
  275. JuceCustomUIView* const 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 (juce::Component* const ed = getEditor())
  314. ed->setBounds (getLocalBounds());
  315. repaint();
  316. }
  317. #if JUCE_WINDOWS
  318. void globalFocusChanged (juce::Component*) override
  319. {
  320. #if ! JucePlugin_EditorRequiresKeyboardFocus
  321. if (hasKeyboardFocus (true))
  322. passFocusToHostWindow (hostWindow);
  323. #endif
  324. }
  325. #endif
  326. void childBoundsChanged (juce::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)
  359. {
  360. if (JuceCustomUIView* const v = getView())
  361. v->updateSize();
  362. CEffectProcessRTAS::GetViewRect (size);
  363. }
  364. CPlugInView* CreateCPlugInView()
  365. {
  366. return new JuceCustomUIView (juceFilter, this);
  367. }
  368. void SetViewPort (GrafPtr port)
  369. {
  370. CEffectProcessRTAS::SetViewPort (port);
  371. if (JuceCustomUIView* const v = getView())
  372. v->attachToWindow (port);
  373. }
  374. //==============================================================================
  375. protected:
  376. ComponentResult GetDelaySamplesLong (long* aNumSamples)
  377. {
  378. if (aNumSamples != nullptr)
  379. *aNumSamples = juceFilter != nullptr ? juceFilter->getLatencySamples() : 0;
  380. return noErr;
  381. }
  382. //==============================================================================
  383. void EffectInit()
  384. {
  385. SFicPlugInStemFormats stems;
  386. GetProcessType()->GetStemFormats (&stems);
  387. juceFilter->setPlayConfigDetails (fNumInputs, fNumOutputs,
  388. juceFilter->getSampleRate(), juceFilter->getBlockSize());
  389. AddControl (new CPluginControl_OnOff ('bypa', "Master Bypass\nMastrByp\nMByp\nByp", false, true));
  390. DefineMasterBypassControlIndex (bypassControlIndex);
  391. for (int i = 0; i < juceFilter->getNumParameters(); ++i)
  392. AddControl (new JucePluginControl (juceFilter, i));
  393. // we need to do this midi log-in to get timecode, regardless of whether
  394. // the plugin actually uses midi...
  395. if (MIDILogIn() == noErr)
  396. {
  397. #if JucePlugin_WantsMidiInput
  398. if (CEffectType* const type = dynamic_cast <CEffectType*> (this->GetProcessType()))
  399. {
  400. char nodeName [64];
  401. type->GetProcessTypeName (63, nodeName);
  402. p2cstrcpy (nodeName, reinterpret_cast <unsigned char*> (nodeName));
  403. midiBufferNode = new CEffectMIDIOtherBufferedNode (&mMIDIWorld,
  404. 8192,
  405. eLocalNode,
  406. nodeName,
  407. midiBuffer);
  408. midiBufferNode->Initialize (0xffff, true);
  409. }
  410. #endif
  411. }
  412. midiTransport = new CEffectMIDITransport (&mMIDIWorld);
  413. juceFilter->setPlayHead (this);
  414. juceFilter->addListener (this);
  415. midiEvents.ensureSize (2048);
  416. }
  417. void handleAsyncUpdate()
  418. {
  419. if (! prepared)
  420. {
  421. sampleRate = gProcessGroup->GetSampleRate();
  422. jassert (sampleRate > 0);
  423. channels.calloc (jmax (juceFilter->getNumInputChannels(),
  424. juceFilter->getNumOutputChannels()));
  425. juceFilter->setPlayConfigDetails (fNumInputs, fNumOutputs,
  426. sampleRate, mRTGlobals->mHWBufferSizeInSamples);
  427. juceFilter->prepareToPlay (sampleRate, mRTGlobals->mHWBufferSizeInSamples);
  428. prepared = true;
  429. }
  430. }
  431. void RenderAudio (float** inputs, float** outputs, long numSamples)
  432. {
  433. if (! prepared)
  434. {
  435. asyncUpdater->triggerAsyncUpdate();
  436. bypassBuffers (inputs, outputs, numSamples);
  437. return;
  438. }
  439. #if JucePlugin_WantsMidiInput
  440. midiEvents.clear();
  441. const Cmn_UInt32 bufferSize = mRTGlobals->mHWBufferSizeInSamples;
  442. if (midiBufferNode != nullptr)
  443. {
  444. if (midiBufferNode->GetAdvanceScheduleTime() != bufferSize)
  445. midiBufferNode->SetAdvanceScheduleTime (bufferSize);
  446. if (midiBufferNode->FillMIDIBuffer (mRTGlobals->mRunningTime, numSamples) == noErr)
  447. {
  448. jassert (midiBufferNode->GetBufferPtr() != nullptr);
  449. const int numMidiEvents = midiBufferNode->GetBufferSize();
  450. for (int i = 0; i < numMidiEvents; ++i)
  451. {
  452. const DirectMidiPacket& m = midiBuffer[i];
  453. jassert ((int) m.mTimestamp < numSamples);
  454. midiEvents.addEvent (m.mData, m.mLength,
  455. jlimit (0, (int) numSamples - 1, (int) m.mTimestamp));
  456. }
  457. }
  458. }
  459. #endif
  460. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  461. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  462. (void) numMidiEventsComingIn;
  463. #endif
  464. {
  465. const ScopedLock sl (juceFilter->getCallbackLock());
  466. const int numIn = juceFilter->getNumInputChannels();
  467. const int numOut = juceFilter->getNumOutputChannels();
  468. const int totalChans = jmax (numIn, numOut);
  469. if (juceFilter->isSuspended())
  470. {
  471. for (int i = 0; i < numOut; ++i)
  472. FloatVectorOperations::clear (outputs [i], numSamples);
  473. }
  474. else
  475. {
  476. {
  477. int i;
  478. for (i = 0; i < numOut; ++i)
  479. {
  480. channels[i] = outputs [i];
  481. if (i < numIn && inputs != outputs)
  482. FloatVectorOperations::copy (outputs [i], inputs[i], numSamples);
  483. }
  484. for (; i < numIn; ++i)
  485. channels [i] = inputs [i];
  486. }
  487. AudioSampleBuffer chans (channels, totalChans, numSamples);
  488. if (mBypassed)
  489. juceFilter->processBlockBypassed (chans, midiEvents);
  490. else
  491. juceFilter->processBlock (chans, midiEvents);
  492. }
  493. }
  494. if (! midiEvents.isEmpty())
  495. {
  496. #if JucePlugin_ProducesMidiOutput
  497. const juce::uint8* midiEventData;
  498. int midiEventSize, midiEventPosition;
  499. MidiBuffer::Iterator i (midiEvents);
  500. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  501. {
  502. //jassert (midiEventPosition >= 0 && midiEventPosition < (int) numSamples);
  503. }
  504. #elif JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  505. // if your plugin creates midi messages, you'll need to set
  506. // the JucePlugin_ProducesMidiOutput macro to 1 in your
  507. // JucePluginCharacteristics.h file
  508. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  509. #endif
  510. midiEvents.clear();
  511. }
  512. }
  513. //==============================================================================
  514. ComponentResult GetChunkSize (OSType chunkID, long* size)
  515. {
  516. if (chunkID == juceChunkType)
  517. {
  518. tempFilterData.setSize (0);
  519. juceFilter->getStateInformation (tempFilterData);
  520. *size = sizeof (SFicPlugInChunkHeader) + tempFilterData.getSize();
  521. return noErr;
  522. }
  523. return CEffectProcessMIDI::GetChunkSize (chunkID, size);
  524. }
  525. ComponentResult GetChunk (OSType chunkID, SFicPlugInChunk* chunk)
  526. {
  527. if (chunkID == juceChunkType)
  528. {
  529. if (tempFilterData.getSize() == 0)
  530. juceFilter->getStateInformation (tempFilterData);
  531. chunk->fSize = sizeof (SFicPlugInChunkHeader) + tempFilterData.getSize();
  532. tempFilterData.copyTo ((void*) chunk->fData, 0, tempFilterData.getSize());
  533. tempFilterData.setSize (0);
  534. return noErr;
  535. }
  536. return CEffectProcessMIDI::GetChunk (chunkID, chunk);
  537. }
  538. ComponentResult SetChunk (OSType chunkID, SFicPlugInChunk* chunk)
  539. {
  540. if (chunkID == juceChunkType)
  541. {
  542. tempFilterData.setSize (0);
  543. if (chunk->fSize - sizeof (SFicPlugInChunkHeader) > 0)
  544. {
  545. juceFilter->setStateInformation ((void*) chunk->fData,
  546. chunk->fSize - sizeof (SFicPlugInChunkHeader));
  547. }
  548. return noErr;
  549. }
  550. return CEffectProcessMIDI::SetChunk (chunkID, chunk);
  551. }
  552. //==============================================================================
  553. ComponentResult UpdateControlValue (long controlIndex, long value)
  554. {
  555. if (controlIndex != bypassControlIndex)
  556. juceFilter->setParameter (controlIndex - 2, longToFloat (value));
  557. else
  558. mBypassed = (value > 0);
  559. return CProcess::UpdateControlValue (controlIndex, value);
  560. }
  561. //==============================================================================
  562. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info)
  563. {
  564. // this method can only be called while the plugin is running
  565. jassert (prepared);
  566. Cmn_Float64 bpm = 120.0;
  567. Cmn_Int32 num = 4, denom = 4;
  568. Cmn_Int64 ticks = 0;
  569. Cmn_Bool isPlaying = false;
  570. if (midiTransport != nullptr)
  571. {
  572. midiTransport->GetCurrentTempo (&bpm);
  573. midiTransport->IsTransportPlaying (&isPlaying);
  574. midiTransport->GetCurrentMeter (&num, &denom);
  575. // (The following is a work-around because GetCurrentTickPosition() doesn't work correctly).
  576. Cmn_Int64 sampleLocation;
  577. if (isPlaying)
  578. midiTransport->GetCurrentRTASSampleLocation (&sampleLocation);
  579. else
  580. midiTransport->GetCurrentTDMSampleLocation (&sampleLocation);
  581. midiTransport->GetCustomTickPosition (&ticks, sampleLocation);
  582. info.timeInSamples = (int64) sampleLocation;
  583. info.timeInSeconds = sampleLocation / sampleRate;
  584. }
  585. else
  586. {
  587. info.timeInSamples = 0;
  588. info.timeInSeconds = 0;
  589. }
  590. info.bpm = bpm;
  591. info.timeSigNumerator = num;
  592. info.timeSigDenominator = denom;
  593. info.isPlaying = isPlaying;
  594. info.isRecording = false;
  595. info.ppqPosition = ticks / 960000.0;
  596. info.ppqPositionOfLastBarStart = 0; //xxx no idea how to get this correctly..
  597. info.isLooping = false;
  598. info.ppqLoopStart = 0;
  599. info.ppqLoopEnd = 0;
  600. double framesPerSec = 24.0;
  601. switch (fTimeCodeInfo.mFrameRate)
  602. {
  603. case ficFrameRate_24Frame: info.frameRate = AudioPlayHead::fps24; break;
  604. case ficFrameRate_25Frame: info.frameRate = AudioPlayHead::fps25; framesPerSec = 25.0; break;
  605. case ficFrameRate_2997NonDrop: info.frameRate = AudioPlayHead::fps2997; framesPerSec = 29.97002997; break;
  606. case ficFrameRate_2997DropFrame: info.frameRate = AudioPlayHead::fps2997drop; framesPerSec = 29.97002997; break;
  607. case ficFrameRate_30NonDrop: info.frameRate = AudioPlayHead::fps30; framesPerSec = 30.0; break;
  608. case ficFrameRate_30DropFrame: info.frameRate = AudioPlayHead::fps30drop; framesPerSec = 30.0; break;
  609. case ficFrameRate_23976: info.frameRate = AudioPlayHead::fps24; framesPerSec = 23.976; break;
  610. default: info.frameRate = AudioPlayHead::fpsUnknown; break;
  611. }
  612. info.editOriginTime = fTimeCodeInfo.mFrameOffset / framesPerSec;
  613. return true;
  614. }
  615. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue)
  616. {
  617. SetControlValue (index + 2, floatToLong (newValue));
  618. }
  619. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index)
  620. {
  621. TouchControl (index + 2);
  622. }
  623. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index)
  624. {
  625. ReleaseControl (index + 2);
  626. }
  627. void audioProcessorChanged (AudioProcessor*)
  628. {
  629. // xxx is there an RTAS equivalent?
  630. }
  631. void touchAllParameters()
  632. {
  633. for (int i = 0; i < juceFilter->getNumParameters(); ++i)
  634. {
  635. audioProcessorParameterChangeGestureBegin (0, i);
  636. audioProcessorParameterChanged (0, i, juceFilter->getParameter (i));
  637. audioProcessorParameterChangeGestureEnd (0, i);
  638. }
  639. }
  640. public:
  641. // Need to use an intermediate class here rather than inheriting from AsyncUpdater, so that it can
  642. // be deleted before shutting down juce in our destructor.
  643. class InternalAsyncUpdater : public AsyncUpdater
  644. {
  645. public:
  646. InternalAsyncUpdater (JucePlugInProcess& owner_) : owner (owner_) {}
  647. void handleAsyncUpdate() { owner.handleAsyncUpdate(); }
  648. private:
  649. JucePlugInProcess& owner;
  650. };
  651. //==============================================================================
  652. private:
  653. ScopedPointer<AudioProcessor> juceFilter;
  654. MidiBuffer midiEvents;
  655. ScopedPointer<CEffectMIDIOtherBufferedNode> midiBufferNode;
  656. ScopedPointer<CEffectMIDITransport> midiTransport;
  657. DirectMidiPacket midiBuffer [midiBufferSize];
  658. ScopedPointer<InternalAsyncUpdater> asyncUpdater;
  659. juce::MemoryBlock tempFilterData;
  660. HeapBlock <float*> channels;
  661. bool prepared;
  662. double sampleRate;
  663. static float longToFloat (const long n) noexcept
  664. {
  665. return (float) ((((double) n) + (double) 0x80000000) / (double) 0xffffffff);
  666. }
  667. static long floatToLong (const float n) noexcept
  668. {
  669. return roundToInt (jlimit (-(double) 0x80000000, (double) 0x7fffffff,
  670. n * (double) 0xffffffff - (double) 0x80000000));
  671. }
  672. void bypassBuffers (float** const inputs, float** const outputs, const long numSamples) const
  673. {
  674. for (int i = fNumOutputs; --i >= 0;)
  675. {
  676. if (i < fNumInputs)
  677. FloatVectorOperations::copy (outputs[i], inputs[i], numSamples);
  678. else
  679. FloatVectorOperations::clear (outputs[i], numSamples);
  680. }
  681. }
  682. //==============================================================================
  683. class JucePluginControl : public CPluginControl
  684. {
  685. public:
  686. //==============================================================================
  687. JucePluginControl (AudioProcessor* const juceFilter_, const int index_)
  688. : juceFilter (juceFilter_),
  689. index (index_)
  690. {
  691. }
  692. //==============================================================================
  693. OSType GetID() const { return index + 1; }
  694. long GetDefaultValue() const { return floatToLong (juceFilter->getParameterDefaultValue (index)); }
  695. void SetDefaultValue (long) {}
  696. long GetNumSteps() const { return juceFilter->getParameterNumSteps (index); }
  697. long ConvertStringToValue (const char* valueString) const
  698. {
  699. return floatToLong (String (valueString).getFloatValue());
  700. }
  701. Cmn_Bool IsKeyValid (long key) const { return true; }
  702. void GetNameOfLength (char* name, int maxLength, OSType inControllerType) const
  703. {
  704. // Pro-tools expects all your parameters to have valid names!
  705. jassert (juceFilter->getParameterName (index).isNotEmpty());
  706. juceFilter->getParameterName (index, maxLength).copyToUTF8 (name, (size_t) maxLength + 1);
  707. }
  708. long GetPriority() const { return kFicCooperativeTaskPriority; }
  709. long GetOrientation() const
  710. {
  711. return kDAE_LeftMinRightMax | kDAE_BottomMinTopMax
  712. | kDAE_RotarySingleDotMode | kDAE_RotaryLeftMinRightMax;
  713. }
  714. long GetControlType() const { return kDAE_ContinuousValues; }
  715. void GetValueString (char* valueString, int maxLength, long value) const
  716. {
  717. juceFilter->getParameterText (index, maxLength).copyToUTF8 (valueString, (size_t) maxLength + 1);
  718. }
  719. Cmn_Bool IsAutomatable() const
  720. {
  721. return juceFilter->isParameterAutomatable (index);
  722. }
  723. private:
  724. //==============================================================================
  725. AudioProcessor* const juceFilter;
  726. const int index;
  727. JUCE_DECLARE_NON_COPYABLE (JucePluginControl)
  728. };
  729. };
  730. //==============================================================================
  731. class JucePlugInGroup : public CEffectGroupMIDI
  732. {
  733. public:
  734. //==============================================================================
  735. JucePlugInGroup()
  736. {
  737. DefineManufacturerNamesAndID (JucePlugin_Manufacturer, JucePlugin_RTASManufacturerCode);
  738. DefinePlugInNamesAndVersion (createRTASName().toUTF8(), JucePlugin_VersionCode);
  739. #if JUCE_RTAS_PLUGINGESTALT_IS_CACHEABLE
  740. AddGestalt (pluginGestalt_IsCacheable);
  741. #endif
  742. }
  743. ~JucePlugInGroup()
  744. {
  745. shutdownJuce_GUI();
  746. }
  747. //==============================================================================
  748. void CreateEffectTypes()
  749. {
  750. const short channelConfigs[][2] = { JucePlugin_PreferredChannelConfigurations };
  751. const int numConfigs = numElementsInArray (channelConfigs);
  752. // You need to actually add some configurations to the JucePlugin_PreferredChannelConfigurations
  753. // value in your JucePluginCharacteristics.h file..
  754. jassert (numConfigs > 0);
  755. for (int i = 0; i < numConfigs; ++i)
  756. {
  757. CEffectType* const type
  758. = new CEffectTypeRTAS ('jcaa' + i,
  759. JucePlugin_RTASProductId,
  760. JucePlugin_RTASCategory);
  761. type->DefineTypeNames (createRTASName().toRawUTF8());
  762. type->DefineSampleRateSupport (eSupports48kAnd96kAnd192k);
  763. type->DefineStemFormats (getFormatForChans (channelConfigs [i][0] != 0 ? channelConfigs [i][0] : channelConfigs [i][1]),
  764. getFormatForChans (channelConfigs [i][1] != 0 ? channelConfigs [i][1] : channelConfigs [i][0]));
  765. #if ! JucePlugin_RTASDisableBypass
  766. type->AddGestalt (pluginGestalt_CanBypass);
  767. #endif
  768. #if JucePlugin_RTASDisableMultiMono
  769. type->AddGestalt (pluginGestalt_DoesntSupportMultiMono);
  770. #endif
  771. type->AddGestalt (pluginGestalt_SupportsVariableQuanta);
  772. type->AttachEffectProcessCreator (createNewProcess);
  773. AddEffectType (type);
  774. }
  775. }
  776. void Initialize()
  777. {
  778. CEffectGroupMIDI::Initialize();
  779. }
  780. //==============================================================================
  781. private:
  782. static CEffectProcess* createNewProcess()
  783. {
  784. #if JUCE_WINDOWS
  785. Process::setCurrentModuleInstanceHandle (gThisModule);
  786. #endif
  787. initialiseJuce_GUI();
  788. return new JucePlugInProcess();
  789. }
  790. static String createRTASName()
  791. {
  792. return String (JucePlugin_Name) + "\n"
  793. + String (JucePlugin_Desc);
  794. }
  795. static EPlugIn_StemFormat getFormatForChans (const int numChans) noexcept
  796. {
  797. switch (numChans)
  798. {
  799. case 0: return ePlugIn_StemFormat_Generic;
  800. case 1: return ePlugIn_StemFormat_Mono;
  801. case 2: return ePlugIn_StemFormat_Stereo;
  802. case 3: return ePlugIn_StemFormat_LCR;
  803. case 4: return ePlugIn_StemFormat_Quad;
  804. case 5: return ePlugIn_StemFormat_5dot0;
  805. case 6: return ePlugIn_StemFormat_5dot1;
  806. #if PT_VERS_MAJOR >= 9
  807. case 7: return ePlugIn_StemFormat_7dot0DTS;
  808. case 8: return ePlugIn_StemFormat_7dot1DTS;
  809. #else
  810. case 7: return ePlugIn_StemFormat_7dot0;
  811. case 8: return ePlugIn_StemFormat_7dot1;
  812. #endif
  813. default: jassertfalse; break; // hmm - not a valid number of chans for RTAS..
  814. }
  815. return ePlugIn_StemFormat_Generic;
  816. }
  817. };
  818. void initialiseMacRTAS();
  819. CProcessGroupInterface* CProcessGroup::CreateProcessGroup()
  820. {
  821. #if JUCE_MAC
  822. initialiseMacRTAS();
  823. #endif
  824. return new JucePlugInGroup();
  825. }
  826. #endif