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.

2209 lines
80KB

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