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.

2225 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_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. if ((ti->flags & Vst2::kVstSmpteValid) != 0)
  495. {
  496. AudioPlayHead::FrameRateType rate = AudioPlayHead::fpsUnknown;
  497. double fps = 1.0;
  498. switch (ti->smpteFrameRate)
  499. {
  500. case Vst2::kVstSmpte239fps: rate = AudioPlayHead::fps23976; fps = 24.0 * 1000.0 / 1001.0; break;
  501. case Vst2::kVstSmpte24fps: rate = AudioPlayHead::fps24; fps = 24.0; break;
  502. case Vst2::kVstSmpte25fps: rate = AudioPlayHead::fps25; fps = 25.0; break;
  503. case Vst2::kVstSmpte2997fps: rate = AudioPlayHead::fps2997; fps = 30.0 * 1000.0 / 1001.0; break;
  504. case Vst2::kVstSmpte30fps: rate = AudioPlayHead::fps30; fps = 30.0; break;
  505. case Vst2::kVstSmpte2997dfps: rate = AudioPlayHead::fps2997drop; fps = 30.0 * 1000.0 / 1001.0; break;
  506. case Vst2::kVstSmpte30dfps: rate = AudioPlayHead::fps30drop; fps = 30.0; break;
  507. case Vst2::kVstSmpteFilm16mm:
  508. case Vst2::kVstSmpteFilm35mm: fps = 24.0; break;
  509. case Vst2::kVstSmpte249fps: fps = 25.0 * 1000.0 / 1001.0; break;
  510. case Vst2::kVstSmpte599fps: fps = 60.0 * 1000.0 / 1001.0; break;
  511. case Vst2::kVstSmpte60fps: fps = 60; break;
  512. default: jassertfalse; // unknown frame-rate..
  513. }
  514. info.frameRate = rate;
  515. info.editOriginTime = ti->smpteOffset / (80.0 * fps);
  516. }
  517. else
  518. {
  519. info.frameRate = AudioPlayHead::fpsUnknown;
  520. info.editOriginTime = 0;
  521. }
  522. info.isRecording = (ti->flags & Vst2::kVstTransportRecording) != 0;
  523. info.isPlaying = (ti->flags & (Vst2::kVstTransportRecording | Vst2::kVstTransportPlaying)) != 0;
  524. info.isLooping = (ti->flags & Vst2::kVstTransportCycleActive) != 0;
  525. if ((ti->flags & Vst2::kVstCyclePosValid) != 0)
  526. {
  527. info.ppqLoopStart = ti->cycleStartPos;
  528. info.ppqLoopEnd = ti->cycleEndPos;
  529. }
  530. else
  531. {
  532. info.ppqLoopStart = 0;
  533. info.ppqLoopEnd = 0;
  534. }
  535. return true;
  536. }
  537. //==============================================================================
  538. float getParameter (int32 index) const
  539. {
  540. if (auto* param = juceParameters.getParamForIndex (index))
  541. return param->getValue();
  542. return 0.0f;
  543. }
  544. static float getParameterCB (Vst2::AEffect* vstInterface, int32 index)
  545. {
  546. return getWrapper (vstInterface)->getParameter (index);
  547. }
  548. void setParameter (int32 index, float value)
  549. {
  550. if (auto* param = juceParameters.getParamForIndex (index))
  551. setValueAndNotifyIfChanged (*param, value);
  552. }
  553. static void setParameterCB (Vst2::AEffect* vstInterface, int32 index, float value)
  554. {
  555. getWrapper (vstInterface)->setParameter (index, value);
  556. }
  557. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  558. {
  559. if (inParameterChangedCallback.get())
  560. {
  561. inParameterChangedCallback = false;
  562. return;
  563. }
  564. if (hostCallback != nullptr)
  565. hostCallback (&vstEffect, Vst2::audioMasterAutomate, index, 0, nullptr, newValue);
  566. }
  567. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override
  568. {
  569. if (hostCallback != nullptr)
  570. hostCallback (&vstEffect, Vst2::audioMasterBeginEdit, index, 0, nullptr, 0);
  571. }
  572. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override
  573. {
  574. if (hostCallback != nullptr)
  575. hostCallback (&vstEffect, Vst2::audioMasterEndEdit, index, 0, nullptr, 0);
  576. }
  577. void parameterValueChanged (int, float newValue) override
  578. {
  579. // this can only come from the bypass parameter
  580. isBypassed = (newValue != 0.0f);
  581. }
  582. void parameterGestureChanged (int, bool) override {}
  583. void audioProcessorChanged (AudioProcessor*, const ChangeDetails& details) override
  584. {
  585. hostChangeUpdater.update (details);
  586. }
  587. bool getPinProperties (Vst2::VstPinProperties& properties, bool direction, int index) const
  588. {
  589. if (processor->isMidiEffect())
  590. return false;
  591. int channelIdx, busIdx;
  592. // fill with default
  593. properties.flags = 0;
  594. properties.label[0] = 0;
  595. properties.shortLabel[0] = 0;
  596. properties.arrangementType = Vst2::kSpeakerArrEmpty;
  597. if ((channelIdx = processor->getOffsetInBusBufferForAbsoluteChannelIndex (direction, index, busIdx)) >= 0)
  598. {
  599. auto& bus = *processor->getBus (direction, busIdx);
  600. auto& channelSet = bus.getCurrentLayout();
  601. auto channelType = channelSet.getTypeOfChannel (channelIdx);
  602. properties.flags = Vst2::kVstPinIsActive | Vst2::kVstPinUseSpeaker;
  603. properties.arrangementType = SpeakerMappings::channelSetToVstArrangementType (channelSet);
  604. String label = bus.getName();
  605. #ifdef JucePlugin_PreferredChannelConfigurations
  606. label += " " + String (channelIdx);
  607. #else
  608. if (channelSet.size() > 1)
  609. label += " " + AudioChannelSet::getAbbreviatedChannelTypeName (channelType);
  610. #endif
  611. label.copyToUTF8 (properties.label, (size_t) (Vst2::kVstMaxLabelLen + 1));
  612. label.copyToUTF8 (properties.shortLabel, (size_t) (Vst2::kVstMaxShortLabelLen + 1));
  613. if (channelType == AudioChannelSet::left
  614. || channelType == AudioChannelSet::leftSurround
  615. || channelType == AudioChannelSet::leftCentre
  616. || channelType == AudioChannelSet::leftSurroundSide
  617. || channelType == AudioChannelSet::topFrontLeft
  618. || channelType == AudioChannelSet::topRearLeft
  619. || channelType == AudioChannelSet::leftSurroundRear
  620. || channelType == AudioChannelSet::wideLeft)
  621. properties.flags |= Vst2::kVstPinIsStereo;
  622. return true;
  623. }
  624. return false;
  625. }
  626. //==============================================================================
  627. void timerCallback() override
  628. {
  629. if (shouldDeleteEditor)
  630. {
  631. shouldDeleteEditor = false;
  632. deleteEditor (true);
  633. }
  634. {
  635. ScopedLock lock (stateInformationLock);
  636. if (chunkMemoryTime > 0
  637. && chunkMemoryTime < juce::Time::getApproximateMillisecondCounter() - 2000
  638. && ! recursionCheck)
  639. {
  640. chunkMemory.reset();
  641. chunkMemoryTime = 0;
  642. }
  643. }
  644. if (editorComp != nullptr)
  645. editorComp->checkVisibility();
  646. }
  647. void setHasEditorFlag (bool shouldSetHasEditor)
  648. {
  649. auto hasEditor = (vstEffect.flags & Vst2::effFlagsHasEditor) != 0;
  650. if (shouldSetHasEditor == hasEditor)
  651. return;
  652. if (shouldSetHasEditor)
  653. vstEffect.flags |= Vst2::effFlagsHasEditor;
  654. else
  655. vstEffect.flags &= ~Vst2::effFlagsHasEditor;
  656. }
  657. void createEditorComp()
  658. {
  659. if (hasShutdown || processor == nullptr)
  660. return;
  661. if (editorComp == nullptr)
  662. {
  663. if (auto* ed = processor->createEditorIfNeeded())
  664. {
  665. setHasEditorFlag (true);
  666. editorComp.reset (new EditorCompWrapper (*this, *ed));
  667. }
  668. else
  669. {
  670. setHasEditorFlag (false);
  671. }
  672. }
  673. shouldDeleteEditor = false;
  674. }
  675. void deleteEditor (bool canDeleteLaterIfModal)
  676. {
  677. JUCE_AUTORELEASEPOOL
  678. {
  679. PopupMenu::dismissAllActiveMenus();
  680. jassert (! recursionCheck);
  681. ScopedValueSetter<bool> svs (recursionCheck, true, false);
  682. if (editorComp != nullptr)
  683. {
  684. if (auto* modalComponent = Component::getCurrentlyModalComponent())
  685. {
  686. modalComponent->exitModalState (0);
  687. if (canDeleteLaterIfModal)
  688. {
  689. shouldDeleteEditor = true;
  690. return;
  691. }
  692. }
  693. editorComp->detachHostWindow();
  694. if (auto* ed = editorComp->getEditorComp())
  695. processor->editorBeingDeleted (ed);
  696. editorComp = nullptr;
  697. // there's some kind of component currently modal, but the host
  698. // is trying to delete our plugin. You should try to avoid this happening..
  699. jassert (Component::getCurrentlyModalComponent() == nullptr);
  700. }
  701. }
  702. }
  703. pointer_sized_int dispatcher (int32 opCode, VstOpCodeArguments args)
  704. {
  705. if (hasShutdown)
  706. return 0;
  707. switch (opCode)
  708. {
  709. case Vst2::effOpen: return handleOpen (args);
  710. case Vst2::effClose: return handleClose (args);
  711. case Vst2::effSetProgram: return handleSetCurrentProgram (args);
  712. case Vst2::effGetProgram: return handleGetCurrentProgram (args);
  713. case Vst2::effSetProgramName: return handleSetCurrentProgramName (args);
  714. case Vst2::effGetProgramName: return handleGetCurrentProgramName (args);
  715. case Vst2::effGetParamLabel: return handleGetParameterLabel (args);
  716. case Vst2::effGetParamDisplay: return handleGetParameterText (args);
  717. case Vst2::effGetParamName: return handleGetParameterName (args);
  718. case Vst2::effSetSampleRate: return handleSetSampleRate (args);
  719. case Vst2::effSetBlockSize: return handleSetBlockSize (args);
  720. case Vst2::effMainsChanged: return handleResumeSuspend (args);
  721. case Vst2::effEditGetRect: return handleGetEditorBounds (args);
  722. case Vst2::effEditOpen: return handleOpenEditor (args);
  723. case Vst2::effEditClose: return handleCloseEditor (args);
  724. case Vst2::effIdentify: return (pointer_sized_int) ByteOrder::bigEndianInt ("NvEf");
  725. case Vst2::effGetChunk: return handleGetData (args);
  726. case Vst2::effSetChunk: return handleSetData (args);
  727. case Vst2::effProcessEvents: return handlePreAudioProcessingEvents (args);
  728. case Vst2::effCanBeAutomated: return handleIsParameterAutomatable (args);
  729. case Vst2::effString2Parameter: return handleParameterValueForText (args);
  730. case Vst2::effGetProgramNameIndexed: return handleGetProgramName (args);
  731. case Vst2::effGetInputProperties: return handleGetInputPinProperties (args);
  732. case Vst2::effGetOutputProperties: return handleGetOutputPinProperties (args);
  733. case Vst2::effGetPlugCategory: return handleGetPlugInCategory (args);
  734. case Vst2::effSetSpeakerArrangement: return handleSetSpeakerConfiguration (args);
  735. case Vst2::effSetBypass: return handleSetBypass (args);
  736. case Vst2::effGetEffectName: return handleGetPlugInName (args);
  737. case Vst2::effGetProductString: return handleGetPlugInName (args);
  738. case Vst2::effGetVendorString: return handleGetManufacturerName (args);
  739. case Vst2::effGetVendorVersion: return handleGetManufacturerVersion (args);
  740. case Vst2::effVendorSpecific: return handleManufacturerSpecific (args);
  741. case Vst2::effCanDo: return handleCanPlugInDo (args);
  742. case Vst2::effGetTailSize: return handleGetTailSize (args);
  743. case Vst2::effKeysRequired: return handleKeyboardFocusRequired (args);
  744. case Vst2::effGetVstVersion: return handleGetVstInterfaceVersion (args);
  745. case Vst2::effGetCurrentMidiProgram: return handleGetCurrentMidiProgram (args);
  746. case Vst2::effGetSpeakerArrangement: return handleGetSpeakerConfiguration (args);
  747. case Vst2::effSetTotalSampleToProcess: return handleSetNumberOfSamplesToProcess (args);
  748. case Vst2::effSetProcessPrecision: return handleSetSampleFloatType (args);
  749. case Vst2::effGetNumMidiInputChannels: return handleGetNumMidiInputChannels();
  750. case Vst2::effGetNumMidiOutputChannels: return handleGetNumMidiOutputChannels();
  751. default: return 0;
  752. }
  753. }
  754. static pointer_sized_int dispatcherCB (Vst2::AEffect* vstInterface, int32 opCode, int32 index,
  755. pointer_sized_int value, void* ptr, float opt)
  756. {
  757. auto* wrapper = getWrapper (vstInterface);
  758. VstOpCodeArguments args = { index, value, ptr, opt };
  759. if (opCode == Vst2::effClose)
  760. {
  761. wrapper->dispatcher (opCode, args);
  762. delete wrapper;
  763. return 1;
  764. }
  765. return wrapper->dispatcher (opCode, args);
  766. }
  767. //==============================================================================
  768. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  769. // chores when it changes or repaints.
  770. struct EditorCompWrapper : public Component
  771. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  772. , public Timer
  773. #endif
  774. {
  775. EditorCompWrapper (JuceVSTWrapper& w, AudioProcessorEditor& editor)
  776. : wrapper (w)
  777. {
  778. editor.setOpaque (true);
  779. addAndMakeVisible (editor);
  780. auto editorBounds = getSizeToContainChild();
  781. setSize (editorBounds.getWidth(), editorBounds.getHeight());
  782. #if JUCE_WINDOWS
  783. if (! getHostType().isReceptor())
  784. addMouseListener (this, true);
  785. #endif
  786. setOpaque (true);
  787. }
  788. ~EditorCompWrapper() override
  789. {
  790. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  791. // have been transferred to another parent which takes over ownership.
  792. }
  793. void paint (Graphics& g) override
  794. {
  795. g.fillAll (Colours::black);
  796. }
  797. void getEditorBounds (Vst2::ERect& bounds)
  798. {
  799. auto editorBounds = getSizeToContainChild();
  800. bounds = convertToHostBounds ({ 0, 0, (int16) editorBounds.getHeight(), (int16) editorBounds.getWidth() });
  801. }
  802. void attachToHost (VstOpCodeArguments args)
  803. {
  804. setVisible (false);
  805. #if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
  806. addToDesktop (0, args.ptr);
  807. hostWindow = (HostWindowType) args.ptr;
  808. #if JUCE_LINUX || JUCE_BSD
  809. X11Symbols::getInstance()->xReparentWindow (display,
  810. (Window) getWindowHandle(),
  811. (HostWindowType) hostWindow,
  812. 0, 0);
  813. #elif JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  814. checkHostWindowScaleFactor();
  815. startTimer (500);
  816. #endif
  817. #elif JUCE_MAC
  818. hostWindow = attachComponentToWindowRefVST (this, args.ptr, wrapper.useNSView);
  819. #endif
  820. setVisible (true);
  821. }
  822. void detachHostWindow()
  823. {
  824. #if JUCE_MAC
  825. if (hostWindow != nullptr)
  826. detachComponentFromWindowRefVST (this, hostWindow, wrapper.useNSView);
  827. #endif
  828. hostWindow = {};
  829. }
  830. void checkVisibility()
  831. {
  832. #if JUCE_MAC
  833. if (hostWindow != nullptr)
  834. checkWindowVisibilityVST (hostWindow, this, wrapper.useNSView);
  835. #endif
  836. }
  837. AudioProcessorEditor* getEditorComp() const noexcept
  838. {
  839. return dynamic_cast<AudioProcessorEditor*> (getChildComponent (0));
  840. }
  841. void resized() override
  842. {
  843. if (auto* pluginEditor = getEditorComp())
  844. {
  845. if (! resizingParent)
  846. {
  847. auto newBounds = getLocalBounds();
  848. {
  849. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  850. pluginEditor->setBounds (pluginEditor->getLocalArea (this, newBounds).withPosition (0, 0));
  851. }
  852. lastBounds = newBounds;
  853. }
  854. updateWindowSize();
  855. }
  856. #if JUCE_MAC && ! JUCE_64BIT
  857. if (! wrapper.useNSView)
  858. updateEditorCompBoundsVST (this);
  859. #endif
  860. }
  861. void parentSizeChanged() override
  862. {
  863. updateWindowSize();
  864. }
  865. void childBoundsChanged (Component*) override
  866. {
  867. if (resizingChild)
  868. return;
  869. auto newBounds = getSizeToContainChild();
  870. if (newBounds != lastBounds)
  871. {
  872. updateWindowSize();
  873. lastBounds = newBounds;
  874. }
  875. }
  876. juce::Rectangle<int> getSizeToContainChild()
  877. {
  878. if (auto* pluginEditor = getEditorComp())
  879. return getLocalArea (pluginEditor, pluginEditor->getLocalBounds());
  880. return {};
  881. }
  882. void updateWindowSize()
  883. {
  884. if (! resizingParent
  885. && getEditorComp() != nullptr
  886. && hostWindow != HostWindowType{})
  887. {
  888. auto editorBounds = getSizeToContainChild();
  889. resizeHostWindow (editorBounds.getWidth(), editorBounds.getHeight());
  890. {
  891. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  892. #if JUCE_LINUX || JUCE_BSD // setSize() on linux causes renoise and energyxt to fail.
  893. auto rect = convertToHostBounds ({ 0, 0, (int16) editorBounds.getHeight(), (int16) editorBounds.getWidth() });
  894. X11Symbols::getInstance()->xResizeWindow (display, (Window) getWindowHandle(),
  895. static_cast<unsigned int> (rect.right - rect.left),
  896. static_cast<unsigned int> (rect.bottom - rect.top));
  897. #else
  898. setSize (editorBounds.getWidth(), editorBounds.getHeight());
  899. #endif
  900. }
  901. #if JUCE_MAC
  902. resizeHostWindow (editorBounds.getWidth(), editorBounds.getHeight()); // (doing this a second time seems to be necessary in tracktion)
  903. #endif
  904. }
  905. }
  906. void resizeHostWindow (int newWidth, int newHeight)
  907. {
  908. auto rect = convertToHostBounds ({ 0, 0, (int16) newHeight, (int16) newWidth });
  909. newWidth = rect.right - rect.left;
  910. newHeight = rect.bottom - rect.top;
  911. bool sizeWasSuccessful = false;
  912. if (auto host = wrapper.hostCallback)
  913. {
  914. auto status = host (wrapper.getAEffect(), Vst2::audioMasterCanDo, 0, 0, const_cast<char*> ("sizeWindow"), 0);
  915. if (status == (pointer_sized_int) 1 || getHostType().isAbletonLive())
  916. {
  917. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  918. sizeWasSuccessful = (host (wrapper.getAEffect(), Vst2::audioMasterSizeWindow,
  919. newWidth, newHeight, nullptr, 0) != 0);
  920. }
  921. }
  922. // some hosts don't support the sizeWindow call, so do it manually..
  923. if (! sizeWasSuccessful)
  924. {
  925. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  926. #if JUCE_MAC
  927. setNativeHostWindowSizeVST (hostWindow, this, newWidth, newHeight, wrapper.useNSView);
  928. #elif JUCE_LINUX || JUCE_BSD
  929. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  930. setSize (newWidth, newHeight);
  931. #else
  932. int dw = 0;
  933. int dh = 0;
  934. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  935. HWND w = (HWND) getWindowHandle();
  936. while (w != nullptr)
  937. {
  938. HWND parent = getWindowParent (w);
  939. if (parent == nullptr)
  940. break;
  941. TCHAR windowType [32] = { 0 };
  942. GetClassName (parent, windowType, 31);
  943. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  944. break;
  945. RECT windowPos, parentPos;
  946. GetWindowRect (w, &windowPos);
  947. GetWindowRect (parent, &parentPos);
  948. if (w != (HWND) getWindowHandle())
  949. SetWindowPos (w, nullptr, 0, 0, newWidth + dw, newHeight + dh,
  950. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  951. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  952. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  953. w = parent;
  954. if (dw == 2 * frameThickness)
  955. break;
  956. if (dw > 100 || dh > 100)
  957. w = nullptr;
  958. }
  959. if (w != nullptr)
  960. SetWindowPos (w, nullptr, 0, 0, newWidth + dw, newHeight + dh,
  961. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  962. #endif
  963. }
  964. }
  965. void setContentScaleFactor (float scale)
  966. {
  967. if (! approximatelyEqual (scale, editorScaleFactor))
  968. {
  969. editorScaleFactor = scale;
  970. if (auto* pluginEditor = getEditorComp())
  971. {
  972. auto prevEditorBounds = pluginEditor->getLocalArea (this, lastBounds);
  973. {
  974. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  975. pluginEditor->setScaleFactor (editorScaleFactor);
  976. pluginEditor->setBounds (prevEditorBounds.withPosition (0, 0));
  977. }
  978. lastBounds = getSizeToContainChild();
  979. updateWindowSize();
  980. }
  981. }
  982. }
  983. #if JUCE_WINDOWS
  984. void mouseDown (const MouseEvent&) override
  985. {
  986. broughtToFront();
  987. }
  988. void broughtToFront() override
  989. {
  990. // for hosts like nuendo, need to also pop the MDI container to the
  991. // front when our comp is clicked on.
  992. if (! isCurrentlyBlockedByAnotherModalComponent())
  993. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  994. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  995. }
  996. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  997. void checkHostWindowScaleFactor()
  998. {
  999. auto hostWindowScale = (float) getScaleFactorForWindow ((HostWindowType) hostWindow);
  1000. if (hostWindowScale > 0.0f && ! approximatelyEqual (hostWindowScale, editorScaleFactor))
  1001. wrapper.handleSetContentScaleFactor (hostWindowScale);
  1002. }
  1003. void timerCallback() override
  1004. {
  1005. checkHostWindowScaleFactor();
  1006. }
  1007. #endif
  1008. #endif
  1009. #if JUCE_MAC
  1010. bool keyPressed (const KeyPress&) override
  1011. {
  1012. // If we have an unused keypress, move the key-focus to a host window
  1013. // and re-inject the event..
  1014. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1015. }
  1016. #endif
  1017. private:
  1018. //==============================================================================
  1019. static Vst2::ERect convertToHostBounds (const Vst2::ERect& rect)
  1020. {
  1021. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1022. if (approximatelyEqual (desktopScale, 1.0f))
  1023. return rect;
  1024. return { (int16) roundToInt (rect.top * desktopScale),
  1025. (int16) roundToInt (rect.left * desktopScale),
  1026. (int16) roundToInt (rect.bottom * desktopScale),
  1027. (int16) roundToInt (rect.right * desktopScale) };
  1028. }
  1029. //==============================================================================
  1030. JuceVSTWrapper& wrapper;
  1031. bool resizingChild = false, resizingParent = false;
  1032. float editorScaleFactor = 1.0f;
  1033. juce::Rectangle<int> lastBounds;
  1034. #if JUCE_LINUX || JUCE_BSD
  1035. using HostWindowType = ::Window;
  1036. ::Display* display = XWindowSystem::getInstance()->getDisplay();
  1037. #elif JUCE_WINDOWS
  1038. using HostWindowType = HWND;
  1039. WindowsHooks hooks;
  1040. #else
  1041. using HostWindowType = void*;
  1042. #endif
  1043. HostWindowType hostWindow = {};
  1044. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1045. };
  1046. //==============================================================================
  1047. private:
  1048. struct HostChangeUpdater : private AsyncUpdater
  1049. {
  1050. explicit HostChangeUpdater (JuceVSTWrapper& o) : owner (o) {}
  1051. ~HostChangeUpdater() override { cancelPendingUpdate(); }
  1052. void update (const ChangeDetails& details)
  1053. {
  1054. if (details.latencyChanged)
  1055. {
  1056. owner.vstEffect.initialDelay = owner.processor->getLatencySamples();
  1057. callbackBits |= audioMasterIOChangedBit;
  1058. }
  1059. if (details.parameterInfoChanged || details.programChanged)
  1060. callbackBits |= audioMasterUpdateDisplayBit;
  1061. triggerAsyncUpdate();
  1062. }
  1063. private:
  1064. void handleAsyncUpdate() override
  1065. {
  1066. const auto callbacksToFire = callbackBits.exchange (0);
  1067. if (auto* callback = owner.hostCallback)
  1068. {
  1069. struct FlagPair
  1070. {
  1071. Vst2::AudioMasterOpcodesX opcode;
  1072. int bit;
  1073. };
  1074. constexpr FlagPair pairs[] { { Vst2::audioMasterUpdateDisplay, audioMasterUpdateDisplayBit },
  1075. { Vst2::audioMasterIOChanged, audioMasterIOChangedBit } };
  1076. for (const auto& pair : pairs)
  1077. if ((callbacksToFire & pair.bit) != 0)
  1078. callback (&owner.vstEffect, pair.opcode, 0, 0, nullptr, 0);
  1079. }
  1080. }
  1081. static constexpr auto audioMasterUpdateDisplayBit = 1 << 0;
  1082. static constexpr auto audioMasterIOChangedBit = 1 << 1;
  1083. JuceVSTWrapper& owner;
  1084. std::atomic<int> callbackBits { 0 };
  1085. };
  1086. static JuceVSTWrapper* getWrapper (Vst2::AEffect* v) noexcept { return static_cast<JuceVSTWrapper*> (v->object); }
  1087. bool isProcessLevelOffline()
  1088. {
  1089. return hostCallback != nullptr
  1090. && (int32) hostCallback (&vstEffect, Vst2::audioMasterGetCurrentProcessLevel, 0, 0, nullptr, 0) == 4;
  1091. }
  1092. static int32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1093. {
  1094. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1095. return (int32) hexVersion;
  1096. #else
  1097. // Currently, only Cubase displays the version number to the user
  1098. // We are hoping here that when other DAWs start to display the version
  1099. // number, that they do so according to yfede's encoding table in the link
  1100. // below. If not, then this code will need an if (isSteinberg()) in the
  1101. // future.
  1102. int major = (hexVersion >> 16) & 0xff;
  1103. int minor = (hexVersion >> 8) & 0xff;
  1104. int bugfix = hexVersion & 0xff;
  1105. // for details, see: https://forum.juce.com/t/issues-with-version-integer-reported-by-vst2/23867
  1106. // Encoding B
  1107. if (major < 1)
  1108. return major * 1000 + minor * 100 + bugfix * 10;
  1109. // Encoding E
  1110. if (major > 100)
  1111. return major * 10000000 + minor * 100000 + bugfix * 1000;
  1112. // Encoding D
  1113. return static_cast<int32> (hexVersion);
  1114. #endif
  1115. }
  1116. //==============================================================================
  1117. #if JUCE_WINDOWS
  1118. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1119. static void checkWhetherMessageThreadIsCorrect()
  1120. {
  1121. auto host = getHostType();
  1122. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1123. {
  1124. if (! messageThreadIsDefinitelyCorrect)
  1125. {
  1126. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1127. struct MessageThreadCallback : public CallbackMessage
  1128. {
  1129. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1130. void messageCallback() override { triggered = true; }
  1131. bool& triggered;
  1132. };
  1133. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1134. }
  1135. }
  1136. }
  1137. #else
  1138. static void checkWhetherMessageThreadIsCorrect() {}
  1139. #endif
  1140. void setValueAndNotifyIfChanged (AudioProcessorParameter& param, float newValue)
  1141. {
  1142. if (param.getValue() == newValue)
  1143. return;
  1144. inParameterChangedCallback = true;
  1145. param.setValueNotifyingHost (newValue);
  1146. }
  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. setValueAndNotifyIfChanged (*param, param->getValueForText (String::fromUTF8 ((char*) args.ptr)));
  1375. return 1;
  1376. }
  1377. }
  1378. return 0;
  1379. }
  1380. pointer_sized_int handleGetProgramName (VstOpCodeArguments args)
  1381. {
  1382. if (processor != nullptr && isPositiveAndBelow (args.index, processor->getNumPrograms()))
  1383. {
  1384. processor->getProgramName (args.index).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1385. return 1;
  1386. }
  1387. return 0;
  1388. }
  1389. pointer_sized_int handleGetInputPinProperties (VstOpCodeArguments args)
  1390. {
  1391. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, true, args.index)) ? 1 : 0;
  1392. }
  1393. pointer_sized_int handleGetOutputPinProperties (VstOpCodeArguments args)
  1394. {
  1395. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, false, args.index)) ? 1 : 0;
  1396. }
  1397. pointer_sized_int handleGetPlugInCategory (VstOpCodeArguments)
  1398. {
  1399. return Vst2::JucePlugin_VSTCategory;
  1400. }
  1401. pointer_sized_int handleSetSpeakerConfiguration (VstOpCodeArguments args)
  1402. {
  1403. auto* pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.value);
  1404. auto* pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.ptr);
  1405. if (processor->isMidiEffect())
  1406. return 0;
  1407. auto numIns = processor->getBusCount (true);
  1408. auto numOuts = processor->getBusCount (false);
  1409. if (pluginInput != nullptr && pluginInput->type >= 0)
  1410. {
  1411. // inconsistent request?
  1412. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput).size() != pluginInput->numChannels)
  1413. return 0;
  1414. }
  1415. if (pluginOutput != nullptr && pluginOutput->type >= 0)
  1416. {
  1417. // inconsistent request?
  1418. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput).size() != pluginOutput->numChannels)
  1419. return 0;
  1420. }
  1421. if (pluginInput != nullptr && pluginInput->numChannels > 0 && numIns == 0)
  1422. return 0;
  1423. if (pluginOutput != nullptr && pluginOutput->numChannels > 0 && numOuts == 0)
  1424. return 0;
  1425. auto layouts = processor->getBusesLayout();
  1426. if (pluginInput != nullptr && pluginInput-> numChannels >= 0 && numIns > 0)
  1427. layouts.getChannelSet (true, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  1428. if (pluginOutput != nullptr && pluginOutput->numChannels >= 0 && numOuts > 0)
  1429. layouts.getChannelSet (false, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  1430. #ifdef JucePlugin_PreferredChannelConfigurations
  1431. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1432. if (! AudioProcessor::containsLayout (layouts, configs))
  1433. return 0;
  1434. #endif
  1435. return processor->setBusesLayout (layouts) ? 1 : 0;
  1436. }
  1437. pointer_sized_int handleSetBypass (VstOpCodeArguments args)
  1438. {
  1439. isBypassed = (args.value != 0);
  1440. if (auto* bypass = processor->getBypassParameter())
  1441. bypass->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  1442. return 1;
  1443. }
  1444. pointer_sized_int handleGetPlugInName (VstOpCodeArguments args)
  1445. {
  1446. String (JucePlugin_Name).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1447. return 1;
  1448. }
  1449. pointer_sized_int handleGetManufacturerName (VstOpCodeArguments args)
  1450. {
  1451. String (JucePlugin_Manufacturer).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1452. return 1;
  1453. }
  1454. pointer_sized_int handleGetManufacturerVersion (VstOpCodeArguments)
  1455. {
  1456. return convertHexVersionToDecimal (JucePlugin_VersionCode);
  1457. }
  1458. pointer_sized_int handleManufacturerSpecific (VstOpCodeArguments args)
  1459. {
  1460. if (handleManufacturerSpecificVST2Opcode (args.index, args.value, args.ptr, args.opt))
  1461. return 1;
  1462. if (args.index == (int32) ByteOrder::bigEndianInt ("PreS")
  1463. && args.value == (int32) ByteOrder::bigEndianInt ("AeCs"))
  1464. return handleSetContentScaleFactor (args.opt);
  1465. if (args.index == Vst2::effGetParamDisplay)
  1466. return handleCockosGetParameterText (args.value, args.ptr, args.opt);
  1467. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor.get()))
  1468. return callbackHandler->handleVstManufacturerSpecific (args.index, args.value, args.ptr, args.opt);
  1469. return 0;
  1470. }
  1471. pointer_sized_int handleCanPlugInDo (VstOpCodeArguments args)
  1472. {
  1473. auto text = (const char*) args.ptr;
  1474. auto matches = [=] (const char* s) { return strcmp (text, s) == 0; };
  1475. if (matches ("receiveVstEvents")
  1476. || matches ("receiveVstMidiEvent")
  1477. || matches ("receiveVstMidiEvents"))
  1478. {
  1479. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1480. return 1;
  1481. #else
  1482. return -1;
  1483. #endif
  1484. }
  1485. if (matches ("sendVstEvents")
  1486. || matches ("sendVstMidiEvent")
  1487. || matches ("sendVstMidiEvents"))
  1488. {
  1489. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1490. return 1;
  1491. #else
  1492. return -1;
  1493. #endif
  1494. }
  1495. if (matches ("receiveVstTimeInfo")
  1496. || matches ("conformsToWindowRules")
  1497. || matches ("supportsViewDpiScaling")
  1498. || matches ("bypass"))
  1499. {
  1500. return 1;
  1501. }
  1502. // This tells Wavelab to use the UI thread to invoke open/close,
  1503. // like all other hosts do.
  1504. if (matches ("openCloseAnyThread"))
  1505. return -1;
  1506. if (matches ("MPE"))
  1507. return processor->supportsMPE() ? 1 : 0;
  1508. #if JUCE_MAC
  1509. if (matches ("hasCockosViewAsConfig"))
  1510. {
  1511. useNSView = true;
  1512. return (int32) 0xbeef0000;
  1513. }
  1514. #endif
  1515. if (matches ("hasCockosExtensions"))
  1516. return (int32) 0xbeef0000;
  1517. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor.get()))
  1518. return callbackHandler->handleVstPluginCanDo (args.index, args.value, args.ptr, args.opt);
  1519. return 0;
  1520. }
  1521. pointer_sized_int handleGetTailSize (VstOpCodeArguments)
  1522. {
  1523. if (processor != nullptr)
  1524. {
  1525. int32 result;
  1526. auto tailSeconds = processor->getTailLengthSeconds();
  1527. if (tailSeconds == std::numeric_limits<double>::infinity())
  1528. result = std::numeric_limits<int32>::max();
  1529. else
  1530. result = static_cast<int32> (tailSeconds * sampleRate);
  1531. return result; // Vst2 expects an int32 upcasted to a intptr_t here
  1532. }
  1533. return 0;
  1534. }
  1535. pointer_sized_int handleKeyboardFocusRequired (VstOpCodeArguments)
  1536. {
  1537. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6326)
  1538. return (JucePlugin_EditorRequiresKeyboardFocus != 0) ? 1 : 0;
  1539. JUCE_END_IGNORE_WARNINGS_MSVC
  1540. }
  1541. pointer_sized_int handleGetVstInterfaceVersion (VstOpCodeArguments)
  1542. {
  1543. return kVstVersion;
  1544. }
  1545. pointer_sized_int handleGetCurrentMidiProgram (VstOpCodeArguments)
  1546. {
  1547. return -1;
  1548. }
  1549. pointer_sized_int handleGetSpeakerConfiguration (VstOpCodeArguments args)
  1550. {
  1551. auto** pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.value);
  1552. auto** pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.ptr);
  1553. if (pluginHasSidechainsOrAuxs() || processor->isMidiEffect())
  1554. return false;
  1555. auto inputLayout = processor->getChannelLayoutOfBus (true, 0);
  1556. auto outputLayout = processor->getChannelLayoutOfBus (false, 0);
  1557. auto speakerBaseSize = sizeof (Vst2::VstSpeakerArrangement) - (sizeof (Vst2::VstSpeakerProperties) * 8);
  1558. cachedInArrangement .malloc (speakerBaseSize + (static_cast<std::size_t> (inputLayout. size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1559. cachedOutArrangement.malloc (speakerBaseSize + (static_cast<std::size_t> (outputLayout.size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1560. *pluginInput = cachedInArrangement. getData();
  1561. *pluginOutput = cachedOutArrangement.getData();
  1562. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (true, 0), **pluginInput);
  1563. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (false, 0), **pluginOutput);
  1564. return 1;
  1565. }
  1566. pointer_sized_int handleSetNumberOfSamplesToProcess (VstOpCodeArguments args)
  1567. {
  1568. return args.value;
  1569. }
  1570. pointer_sized_int handleSetSampleFloatType (VstOpCodeArguments args)
  1571. {
  1572. if (! isProcessing)
  1573. {
  1574. if (processor != nullptr)
  1575. {
  1576. processor->setProcessingPrecision ((args.value == Vst2::kVstProcessPrecision64
  1577. && processor->supportsDoublePrecisionProcessing())
  1578. ? AudioProcessor::doublePrecision
  1579. : AudioProcessor::singlePrecision);
  1580. return 1;
  1581. }
  1582. }
  1583. return 0;
  1584. }
  1585. pointer_sized_int handleSetContentScaleFactor (float scale)
  1586. {
  1587. #if ! JUCE_MAC
  1588. if (editorComp != nullptr)
  1589. editorComp->setContentScaleFactor (scale);
  1590. #else
  1591. ignoreUnused (scale);
  1592. #endif
  1593. return 1;
  1594. }
  1595. pointer_sized_int handleCockosGetParameterText (pointer_sized_int paramIndex,
  1596. void* dest,
  1597. float value)
  1598. {
  1599. if (processor != nullptr && dest != nullptr)
  1600. {
  1601. if (auto* param = juceParameters.getParamForIndex ((int) paramIndex))
  1602. {
  1603. if (! LegacyAudioParameter::isLegacy (param))
  1604. {
  1605. String text (param->getText (value, 1024));
  1606. memcpy (dest, text.toRawUTF8(), ((size_t) text.length()) + 1);
  1607. return 0xbeef;
  1608. }
  1609. }
  1610. }
  1611. return 0;
  1612. }
  1613. //==============================================================================
  1614. pointer_sized_int handleGetNumMidiInputChannels()
  1615. {
  1616. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1617. #ifdef JucePlugin_VSTNumMidiInputs
  1618. return JucePlugin_VSTNumMidiInputs;
  1619. #else
  1620. return 16;
  1621. #endif
  1622. #else
  1623. return 0;
  1624. #endif
  1625. }
  1626. pointer_sized_int handleGetNumMidiOutputChannels()
  1627. {
  1628. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1629. #ifdef JucePlugin_VSTNumMidiOutputs
  1630. return JucePlugin_VSTNumMidiOutputs;
  1631. #else
  1632. return 16;
  1633. #endif
  1634. #else
  1635. return 0;
  1636. #endif
  1637. }
  1638. //==============================================================================
  1639. ScopedJuceInitialiser_GUI libraryInitialiser;
  1640. #if JUCE_LINUX || JUCE_BSD
  1641. SharedResourcePointer<MessageThread> messageThread;
  1642. #endif
  1643. Vst2::audioMasterCallback hostCallback;
  1644. std::unique_ptr<AudioProcessor> processor;
  1645. double sampleRate = 44100.0;
  1646. int32 blockSize = 1024;
  1647. Vst2::AEffect vstEffect;
  1648. CriticalSection stateInformationLock;
  1649. juce::MemoryBlock chunkMemory;
  1650. uint32 chunkMemoryTime = 0;
  1651. std::unique_ptr<EditorCompWrapper> editorComp;
  1652. Vst2::ERect editorRect;
  1653. MidiBuffer midiEvents;
  1654. VSTMidiEventList outgoingEvents;
  1655. LegacyAudioParametersWrapper juceParameters;
  1656. bool isProcessing = false, isBypassed = false, hasShutdown = false;
  1657. bool firstProcessCallback = true, shouldDeleteEditor = false;
  1658. #if JUCE_MAC
  1659. #if JUCE_64BIT
  1660. bool useNSView = true;
  1661. #else
  1662. bool useNSView = false;
  1663. #endif
  1664. #endif
  1665. VstTempBuffers<float> floatTempBuffers;
  1666. VstTempBuffers<double> doubleTempBuffers;
  1667. int maxNumInChannels = 0, maxNumOutChannels = 0;
  1668. HeapBlock<Vst2::VstSpeakerArrangement> cachedInArrangement, cachedOutArrangement;
  1669. ThreadLocalValue<bool> inParameterChangedCallback;
  1670. HostChangeUpdater hostChangeUpdater { *this };
  1671. //==============================================================================
  1672. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1673. };
  1674. //==============================================================================
  1675. namespace
  1676. {
  1677. Vst2::AEffect* pluginEntryPoint (Vst2::audioMasterCallback audioMaster)
  1678. {
  1679. JUCE_AUTORELEASEPOOL
  1680. {
  1681. ScopedJuceInitialiser_GUI libraryInitialiser;
  1682. #if JUCE_LINUX || JUCE_BSD
  1683. SharedResourcePointer<MessageThread> messageThread;
  1684. #endif
  1685. try
  1686. {
  1687. if (audioMaster (nullptr, Vst2::audioMasterVersion, 0, 0, nullptr, 0) != 0)
  1688. {
  1689. #if JUCE_LINUX || JUCE_BSD
  1690. MessageManagerLock mmLock;
  1691. #endif
  1692. std::unique_ptr<AudioProcessor> processor { createPluginFilterOfType (AudioProcessor::wrapperType_VST) };
  1693. auto* processorPtr = processor.get();
  1694. auto* wrapper = new JuceVSTWrapper (audioMaster, std::move (processor));
  1695. auto* aEffect = wrapper->getAEffect();
  1696. if (auto* callbackHandler = dynamic_cast<VSTCallbackHandler*> (processorPtr))
  1697. {
  1698. callbackHandler->handleVstHostCallbackAvailable ([audioMaster, aEffect] (int32 opcode, int32 index, pointer_sized_int value, void* ptr, float opt)
  1699. {
  1700. return audioMaster (aEffect, opcode, index, value, ptr, opt);
  1701. });
  1702. }
  1703. return aEffect;
  1704. }
  1705. }
  1706. catch (...)
  1707. {}
  1708. }
  1709. return nullptr;
  1710. }
  1711. }
  1712. #if ! JUCE_WINDOWS
  1713. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1714. #endif
  1715. //==============================================================================
  1716. // Mac startup code..
  1717. #if JUCE_MAC
  1718. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1719. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1720. {
  1721. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1722. initialiseMacVST();
  1723. return pluginEntryPoint (audioMaster);
  1724. }
  1725. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster);
  1726. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster)
  1727. {
  1728. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1729. initialiseMacVST();
  1730. return pluginEntryPoint (audioMaster);
  1731. }
  1732. //==============================================================================
  1733. // Linux startup code..
  1734. #elif JUCE_LINUX || JUCE_BSD
  1735. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1736. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1737. {
  1738. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1739. return pluginEntryPoint (audioMaster);
  1740. }
  1741. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster) asm ("main");
  1742. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster)
  1743. {
  1744. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1745. return VSTPluginMain (audioMaster);
  1746. }
  1747. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1748. __attribute__((constructor)) void myPluginInit() {}
  1749. __attribute__((destructor)) void myPluginFini() {}
  1750. //==============================================================================
  1751. // Win32 startup code..
  1752. #else
  1753. extern "C" __declspec (dllexport) Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1754. {
  1755. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1756. return pluginEntryPoint (audioMaster);
  1757. }
  1758. #if ! defined (JUCE_64BIT) && JUCE_MSVC // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1759. extern "C" __declspec (dllexport) int main (Vst2::audioMasterCallback audioMaster)
  1760. {
  1761. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1762. return (int) pluginEntryPoint (audioMaster);
  1763. }
  1764. #endif
  1765. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1766. {
  1767. if (reason == DLL_PROCESS_ATTACH)
  1768. Process::setCurrentModuleInstanceHandle (instance);
  1769. return true;
  1770. }
  1771. #endif
  1772. JUCE_END_IGNORE_WARNINGS_MSVC
  1773. #endif