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.

2258 lines
79KB

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