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.

1478 lines
47KB

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