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.

1504 lines
43KB

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