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.

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