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.

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