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.

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