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.

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