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.

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