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.

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