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.

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