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.

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