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.

2269 lines
81KB

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