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.

1119 lines
37KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. #include "juce_RTASCompileFlags.h"
  24. #ifdef _MSC_VER
  25. // the Digidesign projects all use a struct alignment of 2..
  26. #pragma pack (2)
  27. #pragma warning (disable: 4267)
  28. #include "ForcedInclude.h"
  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_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\EffectClasses
  36. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\ProcessClasses
  37. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\ProcessClasses\Interfaces
  38. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Utilities
  39. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\RTASP_Adapt
  40. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\CoreClasses
  41. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Controls
  42. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Meters
  43. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\ViewClasses
  44. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\DSPClasses
  45. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\PluginLibrary\Interfaces
  46. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\common
  47. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\common\Platform
  48. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugins\SignalProcessing\Public
  49. c:\yourdirectory\PT_711_SDK\AlturaPorts\TDMPlugIns\DSPManager\Interfaces
  50. c:\yourdirectory\PT_711_SDK\AlturaPorts\SADriver\Interfaces
  51. c:\yourdirectory\PT_711_SDK\AlturaPorts\DigiPublic\Interfaces
  52. c:\yourdirectory\PT_711_SDK\AlturaPorts\Fic\Interfaces\DAEClient
  53. c:\yourdirectory\PT_711_SDK\AlturaPorts\NewFileLibs\Cmn
  54. c:\yourdirectory\PT_711_SDK\AlturaPorts\NewFileLibs\DOA
  55. c:\yourdirectory\PT_711_SDK\AlturaPorts\AlturaSource\PPC_H
  56. c:\yourdirectory\PT_711_SDK\AlturaPorts\AlturaSource\AppSupport
  57. */
  58. #include "CEffectGroupMIDI.h"
  59. #include "CEffectProcessMIDI.h"
  60. #include "CEffectProcessRTAS.h"
  61. #include "CCustomView.h"
  62. #include "CEffectTypeRTAS.h"
  63. #include "CPluginControl.h"
  64. #include "CPluginControl_OnOff.h"
  65. #include "FicProcessTokens.h"
  66. //==============================================================================
  67. #ifdef _MSC_VER
  68. #pragma pack (push, 8)
  69. #endif
  70. #include "../../../../../juce.h"
  71. #include "../../juce_IncludeCharacteristics.h"
  72. #ifdef _MSC_VER
  73. #pragma pack (pop)
  74. #endif
  75. #undef Component
  76. #undef MemoryBlock
  77. //==============================================================================
  78. #if JUCE_WIN32
  79. extern void JUCE_CALLTYPE attachSubWindow (void* hostWindow, int& titleW, int& titleH, juce::Component* comp);
  80. extern void JUCE_CALLTYPE resizeHostWindow (void* hostWindow, int& titleW, int& titleH, juce::Component* comp);
  81. #if ! JucePlugin_EditorRequiresKeyboardFocus
  82. extern void JUCE_CALLTYPE passFocusToHostWindow (void* hostWindow);
  83. #endif
  84. #endif
  85. const int midiBufferSize = 1024;
  86. const OSType juceChunkType = 'juce';
  87. static const int bypassControlIndex = 1;
  88. //==============================================================================
  89. /** Somewhere in the codebase of your plugin, you need to implement this function
  90. and make it return a new instance of the filter subclass that you're building.
  91. */
  92. extern AudioProcessor* JUCE_CALLTYPE createPluginFilter();
  93. //==============================================================================
  94. static float longToFloat (const long n) throw()
  95. {
  96. return (float) ((((double) n) + (double) 0x80000000) / (double) 0xffffffff);
  97. }
  98. static long floatToLong (const float n) throw()
  99. {
  100. return roundDoubleToInt (jlimit (-(double) 0x80000000,
  101. (double) 0x7fffffff,
  102. n * (double) 0xffffffff - (double) 0x80000000));
  103. }
  104. static int numInstances = 0;
  105. //==============================================================================
  106. class JucePlugInProcess : public CEffectProcessMIDI,
  107. public CEffectProcessRTAS,
  108. public AudioProcessorListener,
  109. public AudioPlayHead,
  110. public AsyncUpdater
  111. {
  112. public:
  113. //==============================================================================
  114. JucePlugInProcess()
  115. : channels (0),
  116. prepared (false),
  117. midiBufferNode (0),
  118. midiTransport (0),
  119. sampleRate (44100.0)
  120. {
  121. juceFilter = createPluginFilter();
  122. jassert (juceFilter != 0);
  123. AddChunk (juceChunkType, "Juce Audio Plugin Data");
  124. ++numInstances;
  125. }
  126. ~JucePlugInProcess()
  127. {
  128. if (mLoggedIn)
  129. MIDILogOut();
  130. deleteAndZero (midiBufferNode);
  131. deleteAndZero (midiTransport);
  132. if (prepared)
  133. juceFilter->releaseResources();
  134. delete juceFilter;
  135. juce_free (channels);
  136. if (--numInstances == 0)
  137. shutdownJuce_GUI();
  138. }
  139. //==============================================================================
  140. class JuceCustomUIView : public CCustomView,
  141. public Timer
  142. {
  143. public:
  144. //==============================================================================
  145. JuceCustomUIView (AudioProcessor* const filter_,
  146. JucePlugInProcess* const process_)
  147. : filter (filter_),
  148. process (process_),
  149. editorComp (0),
  150. wrapper (0)
  151. {
  152. // setting the size in here crashes PT for some reason, so keep it simple..
  153. }
  154. ~JuceCustomUIView()
  155. {
  156. deleteEditorComp();
  157. }
  158. //==============================================================================
  159. void updateSize()
  160. {
  161. if (editorComp == 0)
  162. {
  163. editorComp = filter->createEditorIfNeeded();
  164. jassert (editorComp != 0);
  165. }
  166. Rect oldRect;
  167. GetRect (&oldRect);
  168. Rect r;
  169. r.left = 0;
  170. r.top = 0;
  171. r.right = editorComp->getWidth();
  172. r.bottom = editorComp->getHeight();
  173. SetRect (&r);
  174. if ((oldRect.right != r.right) || (oldRect.bottom != r.bottom))
  175. startTimer (50);
  176. }
  177. void timerCallback()
  178. {
  179. if (! JUCE_NAMESPACE::Component::isMouseButtonDownAnywhere())
  180. {
  181. stopTimer();
  182. // Send a token to the host to tell it about the resize
  183. SSetProcessWindowResizeToken token (process->fRootNameId, process->fRootNameId);
  184. FicSDSDispatchToken (&token);
  185. }
  186. }
  187. void attachToWindow (GrafPtr port)
  188. {
  189. if (port != 0)
  190. {
  191. updateSize();
  192. #if JUCE_WIN32
  193. void* const hostWindow = (void*) ASI_GethWnd ((WindowPtr) port);
  194. #else
  195. void* const hostWindow = (void*) GetWindowFromPort (port);
  196. #endif
  197. deleteAndZero (wrapper);
  198. wrapper = new EditorCompWrapper (hostWindow, editorComp, this);
  199. }
  200. else
  201. {
  202. deleteEditorComp();
  203. }
  204. }
  205. void DrawContents (Rect*)
  206. {
  207. if (wrapper != 0)
  208. {
  209. ComponentPeer* const peer = wrapper->getPeer();
  210. if (peer != 0)
  211. {
  212. #if JUCE_WIN32
  213. // (seems to be required in PT6.4, but not in 7.x)
  214. peer->repaint (0, 0, wrapper->getWidth(), wrapper->getHeight());
  215. #elif JUCE_PPC
  216. // This crap is needed because if you resize a window, PT doesn't
  217. // update its clip region, so only part of your new window gets drawn.
  218. // This overrides the clipping region that's being passed into the Draw
  219. // method.
  220. Rect visible;
  221. GetVisibleRect (&visible);
  222. RestoreFocus();
  223. Focus (&visible);
  224. #endif
  225. peer->performAnyPendingRepaintsNow();
  226. }
  227. }
  228. }
  229. void DrawBackground (Rect* r)
  230. {
  231. }
  232. //==============================================================================
  233. private:
  234. AudioProcessor* const filter;
  235. JucePlugInProcess* const process;
  236. juce::Component* wrapper;
  237. AudioProcessorEditor* editorComp;
  238. void deleteEditorComp()
  239. {
  240. if (editorComp != 0)
  241. {
  242. PopupMenu::dismissAllActiveMenus();
  243. juce::Component* const modalComponent = juce::Component::getCurrentlyModalComponent();
  244. if (modalComponent != 0)
  245. modalComponent->exitModalState (0);
  246. filter->editorBeingDeleted (editorComp);
  247. deleteAndZero (editorComp);
  248. deleteAndZero (wrapper);
  249. }
  250. }
  251. //==============================================================================
  252. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  253. // chores when it changes or repaints.
  254. class EditorCompWrapper : public juce::Component,
  255. #if JUCE_MAC
  256. public Timer
  257. #else
  258. public FocusChangeListener
  259. #endif
  260. {
  261. public:
  262. EditorCompWrapper (void* const hostWindow_,
  263. AudioProcessorEditor* const editorComp,
  264. JuceCustomUIView* const owner_)
  265. : hostWindow (hostWindow_),
  266. owner (owner_),
  267. titleW (0),
  268. titleH (0)
  269. #if JUCE_MAC
  270. , forcedRepaintTimer (0)
  271. #endif
  272. {
  273. #if ! JucePlugin_EditorRequiresKeyboardFocus
  274. setWantsKeyboardFocus (false);
  275. #endif
  276. setOpaque (true);
  277. setBroughtToFrontOnMouseClick (true);
  278. setBounds (editorComp->getBounds());
  279. editorComp->setTopLeftPosition (0, 0);
  280. addAndMakeVisible (editorComp);
  281. #if JUCE_WIN32
  282. attachSubWindow (hostWindow, titleW, titleH, this);
  283. setVisible (true);
  284. #else
  285. SetAutomaticControlDragTrackingEnabledForWindow ((WindowRef) hostWindow_, true);
  286. WindowAttributes attributes;
  287. GetWindowAttributes ((WindowRef) hostWindow_, &attributes);
  288. parentView = 0;
  289. if ((attributes & kWindowCompositingAttribute) != 0)
  290. {
  291. HIViewRef root = HIViewGetRoot ((WindowRef) hostWindow_);
  292. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  293. if (parentView == 0)
  294. parentView = root;
  295. }
  296. else
  297. {
  298. GetRootControl ((WindowRef) hostWindow_, (ControlRef*) &parentView);
  299. if (parentView == 0)
  300. CreateRootControl ((WindowRef) hostWindow_, (ControlRef*) &parentView);
  301. }
  302. jassert (parentView != 0);
  303. Rect clientRect;
  304. GetWindowBounds ((WindowRef) hostWindow, kWindowContentRgn, &clientRect);
  305. titleW = clientRect.right - clientRect.left;
  306. titleH = jmax (0, (clientRect.bottom - clientRect.top) - getHeight());
  307. setTopLeftPosition (0, 0);
  308. HIViewSetNeedsDisplay (parentView, true);
  309. setVisible (true);
  310. addToDesktop (ComponentPeer::windowRepaintedExplictly, (void*) parentView);
  311. HIViewRef pluginView = HIViewGetFirstSubview (parentView);
  312. #if ! JucePlugin_EditorRequiresKeyboardFocus
  313. HIViewSetActivated (pluginView, false);
  314. #endif
  315. /* This is a convoluted and desperate workaround for a Digi (or maybe Apple)
  316. layout bug. Until the parent control gets some kind of mouse-move
  317. event, then our plugin's HIView remains stuck at (0, 0) in the
  318. window (despite drawing correctly), which blocks mouse events from
  319. getting to the widgets above it.
  320. After days of frustration the only hack I can find that works
  321. is to use this arcane function to redirect mouse events to
  322. the parent, while running a timer to spot the moment when our
  323. view mysteriously snaps back to its correct location.
  324. If anyone at Digi or Apple is reading this and they realise that it's
  325. their fault, could they please give me back the week of my life that
  326. they made me waste on this rubbish. Thankyou.
  327. */
  328. SetControlSupervisor (pluginView, parentView);
  329. startTimer (150);
  330. #endif
  331. #if JUCE_WIN32 && ! JucePlugin_EditorRequiresKeyboardFocus
  332. Desktop::getInstance().addFocusChangeListener (this);
  333. #endif
  334. }
  335. ~EditorCompWrapper()
  336. {
  337. #if JUCE_WIN32 && ! JucePlugin_EditorRequiresKeyboardFocus
  338. Desktop::getInstance().removeFocusChangeListener (this);
  339. #endif
  340. #if JUCE_MAC
  341. delete forcedRepaintTimer;
  342. #endif
  343. }
  344. void paint (Graphics&)
  345. {
  346. #if JUCE_MAC
  347. if (forcedRepaintTimer != 0)
  348. forcedRepaintTimer->stopTimer();
  349. #endif
  350. }
  351. void resized()
  352. {
  353. juce::Component* const c = getChildComponent (0);
  354. if (c != 0)
  355. c->setBounds (0, 0, getWidth(), getHeight());
  356. repaint();
  357. }
  358. #if JUCE_MAC
  359. void timerCallback()
  360. {
  361. // Wait for the moment when PT deigns to allow our view to
  362. // take up its actual location (see rant above)
  363. HIViewRef content = 0;
  364. HIViewFindByID (HIViewGetRoot ((WindowRef) hostWindow), kHIViewWindowContentID, &content);
  365. HIPoint p = { 0.0f, 0.0f };
  366. HIViewRef v = HIViewGetFirstSubview (parentView);
  367. HIViewConvertPoint (&p, v, content);
  368. if (p.y > 12)
  369. {
  370. HIViewRef v = HIViewGetFirstSubview (parentView);
  371. SetControlSupervisor (v, 0);
  372. stopTimer();
  373. forcedRepaintTimer = new RepaintCheckTimer (*this);
  374. }
  375. }
  376. #endif
  377. #if JUCE_WIN32
  378. void globalFocusChanged (juce::Component*)
  379. {
  380. #if ! JucePlugin_EditorRequiresKeyboardFocus
  381. if (hasKeyboardFocus (true))
  382. passFocusToHostWindow (hostWindow);
  383. #endif
  384. }
  385. #endif
  386. void childBoundsChanged (juce::Component* child)
  387. {
  388. setSize (child->getWidth(), child->getHeight());
  389. child->setTopLeftPosition (0, 0);
  390. #if JUCE_WIN32
  391. resizeHostWindow (hostWindow, titleW, titleH, this);
  392. owner->updateSize();
  393. #else
  394. Rect r;
  395. GetWindowBounds ((WindowRef) hostWindow, kWindowContentRgn, &r);
  396. HIRect p;
  397. zerostruct (p);
  398. HIViewConvertRect (&p, parentView, 0); // find the X position of our view in case there's space to the left of it
  399. r.right = r.left + jmax (titleW, ((int) p.origin.x) + getWidth());
  400. r.bottom = r.top + getHeight() + titleH;
  401. SetWindowBounds ((WindowRef) hostWindow, kWindowContentRgn, &r);
  402. owner->updateSize();
  403. owner->Invalidate();
  404. #endif
  405. }
  406. //==============================================================================
  407. juce_UseDebuggingNewOperator
  408. #if JUCE_MAC
  409. protected:
  410. void internalRepaint (int x, int y, int w, int h)
  411. {
  412. Component::internalRepaint (x, y, w, h);
  413. owner->Invalidate();
  414. if (forcedRepaintTimer != 0 && ! forcedRepaintTimer->isTimerRunning())
  415. forcedRepaintTimer->startTimer (1000 / 25);
  416. }
  417. HIViewRef parentView;
  418. #endif
  419. private:
  420. void* const hostWindow;
  421. JuceCustomUIView* const owner;
  422. int titleW, titleH;
  423. #if JUCE_MAC
  424. // if PT makes us wait too long for a redraw after we've
  425. // asked for one, this should kick in and force one to happen
  426. class RepaintCheckTimer : public Timer
  427. {
  428. public:
  429. RepaintCheckTimer (EditorCompWrapper& owner_)
  430. : owner (owner_)
  431. {
  432. }
  433. void timerCallback()
  434. {
  435. stopTimer();
  436. ComponentPeer* const peer = owner.getPeer();
  437. if (peer != 0)
  438. peer->performAnyPendingRepaintsNow();
  439. }
  440. EditorCompWrapper& owner;
  441. };
  442. RepaintCheckTimer* forcedRepaintTimer;
  443. #endif
  444. };
  445. };
  446. JuceCustomUIView* getView() const
  447. {
  448. return dynamic_cast <JuceCustomUIView*> (fOurPlugInView);
  449. }
  450. void GetViewRect (Rect* size)
  451. {
  452. if (getView() != 0)
  453. getView()->updateSize();
  454. CEffectProcessRTAS::GetViewRect (size);
  455. }
  456. CPlugInView* CreateCPlugInView()
  457. {
  458. return new JuceCustomUIView (juceFilter, this);
  459. }
  460. void SetViewPort (GrafPtr port)
  461. {
  462. CEffectProcessRTAS::SetViewPort (port);
  463. if (getView() != 0)
  464. getView()->attachToWindow (port);
  465. }
  466. //==============================================================================
  467. protected:
  468. ComponentResult GetDelaySamplesLong (long* aNumSamples)
  469. {
  470. if (aNumSamples != 0)
  471. *aNumSamples = juceFilter != 0 ? juceFilter->getLatencySamples() : 0;
  472. return noErr;
  473. }
  474. //==============================================================================
  475. void EffectInit()
  476. {
  477. SFicPlugInStemFormats stems;
  478. GetProcessType()->GetStemFormats (&stems);
  479. juceFilter->setPlayConfigDetails (fNumInputs, fNumOutputs,
  480. juceFilter->getSampleRate(), juceFilter->getBlockSize());
  481. AddControl (new CPluginControl_OnOff ('bypa', "Master Bypass\nMastrByp\nMByp\nByp", false, true));
  482. DefineMasterBypassControlIndex (bypassControlIndex);
  483. for (int i = 0; i < juceFilter->getNumParameters(); ++i)
  484. AddControl (new JucePluginControl (juceFilter, i));
  485. // we need to do this midi log-in to get timecode, regardless of whether
  486. // the plugin actually uses midi...
  487. if (MIDILogIn() == noErr)
  488. {
  489. #if JucePlugin_WantsMidiInput
  490. CEffectType* const type = dynamic_cast <CEffectType*> (this->GetProcessType());
  491. if (type != 0)
  492. {
  493. char nodeName [64];
  494. type->GetProcessTypeName (63, nodeName);
  495. p2cstrcpy (nodeName, reinterpret_cast <unsigned char*> (nodeName));
  496. midiBufferNode = new CEffectMIDIOtherBufferedNode (&mMIDIWorld,
  497. 8192,
  498. eLocalNode,
  499. nodeName,
  500. midiBuffer);
  501. midiBufferNode->Initialize (1, true);
  502. }
  503. #endif
  504. }
  505. midiTransport = new CEffectMIDITransport (&mMIDIWorld);
  506. juceFilter->setPlayHead (this);
  507. juceFilter->addListener (this);
  508. }
  509. void handleAsyncUpdate()
  510. {
  511. if (! prepared)
  512. {
  513. sampleRate = gProcessGroup->GetSampleRate();
  514. jassert (sampleRate > 0);
  515. juce_free (channels);
  516. channels = (float**) juce_calloc (sizeof (float*) * jmax (juceFilter->getNumInputChannels(),
  517. juceFilter->getNumOutputChannels()));
  518. juceFilter->setPlayConfigDetails (fNumInputs, fNumOutputs,
  519. sampleRate, mRTGlobals->mHWBufferSizeInSamples);
  520. juceFilter->prepareToPlay (sampleRate,
  521. mRTGlobals->mHWBufferSizeInSamples);
  522. prepared = true;
  523. }
  524. }
  525. void RenderAudio (float** inputs, float** outputs, long numSamples)
  526. {
  527. if (! prepared)
  528. {
  529. triggerAsyncUpdate();
  530. bypassBuffers (inputs, outputs, numSamples);
  531. return;
  532. }
  533. if (mBypassed)
  534. {
  535. bypassBuffers (inputs, outputs, numSamples);
  536. return;
  537. }
  538. #if JucePlugin_WantsMidiInput
  539. midiEvents.clear();
  540. const Cmn_UInt32 bufferSize = mRTGlobals->mHWBufferSizeInSamples;
  541. if (midiBufferNode->GetAdvanceScheduleTime() != bufferSize)
  542. midiBufferNode->SetAdvanceScheduleTime (bufferSize);
  543. if (midiBufferNode->FillMIDIBuffer (mRTGlobals->mRunningTime, numSamples) == noErr)
  544. {
  545. jassert (midiBufferNode->GetBufferPtr() != 0);
  546. const int numMidiEvents = midiBufferNode->GetBufferSize();
  547. for (int i = 0; i < numMidiEvents; ++i)
  548. {
  549. const DirectMidiPacket& m = midiBuffer[i];
  550. jassert ((int) m.mTimestamp < numSamples);
  551. midiEvents.addEvent (m.mData, m.mLength,
  552. jlimit (0, (int) numSamples - 1, (int) m.mTimestamp));
  553. }
  554. }
  555. #endif
  556. #if defined (JUCE_DEBUG) || JUCE_LOG_ASSERTIONS
  557. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  558. #endif
  559. {
  560. const ScopedLock sl (juceFilter->getCallbackLock());
  561. const int numIn = juceFilter->getNumInputChannels();
  562. const int numOut = juceFilter->getNumOutputChannels();
  563. const int totalChans = jmax (numIn, numOut);
  564. if (juceFilter->isSuspended())
  565. {
  566. for (int i = 0; i < numOut; ++i)
  567. zeromem (outputs [i], sizeof (float) * numSamples);
  568. }
  569. else
  570. {
  571. {
  572. int i;
  573. for (i = 0; i < numOut; ++i)
  574. {
  575. channels[i] = outputs [i];
  576. if (i < numIn && inputs != outputs)
  577. memcpy (outputs [i], inputs[i], sizeof (float) * numSamples);
  578. }
  579. for (; i < numIn; ++i)
  580. channels [i] = inputs [i];
  581. }
  582. AudioSampleBuffer chans (channels, totalChans, numSamples);
  583. juceFilter->processBlock (chans, midiEvents);
  584. }
  585. }
  586. if (! midiEvents.isEmpty())
  587. {
  588. #if JucePlugin_ProducesMidiOutput
  589. const uint8* midiEventData;
  590. int midiEventSize, midiEventPosition;
  591. MidiBuffer::Iterator i (midiEvents);
  592. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  593. {
  594. // jassert (midiEventPosition >= 0 && midiEventPosition < (int) numSamples);
  595. //xxx
  596. }
  597. #else
  598. // if your plugin creates midi messages, you'll need to set
  599. // the JucePlugin_ProducesMidiOutput macro to 1 in your
  600. // JucePluginCharacteristics.h file
  601. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  602. #endif
  603. midiEvents.clear();
  604. }
  605. }
  606. //==============================================================================
  607. ComponentResult GetChunkSize (OSType chunkID, long* size)
  608. {
  609. if (chunkID == juceChunkType)
  610. {
  611. tempFilterData.setSize (0);
  612. juceFilter->getStateInformation (tempFilterData);
  613. *size = sizeof (SFicPlugInChunkHeader) + tempFilterData.getSize();
  614. return noErr;
  615. }
  616. return CEffectProcessMIDI::GetChunkSize (chunkID, size);
  617. }
  618. ComponentResult GetChunk (OSType chunkID, SFicPlugInChunk* chunk)
  619. {
  620. if (chunkID == juceChunkType)
  621. {
  622. if (tempFilterData.getSize() == 0)
  623. juceFilter->getStateInformation (tempFilterData);
  624. chunk->fSize = sizeof (SFicPlugInChunkHeader) + tempFilterData.getSize();
  625. tempFilterData.copyTo ((void*) chunk->fData, 0, tempFilterData.getSize());
  626. tempFilterData.setSize (0);
  627. return noErr;
  628. }
  629. return CEffectProcessMIDI::GetChunk (chunkID, chunk);
  630. }
  631. ComponentResult SetChunk (OSType chunkID, SFicPlugInChunk* chunk)
  632. {
  633. if (chunkID == juceChunkType)
  634. {
  635. tempFilterData.setSize (0);
  636. if (chunk->fSize - sizeof (SFicPlugInChunkHeader) > 0)
  637. {
  638. juceFilter->setStateInformation ((void*) chunk->fData,
  639. chunk->fSize - sizeof (SFicPlugInChunkHeader));
  640. }
  641. return noErr;
  642. }
  643. return CEffectProcessMIDI::SetChunk (chunkID, chunk);
  644. }
  645. //==============================================================================
  646. ComponentResult UpdateControlValue (long controlIndex, long value)
  647. {
  648. if (controlIndex != bypassControlIndex)
  649. juceFilter->setParameter (controlIndex - 2, longToFloat (value));
  650. else
  651. mBypassed = (value > 0);
  652. return CProcess::UpdateControlValue (controlIndex, value);
  653. }
  654. //==============================================================================
  655. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info)
  656. {
  657. // this method can only be called while the plugin is running
  658. jassert (prepared);
  659. Cmn_Float64 bpm = 120.0;
  660. Cmn_Int32 num = 4, denom = 4;
  661. Cmn_Int64 ticks = 0;
  662. Cmn_Bool isPlaying = false;
  663. if (midiTransport != 0)
  664. {
  665. midiTransport->GetCurrentTempo (&bpm);
  666. midiTransport->IsTransportPlaying (&isPlaying);
  667. midiTransport->GetCurrentMeter (&num, &denom);
  668. midiTransport->GetCurrentTickPosition (&ticks);
  669. }
  670. info.bpm = bpm;
  671. info.timeSigNumerator = num;
  672. info.timeSigDenominator = denom;
  673. info.isPlaying = isPlaying;
  674. info.isRecording = false;
  675. info.ppqPosition = ticks / 960000.0;
  676. info.ppqPositionOfLastBarStart = 0; //xxx no idea how to get this correctly..
  677. // xxx incorrect if there are tempo changes, but there's no
  678. // other way of getting this info..
  679. info.timeInSeconds = ticks * (60.0 / 960000.0) / bpm;
  680. double framesPerSec = 24.0;
  681. switch (fTimeCodeInfo.mFrameRate)
  682. {
  683. case ficFrameRate_24Frame:
  684. info.frameRate = AudioPlayHead::fps24;
  685. break;
  686. case ficFrameRate_25Frame:
  687. info.frameRate = AudioPlayHead::fps25;
  688. framesPerSec = 25.0;
  689. break;
  690. case ficFrameRate_2997NonDrop:
  691. info.frameRate = AudioPlayHead::fps2997;
  692. framesPerSec = 29.97002997;
  693. break;
  694. case ficFrameRate_2997DropFrame:
  695. info.frameRate = AudioPlayHead::fps2997drop;
  696. framesPerSec = 29.97002997;
  697. break;
  698. case ficFrameRate_30NonDrop:
  699. info.frameRate = AudioPlayHead::fps30;
  700. framesPerSec = 30.0;
  701. break;
  702. case ficFrameRate_30DropFrame:
  703. info.frameRate = AudioPlayHead::fps30drop;
  704. framesPerSec = 30.0;
  705. break;
  706. case ficFrameRate_23976:
  707. // xxx not strictly true..
  708. info.frameRate = AudioPlayHead::fps24;
  709. framesPerSec = 23.976;
  710. break;
  711. default:
  712. info.frameRate = AudioPlayHead::fpsUnknown;
  713. break;
  714. }
  715. info.editOriginTime = fTimeCodeInfo.mFrameOffset / framesPerSec;
  716. return true;
  717. }
  718. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue)
  719. {
  720. SetControlValue (index + 2, floatToLong (newValue));
  721. }
  722. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index)
  723. {
  724. TouchControl (index + 2);
  725. }
  726. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index)
  727. {
  728. ReleaseControl (index + 2);
  729. }
  730. void audioProcessorChanged (AudioProcessor*)
  731. {
  732. // xxx is there an RTAS equivalent?
  733. }
  734. //==============================================================================
  735. private:
  736. AudioProcessor* juceFilter;
  737. MidiBuffer midiEvents;
  738. CEffectMIDIOtherBufferedNode* midiBufferNode;
  739. CEffectMIDITransport* midiTransport;
  740. DirectMidiPacket midiBuffer [midiBufferSize];
  741. JUCE_NAMESPACE::MemoryBlock tempFilterData;
  742. float** channels;
  743. bool prepared;
  744. double sampleRate;
  745. void bypassBuffers (float** const inputs, float** const outputs, const long numSamples) const
  746. {
  747. for (int i = fNumOutputs; --i >= 0;)
  748. {
  749. if (i < fNumInputs)
  750. memcpy (outputs[i], inputs[i], numSamples * sizeof (float));
  751. else
  752. zeromem (outputs[i], numSamples * sizeof (float));
  753. }
  754. }
  755. //==============================================================================
  756. class JucePluginControl : public CPluginControl
  757. {
  758. public:
  759. //==============================================================================
  760. JucePluginControl (AudioProcessor* const juceFilter_, const int index_)
  761. : juceFilter (juceFilter_),
  762. index (index_)
  763. {
  764. }
  765. ~JucePluginControl()
  766. {
  767. }
  768. //==============================================================================
  769. OSType GetID() const { return index + 1; }
  770. long GetDefaultValue() const { return floatToLong (0); }
  771. void SetDefaultValue (long) {}
  772. long GetNumSteps() const { return 0xffffffff; }
  773. long ConvertStringToValue (const char* valueString) const
  774. {
  775. return floatToLong (String (valueString).getFloatValue());
  776. }
  777. Cmn_Bool IsKeyValid (long key) const { return true; }
  778. void GetNameOfLength (char* name, int maxLength, OSType inControllerType) const
  779. {
  780. juceFilter->getParameterName (index).copyToBuffer (name, maxLength);
  781. }
  782. long GetPriority() const { return kFicCooperativeTaskPriority; }
  783. long GetOrientation() const
  784. {
  785. return kDAE_LeftMinRightMax | kDAE_BottomMinTopMax
  786. | kDAE_RotarySingleDotMode | kDAE_RotaryLeftMinRightMax;
  787. }
  788. long GetControlType() const { return kDAE_ContinuousValues; }
  789. void GetValueString (char* valueString, int maxLength, long value) const
  790. {
  791. juceFilter->getParameterText (index).copyToBuffer (valueString, maxLength);
  792. }
  793. Cmn_Bool IsAutomatable() const
  794. {
  795. return juceFilter->isParameterAutomatable (index);
  796. }
  797. private:
  798. //==============================================================================
  799. AudioProcessor* const juceFilter;
  800. const int index;
  801. JucePluginControl (const JucePluginControl&);
  802. const JucePluginControl& operator= (const JucePluginControl&);
  803. };
  804. };
  805. //==============================================================================
  806. class JucePlugInGroup : public CEffectGroupMIDI
  807. {
  808. public:
  809. //==============================================================================
  810. JucePlugInGroup()
  811. {
  812. DefineManufacturerNamesAndID (JucePlugin_Manufacturer, JucePlugin_RTASManufacturerCode);
  813. DefinePlugInNamesAndVersion (createRTASName(), JucePlugin_VersionCode);
  814. #ifndef JUCE_DEBUG
  815. AddGestalt (pluginGestalt_IsCacheable);
  816. #endif
  817. }
  818. ~JucePlugInGroup()
  819. {
  820. shutdownJuce_GUI();
  821. shutdownJuce_NonGUI();
  822. }
  823. //==============================================================================
  824. void CreateEffectTypes()
  825. {
  826. const short channelConfigs[][2] = { JucePlugin_PreferredChannelConfigurations };
  827. const int numConfigs = numElementsInArray (channelConfigs);
  828. // You need to actually add some configurations to the JucePlugin_PreferredChannelConfigurations
  829. // value in your JucePluginCharacteristics.h file..
  830. jassert (numConfigs > 0);
  831. for (int i = 0; i < numConfigs; ++i)
  832. {
  833. CEffectType* const type
  834. = new CEffectTypeRTAS ('jcaa' + i,
  835. JucePlugin_RTASProductId,
  836. JucePlugin_RTASCategory);
  837. type->DefineTypeNames (createRTASName());
  838. type->DefineSampleRateSupport (eSupports48kAnd96kAnd192k);
  839. type->DefineStemFormats (getFormatForChans (channelConfigs [i][0]),
  840. getFormatForChans (channelConfigs [i][1]));
  841. type->AddGestalt (pluginGestalt_CanBypass);
  842. type->AddGestalt (pluginGestalt_SupportsVariableQuanta);
  843. type->AttachEffectProcessCreator (createNewProcess);
  844. AddEffectType (type);
  845. }
  846. }
  847. void Initialize()
  848. {
  849. CEffectGroupMIDI::Initialize();
  850. }
  851. //==============================================================================
  852. private:
  853. static CEffectProcess* createNewProcess()
  854. {
  855. // Juce setup
  856. #if JUCE_WIN32
  857. PlatformUtilities::setCurrentModuleInstanceHandle (gThisModule);
  858. #endif
  859. initialiseJuce_GUI();
  860. return new JucePlugInProcess();
  861. }
  862. static const String createRTASName()
  863. {
  864. return String (JucePlugin_Name) + T("\n")
  865. + String (JucePlugin_Name).substring (0, 4);
  866. }
  867. static EPlugIn_StemFormat getFormatForChans (const int numChans) throw()
  868. {
  869. switch (numChans)
  870. {
  871. case 0:
  872. return ePlugIn_StemFormat_Generic;
  873. case 1:
  874. return ePlugIn_StemFormat_Mono;
  875. case 2:
  876. return ePlugIn_StemFormat_Stereo;
  877. case 3:
  878. return ePlugIn_StemFormat_LCR;
  879. case 4:
  880. return ePlugIn_StemFormat_Quad;
  881. case 5:
  882. return ePlugIn_StemFormat_5dot0;
  883. case 6:
  884. return ePlugIn_StemFormat_5dot1;
  885. case 7:
  886. return ePlugIn_StemFormat_6dot1;
  887. case 8:
  888. return ePlugIn_StemFormat_7dot1;
  889. default:
  890. jassertfalse // hmm - not a valid number of chans for RTAS..
  891. break;
  892. }
  893. return ePlugIn_StemFormat_Generic;
  894. }
  895. };
  896. CProcessGroupInterface* CProcessGroup::CreateProcessGroup()
  897. {
  898. initialiseJuce_NonGUI();
  899. return new JucePlugInGroup();
  900. }