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.

1557 lines
45KB

  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. /*
  24. *** DON'T EDIT THIS FILE!! ***
  25. The idea is that everyone's plugins should share this same wrapper
  26. code, so if you start hacking around in here you're missing the point!
  27. If there's a bug or a function you need that can't be done without changing
  28. some of the code in here, give me a shout so we can add it to the library,
  29. rather than branching off and going it alone!
  30. */
  31. //==============================================================================
  32. #ifdef _MSC_VER
  33. #pragma warning (disable : 4996)
  34. #endif
  35. #ifdef _WIN32
  36. #include <windows.h>
  37. #elif defined (LINUX)
  38. #include <X11/Xlib.h>
  39. #include <X11/Xutil.h>
  40. #include <X11/Xatom.h>
  41. #undef KeyPress
  42. #else
  43. #include <Carbon/Carbon.h>
  44. #endif
  45. #ifdef PRAGMA_ALIGN_SUPPORTED
  46. #undef PRAGMA_ALIGN_SUPPORTED
  47. #define PRAGMA_ALIGN_SUPPORTED 1
  48. #endif
  49. #include "../../juce_IncludeCharacteristics.h"
  50. //==============================================================================
  51. /* These files come with the Steinberg VST SDK - to get them, you'll need to
  52. visit the Steinberg website and jump through some hoops to sign up as a
  53. VST developer.
  54. Then, you'll need to make sure your include path contains your "vstsdk2.3" or
  55. "vstsdk2.4" directory.
  56. Note that the JUCE_USE_VSTSDK_2_4 macro should be defined in JucePluginCharacteristics.h
  57. */
  58. #if JUCE_USE_VSTSDK_2_4
  59. // VSTSDK V2.4 includes..
  60. #include "public.sdk/source/vst2.x/audioeffectx.h"
  61. #include "public.sdk/source/vst2.x/aeffeditor.h"
  62. #include "public.sdk/source/vst2.x/audioeffectx.cpp"
  63. #include "public.sdk/source/vst2.x/audioeffect.cpp"
  64. #else
  65. // VSTSDK V2.3 includes..
  66. #include "source/common/audioeffectx.h"
  67. #include "source/common/AEffEditor.hpp"
  68. #include "source/common/audioeffectx.cpp"
  69. #include "source/common/AudioEffect.cpp"
  70. typedef long VstInt32;
  71. typedef long VstIntPtr;
  72. enum Vst2StringConstants
  73. {
  74. kVstMaxNameLen = 64,
  75. kVstMaxLabelLen = 64,
  76. kVstMaxShortLabelLen = 8,
  77. kVstMaxCategLabelLen = 24,
  78. kVstMaxFileNameLen = 100
  79. };
  80. enum VstSmpteFrameRate
  81. {
  82. kVstSmpte24fps = 0, ///< 24 fps
  83. kVstSmpte25fps = 1, ///< 25 fps
  84. kVstSmpte2997fps = 2, ///< 29.97 fps
  85. kVstSmpte30fps = 3, ///< 30 fps
  86. kVstSmpte2997dfps = 4, ///< 29.97 drop
  87. kVstSmpte30dfps = 5, ///< 30 drop
  88. kVstSmpteFilm16mm = 6, ///< Film 16mm
  89. kVstSmpteFilm35mm = 7, ///< Film 35mm
  90. kVstSmpte239fps = 10, ///< HDTV: 23.976 fps
  91. kVstSmpte249fps = 11, ///< HDTV: 24.976 fps
  92. kVstSmpte599fps = 12, ///< HDTV: 59.94 fps
  93. kVstSmpte60fps = 13 ///< HDTV: 60 fps
  94. };
  95. #endif
  96. //==============================================================================
  97. #ifdef _MSC_VER
  98. #pragma pack (push, 8)
  99. #endif
  100. //#include "../../../../../juce_amalgamated.h"
  101. #include "../../../../../juce.h"
  102. #ifdef _MSC_VER
  103. #pragma pack (pop)
  104. #endif
  105. #undef MemoryBlock
  106. class JuceVSTWrapper;
  107. static bool recursionCheck = false;
  108. static JUCE_NAMESPACE::uint32 lastMasterIdleCall = 0;
  109. BEGIN_JUCE_NAMESPACE
  110. extern void juce_callAnyTimersSynchronously();
  111. #if JUCE_MAC
  112. extern void juce_setCurrentExecutableFileNameFromBundleId (const String& bundleId) throw();
  113. extern void* attachComponentToWindowRef (Component* component, void* windowRef);
  114. extern void detachComponentFromWindowRef (Component* component, void* nsWindow);
  115. extern void setNativeHostWindowSize (void* nsWindow, Component* editorComp, int newWidth, int newHeight);
  116. extern void checkWindowVisibility (void* nsWindow, Component* component);
  117. #endif
  118. #if JUCE_LINUX
  119. extern Display* display;
  120. extern bool juce_postMessageToSystemQueue (void* message);
  121. #endif
  122. END_JUCE_NAMESPACE
  123. //==============================================================================
  124. #if JUCE_WIN32
  125. static HWND findMDIParentOf (HWND w)
  126. {
  127. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  128. while (w != 0)
  129. {
  130. HWND parent = GetParent (w);
  131. if (parent == 0)
  132. break;
  133. TCHAR windowType [32];
  134. zeromem (windowType, sizeof (windowType));
  135. GetClassName (parent, windowType, 31);
  136. if (String (windowType).equalsIgnoreCase (T("MDIClient")))
  137. {
  138. w = parent;
  139. break;
  140. }
  141. RECT windowPos;
  142. GetWindowRect (w, &windowPos);
  143. RECT parentPos;
  144. GetWindowRect (parent, &parentPos);
  145. const int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  146. const int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  147. if (dw > 100 || dh > 100)
  148. break;
  149. w = parent;
  150. if (dw == 2 * frameThickness)
  151. break;
  152. }
  153. return w;
  154. }
  155. //==============================================================================
  156. #elif JUCE_LINUX
  157. class SharedMessageThread : public Thread
  158. {
  159. public:
  160. SharedMessageThread()
  161. : Thread (T("VstMessageThread"))
  162. {
  163. startThread (7);
  164. }
  165. ~SharedMessageThread()
  166. {
  167. signalThreadShouldExit();
  168. JUCEApplication::quit();
  169. waitForThreadToExit (5000);
  170. clearSingletonInstance();
  171. }
  172. void run()
  173. {
  174. MessageManager* const messageManager = MessageManager::getInstance();
  175. const int64 originalThreadId = messageManager->getCurrentMessageThread();
  176. messageManager->setCurrentMessageThread (Thread::getCurrentThreadId());
  177. while ((! threadShouldExit()) && messageManager->runDispatchLoopUntil (250))
  178. {
  179. }
  180. messageManager->setCurrentMessageThread (originalThreadId);
  181. }
  182. juce_DeclareSingleton (SharedMessageThread, false)
  183. };
  184. #endif
  185. //==============================================================================
  186. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  187. // chores when it changes or repaints.
  188. class EditorCompWrapper : public Component,
  189. public AsyncUpdater
  190. {
  191. JuceVSTWrapper* wrapper;
  192. public:
  193. EditorCompWrapper (JuceVSTWrapper* const wrapper_,
  194. AudioProcessorEditor* const editor)
  195. : wrapper (wrapper_)
  196. {
  197. setOpaque (true);
  198. editor->setOpaque (true);
  199. setBounds (editor->getBounds());
  200. editor->setTopLeftPosition (0, 0);
  201. addAndMakeVisible (editor);
  202. #if JUCE_WIN32
  203. addMouseListener (this, true);
  204. #endif
  205. }
  206. ~EditorCompWrapper()
  207. {
  208. deleteAllChildren();
  209. }
  210. void paint (Graphics& g)
  211. {
  212. }
  213. void paintOverChildren (Graphics& g)
  214. {
  215. // this causes an async call to masterIdle() to help
  216. // creaky old DAWs like Nuendo repaint themselves while we're
  217. // repainting. Otherwise they just seem to give up and sit there
  218. // waiting.
  219. triggerAsyncUpdate();
  220. }
  221. AudioProcessorEditor* getEditorComp() const
  222. {
  223. return dynamic_cast <AudioProcessorEditor*> (getChildComponent (0));
  224. }
  225. void resized()
  226. {
  227. Component* const c = getChildComponent (0);
  228. if (c != 0)
  229. {
  230. #if JUCE_LINUX
  231. const MessageManagerLock mml;
  232. #endif
  233. c->setBounds (0, 0, getWidth(), getHeight());
  234. }
  235. }
  236. void childBoundsChanged (Component* child);
  237. void handleAsyncUpdate();
  238. #if JUCE_WIN32
  239. void mouseDown (const MouseEvent&)
  240. {
  241. broughtToFront();
  242. }
  243. void broughtToFront()
  244. {
  245. // for hosts like nuendo, need to also pop the MDI container to the
  246. // front when our comp is clicked on.
  247. HWND parent = findMDIParentOf ((HWND) getWindowHandle());
  248. if (parent != 0)
  249. {
  250. SetWindowPos (parent,
  251. HWND_TOP,
  252. 0, 0, 0, 0,
  253. SWP_NOMOVE | SWP_NOSIZE);
  254. }
  255. }
  256. #endif
  257. //==============================================================================
  258. juce_UseDebuggingNewOperator
  259. };
  260. static VoidArray activePlugins;
  261. //==============================================================================
  262. /**
  263. This wraps an AudioProcessor as an AudioEffectX...
  264. */
  265. class JuceVSTWrapper : public AudioEffectX,
  266. private Timer,
  267. public AudioProcessorListener,
  268. public AudioPlayHead
  269. {
  270. public:
  271. //==============================================================================
  272. JuceVSTWrapper (audioMasterCallback audioMaster,
  273. AudioProcessor* const filter_)
  274. : AudioEffectX (audioMaster,
  275. filter_->getNumPrograms(),
  276. filter_->getNumParameters()),
  277. filter (filter_)
  278. {
  279. editorComp = 0;
  280. outgoingEvents = 0;
  281. outgoingEventSize = 0;
  282. chunkMemoryTime = 0;
  283. isProcessing = false;
  284. hasShutdown = false;
  285. firstProcessCallback = true;
  286. shouldDeleteEditor = false;
  287. channels = 0;
  288. numInChans = JucePlugin_MaxNumInputChannels;
  289. numOutChans = JucePlugin_MaxNumOutputChannels;
  290. #if JUCE_MAC || JUCE_LINUX
  291. hostWindow = 0;
  292. #endif
  293. filter->setPlayConfigDetails (numInChans, numOutChans, 0, 0);
  294. filter_->setPlayHead (this);
  295. filter_->addListener (this);
  296. cEffect.flags |= effFlagsHasEditor;
  297. cEffect.version = (long) (JucePlugin_VersionCode);
  298. setUniqueID ((int) (JucePlugin_VSTUniqueID));
  299. #if JucePlugin_WantsMidiInput && ! JUCE_USE_VSTSDK_2_4
  300. wantEvents();
  301. #endif
  302. setNumInputs (numInChans);
  303. setNumOutputs (numOutChans);
  304. canProcessReplacing (true);
  305. #if ! JUCE_USE_VSTSDK_2_4
  306. hasVu (false);
  307. hasClip (false);
  308. #endif
  309. isSynth ((JucePlugin_IsSynth) != 0);
  310. noTail ((JucePlugin_SilenceInProducesSilenceOut) != 0);
  311. setInitialDelay (filter->getLatencySamples());
  312. programsAreChunks (true);
  313. activePlugins.add (this);
  314. }
  315. ~JuceVSTWrapper()
  316. {
  317. stopTimer();
  318. deleteEditor (false);
  319. hasShutdown = true;
  320. delete filter;
  321. filter = 0;
  322. if (outgoingEvents != 0)
  323. {
  324. for (int i = outgoingEventSize; --i >= 0;)
  325. juce_free (outgoingEvents->events[i]);
  326. juce_free (outgoingEvents);
  327. outgoingEvents = 0;
  328. }
  329. jassert (editorComp == 0);
  330. juce_free (channels);
  331. channels = 0;
  332. deleteTempChannels();
  333. jassert (activePlugins.contains (this));
  334. activePlugins.removeValue (this);
  335. if (activePlugins.size() == 0)
  336. {
  337. #if JUCE_LINUX
  338. SharedMessageThread::deleteInstance();
  339. #endif
  340. shutdownJuce_GUI();
  341. }
  342. }
  343. void open()
  344. {
  345. if (editorComp == 0)
  346. {
  347. #if JUCE_LINUX
  348. const MessageManagerLock mml;
  349. #endif
  350. AudioProcessorEditor* const ed = filter->createEditorIfNeeded();
  351. if (ed != 0)
  352. cEffect.flags |= effFlagsHasEditor;
  353. else
  354. cEffect.flags &= ~effFlagsHasEditor;
  355. filter->editorBeingDeleted (ed);
  356. delete ed;
  357. }
  358. startTimer (1000 / 4);
  359. }
  360. void close()
  361. {
  362. jassert (! recursionCheck);
  363. stopTimer();
  364. deleteEditor (false);
  365. }
  366. //==============================================================================
  367. bool getEffectName (char* name)
  368. {
  369. String (JucePlugin_Name).copyToBuffer (name, 64);
  370. return true;
  371. }
  372. bool getVendorString (char* text)
  373. {
  374. String (JucePlugin_Manufacturer).copyToBuffer (text, 64);
  375. return true;
  376. }
  377. bool getProductString (char* text)
  378. {
  379. return getEffectName (text);
  380. }
  381. VstInt32 getVendorVersion()
  382. {
  383. return JucePlugin_VersionCode;
  384. }
  385. VstPlugCategory getPlugCategory()
  386. {
  387. return JucePlugin_VSTCategory;
  388. }
  389. VstInt32 canDo (char* text)
  390. {
  391. VstInt32 result = 0;
  392. if (strcmp (text, "receiveVstEvents") == 0
  393. || strcmp (text, "receiveVstMidiEvent") == 0
  394. || strcmp (text, "receiveVstMidiEvents") == 0)
  395. {
  396. #if JucePlugin_WantsMidiInput
  397. result = 1;
  398. #else
  399. result = -1;
  400. #endif
  401. }
  402. else if (strcmp (text, "sendVstEvents") == 0
  403. || strcmp (text, "sendVstMidiEvent") == 0
  404. || strcmp (text, "sendVstMidiEvents") == 0)
  405. {
  406. #if JucePlugin_ProducesMidiOutput
  407. result = 1;
  408. #else
  409. result = -1;
  410. #endif
  411. }
  412. else if (strcmp (text, "receiveVstTimeInfo") == 0
  413. || strcmp (text, "conformsToWindowRules") == 0)
  414. {
  415. result = 1;
  416. }
  417. return result;
  418. }
  419. bool keysRequired()
  420. {
  421. return (JucePlugin_EditorRequiresKeyboardFocus) != 0;
  422. }
  423. bool getInputProperties (VstInt32 index, VstPinProperties* properties)
  424. {
  425. if (filter == 0 || index >= filter->getNumInputChannels())
  426. return false;
  427. const String name (filter->getInputChannelName ((int) index));
  428. name.copyToBuffer (properties->label, kVstMaxLabelLen - 1);
  429. name.copyToBuffer (properties->shortLabel, kVstMaxShortLabelLen - 1);
  430. properties->flags = kVstPinIsActive;
  431. if (filter->isInputChannelStereoPair ((int) index))
  432. properties->flags |= kVstPinIsStereo;
  433. properties->arrangementType = 0;
  434. return true;
  435. }
  436. bool getOutputProperties (VstInt32 index, VstPinProperties* properties)
  437. {
  438. if (filter == 0 || index >= filter->getNumOutputChannels())
  439. return false;
  440. const String name (filter->getOutputChannelName ((int) index));
  441. name.copyToBuffer (properties->label, kVstMaxLabelLen - 1);
  442. name.copyToBuffer (properties->shortLabel, kVstMaxShortLabelLen - 1);
  443. properties->flags = kVstPinIsActive;
  444. if (filter->isOutputChannelStereoPair ((int) index))
  445. properties->flags |= kVstPinIsStereo;
  446. properties->arrangementType = 0;
  447. return true;
  448. }
  449. //==============================================================================
  450. VstInt32 processEvents (VstEvents* events)
  451. {
  452. #if JucePlugin_WantsMidiInput
  453. for (int i = 0; i < events->numEvents; ++i)
  454. {
  455. const VstEvent* const e = events->events[i];
  456. if (e != 0 && e->type == kVstMidiType)
  457. {
  458. const VstMidiEvent* const vme = (const VstMidiEvent*) e;
  459. midiEvents.addEvent ((const JUCE_NAMESPACE::uint8*) vme->midiData,
  460. 4,
  461. vme->deltaFrames);
  462. }
  463. }
  464. return 1;
  465. #else
  466. return 0;
  467. #endif
  468. }
  469. void process (float** inputs, float** outputs, VstInt32 numSamples)
  470. {
  471. const int numIn = numInChans;
  472. const int numOut = numOutChans;
  473. AudioSampleBuffer temp (numIn, numSamples);
  474. int i;
  475. for (i = numIn; --i >= 0;)
  476. memcpy (temp.getSampleData (i), outputs[i], sizeof (float) * numSamples);
  477. processReplacing (inputs, outputs, numSamples);
  478. AudioSampleBuffer dest (outputs, numOut, numSamples);
  479. for (i = jmin (numIn, numOut); --i >= 0;)
  480. dest.addFrom (i, 0, temp, i, 0, numSamples);
  481. }
  482. void processReplacing (float** inputs, float** outputs, VstInt32 numSamples)
  483. {
  484. if (firstProcessCallback)
  485. {
  486. firstProcessCallback = false;
  487. // if this fails, the host hasn't called resume() before processing
  488. jassert (isProcessing);
  489. // (tragically, some hosts actually need this, although it's stupid to have
  490. // to do it here..)
  491. if (! isProcessing)
  492. resume();
  493. filter->setNonRealtime (getCurrentProcessLevel() == 4 /* kVstProcessLevelOffline */);
  494. #if JUCE_WIN32
  495. if (GetThreadPriority (GetCurrentThread()) <= THREAD_PRIORITY_NORMAL)
  496. filter->setNonRealtime (true);
  497. #endif
  498. }
  499. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  500. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  501. #endif
  502. jassert (activePlugins.contains (this));
  503. {
  504. const ScopedLock sl (filter->getCallbackLock());
  505. const int numIn = numInChans;
  506. const int numOut = numOutChans;
  507. if (filter->isSuspended())
  508. {
  509. for (int i = 0; i < numOut; ++i)
  510. zeromem (outputs[i], sizeof (float) * numSamples);
  511. }
  512. else
  513. {
  514. int i;
  515. for (i = 0; i < numOut; ++i)
  516. {
  517. float* chan = (float*) tempChannels.getUnchecked(i);
  518. if (chan == 0)
  519. {
  520. chan = outputs[i];
  521. // if some output channels are disabled, some hosts supply the same buffer
  522. // for multiple channels - this buggers up our method of copying the
  523. // inputs over the outputs, so we need to create unique temp buffers in this case..
  524. for (int j = i; --j >= 0;)
  525. {
  526. if (outputs[j] == chan)
  527. {
  528. chan = (float*) juce_malloc (sizeof (float) * blockSize * 2);
  529. tempChannels.set (i, chan);
  530. break;
  531. }
  532. }
  533. }
  534. if (i < numIn && chan != inputs[i])
  535. memcpy (chan, inputs[i], sizeof (float) * numSamples);
  536. channels[i] = chan;
  537. }
  538. for (; i < numIn; ++i)
  539. channels[i] = inputs[i];
  540. AudioSampleBuffer chans (channels, jmax (numIn, numOut), numSamples);
  541. filter->processBlock (chans, midiEvents);
  542. }
  543. }
  544. if (! midiEvents.isEmpty())
  545. {
  546. #if JucePlugin_ProducesMidiOutput
  547. const int numEvents = midiEvents.getNumEvents();
  548. ensureOutgoingEventSize (numEvents);
  549. outgoingEvents->numEvents = 0;
  550. const JUCE_NAMESPACE::uint8* midiEventData;
  551. int midiEventSize, midiEventPosition;
  552. MidiBuffer::Iterator i (midiEvents);
  553. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  554. {
  555. if (midiEventSize <= 4)
  556. {
  557. VstMidiEvent* const vme = (VstMidiEvent*) outgoingEvents->events [outgoingEvents->numEvents++];
  558. memcpy (vme->midiData, midiEventData, midiEventSize);
  559. vme->deltaFrames = midiEventPosition;
  560. jassert (vme->deltaFrames >= 0 && vme->deltaFrames < numSamples);
  561. }
  562. }
  563. sendVstEventsToHost (outgoingEvents);
  564. #else
  565. /* This assertion is caused when you've added some events to the
  566. midiMessages array in your processBlock() method, which usually means
  567. that you're trying to send them somewhere. But in this case they're
  568. getting thrown away.
  569. If your plugin does want to send midi messages, you'll need to set
  570. the JucePlugin_ProducesMidiOutput macro to 1 in your
  571. JucePluginCharacteristics.h file.
  572. If you don't want to produce any midi output, then you should clear the
  573. midiMessages array at the end of your processBlock() method, to
  574. indicate that you don't want any of the events to be passed through
  575. to the output.
  576. */
  577. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  578. #endif
  579. midiEvents.clear();
  580. }
  581. }
  582. //==============================================================================
  583. VstInt32 startProcess () { return 0; }
  584. VstInt32 stopProcess () { return 0;}
  585. void resume()
  586. {
  587. if (filter == 0)
  588. return;
  589. isProcessing = true;
  590. juce_free (channels);
  591. channels = (float**) juce_calloc (sizeof (float*) * (numInChans + numOutChans));
  592. double rate = getSampleRate();
  593. jassert (rate > 0);
  594. if (rate <= 0.0)
  595. rate = 44100.0;
  596. const int blockSize = getBlockSize();
  597. jassert (blockSize > 0);
  598. firstProcessCallback = true;
  599. filter->setNonRealtime (getCurrentProcessLevel() == 4 /* kVstProcessLevelOffline */);
  600. filter->setPlayConfigDetails (numInChans, numOutChans,
  601. rate, blockSize);
  602. deleteTempChannels();
  603. filter->prepareToPlay (rate, blockSize);
  604. midiEvents.clear();
  605. setInitialDelay (filter->getLatencySamples());
  606. AudioEffectX::resume();
  607. #if JucePlugin_ProducesMidiOutput
  608. ensureOutgoingEventSize (64);
  609. #endif
  610. #if JucePlugin_WantsMidiInput && ! JUCE_USE_VSTSDK_2_4
  611. wantEvents();
  612. #endif
  613. }
  614. void suspend()
  615. {
  616. if (filter == 0)
  617. return;
  618. AudioEffectX::suspend();
  619. filter->releaseResources();
  620. midiEvents.clear();
  621. isProcessing = false;
  622. juce_free (channels);
  623. channels = 0;
  624. deleteTempChannels();
  625. }
  626. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info)
  627. {
  628. const VstTimeInfo* const ti = getTimeInfo (kVstPpqPosValid
  629. | kVstTempoValid
  630. | kVstBarsValid
  631. //| kVstCyclePosValid
  632. | kVstTimeSigValid
  633. | kVstSmpteValid
  634. | kVstClockValid);
  635. if (ti == 0 || ti->sampleRate <= 0)
  636. return false;
  637. if ((ti->flags & kVstTempoValid) != 0)
  638. info.bpm = ti->tempo;
  639. else
  640. info.bpm = 0.0;
  641. if ((ti->flags & kVstTimeSigValid) != 0)
  642. {
  643. info.timeSigNumerator = ti->timeSigNumerator;
  644. info.timeSigDenominator = ti->timeSigDenominator;
  645. }
  646. else
  647. {
  648. info.timeSigNumerator = 4;
  649. info.timeSigDenominator = 4;
  650. }
  651. info.timeInSeconds = ti->samplePos / ti->sampleRate;
  652. if ((ti->flags & kVstPpqPosValid) != 0)
  653. info.ppqPosition = ti->ppqPos;
  654. else
  655. info.ppqPosition = 0.0;
  656. if ((ti->flags & kVstBarsValid) != 0)
  657. info.ppqPositionOfLastBarStart = ti->barStartPos;
  658. else
  659. info.ppqPositionOfLastBarStart = 0.0;
  660. if ((ti->flags & kVstSmpteValid) != 0)
  661. {
  662. AudioPlayHead::FrameRateType rate = AudioPlayHead::fpsUnknown;
  663. double fps = 1.0;
  664. switch (ti->smpteFrameRate)
  665. {
  666. case kVstSmpte24fps:
  667. rate = AudioPlayHead::fps24;
  668. fps = 24.0;
  669. break;
  670. case kVstSmpte25fps:
  671. rate = AudioPlayHead::fps25;
  672. fps = 25.0;
  673. break;
  674. case kVstSmpte2997fps:
  675. rate = AudioPlayHead::fps2997;
  676. fps = 29.97;
  677. break;
  678. case kVstSmpte30fps:
  679. rate = AudioPlayHead::fps30;
  680. fps = 30.0;
  681. break;
  682. case kVstSmpte2997dfps:
  683. rate = AudioPlayHead::fps2997drop;
  684. fps = 29.97;
  685. break;
  686. case kVstSmpte30dfps:
  687. rate = AudioPlayHead::fps30drop;
  688. fps = 30.0;
  689. break;
  690. case kVstSmpteFilm16mm:
  691. case kVstSmpteFilm35mm:
  692. fps = 24.0;
  693. break;
  694. case kVstSmpte239fps: fps = 23.976; break;
  695. case kVstSmpte249fps: fps = 24.976; break;
  696. case kVstSmpte599fps: fps = 59.94; break;
  697. case kVstSmpte60fps: fps = 60; break;
  698. default:
  699. jassertfalse // unknown frame-rate..
  700. }
  701. info.frameRate = rate;
  702. info.editOriginTime = ti->smpteOffset / (80.0 * fps);
  703. }
  704. else
  705. {
  706. info.frameRate = AudioPlayHead::fpsUnknown;
  707. info.editOriginTime = 0;
  708. }
  709. info.isRecording = (ti->flags & kVstTransportRecording) != 0;
  710. info.isPlaying = (ti->flags & kVstTransportPlaying) != 0 || info.isRecording;
  711. return true;
  712. }
  713. //==============================================================================
  714. VstInt32 getProgram()
  715. {
  716. return filter != 0 ? filter->getCurrentProgram() : 0;
  717. }
  718. void setProgram (VstInt32 program)
  719. {
  720. if (filter != 0)
  721. filter->setCurrentProgram (program);
  722. }
  723. void setProgramName (char* name)
  724. {
  725. if (filter != 0)
  726. filter->changeProgramName (filter->getCurrentProgram(), name);
  727. }
  728. void getProgramName (char* name)
  729. {
  730. if (filter != 0)
  731. filter->getProgramName (filter->getCurrentProgram()).copyToBuffer (name, 24);
  732. }
  733. bool getProgramNameIndexed (VstInt32 category, VstInt32 index, char* text)
  734. {
  735. if (filter != 0 && ((unsigned int) index) < (unsigned int) filter->getNumPrograms())
  736. {
  737. filter->getProgramName (index).copyToBuffer (text, 24);
  738. return true;
  739. }
  740. return false;
  741. }
  742. //==============================================================================
  743. float getParameter (VstInt32 index)
  744. {
  745. if (filter == 0)
  746. return 0.0f;
  747. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  748. return filter->getParameter (index);
  749. }
  750. void setParameter (VstInt32 index, float value)
  751. {
  752. if (filter != 0)
  753. {
  754. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  755. filter->setParameter (index, value);
  756. }
  757. }
  758. void getParameterDisplay (VstInt32 index, char* text)
  759. {
  760. if (filter != 0)
  761. {
  762. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  763. filter->getParameterText (index).copyToBuffer (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  764. }
  765. }
  766. void getParameterName (VstInt32 index, char* text)
  767. {
  768. if (filter != 0)
  769. {
  770. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  771. filter->getParameterName (index).copyToBuffer (text, 16); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  772. }
  773. }
  774. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue)
  775. {
  776. setParameterAutomated (index, newValue);
  777. }
  778. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index)
  779. {
  780. beginEdit (index);
  781. }
  782. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index)
  783. {
  784. endEdit (index);
  785. }
  786. void audioProcessorChanged (AudioProcessor*)
  787. {
  788. updateDisplay();
  789. }
  790. bool canParameterBeAutomated (VstInt32 index)
  791. {
  792. return filter != 0 && filter->isParameterAutomatable ((int) index);
  793. }
  794. bool setSpeakerArrangement (VstSpeakerArrangement* pluginInput,
  795. VstSpeakerArrangement* pluginOutput)
  796. {
  797. // if this method isn't implemented, nuendo4 + cubase4 crash when you've got multiple channels..
  798. numInChans = pluginInput->numChannels;
  799. numOutChans = pluginOutput->numChannels;
  800. filter->setPlayConfigDetails (numInChans, numOutChans,
  801. filter->getSampleRate(),
  802. filter->getBlockSize());
  803. return true;
  804. }
  805. //==============================================================================
  806. VstInt32 getChunk (void** data, bool onlyStoreCurrentProgramData)
  807. {
  808. if (filter == 0)
  809. return 0;
  810. chunkMemory.setSize (0);
  811. if (onlyStoreCurrentProgramData)
  812. filter->getCurrentProgramStateInformation (chunkMemory);
  813. else
  814. filter->getStateInformation (chunkMemory);
  815. *data = (void*) chunkMemory;
  816. // because the chunk is only needed temporarily by the host (or at least you'd
  817. // hope so) we'll give it a while and then free it in the timer callback.
  818. chunkMemoryTime = JUCE_NAMESPACE::Time::getApproximateMillisecondCounter();
  819. return chunkMemory.getSize();
  820. }
  821. VstInt32 setChunk (void* data, VstInt32 byteSize, bool onlyRestoreCurrentProgramData)
  822. {
  823. if (filter == 0)
  824. return 0;
  825. chunkMemory.setSize (0);
  826. chunkMemoryTime = 0;
  827. if (byteSize > 0 && data != 0)
  828. {
  829. if (onlyRestoreCurrentProgramData)
  830. filter->setCurrentProgramStateInformation (data, byteSize);
  831. else
  832. filter->setStateInformation (data, byteSize);
  833. }
  834. return 0;
  835. }
  836. void timerCallback()
  837. {
  838. if (shouldDeleteEditor)
  839. {
  840. shouldDeleteEditor = false;
  841. deleteEditor (true);
  842. }
  843. if (chunkMemoryTime > 0
  844. && chunkMemoryTime < JUCE_NAMESPACE::Time::getApproximateMillisecondCounter() - 2000
  845. && ! recursionCheck)
  846. {
  847. chunkMemoryTime = 0;
  848. chunkMemory.setSize (0);
  849. }
  850. #if JUCE_MAC
  851. if (hostWindow != 0)
  852. checkWindowVisibility (hostWindow, editorComp);
  853. #endif
  854. tryMasterIdle();
  855. }
  856. void tryMasterIdle()
  857. {
  858. if (Component::isMouseButtonDownAnywhere()
  859. && ! recursionCheck)
  860. {
  861. const JUCE_NAMESPACE::uint32 now = JUCE_NAMESPACE::Time::getMillisecondCounter();
  862. if (now > lastMasterIdleCall + 20 && editorComp != 0)
  863. {
  864. lastMasterIdleCall = now;
  865. recursionCheck = true;
  866. masterIdle();
  867. recursionCheck = false;
  868. }
  869. }
  870. }
  871. void doIdleCallback()
  872. {
  873. // (wavelab calls this on a separate thread and causes a deadlock)..
  874. if (MessageManager::getInstance()->isThisTheMessageThread()
  875. && ! recursionCheck)
  876. {
  877. const MessageManagerLock mml;
  878. recursionCheck = true;
  879. juce_callAnyTimersSynchronously();
  880. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  881. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  882. recursionCheck = false;
  883. }
  884. }
  885. void createEditorComp()
  886. {
  887. if (hasShutdown || filter == 0)
  888. return;
  889. if (editorComp == 0)
  890. {
  891. #if JUCE_LINUX
  892. const MessageManagerLock mml;
  893. #endif
  894. AudioProcessorEditor* const ed = filter->createEditorIfNeeded();
  895. if (ed != 0)
  896. {
  897. cEffect.flags |= effFlagsHasEditor;
  898. ed->setOpaque (true);
  899. ed->setVisible (true);
  900. editorComp = new EditorCompWrapper (this, ed);
  901. }
  902. else
  903. {
  904. cEffect.flags &= ~effFlagsHasEditor;
  905. }
  906. }
  907. shouldDeleteEditor = false;
  908. }
  909. void deleteEditor (bool canDeleteLaterIfModal)
  910. {
  911. PopupMenu::dismissAllActiveMenus();
  912. jassert (! recursionCheck);
  913. recursionCheck = true;
  914. #if JUCE_LINUX
  915. const MessageManagerLock mml;
  916. #endif
  917. if (editorComp != 0)
  918. {
  919. Component* const modalComponent = Component::getCurrentlyModalComponent();
  920. if (modalComponent != 0)
  921. {
  922. modalComponent->exitModalState (0);
  923. if (canDeleteLaterIfModal)
  924. {
  925. shouldDeleteEditor = true;
  926. return;
  927. }
  928. }
  929. #if JUCE_MAC
  930. detachComponentFromWindowRef (editorComp, hostWindow);
  931. hostWindow = 0;
  932. #endif
  933. filter->editorBeingDeleted (editorComp->getEditorComp());
  934. deleteAndZero (editorComp);
  935. // there's some kind of component currently modal, but the host
  936. // is trying to delete our plugin. You should try to avoid this happening..
  937. jassert (Component::getCurrentlyModalComponent() == 0);
  938. }
  939. #if JUCE_LINUX
  940. hostWindow = 0;
  941. #endif
  942. recursionCheck = false;
  943. }
  944. VstIntPtr dispatcher (VstInt32 opCode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  945. {
  946. if (hasShutdown)
  947. return 0;
  948. if (opCode == effEditIdle)
  949. {
  950. doIdleCallback();
  951. return 0;
  952. }
  953. else if (opCode == effEditOpen)
  954. {
  955. jassert (! recursionCheck);
  956. deleteEditor (true);
  957. createEditorComp();
  958. if (editorComp != 0)
  959. {
  960. #if JUCE_LINUX
  961. const MessageManagerLock mml;
  962. #endif
  963. editorComp->setOpaque (true);
  964. editorComp->setVisible (false);
  965. #if JUCE_WIN32
  966. editorComp->addToDesktop (0);
  967. hostWindow = (HWND) ptr;
  968. HWND editorWnd = (HWND) editorComp->getWindowHandle();
  969. SetParent (editorWnd, hostWindow);
  970. DWORD val = GetWindowLong (editorWnd, GWL_STYLE);
  971. val = (val & ~WS_POPUP) | WS_CHILD;
  972. SetWindowLong (editorWnd, GWL_STYLE, val);
  973. #elif JUCE_LINUX
  974. editorComp->addToDesktop (0);
  975. hostWindow = (Window) ptr;
  976. Window editorWnd = (Window) editorComp->getWindowHandle();
  977. XReparentWindow (display, editorWnd, hostWindow, 0, 0);
  978. #else
  979. hostWindow = attachComponentToWindowRef (editorComp, (WindowRef) ptr);
  980. #endif
  981. editorComp->setVisible (true);
  982. return 1;
  983. }
  984. }
  985. else if (opCode == effEditClose)
  986. {
  987. deleteEditor (true);
  988. return 0;
  989. }
  990. else if (opCode == effEditGetRect)
  991. {
  992. createEditorComp();
  993. if (editorComp != 0)
  994. {
  995. editorSize.left = 0;
  996. editorSize.top = 0;
  997. editorSize.right = editorComp->getWidth();
  998. editorSize.bottom = editorComp->getHeight();
  999. *((ERect**) ptr) = &editorSize;
  1000. return (VstIntPtr) &editorSize;
  1001. }
  1002. else
  1003. {
  1004. return 0;
  1005. }
  1006. }
  1007. return AudioEffectX::dispatcher (opCode, index, value, ptr, opt);
  1008. }
  1009. void resizeHostWindow (int newWidth, int newHeight)
  1010. {
  1011. if (editorComp != 0)
  1012. {
  1013. #if ! JUCE_LINUX // linux hosts shouldn't be trusted!
  1014. if (! (canHostDo ("sizeWindow") && sizeWindow (newWidth, newHeight)))
  1015. #endif
  1016. {
  1017. // some hosts don't support the sizeWindow call, so do it manually..
  1018. #if JUCE_MAC
  1019. setNativeHostWindowSize (hostWindow, editorComp, newWidth, newHeight);
  1020. #elif JUCE_LINUX
  1021. Window root;
  1022. int x, y;
  1023. unsigned int width, height, border, depth;
  1024. XGetGeometry (display, hostWindow, &root,
  1025. &x, &y, &width, &height, &border, &depth);
  1026. newWidth += (width + border) - editorComp->getWidth();
  1027. newHeight += (height + border) - editorComp->getHeight();
  1028. XResizeWindow (display, hostWindow, newWidth, newHeight);
  1029. #else
  1030. int dw = 0;
  1031. int dh = 0;
  1032. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  1033. HWND w = (HWND) editorComp->getWindowHandle();
  1034. while (w != 0)
  1035. {
  1036. HWND parent = GetParent (w);
  1037. if (parent == 0)
  1038. break;
  1039. TCHAR windowType [32];
  1040. zeromem (windowType, sizeof (windowType));
  1041. GetClassName (parent, windowType, 31);
  1042. if (String (windowType).equalsIgnoreCase (T("MDIClient")))
  1043. break;
  1044. RECT windowPos;
  1045. GetWindowRect (w, &windowPos);
  1046. RECT parentPos;
  1047. GetWindowRect (parent, &parentPos);
  1048. SetWindowPos (w, 0, 0, 0,
  1049. newWidth + dw,
  1050. newHeight + dh,
  1051. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1052. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1053. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1054. w = parent;
  1055. if (dw == 2 * frameThickness)
  1056. break;
  1057. if (dw > 100 || dh > 100)
  1058. w = 0;
  1059. }
  1060. if (w != 0)
  1061. SetWindowPos (w, 0, 0, 0,
  1062. newWidth + dw,
  1063. newHeight + dh,
  1064. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1065. #endif
  1066. }
  1067. if (editorComp->getPeer() != 0)
  1068. editorComp->getPeer()->handleMovedOrResized();
  1069. }
  1070. }
  1071. //==============================================================================
  1072. juce_UseDebuggingNewOperator
  1073. private:
  1074. AudioProcessor* filter;
  1075. JUCE_NAMESPACE::MemoryBlock chunkMemory;
  1076. JUCE_NAMESPACE::uint32 chunkMemoryTime;
  1077. EditorCompWrapper* editorComp;
  1078. ERect editorSize;
  1079. MidiBuffer midiEvents;
  1080. VstEvents* outgoingEvents;
  1081. int outgoingEventSize;
  1082. bool isProcessing;
  1083. bool hasShutdown;
  1084. bool firstProcessCallback;
  1085. int diffW, diffH;
  1086. int numInChans, numOutChans;
  1087. float** channels;
  1088. VoidArray tempChannels; // see note in processReplacing()
  1089. bool hasCreatedTempChannels;
  1090. bool shouldDeleteEditor;
  1091. void deleteTempChannels()
  1092. {
  1093. int i;
  1094. for (i = tempChannels.size(); --i >= 0;)
  1095. juce_free (tempChannels.getUnchecked(i));
  1096. tempChannels.clear();
  1097. if (filter != 0)
  1098. tempChannels.insertMultiple (0, 0, filter->getNumInputChannels() + filter->getNumOutputChannels());
  1099. hasCreatedTempChannels = false;
  1100. }
  1101. void ensureOutgoingEventSize (int numEvents)
  1102. {
  1103. if (outgoingEventSize < numEvents)
  1104. {
  1105. numEvents += 32;
  1106. const int size = 16 + sizeof (VstEvent*) * numEvents;
  1107. if (outgoingEvents == 0)
  1108. outgoingEvents = (VstEvents*) juce_calloc (size);
  1109. else
  1110. outgoingEvents = (VstEvents*) juce_realloc (outgoingEvents, size);
  1111. for (int i = outgoingEventSize; i < numEvents; ++i)
  1112. {
  1113. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  1114. e->type = kVstMidiType;
  1115. e->byteSize = 24;
  1116. outgoingEvents->events[i] = (VstEvent*) e;
  1117. }
  1118. outgoingEventSize = numEvents;
  1119. }
  1120. }
  1121. const String getHostName()
  1122. {
  1123. char host[256];
  1124. zeromem (host, sizeof (host));
  1125. getHostProductString (host);
  1126. return host;
  1127. }
  1128. #if JUCE_MAC
  1129. void* hostWindow;
  1130. #elif JUCE_LINUX
  1131. Window hostWindow;
  1132. #else
  1133. HWND hostWindow;
  1134. #endif
  1135. };
  1136. //==============================================================================
  1137. void EditorCompWrapper::childBoundsChanged (Component* child)
  1138. {
  1139. child->setTopLeftPosition (0, 0);
  1140. const int cw = child->getWidth();
  1141. const int ch = child->getHeight();
  1142. wrapper->resizeHostWindow (cw, ch);
  1143. setSize (cw, ch);
  1144. #if JUCE_MAC
  1145. wrapper->resizeHostWindow (cw, ch); // (doing this a second time seems to be necessary in tracktion)
  1146. #endif
  1147. }
  1148. void EditorCompWrapper::handleAsyncUpdate()
  1149. {
  1150. wrapper->tryMasterIdle();
  1151. }
  1152. //==============================================================================
  1153. /** Somewhere in the codebase of your plugin, you need to implement this function
  1154. and make it create an instance of the filter subclass that you're building.
  1155. */
  1156. extern AudioProcessor* JUCE_CALLTYPE createPluginFilter();
  1157. //==============================================================================
  1158. static AEffect* pluginEntryPoint (audioMasterCallback audioMaster)
  1159. {
  1160. initialiseJuce_GUI();
  1161. #if JUCE_MAC && defined (JucePlugin_CFBundleIdentifier)
  1162. juce_setCurrentExecutableFileNameFromBundleId (JucePlugin_CFBundleIdentifier);
  1163. #endif
  1164. try
  1165. {
  1166. if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0)
  1167. {
  1168. AudioProcessor* const filter = createPluginFilter();
  1169. if (filter != 0)
  1170. {
  1171. JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter);
  1172. return wrapper->getAeffect();
  1173. }
  1174. }
  1175. }
  1176. catch (...)
  1177. {}
  1178. return 0;
  1179. }
  1180. //==============================================================================
  1181. // Mac startup code..
  1182. #if JUCE_MAC
  1183. extern "C" __attribute__ ((visibility("default"))) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1184. {
  1185. return pluginEntryPoint (audioMaster);
  1186. }
  1187. extern "C" __attribute__ ((visibility("default"))) AEffect* main_macho (audioMasterCallback audioMaster)
  1188. {
  1189. return pluginEntryPoint (audioMaster);
  1190. }
  1191. //==============================================================================
  1192. // Linux startup code..
  1193. #elif JUCE_LINUX
  1194. extern "C" AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1195. {
  1196. initialiseJuce_GUI();
  1197. SharedMessageThread::getInstance();
  1198. return pluginEntryPoint (audioMaster);
  1199. }
  1200. extern "C" __attribute__ ((visibility("default"))) AEffect* main_plugin (audioMasterCallback audioMaster) asm ("main");
  1201. extern "C" __attribute__ ((visibility("default"))) AEffect* main_plugin (audioMasterCallback audioMaster)
  1202. {
  1203. return VSTPluginMain (audioMaster);
  1204. }
  1205. __attribute__((constructor)) void myPluginInit()
  1206. {
  1207. // don't put initialiseJuce_GUI here... it will crash !
  1208. }
  1209. __attribute__((destructor)) void myPluginFini()
  1210. {
  1211. // don't put shutdownJuce_GUI here... it will crash !
  1212. }
  1213. //==============================================================================
  1214. // Win32 startup code..
  1215. #else
  1216. extern "C" __declspec (dllexport) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1217. {
  1218. return pluginEntryPoint (audioMaster);
  1219. }
  1220. extern "C" __declspec (dllexport) void* main (audioMasterCallback audioMaster)
  1221. {
  1222. return (void*) pluginEntryPoint (audioMaster);
  1223. }
  1224. BOOL WINAPI DllMain (HINSTANCE instance, DWORD dwReason, LPVOID)
  1225. {
  1226. if (dwReason == DLL_PROCESS_ATTACH)
  1227. PlatformUtilities::setCurrentModuleInstanceHandle (instance);
  1228. return TRUE;
  1229. }
  1230. #endif