The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1557 lines
46KB

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