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.

2234 lines
80KB

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