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.

1009 lines
35KB

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