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.

1003 lines
35KB

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