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.

2238 lines
79KB

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