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.

1690 lines
56KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. // Your project must contain an AppConfig.h file with your project-specific settings in it,
  18. // and your header search path must make it accessible to the module's files.
  19. #include "AppConfig.h"
  20. #include "../utility/juce_CheckSettingMacros.h"
  21. #include "../../juce_core/native/juce_mac_ClangBugWorkaround.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. #ifndef _MSC_VER
  46. #define __cdecl
  47. #endif
  48. #ifdef __clang__
  49. #pragma clang diagnostic push
  50. #pragma clang diagnostic ignored "-Wconversion"
  51. #pragma clang diagnostic ignored "-Wshadow"
  52. #pragma clang diagnostic ignored "-Wdeprecated-register"
  53. #pragma clang diagnostic ignored "-Wunused-parameter"
  54. #pragma clang diagnostic ignored "-Wdeprecated-writable-strings"
  55. #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  56. #endif
  57. #ifdef _MSC_VER
  58. #pragma warning (push)
  59. #pragma warning (disable : 4458)
  60. #endif
  61. /* These files come with the Steinberg VST SDK - to get them, you'll need to
  62. visit the Steinberg website and agree to whatever is currently required to
  63. get them. The best version to get is the VST3 SDK, which also contains
  64. the older VST2.4 files.
  65. Then, you'll need to make sure your include path contains your "VST SDK3"
  66. directory (or whatever you've named it on your machine). The introjucer has
  67. a special box for setting this path.
  68. */
  69. #include <public.sdk/source/vst2.x/audioeffectx.h>
  70. #include <public.sdk/source/vst2.x/aeffeditor.h>
  71. #include <public.sdk/source/vst2.x/audioeffectx.cpp>
  72. #include <public.sdk/source/vst2.x/audioeffect.cpp>
  73. #if ! VST_2_4_EXTENSIONS
  74. #error "It looks like you're trying to include an out-of-date VSTSDK version - make sure you have at least version 2.4"
  75. #endif
  76. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  77. #define JUCE_VST3_CAN_REPLACE_VST2 1
  78. #endif
  79. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  80. #include <pluginterfaces/base/funknown.h>
  81. namespace juce { extern Steinberg::FUID getJuceVST3ComponentIID(); }
  82. #endif
  83. #ifdef _MSC_VER
  84. #pragma warning (pop)
  85. #endif
  86. #ifdef __clang__
  87. #pragma clang diagnostic pop
  88. #endif
  89. //==============================================================================
  90. #ifdef _MSC_VER
  91. #pragma pack (push, 8)
  92. #endif
  93. #include "../utility/juce_IncludeModuleHeaders.h"
  94. #include "../utility/juce_FakeMouseMoveGenerator.h"
  95. #include "../utility/juce_WindowsHooks.h"
  96. #ifdef _MSC_VER
  97. #pragma pack (pop)
  98. #endif
  99. #undef MemoryBlock
  100. class JuceVSTWrapper;
  101. static bool recursionCheck = false;
  102. static juce::uint32 lastMasterIdleCall = 0;
  103. namespace juce
  104. {
  105. #if JUCE_MAC
  106. extern void initialiseMacVST();
  107. extern void* attachComponentToWindowRefVST (Component*, void* parent, bool isNSView);
  108. extern void detachComponentFromWindowRefVST (Component*, void* window, bool isNSView);
  109. extern void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  110. extern void checkWindowVisibilityVST (void* window, Component*, bool isNSView);
  111. extern bool forwardCurrentKeyEventToHostVST (Component*, bool isNSView);
  112. #if ! JUCE_64BIT
  113. extern void updateEditorCompBoundsVST (Component*);
  114. #endif
  115. #endif
  116. #if JUCE_LINUX
  117. extern Display* display;
  118. #endif
  119. }
  120. //==============================================================================
  121. #if JUCE_WINDOWS
  122. namespace
  123. {
  124. // Returns the actual container window, unlike GetParent, which can also return a separate owner window.
  125. static HWND getWindowParent (HWND w) noexcept { return GetAncestor (w, GA_PARENT); }
  126. static HWND findMDIParentOf (HWND w)
  127. {
  128. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  129. while (w != 0)
  130. {
  131. HWND parent = getWindowParent (w);
  132. if (parent == 0)
  133. break;
  134. TCHAR windowType[32] = { 0 };
  135. GetClassName (parent, windowType, 31);
  136. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  137. return parent;
  138. RECT windowPos, parentPos;
  139. GetWindowRect (w, &windowPos);
  140. GetWindowRect (parent, &parentPos);
  141. const int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  142. const int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  143. if (dw > 100 || dh > 100)
  144. break;
  145. w = parent;
  146. if (dw == 2 * frameThickness)
  147. break;
  148. }
  149. return w;
  150. }
  151. static bool messageThreadIsDefinitelyCorrect = false;
  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. JUCEApplicationBase::quit();
  170. waitForThreadToExit (5000);
  171. clearSingletonInstance();
  172. }
  173. void run() override
  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. public AudioProcessorListener,
  194. public AudioPlayHead,
  195. private Timer,
  196. private AsyncUpdater
  197. {
  198. private:
  199. //==============================================================================
  200. template <typename FloatType>
  201. struct VstTempBuffers
  202. {
  203. VstTempBuffers() {}
  204. ~VstTempBuffers() { release(); }
  205. void release() noexcept
  206. {
  207. for (int i = tempChannels.size(); --i >= 0;)
  208. delete[] (tempChannels.getUnchecked(i));
  209. tempChannels.clear();
  210. }
  211. HeapBlock<FloatType*> channels;
  212. Array<FloatType*> tempChannels; // see note in processReplacing()
  213. juce::AudioBuffer<FloatType> processTempBuffer;
  214. };
  215. public:
  216. //==============================================================================
  217. JuceVSTWrapper (audioMasterCallback audioMasterCB, AudioProcessor* const af)
  218. : AudioEffectX (audioMasterCB, af->getNumPrograms(), af->getNumParameters()),
  219. filter (af),
  220. chunkMemoryTime (0),
  221. speakerIn (kSpeakerArrEmpty),
  222. speakerOut (kSpeakerArrEmpty),
  223. numInChans (JucePlugin_MaxNumInputChannels),
  224. numOutChans (JucePlugin_MaxNumOutputChannels),
  225. isProcessing (false),
  226. isBypassed (false),
  227. hasShutdown (false),
  228. isInSizeWindow (false),
  229. firstProcessCallback (true),
  230. shouldDeleteEditor (false),
  231. #if JUCE_64BIT
  232. useNSView (true),
  233. #else
  234. useNSView (false),
  235. #endif
  236. hostWindow (0)
  237. {
  238. filter->setPlayConfigDetails (numInChans, numOutChans, 0, 0);
  239. filter->setPlayHead (this);
  240. filter->addListener (this);
  241. cEffect.flags |= effFlagsHasEditor;
  242. cEffect.version = convertHexVersionToDecimal (JucePlugin_VersionCode);
  243. setUniqueID ((int) (JucePlugin_VSTUniqueID));
  244. setNumInputs (numInChans);
  245. setNumOutputs (numOutChans);
  246. canProcessReplacing (true);
  247. canDoubleReplacing (filter->supportsDoublePrecisionProcessing());
  248. isSynth ((JucePlugin_IsSynth) != 0);
  249. setInitialDelay (filter->getLatencySamples());
  250. programsAreChunks (true);
  251. // NB: For reasons best known to themselves, some hosts fail to load/save plugin
  252. // state correctly if the plugin doesn't report that it has at least 1 program.
  253. jassert (af->getNumPrograms() > 0);
  254. activePlugins.add (this);
  255. }
  256. ~JuceVSTWrapper()
  257. {
  258. JUCE_AUTORELEASEPOOL
  259. {
  260. {
  261. #if JUCE_LINUX
  262. MessageManagerLock mmLock;
  263. #endif
  264. stopTimer();
  265. deleteEditor (false);
  266. hasShutdown = true;
  267. delete filter;
  268. filter = nullptr;
  269. jassert (editorComp == 0);
  270. deleteTempChannels();
  271. jassert (activePlugins.contains (this));
  272. activePlugins.removeFirstMatchingValue (this);
  273. }
  274. if (activePlugins.size() == 0)
  275. {
  276. #if JUCE_LINUX
  277. SharedMessageThread::deleteInstance();
  278. #endif
  279. shutdownJuce_GUI();
  280. #if JUCE_WINDOWS
  281. messageThreadIsDefinitelyCorrect = false;
  282. #endif
  283. }
  284. }
  285. }
  286. void open() override
  287. {
  288. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  289. if (filter->hasEditor())
  290. cEffect.flags |= effFlagsHasEditor;
  291. else
  292. cEffect.flags &= ~effFlagsHasEditor;
  293. }
  294. void close() override
  295. {
  296. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  297. stopTimer();
  298. if (MessageManager::getInstance()->isThisTheMessageThread())
  299. deleteEditor (false);
  300. }
  301. //==============================================================================
  302. bool getEffectName (char* name) override
  303. {
  304. String (JucePlugin_Name).copyToUTF8 (name, 64);
  305. return true;
  306. }
  307. bool getVendorString (char* text) override
  308. {
  309. String (JucePlugin_Manufacturer).copyToUTF8 (text, 64);
  310. return true;
  311. }
  312. bool getProductString (char* text) override { return getEffectName (text); }
  313. VstInt32 getVendorVersion() override { return convertHexVersionToDecimal (JucePlugin_VersionCode); }
  314. VstPlugCategory getPlugCategory() override { return JucePlugin_VSTCategory; }
  315. bool keysRequired() { return (JucePlugin_EditorRequiresKeyboardFocus) != 0; }
  316. VstInt32 canDo (char* text) override
  317. {
  318. if (strcmp (text, "receiveVstEvents") == 0
  319. || strcmp (text, "receiveVstMidiEvent") == 0
  320. || strcmp (text, "receiveVstMidiEvents") == 0)
  321. {
  322. #if JucePlugin_WantsMidiInput
  323. return 1;
  324. #else
  325. return -1;
  326. #endif
  327. }
  328. if (strcmp (text, "sendVstEvents") == 0
  329. || strcmp (text, "sendVstMidiEvent") == 0
  330. || strcmp (text, "sendVstMidiEvents") == 0)
  331. {
  332. #if JucePlugin_ProducesMidiOutput
  333. return 1;
  334. #else
  335. return -1;
  336. #endif
  337. }
  338. if (strcmp (text, "receiveVstTimeInfo") == 0
  339. || strcmp (text, "conformsToWindowRules") == 0
  340. || strcmp (text, "bypass") == 0)
  341. {
  342. return 1;
  343. }
  344. if (strcmp (text, "openCloseAnyThread") == 0)
  345. {
  346. // This tells Wavelab to use the UI thread to invoke open/close,
  347. // like all other hosts do.
  348. return -1;
  349. }
  350. #if JUCE_MAC
  351. if (strcmp (text, "hasCockosViewAsConfig") == 0)
  352. {
  353. useNSView = true;
  354. return (VstInt32) 0xbeef0000;
  355. }
  356. #endif
  357. return 0;
  358. }
  359. VstIntPtr vendorSpecific (VstInt32 lArg, VstIntPtr lArg2, void* ptrArg, float floatArg) override
  360. {
  361. (void) lArg; (void) lArg2; (void) ptrArg; (void) floatArg;
  362. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  363. if ((lArg == 'stCA' || lArg == 'stCa') && lArg2 == 'FUID' && ptrArg != nullptr)
  364. {
  365. memcpy (ptrArg, getJuceVST3ComponentIID(), 16);
  366. return 1;
  367. }
  368. #endif
  369. return 0;
  370. }
  371. bool getInputProperties (VstInt32 index, VstPinProperties* properties) override
  372. {
  373. if (filter == nullptr || index >= JucePlugin_MaxNumInputChannels)
  374. return false;
  375. setPinProperties (*properties, filter->getInputChannelName ((int) index),
  376. speakerIn, filter->isInputChannelStereoPair ((int) index));
  377. return true;
  378. }
  379. bool getOutputProperties (VstInt32 index, VstPinProperties* properties) override
  380. {
  381. if (filter == nullptr || index >= JucePlugin_MaxNumOutputChannels)
  382. return false;
  383. setPinProperties (*properties, filter->getOutputChannelName ((int) index),
  384. speakerOut, filter->isOutputChannelStereoPair ((int) index));
  385. return true;
  386. }
  387. static void setPinProperties (VstPinProperties& properties, const String& name,
  388. VstSpeakerArrangementType type, const bool isPair)
  389. {
  390. name.copyToUTF8 (properties.label, (size_t) (kVstMaxLabelLen - 1));
  391. name.copyToUTF8 (properties.shortLabel, (size_t) (kVstMaxShortLabelLen - 1));
  392. if (type != kSpeakerArrEmpty)
  393. {
  394. properties.flags = kVstPinUseSpeaker;
  395. properties.arrangementType = type;
  396. }
  397. else
  398. {
  399. properties.flags = kVstPinIsActive;
  400. properties.arrangementType = 0;
  401. if (isPair)
  402. properties.flags |= kVstPinIsStereo;
  403. }
  404. }
  405. bool setBypass (bool b) override
  406. {
  407. isBypassed = b;
  408. return true;
  409. }
  410. VstInt32 getGetTailSize() override
  411. {
  412. if (filter != nullptr)
  413. return (VstInt32) (filter->getTailLengthSeconds() * getSampleRate());
  414. return 0;
  415. }
  416. //==============================================================================
  417. VstInt32 processEvents (VstEvents* events) override
  418. {
  419. #if JucePlugin_WantsMidiInput
  420. VSTMidiEventList::addEventsToMidiBuffer (events, midiEvents);
  421. return 1;
  422. #else
  423. (void) events;
  424. return 0;
  425. #endif
  426. }
  427. void process (float** inputs, float** outputs, VstInt32 numSamples)
  428. {
  429. VstTempBuffers<float>& tmpBuffers = floatTempBuffers;
  430. const int numIn = numInChans;
  431. const int numOut = numOutChans;
  432. tmpBuffers.processTempBuffer.setSize (numIn, numSamples, false, false, true);
  433. for (int i = numIn; --i >= 0;)
  434. tmpBuffers.processTempBuffer.copyFrom (i, 0, outputs[i], numSamples);
  435. processReplacing (inputs, outputs, numSamples);
  436. AudioSampleBuffer dest (outputs, numOut, numSamples);
  437. for (int i = jmin (numIn, numOut); --i >= 0;)
  438. dest.addFrom (i, 0, tmpBuffers.processTempBuffer, i, 0, numSamples);
  439. }
  440. template <typename FloatType>
  441. void internalProcessReplacing (FloatType** inputs, FloatType** outputs,
  442. VstInt32 numSamples, VstTempBuffers<FloatType>& tmpBuffers)
  443. {
  444. if (firstProcessCallback)
  445. {
  446. firstProcessCallback = false;
  447. // if this fails, the host hasn't called resume() before processing
  448. jassert (isProcessing);
  449. // (tragically, some hosts actually need this, although it's stupid to have
  450. // to do it here..)
  451. if (! isProcessing)
  452. resume();
  453. filter->setNonRealtime (getCurrentProcessLevel() == 4 /* kVstProcessLevelOffline */);
  454. }
  455. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  456. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  457. #endif
  458. jassert (activePlugins.contains (this));
  459. {
  460. const ScopedLock sl (filter->getCallbackLock());
  461. const int numIn = numInChans;
  462. const int numOut = numOutChans;
  463. if (filter->isSuspended())
  464. {
  465. for (int i = 0; i < numOut; ++i)
  466. FloatVectorOperations::clear (outputs[i], numSamples);
  467. }
  468. else
  469. {
  470. int i;
  471. for (i = 0; i < numOut; ++i)
  472. {
  473. FloatType* chan = tmpBuffers.tempChannels.getUnchecked(i);
  474. if (chan == nullptr)
  475. {
  476. chan = outputs[i];
  477. // if some output channels are disabled, some hosts supply the same buffer
  478. // for multiple channels - this buggers up our method of copying the
  479. // inputs over the outputs, so we need to create unique temp buffers in this case..
  480. for (int j = i; --j >= 0;)
  481. {
  482. if (outputs[j] == chan)
  483. {
  484. chan = new FloatType [blockSize * 2];
  485. tmpBuffers.tempChannels.set (i, chan);
  486. break;
  487. }
  488. }
  489. }
  490. if (i < numIn && chan != inputs[i])
  491. memcpy (chan, inputs[i], sizeof (FloatType) * (size_t) numSamples);
  492. tmpBuffers.channels[i] = chan;
  493. }
  494. for (; i < numIn; ++i)
  495. tmpBuffers.channels[i] = inputs[i];
  496. {
  497. AudioBuffer<FloatType> chans (tmpBuffers.channels, jmax (numIn, numOut), numSamples);
  498. if (isBypassed)
  499. filter->processBlockBypassed (chans, midiEvents);
  500. else
  501. filter->processBlock (chans, midiEvents);
  502. }
  503. // copy back any temp channels that may have been used..
  504. for (i = 0; i < numOut; ++i)
  505. if (const FloatType* const chan = tmpBuffers.tempChannels.getUnchecked(i))
  506. memcpy (outputs[i], chan, sizeof (FloatType) * (size_t) numSamples);
  507. }
  508. }
  509. if (! midiEvents.isEmpty())
  510. {
  511. #if JucePlugin_ProducesMidiOutput
  512. const int numEvents = midiEvents.getNumEvents();
  513. outgoingEvents.ensureSize (numEvents);
  514. outgoingEvents.clear();
  515. const juce::uint8* midiEventData;
  516. int midiEventSize, midiEventPosition;
  517. MidiBuffer::Iterator i (midiEvents);
  518. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  519. {
  520. jassert (midiEventPosition >= 0 && midiEventPosition < numSamples);
  521. outgoingEvents.addEvent (midiEventData, midiEventSize, midiEventPosition);
  522. }
  523. sendVstEventsToHost (outgoingEvents.events);
  524. #elif JUCE_DEBUG
  525. /* This assertion is caused when you've added some events to the
  526. midiMessages array in your processBlock() method, which usually means
  527. that you're trying to send them somewhere. But in this case they're
  528. getting thrown away.
  529. If your plugin does want to send midi messages, you'll need to set
  530. the JucePlugin_ProducesMidiOutput macro to 1 in your
  531. JucePluginCharacteristics.h file.
  532. If you don't want to produce any midi output, then you should clear the
  533. midiMessages array at the end of your processBlock() method, to
  534. indicate that you don't want any of the events to be passed through
  535. to the output.
  536. */
  537. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  538. #endif
  539. midiEvents.clear();
  540. }
  541. }
  542. void processReplacing (float** inputs, float** outputs, VstInt32 sampleFrames) override
  543. {
  544. jassert (! filter->isUsingDoublePrecision());
  545. internalProcessReplacing (inputs, outputs, sampleFrames, floatTempBuffers);
  546. }
  547. void processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames) override
  548. {
  549. jassert (filter->isUsingDoublePrecision());
  550. internalProcessReplacing (inputs, outputs, sampleFrames, doubleTempBuffers);
  551. }
  552. //==============================================================================
  553. VstInt32 startProcess() override { return 0; }
  554. VstInt32 stopProcess() override { return 0; }
  555. //==============================================================================
  556. bool setProcessPrecision (VstInt32 vstPrecision) override
  557. {
  558. if (! isProcessing)
  559. {
  560. if (filter != nullptr)
  561. {
  562. filter->setProcessingPrecision (vstPrecision == kVstProcessPrecision64 && filter->supportsDoublePrecisionProcessing()
  563. ? AudioProcessor::doublePrecision
  564. : AudioProcessor::singlePrecision);
  565. return true;
  566. }
  567. }
  568. return false;
  569. }
  570. void resume() override
  571. {
  572. if (filter != nullptr)
  573. {
  574. isProcessing = true;
  575. floatTempBuffers.channels.calloc ((size_t) (numInChans + numOutChans));
  576. doubleTempBuffers.channels.calloc ((size_t) (numInChans + numOutChans));
  577. double rate = getSampleRate();
  578. jassert (rate > 0);
  579. if (rate <= 0.0)
  580. rate = 44100.0;
  581. const int currentBlockSize = getBlockSize();
  582. jassert (currentBlockSize > 0);
  583. firstProcessCallback = true;
  584. filter->setNonRealtime (getCurrentProcessLevel() == 4 /* kVstProcessLevelOffline */);
  585. filter->setPlayConfigDetails (numInChans, numOutChans, rate, currentBlockSize);
  586. deleteTempChannels();
  587. filter->prepareToPlay (rate, currentBlockSize);
  588. midiEvents.ensureSize (2048);
  589. midiEvents.clear();
  590. setInitialDelay (filter->getLatencySamples());
  591. AudioEffectX::resume();
  592. #if JucePlugin_ProducesMidiOutput
  593. outgoingEvents.ensureSize (512);
  594. #endif
  595. }
  596. }
  597. void suspend() override
  598. {
  599. if (filter != nullptr)
  600. {
  601. AudioEffectX::suspend();
  602. filter->releaseResources();
  603. outgoingEvents.freeEvents();
  604. isProcessing = false;
  605. floatTempBuffers.channels.free();
  606. doubleTempBuffers.channels.free();
  607. deleteTempChannels();
  608. }
  609. }
  610. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info) override
  611. {
  612. const VstTimeInfo* const ti = getTimeInfo (kVstPpqPosValid | kVstTempoValid | kVstBarsValid | kVstCyclePosValid
  613. | kVstTimeSigValid | kVstSmpteValid | kVstClockValid);
  614. if (ti == nullptr || ti->sampleRate <= 0)
  615. return false;
  616. info.bpm = (ti->flags & kVstTempoValid) != 0 ? ti->tempo : 0.0;
  617. if ((ti->flags & kVstTimeSigValid) != 0)
  618. {
  619. info.timeSigNumerator = ti->timeSigNumerator;
  620. info.timeSigDenominator = ti->timeSigDenominator;
  621. }
  622. else
  623. {
  624. info.timeSigNumerator = 4;
  625. info.timeSigDenominator = 4;
  626. }
  627. info.timeInSamples = (int64) (ti->samplePos + 0.5);
  628. info.timeInSeconds = ti->samplePos / ti->sampleRate;
  629. info.ppqPosition = (ti->flags & kVstPpqPosValid) != 0 ? ti->ppqPos : 0.0;
  630. info.ppqPositionOfLastBarStart = (ti->flags & kVstBarsValid) != 0 ? ti->barStartPos : 0.0;
  631. if ((ti->flags & kVstSmpteValid) != 0)
  632. {
  633. AudioPlayHead::FrameRateType rate = AudioPlayHead::fpsUnknown;
  634. double fps = 1.0;
  635. switch (ti->smpteFrameRate)
  636. {
  637. case kVstSmpte24fps: rate = AudioPlayHead::fps24; fps = 24.0; break;
  638. case kVstSmpte25fps: rate = AudioPlayHead::fps25; fps = 25.0; break;
  639. case kVstSmpte2997fps: rate = AudioPlayHead::fps2997; fps = 29.97; break;
  640. case kVstSmpte30fps: rate = AudioPlayHead::fps30; fps = 30.0; break;
  641. case kVstSmpte2997dfps: rate = AudioPlayHead::fps2997drop; fps = 29.97; break;
  642. case kVstSmpte30dfps: rate = AudioPlayHead::fps30drop; fps = 30.0; break;
  643. case kVstSmpteFilm16mm:
  644. case kVstSmpteFilm35mm: fps = 24.0; break;
  645. case kVstSmpte239fps: fps = 23.976; break;
  646. case kVstSmpte249fps: fps = 24.976; break;
  647. case kVstSmpte599fps: fps = 59.94; break;
  648. case kVstSmpte60fps: fps = 60; break;
  649. default: jassertfalse; // unknown frame-rate..
  650. }
  651. info.frameRate = rate;
  652. info.editOriginTime = ti->smpteOffset / (80.0 * fps);
  653. }
  654. else
  655. {
  656. info.frameRate = AudioPlayHead::fpsUnknown;
  657. info.editOriginTime = 0;
  658. }
  659. info.isRecording = (ti->flags & kVstTransportRecording) != 0;
  660. info.isPlaying = (ti->flags & (kVstTransportRecording | kVstTransportPlaying)) != 0;
  661. info.isLooping = (ti->flags & kVstTransportCycleActive) != 0;
  662. if ((ti->flags & kVstCyclePosValid) != 0)
  663. {
  664. info.ppqLoopStart = ti->cycleStartPos;
  665. info.ppqLoopEnd = ti->cycleEndPos;
  666. }
  667. else
  668. {
  669. info.ppqLoopStart = 0;
  670. info.ppqLoopEnd = 0;
  671. }
  672. return true;
  673. }
  674. //==============================================================================
  675. VstInt32 getProgram() override
  676. {
  677. return filter != nullptr ? filter->getCurrentProgram() : 0;
  678. }
  679. void setProgram (VstInt32 program) override
  680. {
  681. if (filter != nullptr)
  682. filter->setCurrentProgram (program);
  683. }
  684. void setProgramName (char* name) override
  685. {
  686. if (filter != nullptr)
  687. filter->changeProgramName (filter->getCurrentProgram(), name);
  688. }
  689. void getProgramName (char* name) override
  690. {
  691. if (filter != nullptr)
  692. filter->getProgramName (filter->getCurrentProgram()).copyToUTF8 (name, 24);
  693. }
  694. bool getProgramNameIndexed (VstInt32 /*category*/, VstInt32 index, char* text) override
  695. {
  696. if (filter != nullptr && isPositiveAndBelow (index, filter->getNumPrograms()))
  697. {
  698. filter->getProgramName (index).copyToUTF8 (text, 24);
  699. return true;
  700. }
  701. return false;
  702. }
  703. //==============================================================================
  704. float getParameter (VstInt32 index) override
  705. {
  706. if (filter == nullptr)
  707. return 0.0f;
  708. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  709. return filter->getParameter (index);
  710. }
  711. void setParameter (VstInt32 index, float value) override
  712. {
  713. if (filter != nullptr)
  714. {
  715. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  716. filter->setParameter (index, value);
  717. }
  718. }
  719. void getParameterDisplay (VstInt32 index, char* text) override
  720. {
  721. if (filter != nullptr)
  722. {
  723. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  724. filter->getParameterText (index, 24).copyToUTF8 (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  725. }
  726. }
  727. bool string2parameter (VstInt32 index, char* text) override
  728. {
  729. if (filter != nullptr)
  730. {
  731. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  732. if (AudioProcessorParameter* p = filter->getParameters()[index])
  733. {
  734. filter->setParameter (index, p->getValueForText (String::fromUTF8 (text)));
  735. return true;
  736. }
  737. }
  738. return false;
  739. }
  740. void getParameterName (VstInt32 index, char* text) override
  741. {
  742. if (filter != nullptr)
  743. {
  744. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  745. filter->getParameterName (index, 16).copyToUTF8 (text, 16); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  746. }
  747. }
  748. void getParameterLabel (VstInt32 index, char* text) override
  749. {
  750. if (filter != nullptr)
  751. {
  752. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  753. filter->getParameterLabel (index).copyToUTF8 (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  754. }
  755. }
  756. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  757. {
  758. if (audioMaster != nullptr)
  759. audioMaster (&cEffect, audioMasterAutomate, index, 0, 0, newValue);
  760. }
  761. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit (index); }
  762. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit (index); }
  763. void audioProcessorChanged (AudioProcessor*) override
  764. {
  765. setInitialDelay (filter->getLatencySamples());
  766. updateDisplay();
  767. triggerAsyncUpdate();
  768. }
  769. void handleAsyncUpdate() override
  770. {
  771. ioChanged();
  772. }
  773. bool canParameterBeAutomated (VstInt32 index) override
  774. {
  775. return filter != nullptr && filter->isParameterAutomatable ((int) index);
  776. }
  777. struct ChannelConfigComparator
  778. {
  779. static int compareElements (const short* const first, const short* const second) noexcept
  780. {
  781. if (first[0] < second[0]) return -1;
  782. if (first[0] > second[0]) return 1;
  783. if (first[1] < second[1]) return -1;
  784. if (first[1] > second[1]) return 1;
  785. return 0;
  786. }
  787. };
  788. bool setSpeakerArrangement (VstSpeakerArrangement* pluginInput,
  789. VstSpeakerArrangement* pluginOutput) override
  790. {
  791. short channelConfigs[][2] = { JucePlugin_PreferredChannelConfigurations };
  792. Array<short*> channelConfigsSorted;
  793. ChannelConfigComparator comp;
  794. for (int i = 0; i < numElementsInArray (channelConfigs); ++i)
  795. channelConfigsSorted.addSorted (comp, channelConfigs[i]);
  796. for (int i = channelConfigsSorted.size(); --i >= 0;)
  797. {
  798. const short* const config = channelConfigsSorted.getUnchecked(i);
  799. bool inCountMatches = (config[0] == pluginInput->numChannels);
  800. bool outCountMatches = (config[1] == pluginOutput->numChannels);
  801. if (inCountMatches && outCountMatches)
  802. {
  803. speakerIn = (VstSpeakerArrangementType) pluginInput->type;
  804. speakerOut = (VstSpeakerArrangementType) pluginOutput->type;
  805. numInChans = pluginInput->numChannels;
  806. numOutChans = pluginOutput->numChannels;
  807. filter->setPlayConfigDetails (numInChans, numOutChans,
  808. filter->getSampleRate(),
  809. filter->getBlockSize());
  810. filter->setSpeakerArrangement (getSpeakerArrangementString (speakerIn),
  811. getSpeakerArrangementString (speakerOut));
  812. return true;
  813. }
  814. }
  815. filter->setSpeakerArrangement (String::empty, String::empty);
  816. return false;
  817. }
  818. static const char* getSpeakerArrangementString (VstSpeakerArrangementType type) noexcept
  819. {
  820. switch (type)
  821. {
  822. case kSpeakerArrMono: return "M";
  823. case kSpeakerArrStereo: return "L R";
  824. case kSpeakerArrStereoSurround: return "Ls Rs";
  825. case kSpeakerArrStereoCenter: return "Lc Rc";
  826. case kSpeakerArrStereoSide: return "Sl Sr";
  827. case kSpeakerArrStereoCLfe: return "C Lfe";
  828. case kSpeakerArr30Cine: return "L R C";
  829. case kSpeakerArr30Music: return "L R S";
  830. case kSpeakerArr31Cine: return "L R C Lfe";
  831. case kSpeakerArr31Music: return "L R Lfe S";
  832. case kSpeakerArr40Cine: return "L R C S";
  833. case kSpeakerArr40Music: return "L R Ls Rs";
  834. case kSpeakerArr41Cine: return "L R C Lfe S";
  835. case kSpeakerArr41Music: return "L R Lfe Ls Rs";
  836. case kSpeakerArr50: return "L R C Ls Rs" ;
  837. case kSpeakerArr51: return "L R C Lfe Ls Rs";
  838. case kSpeakerArr60Cine: return "L R C Ls Rs Cs";
  839. case kSpeakerArr60Music: return "L R Ls Rs Sl Sr ";
  840. case kSpeakerArr61Cine: return "L R C Lfe Ls Rs Cs";
  841. case kSpeakerArr61Music: return "L R Lfe Ls Rs Sl Sr";
  842. case kSpeakerArr70Cine: return "L R C Ls Rs Lc Rc ";
  843. case kSpeakerArr70Music: return "L R C Ls Rs Sl Sr";
  844. case kSpeakerArr71Cine: return "L R C Lfe Ls Rs Lc Rc";
  845. case kSpeakerArr71Music: return "L R C Lfe Ls Rs Sl Sr";
  846. case kSpeakerArr80Cine: return "L R C Ls Rs Lc Rc Cs";
  847. case kSpeakerArr80Music: return "L R C Ls Rs Cs Sl Sr";
  848. case kSpeakerArr81Cine: return "L R C Lfe Ls Rs Lc Rc Cs";
  849. case kSpeakerArr81Music: return "L R C Lfe Ls Rs Cs Sl Sr" ;
  850. case kSpeakerArr102: return "L R C Lfe Ls Rs Tfl Tfc Tfr Trl Trr Lfe2";
  851. default: break;
  852. }
  853. return nullptr;
  854. }
  855. //==============================================================================
  856. VstInt32 getChunk (void** data, bool onlyStoreCurrentProgramData) override
  857. {
  858. if (filter == nullptr)
  859. return 0;
  860. chunkMemory.reset();
  861. if (onlyStoreCurrentProgramData)
  862. filter->getCurrentProgramStateInformation (chunkMemory);
  863. else
  864. filter->getStateInformation (chunkMemory);
  865. *data = (void*) chunkMemory.getData();
  866. // because the chunk is only needed temporarily by the host (or at least you'd
  867. // hope so) we'll give it a while and then free it in the timer callback.
  868. chunkMemoryTime = juce::Time::getApproximateMillisecondCounter();
  869. return (VstInt32) chunkMemory.getSize();
  870. }
  871. VstInt32 setChunk (void* data, VstInt32 byteSize, bool onlyRestoreCurrentProgramData) override
  872. {
  873. if (filter != nullptr)
  874. {
  875. chunkMemory.reset();
  876. chunkMemoryTime = 0;
  877. if (byteSize > 0 && data != nullptr)
  878. {
  879. if (onlyRestoreCurrentProgramData)
  880. filter->setCurrentProgramStateInformation (data, byteSize);
  881. else
  882. filter->setStateInformation (data, byteSize);
  883. }
  884. }
  885. return 0;
  886. }
  887. void timerCallback() override
  888. {
  889. if (shouldDeleteEditor)
  890. {
  891. shouldDeleteEditor = false;
  892. deleteEditor (true);
  893. }
  894. if (chunkMemoryTime > 0
  895. && chunkMemoryTime < juce::Time::getApproximateMillisecondCounter() - 2000
  896. && ! recursionCheck)
  897. {
  898. chunkMemory.reset();
  899. chunkMemoryTime = 0;
  900. }
  901. #if JUCE_MAC
  902. if (hostWindow != 0)
  903. checkWindowVisibilityVST (hostWindow, editorComp, useNSView);
  904. #endif
  905. tryMasterIdle();
  906. }
  907. void tryMasterIdle()
  908. {
  909. if (Component::isMouseButtonDownAnywhere() && ! recursionCheck)
  910. {
  911. const juce::uint32 now = juce::Time::getMillisecondCounter();
  912. if (now > lastMasterIdleCall + 20 && editorComp != nullptr)
  913. {
  914. lastMasterIdleCall = now;
  915. recursionCheck = true;
  916. masterIdle();
  917. recursionCheck = false;
  918. }
  919. }
  920. }
  921. void doIdleCallback()
  922. {
  923. // (wavelab calls this on a separate thread and causes a deadlock)..
  924. if (MessageManager::getInstance()->isThisTheMessageThread()
  925. && ! recursionCheck)
  926. {
  927. recursionCheck = true;
  928. JUCE_AUTORELEASEPOOL
  929. {
  930. Timer::callPendingTimersSynchronously();
  931. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  932. if (ComponentPeer* p = ComponentPeer::getPeer(i))
  933. p->performAnyPendingRepaintsNow();
  934. recursionCheck = false;
  935. }
  936. }
  937. }
  938. void createEditorComp()
  939. {
  940. if (hasShutdown || filter == nullptr)
  941. return;
  942. if (editorComp == nullptr)
  943. {
  944. if (AudioProcessorEditor* const ed = filter->createEditorIfNeeded())
  945. {
  946. cEffect.flags |= effFlagsHasEditor;
  947. ed->setOpaque (true);
  948. ed->setVisible (true);
  949. editorComp = new EditorCompWrapper (*this, ed);
  950. }
  951. else
  952. {
  953. cEffect.flags &= ~effFlagsHasEditor;
  954. }
  955. }
  956. shouldDeleteEditor = false;
  957. }
  958. void deleteEditor (bool canDeleteLaterIfModal)
  959. {
  960. JUCE_AUTORELEASEPOOL
  961. {
  962. PopupMenu::dismissAllActiveMenus();
  963. jassert (! recursionCheck);
  964. recursionCheck = true;
  965. if (editorComp != nullptr)
  966. {
  967. if (Component* const modalComponent = Component::getCurrentlyModalComponent())
  968. {
  969. modalComponent->exitModalState (0);
  970. if (canDeleteLaterIfModal)
  971. {
  972. shouldDeleteEditor = true;
  973. recursionCheck = false;
  974. return;
  975. }
  976. }
  977. #if JUCE_MAC
  978. if (hostWindow != 0)
  979. {
  980. detachComponentFromWindowRefVST (editorComp, hostWindow, useNSView);
  981. hostWindow = 0;
  982. }
  983. #endif
  984. filter->editorBeingDeleted (editorComp->getEditorComp());
  985. editorComp = nullptr;
  986. // there's some kind of component currently modal, but the host
  987. // is trying to delete our plugin. You should try to avoid this happening..
  988. jassert (Component::getCurrentlyModalComponent() == nullptr);
  989. }
  990. #if JUCE_LINUX
  991. hostWindow = 0;
  992. #endif
  993. recursionCheck = false;
  994. }
  995. }
  996. VstIntPtr dispatcher (VstInt32 opCode, VstInt32 index, VstIntPtr value, void* ptr, float opt) override
  997. {
  998. if (hasShutdown)
  999. return 0;
  1000. if (opCode == effEditIdle)
  1001. {
  1002. doIdleCallback();
  1003. return 0;
  1004. }
  1005. else if (opCode == effEditOpen)
  1006. {
  1007. checkWhetherMessageThreadIsCorrect();
  1008. const MessageManagerLock mmLock;
  1009. jassert (! recursionCheck);
  1010. startTimer (1000 / 4); // performs misc housekeeping chores
  1011. deleteEditor (true);
  1012. createEditorComp();
  1013. if (editorComp != nullptr)
  1014. {
  1015. editorComp->setOpaque (true);
  1016. editorComp->setVisible (false);
  1017. #if JUCE_WINDOWS
  1018. editorComp->addToDesktop (0, ptr);
  1019. hostWindow = (HWND) ptr;
  1020. #elif JUCE_LINUX
  1021. editorComp->addToDesktop (0, ptr);
  1022. hostWindow = (Window) ptr;
  1023. Window editorWnd = (Window) editorComp->getWindowHandle();
  1024. XReparentWindow (display, editorWnd, hostWindow, 0, 0);
  1025. #else
  1026. hostWindow = attachComponentToWindowRefVST (editorComp, ptr, useNSView);
  1027. #endif
  1028. editorComp->setVisible (true);
  1029. return 1;
  1030. }
  1031. }
  1032. else if (opCode == effEditClose)
  1033. {
  1034. checkWhetherMessageThreadIsCorrect();
  1035. const MessageManagerLock mmLock;
  1036. deleteEditor (true);
  1037. return 0;
  1038. }
  1039. else if (opCode == effEditGetRect)
  1040. {
  1041. checkWhetherMessageThreadIsCorrect();
  1042. const MessageManagerLock mmLock;
  1043. createEditorComp();
  1044. if (editorComp != nullptr)
  1045. {
  1046. editorSize.left = 0;
  1047. editorSize.top = 0;
  1048. editorSize.right = (VstInt16) editorComp->getWidth();
  1049. editorSize.bottom = (VstInt16) editorComp->getHeight();
  1050. *((ERect**) ptr) = &editorSize;
  1051. return (VstIntPtr) (pointer_sized_int) &editorSize;
  1052. }
  1053. return 0;
  1054. }
  1055. return AudioEffectX::dispatcher (opCode, index, value, ptr, opt);
  1056. }
  1057. void resizeHostWindow (int newWidth, int newHeight)
  1058. {
  1059. if (editorComp != nullptr)
  1060. {
  1061. bool sizeWasSuccessful = false;
  1062. if (canHostDo (const_cast<char*> ("sizeWindow")))
  1063. {
  1064. isInSizeWindow = true;
  1065. sizeWasSuccessful = sizeWindow (newWidth, newHeight);
  1066. isInSizeWindow = false;
  1067. }
  1068. if (! sizeWasSuccessful)
  1069. {
  1070. // some hosts don't support the sizeWindow call, so do it manually..
  1071. #if JUCE_MAC
  1072. setNativeHostWindowSizeVST (hostWindow, editorComp, newWidth, newHeight, useNSView);
  1073. #elif JUCE_LINUX
  1074. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  1075. editorComp->setSize (newWidth, newHeight);
  1076. #else
  1077. int dw = 0;
  1078. int dh = 0;
  1079. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  1080. HWND w = (HWND) editorComp->getWindowHandle();
  1081. while (w != 0)
  1082. {
  1083. HWND parent = getWindowParent (w);
  1084. if (parent == 0)
  1085. break;
  1086. TCHAR windowType [32] = { 0 };
  1087. GetClassName (parent, windowType, 31);
  1088. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  1089. break;
  1090. RECT windowPos, parentPos;
  1091. GetWindowRect (w, &windowPos);
  1092. GetWindowRect (parent, &parentPos);
  1093. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1094. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1095. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1096. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1097. w = parent;
  1098. if (dw == 2 * frameThickness)
  1099. break;
  1100. if (dw > 100 || dh > 100)
  1101. w = 0;
  1102. }
  1103. if (w != 0)
  1104. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1105. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1106. #endif
  1107. }
  1108. if (ComponentPeer* peer = editorComp->getPeer())
  1109. {
  1110. peer->handleMovedOrResized();
  1111. peer->getComponent().repaint();
  1112. }
  1113. }
  1114. }
  1115. //==============================================================================
  1116. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  1117. // chores when it changes or repaints.
  1118. class EditorCompWrapper : public Component,
  1119. public AsyncUpdater
  1120. {
  1121. public:
  1122. EditorCompWrapper (JuceVSTWrapper& w, AudioProcessorEditor* editor)
  1123. : wrapper (w)
  1124. {
  1125. setOpaque (true);
  1126. editor->setOpaque (true);
  1127. setBounds (editor->getBounds());
  1128. editor->setTopLeftPosition (0, 0);
  1129. addAndMakeVisible (editor);
  1130. #if JUCE_WINDOWS
  1131. if (! getHostType().isReceptor())
  1132. addMouseListener (this, true);
  1133. #endif
  1134. }
  1135. ~EditorCompWrapper()
  1136. {
  1137. deleteAllChildren(); // note that we can't use a ScopedPointer because the editor may
  1138. // have been transferred to another parent which takes over ownership.
  1139. }
  1140. void paint (Graphics&) override {}
  1141. void paintOverChildren (Graphics&) override
  1142. {
  1143. // this causes an async call to masterIdle() to help
  1144. // creaky old DAWs like Nuendo repaint themselves while we're
  1145. // repainting. Otherwise they just seem to give up and sit there
  1146. // waiting.
  1147. triggerAsyncUpdate();
  1148. }
  1149. #if JUCE_MAC
  1150. bool keyPressed (const KeyPress&) override
  1151. {
  1152. // If we have an unused keypress, move the key-focus to a host window
  1153. // and re-inject the event..
  1154. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1155. }
  1156. #endif
  1157. AudioProcessorEditor* getEditorComp() const
  1158. {
  1159. return dynamic_cast<AudioProcessorEditor*> (getChildComponent(0));
  1160. }
  1161. void resized() override
  1162. {
  1163. if (Component* const editorChildComp = getChildComponent(0))
  1164. editorChildComp->setBounds (getLocalBounds());
  1165. #if JUCE_MAC && ! JUCE_64BIT
  1166. if (! wrapper.useNSView)
  1167. updateEditorCompBoundsVST (this);
  1168. #endif
  1169. }
  1170. void childBoundsChanged (Component* child) override
  1171. {
  1172. if (! wrapper.isInSizeWindow)
  1173. {
  1174. child->setTopLeftPosition (0, 0);
  1175. const int cw = child->getWidth();
  1176. const int ch = child->getHeight();
  1177. #if JUCE_MAC
  1178. if (wrapper.useNSView)
  1179. setTopLeftPosition (0, getHeight() - ch);
  1180. #endif
  1181. wrapper.resizeHostWindow (cw, ch);
  1182. #if ! JUCE_LINUX // setSize() on linux causes renoise and energyxt to fail.
  1183. setSize (cw, ch);
  1184. #else
  1185. XResizeWindow (display, (Window) getWindowHandle(), (unsigned int) cw, (unsigned int) ch);
  1186. #endif
  1187. #if JUCE_MAC
  1188. wrapper.resizeHostWindow (cw, ch); // (doing this a second time seems to be necessary in tracktion)
  1189. #endif
  1190. }
  1191. }
  1192. void handleAsyncUpdate() override
  1193. {
  1194. wrapper.tryMasterIdle();
  1195. }
  1196. #if JUCE_WINDOWS
  1197. void mouseDown (const MouseEvent&) override
  1198. {
  1199. broughtToFront();
  1200. }
  1201. void broughtToFront() override
  1202. {
  1203. // for hosts like nuendo, need to also pop the MDI container to the
  1204. // front when our comp is clicked on.
  1205. if (! isCurrentlyBlockedByAnotherModalComponent())
  1206. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  1207. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1208. }
  1209. #endif
  1210. private:
  1211. //==============================================================================
  1212. JuceVSTWrapper& wrapper;
  1213. FakeMouseMoveGenerator fakeMouseGenerator;
  1214. #if JUCE_WINDOWS
  1215. WindowsHooks hooks;
  1216. #endif
  1217. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1218. };
  1219. //==============================================================================
  1220. private:
  1221. AudioProcessor* filter;
  1222. juce::MemoryBlock chunkMemory;
  1223. juce::uint32 chunkMemoryTime;
  1224. ScopedPointer<EditorCompWrapper> editorComp;
  1225. ERect editorSize;
  1226. MidiBuffer midiEvents;
  1227. VSTMidiEventList outgoingEvents;
  1228. VstSpeakerArrangementType speakerIn, speakerOut;
  1229. int numInChans, numOutChans;
  1230. bool isProcessing, isBypassed, hasShutdown, isInSizeWindow, firstProcessCallback;
  1231. bool shouldDeleteEditor, useNSView;
  1232. VstTempBuffers<float> floatTempBuffers;
  1233. VstTempBuffers<double> doubleTempBuffers;
  1234. #if JUCE_MAC
  1235. void* hostWindow;
  1236. #elif JUCE_LINUX
  1237. Window hostWindow;
  1238. #else
  1239. HWND hostWindow;
  1240. #endif
  1241. static inline VstInt32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1242. {
  1243. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1244. return (VstInt32) hexVersion;
  1245. #else
  1246. return (VstInt32) (((hexVersion >> 24) & 0xff) * 1000
  1247. + ((hexVersion >> 16) & 0xff) * 100
  1248. + ((hexVersion >> 8) & 0xff) * 10
  1249. + (hexVersion & 0xff));
  1250. #endif
  1251. }
  1252. //==============================================================================
  1253. #if JUCE_WINDOWS
  1254. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1255. static void checkWhetherMessageThreadIsCorrect()
  1256. {
  1257. const PluginHostType host (getHostType());
  1258. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1259. {
  1260. if (! messageThreadIsDefinitelyCorrect)
  1261. {
  1262. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1263. class MessageThreadCallback : public CallbackMessage
  1264. {
  1265. public:
  1266. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1267. void messageCallback() override
  1268. {
  1269. triggered = true;
  1270. }
  1271. private:
  1272. bool& triggered;
  1273. };
  1274. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1275. }
  1276. }
  1277. }
  1278. #else
  1279. static void checkWhetherMessageThreadIsCorrect() {}
  1280. #endif
  1281. //==============================================================================
  1282. template <typename FloatType>
  1283. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1284. {
  1285. tmpBuffers.release();
  1286. if (filter != nullptr)
  1287. {
  1288. int numChannels = filter->getNumInputChannels() + filter->getNumOutputChannels();
  1289. tmpBuffers.tempChannels.insertMultiple (0, nullptr, numChannels);
  1290. }
  1291. }
  1292. void deleteTempChannels()
  1293. {
  1294. deleteTempChannels (floatTempBuffers);
  1295. deleteTempChannels (doubleTempBuffers);
  1296. }
  1297. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1298. };
  1299. //==============================================================================
  1300. namespace
  1301. {
  1302. AEffect* pluginEntryPoint (audioMasterCallback audioMaster)
  1303. {
  1304. JUCE_AUTORELEASEPOOL
  1305. {
  1306. initialiseJuce_GUI();
  1307. try
  1308. {
  1309. if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0)
  1310. {
  1311. #if JUCE_LINUX
  1312. MessageManagerLock mmLock;
  1313. #endif
  1314. AudioProcessor* const filter = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1315. JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter);
  1316. return wrapper->getAeffect();
  1317. }
  1318. }
  1319. catch (...)
  1320. {}
  1321. }
  1322. return nullptr;
  1323. }
  1324. }
  1325. #if ! JUCE_WINDOWS
  1326. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1327. #endif
  1328. //==============================================================================
  1329. // Mac startup code..
  1330. #if JUCE_MAC
  1331. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster);
  1332. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1333. {
  1334. initialiseMacVST();
  1335. return pluginEntryPoint (audioMaster);
  1336. }
  1337. JUCE_EXPORTED_FUNCTION AEffect* main_macho (audioMasterCallback audioMaster);
  1338. JUCE_EXPORTED_FUNCTION AEffect* main_macho (audioMasterCallback audioMaster)
  1339. {
  1340. initialiseMacVST();
  1341. return pluginEntryPoint (audioMaster);
  1342. }
  1343. //==============================================================================
  1344. // Linux startup code..
  1345. #elif JUCE_LINUX
  1346. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster);
  1347. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1348. {
  1349. SharedMessageThread::getInstance();
  1350. return pluginEntryPoint (audioMaster);
  1351. }
  1352. JUCE_EXPORTED_FUNCTION AEffect* main_plugin (audioMasterCallback audioMaster) asm ("main");
  1353. JUCE_EXPORTED_FUNCTION AEffect* main_plugin (audioMasterCallback audioMaster)
  1354. {
  1355. return VSTPluginMain (audioMaster);
  1356. }
  1357. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1358. __attribute__((constructor)) void myPluginInit() {}
  1359. __attribute__((destructor)) void myPluginFini() {}
  1360. //==============================================================================
  1361. // Win32 startup code..
  1362. #else
  1363. extern "C" __declspec (dllexport) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1364. {
  1365. return pluginEntryPoint (audioMaster);
  1366. }
  1367. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1368. extern "C" __declspec (dllexport) int main (audioMasterCallback audioMaster)
  1369. {
  1370. return (int) pluginEntryPoint (audioMaster);
  1371. }
  1372. #endif
  1373. #endif
  1374. #endif