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.

1524 lines
44KB

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