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.

2303 lines
82KB

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