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.

2252 lines
79KB

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