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.

2260 lines
80KB

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