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.

2260 lines
80KB

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