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.

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