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.

2231 lines
79KB

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