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.

2247 lines
80KB

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