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.

2212 lines
79KB

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