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.

2229 lines
79KB

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