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.

2268 lines
79KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../../juce_core/system/juce_TargetPlatform.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. #include "../utility/juce_IncludeSystemHeaders.h"
  26. #include <juce_core/juce_core.h>
  27. #if JucePlugin_VersionCode < 0x010000 // Major < 0
  28. #if (JucePlugin_VersionCode & 0x00FF00) > (9 * 0x100) // check if Minor number exceeds 9
  29. JUCE_COMPILER_WARNING ("When version has 'major' = 0, VST2 has trouble displaying 'minor' exceeding 9")
  30. #endif
  31. #if (JucePlugin_VersionCode & 0xFF) > 9 // check if Bugfix number exceeds 9
  32. JUCE_COMPILER_WARNING ("When version has 'major' = 0, VST2 has trouble displaying 'bugfix' exceeding 9")
  33. #endif
  34. #elif JucePlugin_VersionCode >= 0x650000 // Major >= 101
  35. #if (JucePlugin_VersionCode & 0x00FF00) > (99 * 0x100) // check if Minor number exceeds 99
  36. JUCE_COMPILER_WARNING ("When version has 'major' > 100, VST2 has trouble displaying 'minor' exceeding 99")
  37. #endif
  38. #if (JucePlugin_VersionCode & 0xFF) > 99 // check if Bugfix number exceeds 99
  39. JUCE_COMPILER_WARNING ("When version has 'major' > 100, VST2 has trouble displaying 'bugfix' exceeding 99")
  40. #endif
  41. #endif
  42. #ifdef PRAGMA_ALIGN_SUPPORTED
  43. #undef PRAGMA_ALIGN_SUPPORTED
  44. #define PRAGMA_ALIGN_SUPPORTED 1
  45. #endif
  46. #ifndef _MSC_VER
  47. #define __cdecl
  48. #endif
  49. #if JUCE_CLANG
  50. #pragma clang diagnostic push
  51. #pragma clang diagnostic ignored "-Wconversion"
  52. #pragma clang diagnostic ignored "-Wshadow"
  53. #pragma clang diagnostic ignored "-Wdeprecated-register"
  54. #pragma clang diagnostic ignored "-Wunused-parameter"
  55. #pragma clang diagnostic ignored "-Wdeprecated-writable-strings"
  56. #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  57. #if __has_warning("-Wzero-as-null-pointer-constant")
  58. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  59. #endif
  60. #endif
  61. #if JUCE_GCC
  62. #pragma GCC diagnostic push
  63. #pragma GCC diagnostic ignored "-Wshadow"
  64. #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
  65. #endif
  66. #ifdef _MSC_VER
  67. #pragma warning (push)
  68. #pragma warning (disable : 4458)
  69. #endif
  70. #define VST_FORCE_DEPRECATED 0
  71. namespace Vst2
  72. {
  73. // If the following files cannot be found then you are probably trying to build
  74. // a VST2 plug-in or a VST2-compatible VST3 plug-in. To do this you must have a
  75. // VST2 SDK in your header search paths or use the "VST (Legacy) SDK Folder"
  76. // field in the Projucer. The VST2 SDK can be obtained from the
  77. // vstsdk3610_11_06_2018_build_37 (or older) VST3 SDK or JUCE version 5.3.2. You
  78. // also need a VST2 license from Steinberg to distribute VST2 plug-ins.
  79. #include "pluginterfaces/vst2.x/aeffect.h"
  80. #include "pluginterfaces/vst2.x/aeffectx.h"
  81. }
  82. using namespace juce;
  83. #ifdef _MSC_VER
  84. #pragma warning (pop)
  85. #endif
  86. #if JUCE_CLANG
  87. #pragma clang diagnostic pop
  88. #endif
  89. #if JUCE_GCC
  90. #pragma GCC diagnostic pop
  91. #endif
  92. //==============================================================================
  93. #ifdef _MSC_VER
  94. #pragma pack (push, 8)
  95. #endif
  96. #define JUCE_VSTINTERFACE_H_INCLUDED 1
  97. #include "../utility/juce_IncludeModuleHeaders.h"
  98. #include "../utility/juce_FakeMouseMoveGenerator.h"
  99. #include "../utility/juce_WindowsHooks.h"
  100. #include "../../juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp"
  101. #include "../../juce_audio_processors/format_types/juce_VSTCommon.h"
  102. #if JUCE_BIG_ENDIAN
  103. #define JUCE_MULTICHAR_CONSTANT(a, b, c, d) (a | (((uint32) b) << 8) | (((uint32) c) << 16) | (((uint32) d) << 24))
  104. #else
  105. #define JUCE_MULTICHAR_CONSTANT(a, b, c, d) (d | (((uint32) c) << 8) | (((uint32) b) << 16) | (((uint32) a) << 24))
  106. #endif
  107. #ifdef _MSC_VER
  108. #pragma pack (pop)
  109. #endif
  110. #undef MemoryBlock
  111. class JuceVSTWrapper;
  112. static bool recursionCheck = false;
  113. namespace juce
  114. {
  115. #if JUCE_MAC
  116. extern JUCE_API void initialiseMacVST();
  117. extern JUCE_API void* attachComponentToWindowRefVST (Component*, void* parent, bool isNSView);
  118. extern JUCE_API void detachComponentFromWindowRefVST (Component*, void* window, bool isNSView);
  119. extern JUCE_API void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  120. extern JUCE_API void checkWindowVisibilityVST (void* window, Component*, bool isNSView);
  121. extern JUCE_API bool forwardCurrentKeyEventToHostVST (Component*, bool isNSView);
  122. #if ! JUCE_64BIT
  123. extern JUCE_API void updateEditorCompBoundsVST (Component*);
  124. #endif
  125. #endif
  126. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  127. extern JUCE_API double getScaleFactorForWindow (HWND);
  128. #endif
  129. extern JUCE_API bool handleManufacturerSpecificVST2Opcode (int32, pointer_sized_int, void*, float);
  130. }
  131. //==============================================================================
  132. #if JUCE_WINDOWS
  133. namespace
  134. {
  135. // Returns the actual container window, unlike GetParent, which can also return a separate owner window.
  136. static HWND getWindowParent (HWND w) noexcept { return GetAncestor (w, GA_PARENT); }
  137. static HWND findMDIParentOf (HWND w)
  138. {
  139. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  140. while (w != 0)
  141. {
  142. auto parent = getWindowParent (w);
  143. if (parent == 0)
  144. break;
  145. TCHAR windowType[32] = { 0 };
  146. GetClassName (parent, windowType, 31);
  147. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  148. return parent;
  149. RECT windowPos, parentPos;
  150. GetWindowRect (w, &windowPos);
  151. GetWindowRect (parent, &parentPos);
  152. auto dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  153. auto dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  154. if (dw > 100 || dh > 100)
  155. break;
  156. w = parent;
  157. if (dw == 2 * frameThickness)
  158. break;
  159. }
  160. return w;
  161. }
  162. static bool messageThreadIsDefinitelyCorrect = false;
  163. }
  164. //==============================================================================
  165. #elif JUCE_LINUX
  166. struct SharedMessageThread : public Thread
  167. {
  168. SharedMessageThread() : Thread ("VstMessageThread")
  169. {
  170. startThread (7);
  171. while (! initialised)
  172. sleep (1);
  173. }
  174. ~SharedMessageThread() override
  175. {
  176. signalThreadShouldExit();
  177. JUCEApplicationBase::quit();
  178. waitForThreadToExit (5000);
  179. clearSingletonInstance();
  180. }
  181. void run() override
  182. {
  183. initialiseJuce_GUI();
  184. initialised = true;
  185. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  186. ScopedXDisplay xDisplay;
  187. while ((! threadShouldExit()) && MessageManager::getInstance()->runDispatchLoopUntil (250))
  188. {}
  189. }
  190. JUCE_DECLARE_SINGLETON (SharedMessageThread, false)
  191. bool initialised = false;
  192. };
  193. JUCE_IMPLEMENT_SINGLETON (SharedMessageThread)
  194. #endif
  195. static Array<void*> activePlugins;
  196. //==============================================================================
  197. // Ableton Live host specific commands
  198. struct AbletonLiveHostSpecific
  199. {
  200. enum
  201. {
  202. KCantBeSuspended = (1 << 2)
  203. };
  204. uint32 magic; // 'AbLi'
  205. int cmd; // 5 = realtime properties
  206. size_t commandSize; // sizeof (int)
  207. int flags; // KCantBeSuspended = (1 << 2)
  208. };
  209. //==============================================================================
  210. /**
  211. This is an AudioEffectX object that holds and wraps our AudioProcessor...
  212. */
  213. class JuceVSTWrapper : public AudioProcessorListener,
  214. public AudioPlayHead,
  215. private Timer,
  216. private AsyncUpdater,
  217. private AudioProcessorParameter::Listener
  218. {
  219. private:
  220. //==============================================================================
  221. template <typename FloatType>
  222. struct VstTempBuffers
  223. {
  224. VstTempBuffers() {}
  225. ~VstTempBuffers() { release(); }
  226. void release() noexcept
  227. {
  228. for (auto* c : tempChannels)
  229. delete[] c;
  230. tempChannels.clear();
  231. }
  232. HeapBlock<FloatType*> channels;
  233. Array<FloatType*> tempChannels; // see note in processReplacing()
  234. juce::AudioBuffer<FloatType> processTempBuffer;
  235. };
  236. /** Use the same names as the VST SDK. */
  237. struct VstOpCodeArguments
  238. {
  239. int32 index;
  240. pointer_sized_int value;
  241. void* ptr;
  242. float opt;
  243. };
  244. public:
  245. //==============================================================================
  246. JuceVSTWrapper (Vst2::audioMasterCallback cb, AudioProcessor* af)
  247. : hostCallback (cb),
  248. processor (af)
  249. {
  250. inParameterChangedCallback = false;
  251. // VST-2 does not support disabling buses: so always enable all of them
  252. processor->enableAllBuses();
  253. findMaxTotalChannels (maxNumInChannels, maxNumOutChannels);
  254. // You must at least have some channels
  255. jassert (processor->isMidiEffect() || (maxNumInChannels > 0 || maxNumOutChannels > 0));
  256. if (processor->isMidiEffect())
  257. maxNumInChannels = maxNumOutChannels = 2;
  258. #ifdef JucePlugin_PreferredChannelConfigurations
  259. processor->setPlayConfigDetails (maxNumInChannels, maxNumOutChannels, 44100.0, 1024);
  260. #endif
  261. processor->setRateAndBufferSizeDetails (0, 0);
  262. processor->setPlayHead (this);
  263. processor->addListener (this);
  264. if (auto* juceParam = processor->getBypassParameter())
  265. juceParam->addListener (this);
  266. juceParameters.update (*processor, false);
  267. memset (&vstEffect, 0, sizeof (vstEffect));
  268. vstEffect.magic = 0x56737450 /* 'VstP' */;
  269. vstEffect.dispatcher = (Vst2::AEffectDispatcherProc) dispatcherCB;
  270. vstEffect.process = nullptr;
  271. vstEffect.setParameter = (Vst2::AEffectSetParameterProc) setParameterCB;
  272. vstEffect.getParameter = (Vst2::AEffectGetParameterProc) getParameterCB;
  273. vstEffect.numPrograms = jmax (1, af->getNumPrograms());
  274. vstEffect.numParams = juceParameters.getNumParameters();
  275. vstEffect.numInputs = maxNumInChannels;
  276. vstEffect.numOutputs = maxNumOutChannels;
  277. vstEffect.initialDelay = processor->getLatencySamples();
  278. vstEffect.object = this;
  279. vstEffect.uniqueID = JucePlugin_VSTUniqueID;
  280. #ifdef JucePlugin_VSTChunkStructureVersion
  281. vstEffect.version = JucePlugin_VSTChunkStructureVersion;
  282. #else
  283. vstEffect.version = JucePlugin_VersionCode;
  284. #endif
  285. vstEffect.processReplacing = (Vst2::AEffectProcessProc) processReplacingCB;
  286. vstEffect.processDoubleReplacing = (Vst2::AEffectProcessDoubleProc) processDoubleReplacingCB;
  287. vstEffect.flags |= Vst2::effFlagsHasEditor;
  288. vstEffect.flags |= Vst2::effFlagsCanReplacing;
  289. if (processor->supportsDoublePrecisionProcessing())
  290. vstEffect.flags |= Vst2::effFlagsCanDoubleReplacing;
  291. vstEffect.flags |= Vst2::effFlagsProgramChunks;
  292. #if JucePlugin_IsSynth
  293. vstEffect.flags |= Vst2::effFlagsIsSynth;
  294. #else
  295. if (processor->getTailLengthSeconds() == 0.0)
  296. vstEffect.flags |= Vst2::effFlagsNoSoundInStop;
  297. #endif
  298. activePlugins.add (this);
  299. }
  300. ~JuceVSTWrapper() override
  301. {
  302. JUCE_AUTORELEASEPOOL
  303. {
  304. {
  305. #if JUCE_LINUX
  306. MessageManagerLock mmLock;
  307. #endif
  308. stopTimer();
  309. deleteEditor (false);
  310. hasShutdown = true;
  311. delete processor;
  312. processor = nullptr;
  313. jassert (editorComp == nullptr);
  314. deleteTempChannels();
  315. jassert (activePlugins.contains (this));
  316. activePlugins.removeFirstMatchingValue (this);
  317. }
  318. if (activePlugins.size() == 0)
  319. {
  320. #if JUCE_LINUX
  321. SharedMessageThread::deleteInstance();
  322. #endif
  323. shutdownJuce_GUI();
  324. #if JUCE_WINDOWS
  325. messageThreadIsDefinitelyCorrect = false;
  326. #endif
  327. }
  328. }
  329. }
  330. Vst2::AEffect* getAEffect() noexcept { return &vstEffect; }
  331. template <typename FloatType>
  332. void internalProcessReplacing (FloatType** inputs, FloatType** outputs,
  333. int32 numSamples, VstTempBuffers<FloatType>& tmpBuffers)
  334. {
  335. const bool isMidiEffect = processor->isMidiEffect();
  336. if (firstProcessCallback)
  337. {
  338. firstProcessCallback = false;
  339. // if this fails, the host hasn't called resume() before processing
  340. jassert (isProcessing);
  341. // (tragically, some hosts actually need this, although it's stupid to have
  342. // to do it here..)
  343. if (! isProcessing)
  344. resume();
  345. processor->setNonRealtime (isProcessLevelOffline());
  346. #if JUCE_WINDOWS
  347. if (getHostType().isWavelab())
  348. {
  349. int priority = GetThreadPriority (GetCurrentThread());
  350. if (priority <= THREAD_PRIORITY_NORMAL && priority >= THREAD_PRIORITY_LOWEST)
  351. processor->setNonRealtime (true);
  352. }
  353. #endif
  354. }
  355. #if JUCE_DEBUG && ! (JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect)
  356. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  357. #endif
  358. jassert (activePlugins.contains (this));
  359. {
  360. const int numIn = processor->getTotalNumInputChannels();
  361. const int numOut = processor->getTotalNumOutputChannels();
  362. const ScopedLock sl (processor->getCallbackLock());
  363. if (processor->isSuspended())
  364. {
  365. for (int i = 0; i < numOut; ++i)
  366. if (outputs[i] != nullptr)
  367. FloatVectorOperations::clear (outputs[i], numSamples);
  368. }
  369. else
  370. {
  371. int i;
  372. for (i = 0; i < numOut; ++i)
  373. {
  374. auto* chan = tmpBuffers.tempChannels.getUnchecked(i);
  375. if (chan == nullptr)
  376. {
  377. chan = outputs[i];
  378. bool bufferPointerReusedForOtherChannels = false;
  379. for (int j = i; --j >= 0;)
  380. {
  381. if (outputs[j] == chan)
  382. {
  383. bufferPointerReusedForOtherChannels = true;
  384. break;
  385. }
  386. }
  387. // if some output channels are disabled, some hosts supply the same buffer
  388. // for multiple channels or supply a nullptr - this buggers up our method
  389. // of copying the inputs over the outputs, so we need to create unique temp
  390. // buffers in this case..
  391. if (bufferPointerReusedForOtherChannels || chan == nullptr)
  392. {
  393. chan = new FloatType [(size_t) blockSize * 2];
  394. tmpBuffers.tempChannels.set (i, chan);
  395. }
  396. }
  397. if (i < numIn)
  398. {
  399. if (chan != inputs[i])
  400. memcpy (chan, inputs[i], (size_t) numSamples * sizeof (FloatType));
  401. }
  402. else
  403. {
  404. FloatVectorOperations::clear (chan, numSamples);
  405. }
  406. tmpBuffers.channels[i] = chan;
  407. }
  408. for (; i < numIn; ++i)
  409. tmpBuffers.channels[i] = inputs[i];
  410. {
  411. const int numChannels = jmax (numIn, numOut);
  412. AudioBuffer<FloatType> chans (tmpBuffers.channels, isMidiEffect ? 0 : numChannels, numSamples);
  413. if (isBypassed)
  414. processor->processBlockBypassed (chans, midiEvents);
  415. else
  416. processor->processBlock (chans, midiEvents);
  417. }
  418. // copy back any temp channels that may have been used..
  419. for (i = 0; i < numOut; ++i)
  420. if (auto* chan = tmpBuffers.tempChannels.getUnchecked(i))
  421. if (auto* dest = outputs[i])
  422. memcpy (dest, chan, (size_t) numSamples * sizeof (FloatType));
  423. }
  424. }
  425. if (! midiEvents.isEmpty())
  426. {
  427. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  428. auto numEvents = midiEvents.getNumEvents();
  429. outgoingEvents.ensureSize (numEvents);
  430. outgoingEvents.clear();
  431. const uint8* midiEventData;
  432. int midiEventSize, midiEventPosition;
  433. MidiBuffer::Iterator i (midiEvents);
  434. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  435. {
  436. jassert (midiEventPosition >= 0 && midiEventPosition < numSamples);
  437. outgoingEvents.addEvent (midiEventData, midiEventSize, midiEventPosition);
  438. }
  439. // Send VST events to the host.
  440. if (hostCallback != nullptr)
  441. hostCallback (&vstEffect, Vst2::audioMasterProcessEvents, 0, 0, outgoingEvents.events, 0);
  442. #elif JUCE_DEBUG
  443. /* This assertion is caused when you've added some events to the
  444. midiMessages array in your processBlock() method, which usually means
  445. that you're trying to send them somewhere. But in this case they're
  446. getting thrown away.
  447. If your plugin does want to send midi messages, you'll need to set
  448. the JucePlugin_ProducesMidiOutput macro to 1 in your
  449. JucePluginCharacteristics.h file.
  450. If you don't want to produce any midi output, then you should clear the
  451. midiMessages array at the end of your processBlock() method, to
  452. indicate that you don't want any of the events to be passed through
  453. to the output.
  454. */
  455. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  456. #endif
  457. midiEvents.clear();
  458. }
  459. }
  460. void processReplacing (float** inputs, float** outputs, int32 sampleFrames)
  461. {
  462. jassert (! processor->isUsingDoublePrecision());
  463. internalProcessReplacing (inputs, outputs, sampleFrames, floatTempBuffers);
  464. }
  465. static void processReplacingCB (Vst2::AEffect* vstInterface, float** inputs, float** outputs, int32 sampleFrames)
  466. {
  467. getWrapper (vstInterface)->processReplacing (inputs, outputs, sampleFrames);
  468. }
  469. void processDoubleReplacing (double** inputs, double** outputs, int32 sampleFrames)
  470. {
  471. jassert (processor->isUsingDoublePrecision());
  472. internalProcessReplacing (inputs, outputs, sampleFrames, doubleTempBuffers);
  473. }
  474. static void processDoubleReplacingCB (Vst2::AEffect* vstInterface, double** inputs, double** outputs, int32 sampleFrames)
  475. {
  476. getWrapper (vstInterface)->processDoubleReplacing (inputs, outputs, sampleFrames);
  477. }
  478. //==============================================================================
  479. void resume()
  480. {
  481. if (processor != nullptr)
  482. {
  483. isProcessing = true;
  484. auto numInAndOutChannels = static_cast<size_t> (vstEffect.numInputs + vstEffect.numOutputs);
  485. floatTempBuffers .channels.calloc (numInAndOutChannels);
  486. doubleTempBuffers.channels.calloc (numInAndOutChannels);
  487. auto currentRate = sampleRate;
  488. auto currentBlockSize = blockSize;
  489. firstProcessCallback = true;
  490. processor->setNonRealtime (isProcessLevelOffline());
  491. processor->setRateAndBufferSizeDetails (currentRate, currentBlockSize);
  492. deleteTempChannels();
  493. processor->prepareToPlay (currentRate, currentBlockSize);
  494. midiEvents.ensureSize (2048);
  495. midiEvents.clear();
  496. vstEffect.initialDelay = processor->getLatencySamples();
  497. /** If this plug-in is a synth or it can receive midi events we need to tell the
  498. host that we want midi. In the SDK this method is marked as deprecated, but
  499. some hosts rely on this behaviour.
  500. */
  501. if (vstEffect.flags & Vst2::effFlagsIsSynth || JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect)
  502. {
  503. if (hostCallback != nullptr)
  504. hostCallback (&vstEffect, Vst2::audioMasterWantMidi, 0, 1, nullptr, 0);
  505. }
  506. if (getHostType().isAbletonLive()
  507. && hostCallback != nullptr
  508. && processor->getTailLengthSeconds() == std::numeric_limits<double>::infinity())
  509. {
  510. AbletonLiveHostSpecific hostCmd;
  511. hostCmd.magic = 0x41624c69; // 'AbLi'
  512. hostCmd.cmd = 5;
  513. hostCmd.commandSize = sizeof (int);
  514. hostCmd.flags = AbletonLiveHostSpecific::KCantBeSuspended;
  515. hostCallback (&vstEffect, Vst2::audioMasterVendorSpecific, 0, 0, &hostCmd, 0.0f);
  516. }
  517. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  518. outgoingEvents.ensureSize (512);
  519. #endif
  520. }
  521. }
  522. void suspend()
  523. {
  524. if (processor != nullptr)
  525. {
  526. processor->releaseResources();
  527. outgoingEvents.freeEvents();
  528. isProcessing = false;
  529. floatTempBuffers.channels.free();
  530. doubleTempBuffers.channels.free();
  531. deleteTempChannels();
  532. }
  533. }
  534. //==============================================================================
  535. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info) override
  536. {
  537. const Vst2::VstTimeInfo* ti = nullptr;
  538. if (hostCallback != nullptr)
  539. {
  540. int32 flags = Vst2::kVstPpqPosValid | Vst2::kVstTempoValid
  541. | Vst2::kVstBarsValid | Vst2::kVstCyclePosValid
  542. | Vst2::kVstTimeSigValid | Vst2::kVstSmpteValid
  543. | Vst2::kVstClockValid;
  544. auto result = hostCallback (&vstEffect, Vst2::audioMasterGetTime, 0, flags, nullptr, 0);
  545. ti = reinterpret_cast<Vst2::VstTimeInfo*> (result);
  546. }
  547. if (ti == nullptr || ti->sampleRate <= 0)
  548. return false;
  549. info.bpm = (ti->flags & Vst2::kVstTempoValid) != 0 ? ti->tempo : 0.0;
  550. if ((ti->flags & Vst2::kVstTimeSigValid) != 0)
  551. {
  552. info.timeSigNumerator = ti->timeSigNumerator;
  553. info.timeSigDenominator = ti->timeSigDenominator;
  554. }
  555. else
  556. {
  557. info.timeSigNumerator = 4;
  558. info.timeSigDenominator = 4;
  559. }
  560. info.timeInSamples = (int64) (ti->samplePos + 0.5);
  561. info.timeInSeconds = ti->samplePos / ti->sampleRate;
  562. info.ppqPosition = (ti->flags & Vst2::kVstPpqPosValid) != 0 ? ti->ppqPos : 0.0;
  563. info.ppqPositionOfLastBarStart = (ti->flags & Vst2::kVstBarsValid) != 0 ? ti->barStartPos : 0.0;
  564. if ((ti->flags & Vst2::kVstSmpteValid) != 0)
  565. {
  566. AudioPlayHead::FrameRateType rate = AudioPlayHead::fpsUnknown;
  567. double fps = 1.0;
  568. switch (ti->smpteFrameRate)
  569. {
  570. case Vst2::kVstSmpte239fps: rate = AudioPlayHead::fps23976; fps = 24.0 * 1000.0 / 1001.0; break;
  571. case Vst2::kVstSmpte24fps: rate = AudioPlayHead::fps24; fps = 24.0; break;
  572. case Vst2::kVstSmpte25fps: rate = AudioPlayHead::fps25; fps = 25.0; break;
  573. case Vst2::kVstSmpte2997fps: rate = AudioPlayHead::fps2997; fps = 30.0 * 1000.0 / 1001.0; break;
  574. case Vst2::kVstSmpte30fps: rate = AudioPlayHead::fps30; fps = 30.0; break;
  575. case Vst2::kVstSmpte2997dfps: rate = AudioPlayHead::fps2997drop; fps = 30.0 * 1000.0 / 1001.0; break;
  576. case Vst2::kVstSmpte30dfps: rate = AudioPlayHead::fps30drop; fps = 30.0; break;
  577. case Vst2::kVstSmpteFilm16mm:
  578. case Vst2::kVstSmpteFilm35mm: fps = 24.0; break;
  579. case Vst2::kVstSmpte249fps: fps = 25.0 * 1000.0 / 1001.0; break;
  580. case Vst2::kVstSmpte599fps: fps = 60.0 * 1000.0 / 1001.0; break;
  581. case Vst2::kVstSmpte60fps: fps = 60; break;
  582. default: jassertfalse; // unknown frame-rate..
  583. }
  584. info.frameRate = rate;
  585. info.editOriginTime = ti->smpteOffset / (80.0 * fps);
  586. }
  587. else
  588. {
  589. info.frameRate = AudioPlayHead::fpsUnknown;
  590. info.editOriginTime = 0;
  591. }
  592. info.isRecording = (ti->flags & Vst2::kVstTransportRecording) != 0;
  593. info.isPlaying = (ti->flags & (Vst2::kVstTransportRecording | Vst2::kVstTransportPlaying)) != 0;
  594. info.isLooping = (ti->flags & Vst2::kVstTransportCycleActive) != 0;
  595. if ((ti->flags & Vst2::kVstCyclePosValid) != 0)
  596. {
  597. info.ppqLoopStart = ti->cycleStartPos;
  598. info.ppqLoopEnd = ti->cycleEndPos;
  599. }
  600. else
  601. {
  602. info.ppqLoopStart = 0;
  603. info.ppqLoopEnd = 0;
  604. }
  605. return true;
  606. }
  607. //==============================================================================
  608. float getParameter (int32 index) const
  609. {
  610. if (auto* param = juceParameters.getParamForIndex (index))
  611. return param->getValue();
  612. return 0.0f;
  613. }
  614. static float getParameterCB (Vst2::AEffect* vstInterface, int32 index)
  615. {
  616. return getWrapper (vstInterface)->getParameter (index);
  617. }
  618. void setParameter (int32 index, float value)
  619. {
  620. if (auto* param = juceParameters.getParamForIndex (index))
  621. {
  622. param->setValue (value);
  623. inParameterChangedCallback = true;
  624. param->sendValueChangedMessageToListeners (value);
  625. }
  626. }
  627. static void setParameterCB (Vst2::AEffect* vstInterface, int32 index, float value)
  628. {
  629. getWrapper (vstInterface)->setParameter (index, value);
  630. }
  631. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  632. {
  633. if (inParameterChangedCallback.get())
  634. {
  635. inParameterChangedCallback = false;
  636. return;
  637. }
  638. if (hostCallback != nullptr)
  639. hostCallback (&vstEffect, Vst2::audioMasterAutomate, index, 0, nullptr, newValue);
  640. }
  641. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override
  642. {
  643. if (hostCallback != nullptr)
  644. hostCallback (&vstEffect, Vst2::audioMasterBeginEdit, index, 0, nullptr, 0);
  645. }
  646. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override
  647. {
  648. if (hostCallback != nullptr)
  649. hostCallback (&vstEffect, Vst2::audioMasterEndEdit, index, 0, nullptr, 0);
  650. }
  651. void parameterValueChanged (int, float newValue) override
  652. {
  653. // this can only come from the bypass parameter
  654. isBypassed = (newValue != 0.0f);
  655. }
  656. void parameterGestureChanged (int, bool) override {}
  657. void audioProcessorChanged (AudioProcessor*) override
  658. {
  659. vstEffect.initialDelay = processor->getLatencySamples();
  660. triggerAsyncUpdate();
  661. }
  662. void handleAsyncUpdate() override
  663. {
  664. if (hostCallback != nullptr)
  665. {
  666. hostCallback (&vstEffect, Vst2::audioMasterUpdateDisplay, 0, 0, nullptr, 0);
  667. hostCallback (&vstEffect, Vst2::audioMasterIOChanged, 0, 0, nullptr, 0);
  668. }
  669. }
  670. bool getPinProperties (Vst2::VstPinProperties& properties, bool direction, int index) const
  671. {
  672. if (processor->isMidiEffect())
  673. return false;
  674. int channelIdx, busIdx;
  675. // fill with default
  676. properties.flags = 0;
  677. properties.label[0] = 0;
  678. properties.shortLabel[0] = 0;
  679. properties.arrangementType = Vst2::kSpeakerArrEmpty;
  680. if ((channelIdx = processor->getOffsetInBusBufferForAbsoluteChannelIndex (direction, index, busIdx)) >= 0)
  681. {
  682. auto& bus = *processor->getBus (direction, busIdx);
  683. auto& channelSet = bus.getCurrentLayout();
  684. auto channelType = channelSet.getTypeOfChannel (channelIdx);
  685. properties.flags = Vst2::kVstPinIsActive | Vst2::kVstPinUseSpeaker;
  686. properties.arrangementType = SpeakerMappings::channelSetToVstArrangementType (channelSet);
  687. String label = bus.getName();
  688. #ifdef JucePlugin_PreferredChannelConfigurations
  689. label += " " + String (channelIdx);
  690. #else
  691. if (channelSet.size() > 1)
  692. label += " " + AudioChannelSet::getAbbreviatedChannelTypeName (channelType);
  693. #endif
  694. label.copyToUTF8 (properties.label, (size_t) (Vst2::kVstMaxLabelLen + 1));
  695. label.copyToUTF8 (properties.shortLabel, (size_t) (Vst2::kVstMaxShortLabelLen + 1));
  696. if (channelType == AudioChannelSet::left
  697. || channelType == AudioChannelSet::leftSurround
  698. || channelType == AudioChannelSet::leftCentre
  699. || channelType == AudioChannelSet::leftSurroundSide
  700. || channelType == AudioChannelSet::topFrontLeft
  701. || channelType == AudioChannelSet::topRearLeft
  702. || channelType == AudioChannelSet::leftSurroundRear
  703. || channelType == AudioChannelSet::wideLeft)
  704. properties.flags |= Vst2::kVstPinIsStereo;
  705. return true;
  706. }
  707. return false;
  708. }
  709. //==============================================================================
  710. void timerCallback() override
  711. {
  712. if (shouldDeleteEditor)
  713. {
  714. shouldDeleteEditor = false;
  715. deleteEditor (true);
  716. }
  717. {
  718. ScopedLock lock (stateInformationLock);
  719. if (chunkMemoryTime > 0
  720. && chunkMemoryTime < juce::Time::getApproximateMillisecondCounter() - 2000
  721. && ! recursionCheck)
  722. {
  723. chunkMemory.reset();
  724. chunkMemoryTime = 0;
  725. }
  726. }
  727. if (editorComp != nullptr)
  728. editorComp->checkVisibility();
  729. }
  730. void setHasEditorFlag (bool shouldSetHasEditor)
  731. {
  732. auto hasEditor = (vstEffect.flags & Vst2::effFlagsHasEditor) != 0;
  733. if (shouldSetHasEditor == hasEditor)
  734. return;
  735. if (shouldSetHasEditor)
  736. vstEffect.flags |= Vst2::effFlagsHasEditor;
  737. else
  738. vstEffect.flags &= ~Vst2::effFlagsHasEditor;
  739. }
  740. void createEditorComp()
  741. {
  742. if (hasShutdown || processor == nullptr)
  743. return;
  744. if (editorComp == nullptr)
  745. {
  746. if (auto* ed = processor->createEditorIfNeeded())
  747. {
  748. setHasEditorFlag (true);
  749. editorComp.reset (new EditorCompWrapper (*this, *ed));
  750. }
  751. else
  752. {
  753. setHasEditorFlag (false);
  754. }
  755. }
  756. shouldDeleteEditor = false;
  757. }
  758. void deleteEditor (bool canDeleteLaterIfModal)
  759. {
  760. JUCE_AUTORELEASEPOOL
  761. {
  762. PopupMenu::dismissAllActiveMenus();
  763. jassert (! recursionCheck);
  764. ScopedValueSetter<bool> svs (recursionCheck, true, false);
  765. if (editorComp != nullptr)
  766. {
  767. if (auto* modalComponent = Component::getCurrentlyModalComponent())
  768. {
  769. modalComponent->exitModalState (0);
  770. if (canDeleteLaterIfModal)
  771. {
  772. shouldDeleteEditor = true;
  773. return;
  774. }
  775. }
  776. editorComp->detachHostWindow();
  777. if (auto* ed = editorComp->getEditorComp())
  778. processor->editorBeingDeleted (ed);
  779. editorComp = nullptr;
  780. // there's some kind of component currently modal, but the host
  781. // is trying to delete our plugin. You should try to avoid this happening..
  782. jassert (Component::getCurrentlyModalComponent() == nullptr);
  783. }
  784. }
  785. }
  786. pointer_sized_int dispatcher (int32 opCode, VstOpCodeArguments args)
  787. {
  788. if (hasShutdown)
  789. return 0;
  790. switch (opCode)
  791. {
  792. case Vst2::effOpen: return handleOpen (args);
  793. case Vst2::effClose: return handleClose (args);
  794. case Vst2::effSetProgram: return handleSetCurrentProgram (args);
  795. case Vst2::effGetProgram: return handleGetCurrentProgram (args);
  796. case Vst2::effSetProgramName: return handleSetCurrentProgramName (args);
  797. case Vst2::effGetProgramName: return handleGetCurrentProgramName (args);
  798. case Vst2::effGetParamLabel: return handleGetParameterLabel (args);
  799. case Vst2::effGetParamDisplay: return handleGetParameterText (args);
  800. case Vst2::effGetParamName: return handleGetParameterName (args);
  801. case Vst2::effSetSampleRate: return handleSetSampleRate (args);
  802. case Vst2::effSetBlockSize: return handleSetBlockSize (args);
  803. case Vst2::effMainsChanged: return handleResumeSuspend (args);
  804. case Vst2::effEditGetRect: return handleGetEditorBounds (args);
  805. case Vst2::effEditOpen: return handleOpenEditor (args);
  806. case Vst2::effEditClose: return handleCloseEditor (args);
  807. case Vst2::effIdentify: return (pointer_sized_int) ByteOrder::bigEndianInt ("NvEf");
  808. case Vst2::effGetChunk: return handleGetData (args);
  809. case Vst2::effSetChunk: return handleSetData (args);
  810. case Vst2::effProcessEvents: return handlePreAudioProcessingEvents (args);
  811. case Vst2::effCanBeAutomated: return handleIsParameterAutomatable (args);
  812. case Vst2::effString2Parameter: return handleParameterValueForText (args);
  813. case Vst2::effGetProgramNameIndexed: return handleGetProgramName (args);
  814. case Vst2::effGetInputProperties: return handleGetInputPinProperties (args);
  815. case Vst2::effGetOutputProperties: return handleGetOutputPinProperties (args);
  816. case Vst2::effGetPlugCategory: return handleGetPlugInCategory (args);
  817. case Vst2::effSetSpeakerArrangement: return handleSetSpeakerConfiguration (args);
  818. case Vst2::effSetBypass: return handleSetBypass (args);
  819. case Vst2::effGetEffectName: return handleGetPlugInName (args);
  820. case Vst2::effGetProductString: return handleGetPlugInName (args);
  821. case Vst2::effGetVendorString: return handleGetManufacturerName (args);
  822. case Vst2::effGetVendorVersion: return handleGetManufacturerVersion (args);
  823. case Vst2::effVendorSpecific: return handleManufacturerSpecific (args);
  824. case Vst2::effCanDo: return handleCanPlugInDo (args);
  825. case Vst2::effGetTailSize: return handleGetTailSize (args);
  826. case Vst2::effKeysRequired: return handleKeyboardFocusRequired (args);
  827. case Vst2::effGetVstVersion: return handleGetVstInterfaceVersion (args);
  828. case Vst2::effGetCurrentMidiProgram: return handleGetCurrentMidiProgram (args);
  829. case Vst2::effGetSpeakerArrangement: return handleGetSpeakerConfiguration (args);
  830. case Vst2::effSetTotalSampleToProcess: return handleSetNumberOfSamplesToProcess (args);
  831. case Vst2::effSetProcessPrecision: return handleSetSampleFloatType (args);
  832. case Vst2::effGetNumMidiInputChannels: return handleGetNumMidiInputChannels();
  833. case Vst2::effGetNumMidiOutputChannels: return handleGetNumMidiOutputChannels();
  834. default: return 0;
  835. }
  836. }
  837. static pointer_sized_int dispatcherCB (Vst2::AEffect* vstInterface, int32 opCode, int32 index,
  838. pointer_sized_int value, void* ptr, float opt)
  839. {
  840. auto* wrapper = getWrapper (vstInterface);
  841. VstOpCodeArguments args = { index, value, ptr, opt };
  842. if (opCode == Vst2::effClose)
  843. {
  844. wrapper->dispatcher (opCode, args);
  845. delete wrapper;
  846. return 1;
  847. }
  848. return wrapper->dispatcher (opCode, args);
  849. }
  850. //==============================================================================
  851. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  852. // chores when it changes or repaints.
  853. struct EditorCompWrapper : public Component
  854. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  855. , public Timer
  856. #endif
  857. {
  858. EditorCompWrapper (JuceVSTWrapper& w, AudioProcessorEditor& editor)
  859. : wrapper (w)
  860. {
  861. editor.setOpaque (true);
  862. editor.setVisible (true);
  863. setOpaque (true);
  864. setTopLeftPosition (editor.getPosition());
  865. editor.setTopLeftPosition (0, 0);
  866. auto b = getLocalArea (&editor, editor.getLocalBounds());
  867. setSize (b.getWidth(), b.getHeight());
  868. addAndMakeVisible (editor);
  869. #if JUCE_WINDOWS
  870. if (! getHostType().isReceptor())
  871. addMouseListener (this, true);
  872. #endif
  873. ignoreUnused (fakeMouseGenerator);
  874. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  875. startTimer (500);
  876. #endif
  877. }
  878. ~EditorCompWrapper() override
  879. {
  880. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  881. // have been transferred to another parent which takes over ownership.
  882. }
  883. void paint (Graphics&) override {}
  884. void getEditorBounds (Vst2::ERect& bounds)
  885. {
  886. auto b = getSizeToContainChild();
  887. bounds = convertToHostBounds ({ 0, 0, (int16) b.getHeight(), (int16) b.getWidth() });
  888. }
  889. void attachToHost (VstOpCodeArguments args)
  890. {
  891. setOpaque (true);
  892. setVisible (false);
  893. #if JUCE_WINDOWS
  894. addToDesktop (0, args.ptr);
  895. hostWindow = (HWND) args.ptr;
  896. #elif JUCE_LINUX
  897. addToDesktop (0, args.ptr);
  898. hostWindow = (Window) args.ptr;
  899. XReparentWindow (display.display, (Window) getWindowHandle(), hostWindow, 0, 0);
  900. #else
  901. hostWindow = attachComponentToWindowRefVST (this, args.ptr, wrapper.useNSView);
  902. #endif
  903. setVisible (true);
  904. }
  905. void detachHostWindow()
  906. {
  907. #if JUCE_MAC
  908. if (hostWindow != nullptr)
  909. {
  910. detachComponentFromWindowRefVST (this, hostWindow, wrapper.useNSView);
  911. hostWindow = nullptr;
  912. }
  913. #endif
  914. #if JUCE_LINUX
  915. hostWindow = {};
  916. #endif
  917. }
  918. void checkVisibility()
  919. {
  920. #if JUCE_MAC
  921. if (hostWindow != nullptr)
  922. checkWindowVisibilityVST (hostWindow, this, wrapper.useNSView);
  923. #endif
  924. }
  925. AudioProcessorEditor* getEditorComp() const noexcept
  926. {
  927. return dynamic_cast<AudioProcessorEditor*> (getChildComponent (0));
  928. }
  929. void resized() override
  930. {
  931. if (auto* ed = getEditorComp())
  932. {
  933. ed->setTopLeftPosition (0, 0);
  934. if (shouldResizeEditor)
  935. {
  936. auto newBounds = getLocalBounds();
  937. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  938. if (! lastBounds.isEmpty() && isWithin (newBounds.toDouble().getAspectRatio(), lastBounds.toDouble().getAspectRatio(), 0.1))
  939. return;
  940. lastBounds = newBounds;
  941. #endif
  942. ed->setBounds (ed->getLocalArea (this, newBounds));
  943. }
  944. updateWindowSize (false);
  945. }
  946. #if JUCE_MAC && ! JUCE_64BIT
  947. if (! wrapper.useNSView)
  948. updateEditorCompBoundsVST (this);
  949. #endif
  950. }
  951. void childBoundsChanged (Component*) override
  952. {
  953. updateWindowSize (false);
  954. }
  955. juce::Rectangle<int> getSizeToContainChild()
  956. {
  957. if (auto* ed = getEditorComp())
  958. return getLocalArea (ed, ed->getLocalBounds());
  959. return {};
  960. }
  961. void updateWindowSize (bool resizeEditor)
  962. {
  963. if (! isInSizeWindow)
  964. {
  965. if (auto* ed = getEditorComp())
  966. {
  967. ed->setTopLeftPosition (0, 0);
  968. auto pos = getSizeToContainChild();
  969. #if JUCE_MAC
  970. if (wrapper.useNSView)
  971. setTopLeftPosition (0, getHeight() - pos.getHeight());
  972. #endif
  973. resizeHostWindow (pos.getWidth(), pos.getHeight());
  974. #if ! JUCE_LINUX // setSize() on linux causes renoise and energyxt to fail.
  975. if (! resizeEditor) // this is needed to prevent an infinite resizing loop due to coordinate rounding
  976. shouldResizeEditor = false;
  977. setSize (pos.getWidth(), pos.getHeight());
  978. shouldResizeEditor = true;
  979. #else
  980. ignoreUnused (resizeEditor);
  981. auto scale = Desktop::getInstance().getGlobalScaleFactor();
  982. if (auto* peer = ed->getPeer())
  983. scale *= (float) peer->getPlatformScaleFactor();
  984. XResizeWindow (display.display, (Window) getWindowHandle(),
  985. static_cast<unsigned int> (roundToInt (pos.getWidth() * scale)),
  986. static_cast<unsigned int> (roundToInt (pos.getHeight() * scale)));
  987. #endif
  988. #if JUCE_MAC
  989. resizeHostWindow (pos.getWidth(), pos.getHeight()); // (doing this a second time seems to be necessary in tracktion)
  990. #endif
  991. }
  992. }
  993. }
  994. void resizeHostWindow (int newWidth, int newHeight)
  995. {
  996. auto rect = convertToHostBounds ({ 0, 0, (int16) newHeight, (int16) newWidth });
  997. newWidth = rect.right - rect.left;
  998. newHeight = rect.bottom - rect.top;
  999. bool sizeWasSuccessful = false;
  1000. if (auto host = wrapper.hostCallback)
  1001. {
  1002. auto status = host (wrapper.getAEffect(), Vst2::audioMasterCanDo, 0, 0, const_cast<char*> ("sizeWindow"), 0);
  1003. if (status == (pointer_sized_int) 1 || getHostType().isAbletonLive())
  1004. {
  1005. const ScopedValueSetter<bool> inSizeWindowSetter (isInSizeWindow, true);
  1006. sizeWasSuccessful = (host (wrapper.getAEffect(), Vst2::audioMasterSizeWindow,
  1007. newWidth, newHeight, nullptr, 0) != 0);
  1008. }
  1009. }
  1010. if (! sizeWasSuccessful)
  1011. {
  1012. // some hosts don't support the sizeWindow call, so do it manually..
  1013. #if JUCE_MAC
  1014. setNativeHostWindowSizeVST (hostWindow, this, newWidth, newHeight, wrapper.useNSView);
  1015. #elif JUCE_LINUX
  1016. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  1017. setSize (newWidth, newHeight);
  1018. #else
  1019. int dw = 0;
  1020. int dh = 0;
  1021. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  1022. HWND w = (HWND) getWindowHandle();
  1023. while (w != 0)
  1024. {
  1025. HWND parent = getWindowParent (w);
  1026. if (parent == 0)
  1027. break;
  1028. TCHAR windowType [32] = { 0 };
  1029. GetClassName (parent, windowType, 31);
  1030. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  1031. break;
  1032. RECT windowPos, parentPos;
  1033. GetWindowRect (w, &windowPos);
  1034. GetWindowRect (parent, &parentPos);
  1035. if (w != (HWND) getWindowHandle())
  1036. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1037. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1038. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1039. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1040. w = parent;
  1041. if (dw == 2 * frameThickness)
  1042. break;
  1043. if (dw > 100 || dh > 100)
  1044. w = 0;
  1045. }
  1046. if (w != 0)
  1047. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1048. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1049. #endif
  1050. }
  1051. if (auto* peer = getPeer())
  1052. {
  1053. peer->handleMovedOrResized();
  1054. repaint();
  1055. }
  1056. }
  1057. void setContentScaleFactor (float scale)
  1058. {
  1059. if (! approximatelyEqual (scale, editorScaleFactor))
  1060. {
  1061. editorScaleFactor = scale;
  1062. if (auto* ed = getEditorComp())
  1063. ed->setScaleFactor (editorScaleFactor);
  1064. updateWindowSize (true);
  1065. }
  1066. }
  1067. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1068. void timerCallback() override
  1069. {
  1070. auto hostWindowScale = (float) getScaleFactorForWindow (hostWindow);
  1071. if (hostWindowScale > 0.0f && ! approximatelyEqual (hostWindowScale, editorScaleFactor))
  1072. wrapper.handleSetContentScaleFactor (hostWindowScale);
  1073. }
  1074. #endif
  1075. #if JUCE_WINDOWS
  1076. void mouseDown (const MouseEvent&) override
  1077. {
  1078. broughtToFront();
  1079. }
  1080. void broughtToFront() override
  1081. {
  1082. // for hosts like nuendo, need to also pop the MDI container to the
  1083. // front when our comp is clicked on.
  1084. if (! isCurrentlyBlockedByAnotherModalComponent())
  1085. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  1086. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1087. }
  1088. #endif
  1089. #if JUCE_MAC
  1090. bool keyPressed (const KeyPress&) override
  1091. {
  1092. // If we have an unused keypress, move the key-focus to a host window
  1093. // and re-inject the event..
  1094. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1095. }
  1096. #endif
  1097. //==============================================================================
  1098. static Vst2::ERect convertToHostBounds (const Vst2::ERect& rect)
  1099. {
  1100. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1101. if (approximatelyEqual (desktopScale, 1.0f))
  1102. return rect;
  1103. return { (int16) roundToInt (rect.top * desktopScale),
  1104. (int16) roundToInt (rect.left * desktopScale),
  1105. (int16) roundToInt (rect.bottom * desktopScale),
  1106. (int16) roundToInt (rect.right * desktopScale)};
  1107. }
  1108. //==============================================================================
  1109. JuceVSTWrapper& wrapper;
  1110. FakeMouseMoveGenerator fakeMouseGenerator;
  1111. bool isInSizeWindow = false;
  1112. bool shouldResizeEditor = true;
  1113. float editorScaleFactor = 1.0f;
  1114. #if JUCE_MAC
  1115. void* hostWindow = nullptr;
  1116. #elif JUCE_LINUX
  1117. ScopedXDisplay display;
  1118. Window hostWindow = {};
  1119. #elif JUCE_WINDOWS
  1120. HWND hostWindow = {};
  1121. WindowsHooks hooks;
  1122. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1123. juce::Rectangle<int> lastBounds;
  1124. #endif
  1125. #endif
  1126. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1127. };
  1128. //==============================================================================
  1129. private:
  1130. static JuceVSTWrapper* getWrapper (Vst2::AEffect* v) noexcept { return static_cast<JuceVSTWrapper*> (v->object); }
  1131. bool isProcessLevelOffline()
  1132. {
  1133. return hostCallback != nullptr
  1134. && (int32) hostCallback (&vstEffect, Vst2::audioMasterGetCurrentProcessLevel, 0, 0, nullptr, 0) == 4;
  1135. }
  1136. static inline int32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1137. {
  1138. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1139. return (int32) hexVersion;
  1140. #else
  1141. // Currently, only Cubase displays the version number to the user
  1142. // We are hoping here that when other DAWs start to display the version
  1143. // number, that they do so according to yfede's encoding table in the link
  1144. // below. If not, then this code will need an if (isSteinberg()) in the
  1145. // future.
  1146. int major = (hexVersion >> 16) & 0xff;
  1147. int minor = (hexVersion >> 8) & 0xff;
  1148. int bugfix = hexVersion & 0xff;
  1149. // for details, see: https://forum.juce.com/t/issues-with-version-integer-reported-by-vst2/23867
  1150. // Encoding B
  1151. if (major < 1)
  1152. return major * 1000 + minor * 100 + bugfix * 10;
  1153. // Encoding E
  1154. if (major > 100)
  1155. return major * 10000000 + minor * 100000 + bugfix * 1000;
  1156. // Encoding D
  1157. return static_cast<int32> (hexVersion);
  1158. #endif
  1159. }
  1160. //==============================================================================
  1161. #if JUCE_WINDOWS
  1162. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1163. static void checkWhetherMessageThreadIsCorrect()
  1164. {
  1165. auto host = getHostType();
  1166. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1167. {
  1168. if (! messageThreadIsDefinitelyCorrect)
  1169. {
  1170. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1171. struct MessageThreadCallback : public CallbackMessage
  1172. {
  1173. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1174. void messageCallback() override { triggered = true; }
  1175. bool& triggered;
  1176. };
  1177. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1178. }
  1179. }
  1180. }
  1181. #else
  1182. static void checkWhetherMessageThreadIsCorrect() {}
  1183. #endif
  1184. //==============================================================================
  1185. template <typename FloatType>
  1186. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1187. {
  1188. tmpBuffers.release();
  1189. if (processor != nullptr)
  1190. tmpBuffers.tempChannels.insertMultiple (0, nullptr, vstEffect.numInputs
  1191. + vstEffect.numOutputs);
  1192. }
  1193. void deleteTempChannels()
  1194. {
  1195. deleteTempChannels (floatTempBuffers);
  1196. deleteTempChannels (doubleTempBuffers);
  1197. }
  1198. //==============================================================================
  1199. void findMaxTotalChannels (int& maxTotalIns, int& maxTotalOuts)
  1200. {
  1201. #ifdef JucePlugin_PreferredChannelConfigurations
  1202. int configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1203. maxTotalIns = maxTotalOuts = 0;
  1204. for (auto& config : configs)
  1205. {
  1206. maxTotalIns = jmax (maxTotalIns, config[0]);
  1207. maxTotalOuts = jmax (maxTotalOuts, config[1]);
  1208. }
  1209. #else
  1210. auto numInputBuses = processor->getBusCount (true);
  1211. auto numOutputBuses = processor->getBusCount (false);
  1212. if (numInputBuses > 1 || numOutputBuses > 1)
  1213. {
  1214. maxTotalIns = maxTotalOuts = 0;
  1215. for (int i = 0; i < numInputBuses; ++i)
  1216. maxTotalIns += processor->getChannelCountOfBus (true, i);
  1217. for (int i = 0; i < numOutputBuses; ++i)
  1218. maxTotalOuts += processor->getChannelCountOfBus (false, i);
  1219. }
  1220. else
  1221. {
  1222. maxTotalIns = numInputBuses > 0 ? processor->getBus (true, 0)->getMaxSupportedChannels (64) : 0;
  1223. maxTotalOuts = numOutputBuses > 0 ? processor->getBus (false, 0)->getMaxSupportedChannels (64) : 0;
  1224. }
  1225. #endif
  1226. }
  1227. bool pluginHasSidechainsOrAuxs() const { return (processor->getBusCount (true) > 1 || processor->getBusCount (false) > 1); }
  1228. //==============================================================================
  1229. /** Host to plug-in calls. */
  1230. pointer_sized_int handleOpen (VstOpCodeArguments)
  1231. {
  1232. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1233. setHasEditorFlag (processor->hasEditor());
  1234. return 0;
  1235. }
  1236. pointer_sized_int handleClose (VstOpCodeArguments)
  1237. {
  1238. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1239. stopTimer();
  1240. if (MessageManager::getInstance()->isThisTheMessageThread())
  1241. deleteEditor (false);
  1242. return 0;
  1243. }
  1244. pointer_sized_int handleSetCurrentProgram (VstOpCodeArguments args)
  1245. {
  1246. if (processor != nullptr && isPositiveAndBelow ((int) args.value, processor->getNumPrograms()))
  1247. processor->setCurrentProgram ((int) args.value);
  1248. return 0;
  1249. }
  1250. pointer_sized_int handleGetCurrentProgram (VstOpCodeArguments)
  1251. {
  1252. return (processor != nullptr && processor->getNumPrograms() > 0 ? processor->getCurrentProgram() : 0);
  1253. }
  1254. pointer_sized_int handleSetCurrentProgramName (VstOpCodeArguments args)
  1255. {
  1256. if (processor != nullptr && processor->getNumPrograms() > 0)
  1257. processor->changeProgramName (processor->getCurrentProgram(), (char*) args.ptr);
  1258. return 0;
  1259. }
  1260. pointer_sized_int handleGetCurrentProgramName (VstOpCodeArguments args)
  1261. {
  1262. if (processor != nullptr && processor->getNumPrograms() > 0)
  1263. processor->getProgramName (processor->getCurrentProgram()).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1264. return 0;
  1265. }
  1266. pointer_sized_int handleGetParameterLabel (VstOpCodeArguments args)
  1267. {
  1268. if (auto* param = juceParameters.getParamForIndex (args.index))
  1269. {
  1270. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1271. param->getLabel().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1272. }
  1273. return 0;
  1274. }
  1275. pointer_sized_int handleGetParameterText (VstOpCodeArguments args)
  1276. {
  1277. if (auto* param = juceParameters.getParamForIndex (args.index))
  1278. {
  1279. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1280. param->getCurrentValueAsText().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1281. }
  1282. return 0;
  1283. }
  1284. pointer_sized_int handleGetParameterName (VstOpCodeArguments args)
  1285. {
  1286. if (auto* param = juceParameters.getParamForIndex (args.index))
  1287. {
  1288. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1289. param->getName (32).copyToUTF8 ((char*) args.ptr, 32 + 1);
  1290. }
  1291. return 0;
  1292. }
  1293. pointer_sized_int handleSetSampleRate (VstOpCodeArguments args)
  1294. {
  1295. sampleRate = args.opt;
  1296. return 0;
  1297. }
  1298. pointer_sized_int handleSetBlockSize (VstOpCodeArguments args)
  1299. {
  1300. blockSize = (int32) args.value;
  1301. return 0;
  1302. }
  1303. pointer_sized_int handleResumeSuspend (VstOpCodeArguments args)
  1304. {
  1305. if (args.value)
  1306. resume();
  1307. else
  1308. suspend();
  1309. return 0;
  1310. }
  1311. pointer_sized_int handleGetEditorBounds (VstOpCodeArguments args)
  1312. {
  1313. checkWhetherMessageThreadIsCorrect();
  1314. const MessageManagerLock mmLock;
  1315. createEditorComp();
  1316. if (editorComp != nullptr)
  1317. {
  1318. editorComp->getEditorBounds (editorBounds);
  1319. *((Vst2::ERect**) args.ptr) = &editorBounds;
  1320. return (pointer_sized_int) &editorBounds;
  1321. }
  1322. return 0;
  1323. }
  1324. pointer_sized_int handleOpenEditor (VstOpCodeArguments args)
  1325. {
  1326. checkWhetherMessageThreadIsCorrect();
  1327. const MessageManagerLock mmLock;
  1328. jassert (! recursionCheck);
  1329. startTimerHz (4); // performs misc housekeeping chores
  1330. deleteEditor (true);
  1331. createEditorComp();
  1332. if (editorComp != nullptr)
  1333. {
  1334. editorComp->attachToHost (args);
  1335. return 1;
  1336. }
  1337. return 0;
  1338. }
  1339. pointer_sized_int handleCloseEditor (VstOpCodeArguments)
  1340. {
  1341. checkWhetherMessageThreadIsCorrect();
  1342. const MessageManagerLock mmLock;
  1343. deleteEditor (true);
  1344. return 0;
  1345. }
  1346. pointer_sized_int handleGetData (VstOpCodeArguments args)
  1347. {
  1348. if (processor == nullptr)
  1349. return 0;
  1350. auto data = (void**) args.ptr;
  1351. bool onlyStoreCurrentProgramData = (args.index != 0);
  1352. ScopedLock lock (stateInformationLock);
  1353. chunkMemory.reset();
  1354. if (onlyStoreCurrentProgramData)
  1355. processor->getCurrentProgramStateInformation (chunkMemory);
  1356. else
  1357. processor->getStateInformation (chunkMemory);
  1358. *data = (void*) chunkMemory.getData();
  1359. // because the chunk is only needed temporarily by the host (or at least you'd
  1360. // hope so) we'll give it a while and then free it in the timer callback.
  1361. chunkMemoryTime = juce::Time::getApproximateMillisecondCounter();
  1362. return (int32) chunkMemory.getSize();
  1363. }
  1364. pointer_sized_int handleSetData (VstOpCodeArguments args)
  1365. {
  1366. if (processor != nullptr)
  1367. {
  1368. void* data = args.ptr;
  1369. int32 byteSize = (int32) args.value;
  1370. bool onlyRestoreCurrentProgramData = (args.index != 0);
  1371. {
  1372. ScopedLock lock (stateInformationLock);
  1373. chunkMemory.reset();
  1374. chunkMemoryTime = 0;
  1375. if (byteSize > 0 && data != nullptr)
  1376. {
  1377. if (onlyRestoreCurrentProgramData)
  1378. processor->setCurrentProgramStateInformation (data, byteSize);
  1379. else
  1380. processor->setStateInformation (data, byteSize);
  1381. }
  1382. }
  1383. }
  1384. return 0;
  1385. }
  1386. pointer_sized_int handlePreAudioProcessingEvents (VstOpCodeArguments args)
  1387. {
  1388. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1389. VSTMidiEventList::addEventsToMidiBuffer ((Vst2::VstEvents*) args.ptr, midiEvents);
  1390. return 1;
  1391. #else
  1392. ignoreUnused (args);
  1393. return 0;
  1394. #endif
  1395. }
  1396. pointer_sized_int handleIsParameterAutomatable (VstOpCodeArguments args)
  1397. {
  1398. if (auto* param = juceParameters.getParamForIndex (args.index))
  1399. {
  1400. const bool isMeter = ((((unsigned int) param->getCategory() & 0xffff0000) >> 16) == 2);
  1401. return (param->isAutomatable() && (! isMeter) ? 1 : 0);
  1402. }
  1403. return 0;
  1404. }
  1405. pointer_sized_int handleParameterValueForText (VstOpCodeArguments args)
  1406. {
  1407. if (auto* param = juceParameters.getParamForIndex (args.index))
  1408. {
  1409. if (! LegacyAudioParameter::isLegacy (param))
  1410. {
  1411. auto value = param->getValueForText (String::fromUTF8 ((char*) args.ptr));
  1412. param->setValue (value);
  1413. inParameterChangedCallback = true;
  1414. param->sendValueChangedMessageToListeners (value);
  1415. return 1;
  1416. }
  1417. }
  1418. return 0;
  1419. }
  1420. pointer_sized_int handleGetProgramName (VstOpCodeArguments args)
  1421. {
  1422. if (processor != nullptr && isPositiveAndBelow (args.index, processor->getNumPrograms()))
  1423. {
  1424. processor->getProgramName (args.index).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1425. return 1;
  1426. }
  1427. return 0;
  1428. }
  1429. pointer_sized_int handleGetInputPinProperties (VstOpCodeArguments args)
  1430. {
  1431. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, true, args.index)) ? 1 : 0;
  1432. }
  1433. pointer_sized_int handleGetOutputPinProperties (VstOpCodeArguments args)
  1434. {
  1435. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, false, args.index)) ? 1 : 0;
  1436. }
  1437. pointer_sized_int handleGetPlugInCategory (VstOpCodeArguments)
  1438. {
  1439. return Vst2::JucePlugin_VSTCategory;
  1440. }
  1441. pointer_sized_int handleSetSpeakerConfiguration (VstOpCodeArguments args)
  1442. {
  1443. auto* pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.value);
  1444. auto* pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.ptr);
  1445. if (processor->isMidiEffect())
  1446. return 0;
  1447. auto numIns = processor->getBusCount (true);
  1448. auto numOuts = processor->getBusCount (false);
  1449. if (pluginInput != nullptr && pluginInput->type >= 0)
  1450. {
  1451. // inconsistent request?
  1452. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput).size() != pluginInput->numChannels)
  1453. return 0;
  1454. }
  1455. if (pluginOutput != nullptr && pluginOutput->type >= 0)
  1456. {
  1457. // inconsistent request?
  1458. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput).size() != pluginOutput->numChannels)
  1459. return 0;
  1460. }
  1461. if (pluginInput != nullptr && pluginInput->numChannels > 0 && numIns == 0)
  1462. return 0;
  1463. if (pluginOutput != nullptr && pluginOutput->numChannels > 0 && numOuts == 0)
  1464. return 0;
  1465. auto layouts = processor->getBusesLayout();
  1466. if (pluginInput != nullptr && pluginInput-> numChannels >= 0 && numIns > 0)
  1467. layouts.getChannelSet (true, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  1468. if (pluginOutput != nullptr && pluginOutput->numChannels >= 0 && numOuts > 0)
  1469. layouts.getChannelSet (false, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  1470. #ifdef JucePlugin_PreferredChannelConfigurations
  1471. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1472. if (! AudioProcessor::containsLayout (layouts, configs))
  1473. return 0;
  1474. #endif
  1475. return processor->setBusesLayout (layouts) ? 1 : 0;
  1476. }
  1477. pointer_sized_int handleSetBypass (VstOpCodeArguments args)
  1478. {
  1479. isBypassed = (args.value != 0);
  1480. if (auto* bypass = processor->getBypassParameter())
  1481. bypass->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  1482. return 1;
  1483. }
  1484. pointer_sized_int handleGetPlugInName (VstOpCodeArguments args)
  1485. {
  1486. String (JucePlugin_Name).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1487. return 1;
  1488. }
  1489. pointer_sized_int handleGetManufacturerName (VstOpCodeArguments args)
  1490. {
  1491. String (JucePlugin_Manufacturer).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1492. return 1;
  1493. }
  1494. pointer_sized_int handleGetManufacturerVersion (VstOpCodeArguments)
  1495. {
  1496. return convertHexVersionToDecimal (JucePlugin_VersionCode);
  1497. }
  1498. pointer_sized_int handleManufacturerSpecific (VstOpCodeArguments args)
  1499. {
  1500. if (handleManufacturerSpecificVST2Opcode (args.index, args.value, args.ptr, args.opt))
  1501. return 1;
  1502. if (args.index == JUCE_MULTICHAR_CONSTANT ('P', 'r', 'e', 'S')
  1503. && args.value == JUCE_MULTICHAR_CONSTANT ('A', 'e', 'C', 's'))
  1504. return handleSetContentScaleFactor (args.opt);
  1505. if (args.index == Vst2::effGetParamDisplay)
  1506. return handleCockosGetParameterText (args.value, args.ptr, args.opt);
  1507. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1508. return callbackHandler->handleVstManufacturerSpecific (args.index, args.value, args.ptr, args.opt);
  1509. return 0;
  1510. }
  1511. pointer_sized_int handleCanPlugInDo (VstOpCodeArguments args)
  1512. {
  1513. auto text = (const char*) args.ptr;
  1514. auto matches = [=](const char* s) { return strcmp (text, s) == 0; };
  1515. if (matches ("receiveVstEvents")
  1516. || matches ("receiveVstMidiEvent")
  1517. || matches ("receiveVstMidiEvents"))
  1518. {
  1519. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1520. return 1;
  1521. #else
  1522. return -1;
  1523. #endif
  1524. }
  1525. if (matches ("sendVstEvents")
  1526. || matches ("sendVstMidiEvent")
  1527. || matches ("sendVstMidiEvents"))
  1528. {
  1529. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1530. return 1;
  1531. #else
  1532. return -1;
  1533. #endif
  1534. }
  1535. if (matches ("receiveVstTimeInfo")
  1536. || matches ("conformsToWindowRules")
  1537. || matches ("supportsViewDpiScaling")
  1538. || matches ("bypass"))
  1539. {
  1540. return 1;
  1541. }
  1542. // This tells Wavelab to use the UI thread to invoke open/close,
  1543. // like all other hosts do.
  1544. if (matches ("openCloseAnyThread"))
  1545. return -1;
  1546. if (matches ("MPE"))
  1547. return processor->supportsMPE() ? 1 : 0;
  1548. #if JUCE_MAC
  1549. if (matches ("hasCockosViewAsConfig"))
  1550. {
  1551. useNSView = true;
  1552. return (int32) 0xbeef0000;
  1553. }
  1554. #endif
  1555. if (matches ("hasCockosExtensions"))
  1556. return (int32) 0xbeef0000;
  1557. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1558. return callbackHandler->handleVstPluginCanDo (args.index, args.value, args.ptr, args.opt);
  1559. return 0;
  1560. }
  1561. pointer_sized_int handleGetTailSize (VstOpCodeArguments)
  1562. {
  1563. if (processor != nullptr)
  1564. {
  1565. int32 result;
  1566. auto tailSeconds = processor->getTailLengthSeconds();
  1567. if (tailSeconds == std::numeric_limits<double>::infinity())
  1568. result = std::numeric_limits<int32>::max();
  1569. else
  1570. result = static_cast<int32> (tailSeconds * sampleRate);
  1571. return result; // Vst2 expects an int32 upcasted to a intptr_t here
  1572. }
  1573. return 0;
  1574. }
  1575. pointer_sized_int handleKeyboardFocusRequired (VstOpCodeArguments)
  1576. {
  1577. return (JucePlugin_EditorRequiresKeyboardFocus != 0) ? 1 : 0;
  1578. }
  1579. pointer_sized_int handleGetVstInterfaceVersion (VstOpCodeArguments)
  1580. {
  1581. return kVstVersion;
  1582. }
  1583. pointer_sized_int handleGetCurrentMidiProgram (VstOpCodeArguments)
  1584. {
  1585. return -1;
  1586. }
  1587. pointer_sized_int handleGetSpeakerConfiguration (VstOpCodeArguments args)
  1588. {
  1589. auto** pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.value);
  1590. auto** pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.ptr);
  1591. if (pluginHasSidechainsOrAuxs() || processor->isMidiEffect())
  1592. return false;
  1593. auto inputLayout = processor->getChannelLayoutOfBus (true, 0);
  1594. auto outputLayout = processor->getChannelLayoutOfBus (false, 0);
  1595. auto speakerBaseSize = sizeof (Vst2::VstSpeakerArrangement) - (sizeof (Vst2::VstSpeakerProperties) * 8);
  1596. cachedInArrangement .malloc (speakerBaseSize + (static_cast<std::size_t> (inputLayout. size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1597. cachedOutArrangement.malloc (speakerBaseSize + (static_cast<std::size_t> (outputLayout.size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1598. *pluginInput = cachedInArrangement. getData();
  1599. *pluginOutput = cachedOutArrangement.getData();
  1600. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (true, 0), **pluginInput);
  1601. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (false, 0), **pluginOutput);
  1602. return 1;
  1603. }
  1604. pointer_sized_int handleSetNumberOfSamplesToProcess (VstOpCodeArguments args)
  1605. {
  1606. return args.value;
  1607. }
  1608. pointer_sized_int handleSetSampleFloatType (VstOpCodeArguments args)
  1609. {
  1610. if (! isProcessing)
  1611. {
  1612. if (processor != nullptr)
  1613. {
  1614. processor->setProcessingPrecision ((args.value == Vst2::kVstProcessPrecision64
  1615. && processor->supportsDoublePrecisionProcessing())
  1616. ? AudioProcessor::doublePrecision
  1617. : AudioProcessor::singlePrecision);
  1618. return 1;
  1619. }
  1620. }
  1621. return 0;
  1622. }
  1623. pointer_sized_int handleSetContentScaleFactor (float scale)
  1624. {
  1625. #if ! JUCE_MAC
  1626. if (editorComp != nullptr)
  1627. editorComp->setContentScaleFactor (scale);
  1628. lastScaleFactorReceived = scale;
  1629. #else
  1630. ignoreUnused (scale);
  1631. #endif
  1632. return 1;
  1633. }
  1634. pointer_sized_int handleCockosGetParameterText (pointer_sized_int paramIndex,
  1635. void* dest,
  1636. float value)
  1637. {
  1638. if (processor != nullptr && dest != nullptr)
  1639. {
  1640. if (auto* param = juceParameters.getParamForIndex ((int) paramIndex))
  1641. {
  1642. if (! LegacyAudioParameter::isLegacy (param))
  1643. {
  1644. String text (param->getText (value, 1024));
  1645. memcpy (dest, text.toRawUTF8(), ((size_t) text.length()) + 1);
  1646. return 0xbeef;
  1647. }
  1648. }
  1649. }
  1650. return 0;
  1651. }
  1652. //==============================================================================
  1653. pointer_sized_int handleGetNumMidiInputChannels()
  1654. {
  1655. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1656. #ifdef JucePlugin_VSTNumMidiInputs
  1657. return JucePlugin_VSTNumMidiInputs;
  1658. #else
  1659. return 16;
  1660. #endif
  1661. #else
  1662. return 0;
  1663. #endif
  1664. }
  1665. pointer_sized_int handleGetNumMidiOutputChannels()
  1666. {
  1667. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1668. #ifdef JucePlugin_VSTNumMidiOutputs
  1669. return JucePlugin_VSTNumMidiOutputs;
  1670. #else
  1671. return 16;
  1672. #endif
  1673. #else
  1674. return 0;
  1675. #endif
  1676. }
  1677. //==============================================================================
  1678. Vst2::audioMasterCallback hostCallback;
  1679. AudioProcessor* processor = {};
  1680. double sampleRate = 44100.0;
  1681. int32 blockSize = 1024;
  1682. Vst2::AEffect vstEffect;
  1683. CriticalSection stateInformationLock;
  1684. juce::MemoryBlock chunkMemory;
  1685. uint32 chunkMemoryTime = 0;
  1686. std::unique_ptr<EditorCompWrapper> editorComp;
  1687. Vst2::ERect editorBounds;
  1688. MidiBuffer midiEvents;
  1689. VSTMidiEventList outgoingEvents;
  1690. #if ! JUCE_MAC
  1691. float lastScaleFactorReceived = 1.0f;
  1692. #endif
  1693. LegacyAudioParametersWrapper juceParameters;
  1694. bool isProcessing = false, isBypassed = false, hasShutdown = false;
  1695. bool firstProcessCallback = true, shouldDeleteEditor = false;
  1696. #if JUCE_MAC
  1697. #if JUCE_64BIT
  1698. bool useNSView = true;
  1699. #else
  1700. bool useNSView = false;
  1701. #endif
  1702. #endif
  1703. VstTempBuffers<float> floatTempBuffers;
  1704. VstTempBuffers<double> doubleTempBuffers;
  1705. int maxNumInChannels = 0, maxNumOutChannels = 0;
  1706. HeapBlock<Vst2::VstSpeakerArrangement> cachedInArrangement, cachedOutArrangement;
  1707. ThreadLocalValue<bool> inParameterChangedCallback;
  1708. //==============================================================================
  1709. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1710. };
  1711. //==============================================================================
  1712. namespace
  1713. {
  1714. Vst2::AEffect* pluginEntryPoint (Vst2::audioMasterCallback audioMaster)
  1715. {
  1716. JUCE_AUTORELEASEPOOL
  1717. {
  1718. initialiseJuce_GUI();
  1719. try
  1720. {
  1721. if (audioMaster (nullptr, Vst2::audioMasterVersion, 0, 0, nullptr, 0) != 0)
  1722. {
  1723. #if JUCE_LINUX
  1724. MessageManagerLock mmLock;
  1725. #endif
  1726. auto* processor = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1727. auto* wrapper = new JuceVSTWrapper (audioMaster, processor);
  1728. auto* aEffect = wrapper->getAEffect();
  1729. if (auto* callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1730. {
  1731. callbackHandler->handleVstHostCallbackAvailable ([audioMaster, aEffect](int32 opcode, int32 index, pointer_sized_int value, void* ptr, float opt)
  1732. {
  1733. return audioMaster (aEffect, opcode, index, value, ptr, opt);
  1734. });
  1735. }
  1736. return aEffect;
  1737. }
  1738. }
  1739. catch (...)
  1740. {}
  1741. }
  1742. return nullptr;
  1743. }
  1744. }
  1745. #if ! JUCE_WINDOWS
  1746. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1747. #endif
  1748. //==============================================================================
  1749. // Mac startup code..
  1750. #if JUCE_MAC
  1751. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1752. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1753. {
  1754. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1755. initialiseMacVST();
  1756. return pluginEntryPoint (audioMaster);
  1757. }
  1758. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster);
  1759. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster)
  1760. {
  1761. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1762. initialiseMacVST();
  1763. return pluginEntryPoint (audioMaster);
  1764. }
  1765. //==============================================================================
  1766. // Linux startup code..
  1767. #elif JUCE_LINUX
  1768. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1769. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1770. {
  1771. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1772. SharedMessageThread::getInstance();
  1773. return pluginEntryPoint (audioMaster);
  1774. }
  1775. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster) asm ("main");
  1776. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster)
  1777. {
  1778. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1779. return VSTPluginMain (audioMaster);
  1780. }
  1781. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1782. __attribute__((constructor)) void myPluginInit() {}
  1783. __attribute__((destructor)) void myPluginFini() {}
  1784. //==============================================================================
  1785. // Win32 startup code..
  1786. #else
  1787. extern "C" __declspec (dllexport) Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1788. {
  1789. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1790. return pluginEntryPoint (audioMaster);
  1791. }
  1792. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1793. extern "C" __declspec (dllexport) int main (Vst2::audioMasterCallback audioMaster)
  1794. {
  1795. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1796. return (int) pluginEntryPoint (audioMaster);
  1797. }
  1798. #endif
  1799. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1800. {
  1801. if (reason == DLL_PROCESS_ATTACH)
  1802. Process::setCurrentModuleInstanceHandle (instance);
  1803. return true;
  1804. }
  1805. #endif
  1806. #endif