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.

2332 lines
82KB

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