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.

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