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.

2310 lines
82KB

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