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.

2235 lines
79KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. #include "../../juce_core/system/juce_CompilerWarnings.h"
  14. #include "../../juce_core/system/juce_TargetPlatform.h"
  15. #include "../utility/juce_CheckSettingMacros.h"
  16. #if JucePlugin_Build_VST
  17. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996 4100)
  18. #include "../utility/juce_IncludeSystemHeaders.h"
  19. #include <juce_core/juce_core.h>
  20. #if JucePlugin_VersionCode < 0x010000 // Major < 0
  21. #if (JucePlugin_VersionCode & 0x00FF00) > (9 * 0x100) // check if Minor number exceeds 9
  22. JUCE_COMPILER_WARNING ("When version has 'major' = 0, VST2 has trouble displaying 'minor' exceeding 9")
  23. #endif
  24. #if (JucePlugin_VersionCode & 0xFF) > 9 // check if Bugfix number exceeds 9
  25. JUCE_COMPILER_WARNING ("When version has 'major' = 0, VST2 has trouble displaying 'bugfix' exceeding 9")
  26. #endif
  27. #elif JucePlugin_VersionCode >= 0x650000 // Major >= 101
  28. #if (JucePlugin_VersionCode & 0x00FF00) > (99 * 0x100) // check if Minor number exceeds 99
  29. JUCE_COMPILER_WARNING ("When version has 'major' > 100, VST2 has trouble displaying 'minor' exceeding 99")
  30. #endif
  31. #if (JucePlugin_VersionCode & 0xFF) > 99 // check if Bugfix number exceeds 99
  32. JUCE_COMPILER_WARNING ("When version has 'major' > 100, VST2 has trouble displaying 'bugfix' exceeding 99")
  33. #endif
  34. #endif
  35. #ifdef PRAGMA_ALIGN_SUPPORTED
  36. #undef PRAGMA_ALIGN_SUPPORTED
  37. #define PRAGMA_ALIGN_SUPPORTED 1
  38. #endif
  39. #ifndef _MSC_VER
  40. #define __cdecl
  41. #endif
  42. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wconversion",
  43. "-Wshadow",
  44. "-Wdeprecated-register",
  45. "-Wunused-parameter",
  46. "-Wdeprecated-writable-strings",
  47. "-Wnon-virtual-dtor",
  48. "-Wzero-as-null-pointer-constant")
  49. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4458)
  50. #define VST_FORCE_DEPRECATED 0
  51. namespace Vst2
  52. {
  53. // If the following files cannot be found then you are probably trying to build
  54. // a VST2 plug-in or a VST2-compatible VST3 plug-in. To do this you must have a
  55. // VST2 SDK in your header search paths or use the "VST (Legacy) SDK Folder"
  56. // field in the Projucer. The VST2 SDK can be obtained from the
  57. // vstsdk3610_11_06_2018_build_37 (or older) VST3 SDK or JUCE version 5.3.2. You
  58. // also need a VST2 license from Steinberg to distribute VST2 plug-ins.
  59. #include "pluginterfaces/vst2.x/aeffect.h"
  60. #include "pluginterfaces/vst2.x/aeffectx.h"
  61. }
  62. JUCE_END_IGNORE_WARNINGS_MSVC
  63. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  64. //==============================================================================
  65. #ifdef _MSC_VER
  66. #pragma pack (push, 8)
  67. #endif
  68. #define JUCE_VSTINTERFACE_H_INCLUDED 1
  69. #define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
  70. #include "../utility/juce_IncludeModuleHeaders.h"
  71. using namespace juce;
  72. #include "../utility/juce_FakeMouseMoveGenerator.h"
  73. #include "../utility/juce_WindowsHooks.h"
  74. #include "../../juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp"
  75. #include "../../juce_audio_processors/format_types/juce_VSTCommon.h"
  76. #if JUCE_BIG_ENDIAN
  77. #define JUCE_MULTICHAR_CONSTANT(a, b, c, d) (a | (((uint32) b) << 8) | (((uint32) c) << 16) | (((uint32) d) << 24))
  78. #else
  79. #define JUCE_MULTICHAR_CONSTANT(a, b, c, d) (d | (((uint32) c) << 8) | (((uint32) b) << 16) | (((uint32) a) << 24))
  80. #endif
  81. #ifdef _MSC_VER
  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. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  846. startTimer (500);
  847. #endif
  848. }
  849. ~EditorCompWrapper() override
  850. {
  851. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  852. // have been transferred to another parent which takes over ownership.
  853. }
  854. void paint (Graphics&) override {}
  855. void getEditorBounds (Vst2::ERect& bounds)
  856. {
  857. auto b = getSizeToContainChild();
  858. bounds = convertToHostBounds ({ 0, 0, (int16) b.getHeight(), (int16) b.getWidth() });
  859. }
  860. void attachToHost (VstOpCodeArguments args)
  861. {
  862. setOpaque (true);
  863. setVisible (false);
  864. #if JUCE_WINDOWS
  865. addToDesktop (0, args.ptr);
  866. hostWindow = (HWND) args.ptr;
  867. #elif JUCE_LINUX
  868. addToDesktop (0, args.ptr);
  869. hostWindow = (Window) args.ptr;
  870. X11Symbols::getInstance()->xReparentWindow (display, (Window) getWindowHandle(), hostWindow, 0, 0);
  871. #else
  872. hostWindow = attachComponentToWindowRefVST (this, args.ptr, wrapper.useNSView);
  873. #endif
  874. setVisible (true);
  875. }
  876. void detachHostWindow()
  877. {
  878. #if JUCE_MAC
  879. if (hostWindow != nullptr)
  880. {
  881. detachComponentFromWindowRefVST (this, hostWindow, wrapper.useNSView);
  882. hostWindow = nullptr;
  883. }
  884. #endif
  885. #if JUCE_LINUX
  886. hostWindow = {};
  887. #endif
  888. }
  889. void checkVisibility()
  890. {
  891. #if JUCE_MAC
  892. if (hostWindow != nullptr)
  893. checkWindowVisibilityVST (hostWindow, this, wrapper.useNSView);
  894. #endif
  895. }
  896. AudioProcessorEditor* getEditorComp() const noexcept
  897. {
  898. return dynamic_cast<AudioProcessorEditor*> (getChildComponent (0));
  899. }
  900. void resized() override
  901. {
  902. if (auto* ed = getEditorComp())
  903. {
  904. ed->setTopLeftPosition (0, 0);
  905. if (shouldResizeEditor)
  906. {
  907. auto newBounds = getLocalBounds();
  908. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  909. if (! lastBounds.isEmpty() && isWithin (newBounds.toDouble().getAspectRatio(), lastBounds.toDouble().getAspectRatio(), 0.1))
  910. return;
  911. lastBounds = newBounds;
  912. #endif
  913. ed->setBounds (ed->getLocalArea (this, newBounds));
  914. }
  915. updateWindowSize (false);
  916. }
  917. #if JUCE_MAC && ! JUCE_64BIT
  918. if (! wrapper.useNSView)
  919. updateEditorCompBoundsVST (this);
  920. #endif
  921. }
  922. void childBoundsChanged (Component*) override
  923. {
  924. updateWindowSize (false);
  925. }
  926. juce::Rectangle<int> getSizeToContainChild()
  927. {
  928. if (auto* ed = getEditorComp())
  929. return getLocalArea (ed, ed->getLocalBounds());
  930. return {};
  931. }
  932. void updateWindowSize (bool resizeEditor)
  933. {
  934. if (! isInSizeWindow)
  935. {
  936. if (auto* ed = getEditorComp())
  937. {
  938. ed->setTopLeftPosition (0, 0);
  939. auto pos = getSizeToContainChild();
  940. #if JUCE_MAC
  941. if (wrapper.useNSView)
  942. setTopLeftPosition (0, getHeight() - pos.getHeight());
  943. #endif
  944. resizeHostWindow (pos.getWidth(), pos.getHeight());
  945. #if ! JUCE_LINUX // setSize() on linux causes renoise and energyxt to fail.
  946. if (! resizeEditor) // this is needed to prevent an infinite resizing loop due to coordinate rounding
  947. shouldResizeEditor = false;
  948. setSize (pos.getWidth(), pos.getHeight());
  949. shouldResizeEditor = true;
  950. #else
  951. ignoreUnused (resizeEditor);
  952. auto scale = Desktop::getInstance().getGlobalScaleFactor();
  953. if (auto* peer = ed->getPeer())
  954. scale *= (float) peer->getPlatformScaleFactor();
  955. X11Symbols::getInstance()->xResizeWindow (display, (Window) getWindowHandle(),
  956. static_cast<unsigned int> (roundToInt (pos.getWidth() * scale)),
  957. static_cast<unsigned int> (roundToInt (pos.getHeight() * scale)));
  958. #endif
  959. #if JUCE_MAC
  960. resizeHostWindow (pos.getWidth(), pos.getHeight()); // (doing this a second time seems to be necessary in tracktion)
  961. #endif
  962. }
  963. }
  964. }
  965. void resizeHostWindow (int newWidth, int newHeight)
  966. {
  967. auto rect = convertToHostBounds ({ 0, 0, (int16) newHeight, (int16) newWidth });
  968. newWidth = rect.right - rect.left;
  969. newHeight = rect.bottom - rect.top;
  970. bool sizeWasSuccessful = false;
  971. if (auto host = wrapper.hostCallback)
  972. {
  973. auto status = host (wrapper.getAEffect(), Vst2::audioMasterCanDo, 0, 0, const_cast<char*> ("sizeWindow"), 0);
  974. if (status == (pointer_sized_int) 1 || getHostType().isAbletonLive())
  975. {
  976. const ScopedValueSetter<bool> inSizeWindowSetter (isInSizeWindow, true);
  977. sizeWasSuccessful = (host (wrapper.getAEffect(), Vst2::audioMasterSizeWindow,
  978. newWidth, newHeight, nullptr, 0) != 0);
  979. }
  980. }
  981. if (! sizeWasSuccessful)
  982. {
  983. // some hosts don't support the sizeWindow call, so do it manually..
  984. #if JUCE_MAC
  985. setNativeHostWindowSizeVST (hostWindow, this, newWidth, newHeight, wrapper.useNSView);
  986. #elif JUCE_LINUX
  987. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  988. setSize (newWidth, newHeight);
  989. #else
  990. int dw = 0;
  991. int dh = 0;
  992. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  993. HWND w = (HWND) getWindowHandle();
  994. while (w != 0)
  995. {
  996. HWND parent = getWindowParent (w);
  997. if (parent == 0)
  998. break;
  999. TCHAR windowType [32] = { 0 };
  1000. GetClassName (parent, windowType, 31);
  1001. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  1002. break;
  1003. RECT windowPos, parentPos;
  1004. GetWindowRect (w, &windowPos);
  1005. GetWindowRect (parent, &parentPos);
  1006. if (w != (HWND) getWindowHandle())
  1007. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1008. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1009. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1010. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1011. w = parent;
  1012. if (dw == 2 * frameThickness)
  1013. break;
  1014. if (dw > 100 || dh > 100)
  1015. w = 0;
  1016. }
  1017. if (w != 0)
  1018. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1019. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1020. #endif
  1021. }
  1022. if (auto* peer = getPeer())
  1023. {
  1024. peer->handleMovedOrResized();
  1025. repaint();
  1026. }
  1027. }
  1028. void setContentScaleFactor (float scale)
  1029. {
  1030. if (! approximatelyEqual (scale, editorScaleFactor))
  1031. {
  1032. editorScaleFactor = scale;
  1033. if (auto* ed = getEditorComp())
  1034. ed->setScaleFactor (editorScaleFactor);
  1035. updateWindowSize (true);
  1036. }
  1037. }
  1038. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1039. void timerCallback() override
  1040. {
  1041. auto hostWindowScale = (float) getScaleFactorForWindow (hostWindow);
  1042. if (hostWindowScale > 0.0f && ! approximatelyEqual (hostWindowScale, editorScaleFactor))
  1043. wrapper.handleSetContentScaleFactor (hostWindowScale);
  1044. }
  1045. #endif
  1046. #if JUCE_WINDOWS
  1047. void mouseDown (const MouseEvent&) override
  1048. {
  1049. broughtToFront();
  1050. }
  1051. void broughtToFront() override
  1052. {
  1053. // for hosts like nuendo, need to also pop the MDI container to the
  1054. // front when our comp is clicked on.
  1055. if (! isCurrentlyBlockedByAnotherModalComponent())
  1056. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  1057. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1058. }
  1059. #endif
  1060. #if JUCE_MAC
  1061. bool keyPressed (const KeyPress&) override
  1062. {
  1063. // If we have an unused keypress, move the key-focus to a host window
  1064. // and re-inject the event..
  1065. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1066. }
  1067. #endif
  1068. //==============================================================================
  1069. static Vst2::ERect convertToHostBounds (const Vst2::ERect& rect)
  1070. {
  1071. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1072. if (approximatelyEqual (desktopScale, 1.0f))
  1073. return rect;
  1074. return { (int16) roundToInt (rect.top * desktopScale),
  1075. (int16) roundToInt (rect.left * desktopScale),
  1076. (int16) roundToInt (rect.bottom * desktopScale),
  1077. (int16) roundToInt (rect.right * desktopScale)};
  1078. }
  1079. //==============================================================================
  1080. JuceVSTWrapper& wrapper;
  1081. FakeMouseMoveGenerator fakeMouseGenerator;
  1082. bool isInSizeWindow = false;
  1083. bool shouldResizeEditor = true;
  1084. float editorScaleFactor = 1.0f;
  1085. #if JUCE_MAC
  1086. void* hostWindow = nullptr;
  1087. #elif JUCE_LINUX
  1088. ::Display* display = XWindowSystem::getInstance()->getDisplay();
  1089. Window hostWindow = {};
  1090. #elif JUCE_WINDOWS
  1091. HWND hostWindow = {};
  1092. WindowsHooks hooks;
  1093. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1094. juce::Rectangle<int> lastBounds;
  1095. #endif
  1096. #endif
  1097. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1098. };
  1099. //==============================================================================
  1100. private:
  1101. static JuceVSTWrapper* getWrapper (Vst2::AEffect* v) noexcept { return static_cast<JuceVSTWrapper*> (v->object); }
  1102. bool isProcessLevelOffline()
  1103. {
  1104. return hostCallback != nullptr
  1105. && (int32) hostCallback (&vstEffect, Vst2::audioMasterGetCurrentProcessLevel, 0, 0, nullptr, 0) == 4;
  1106. }
  1107. static int32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1108. {
  1109. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1110. return (int32) hexVersion;
  1111. #else
  1112. // Currently, only Cubase displays the version number to the user
  1113. // We are hoping here that when other DAWs start to display the version
  1114. // number, that they do so according to yfede's encoding table in the link
  1115. // below. If not, then this code will need an if (isSteinberg()) in the
  1116. // future.
  1117. int major = (hexVersion >> 16) & 0xff;
  1118. int minor = (hexVersion >> 8) & 0xff;
  1119. int bugfix = hexVersion & 0xff;
  1120. // for details, see: https://forum.juce.com/t/issues-with-version-integer-reported-by-vst2/23867
  1121. // Encoding B
  1122. if (major < 1)
  1123. return major * 1000 + minor * 100 + bugfix * 10;
  1124. // Encoding E
  1125. if (major > 100)
  1126. return major * 10000000 + minor * 100000 + bugfix * 1000;
  1127. // Encoding D
  1128. return static_cast<int32> (hexVersion);
  1129. #endif
  1130. }
  1131. //==============================================================================
  1132. #if JUCE_WINDOWS
  1133. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1134. static void checkWhetherMessageThreadIsCorrect()
  1135. {
  1136. auto host = getHostType();
  1137. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1138. {
  1139. if (! messageThreadIsDefinitelyCorrect)
  1140. {
  1141. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1142. struct MessageThreadCallback : public CallbackMessage
  1143. {
  1144. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1145. void messageCallback() override { triggered = true; }
  1146. bool& triggered;
  1147. };
  1148. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1149. }
  1150. }
  1151. }
  1152. #else
  1153. static void checkWhetherMessageThreadIsCorrect() {}
  1154. #endif
  1155. //==============================================================================
  1156. template <typename FloatType>
  1157. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1158. {
  1159. tmpBuffers.release();
  1160. if (processor != nullptr)
  1161. tmpBuffers.tempChannels.insertMultiple (0, nullptr, vstEffect.numInputs
  1162. + vstEffect.numOutputs);
  1163. }
  1164. void deleteTempChannels()
  1165. {
  1166. deleteTempChannels (floatTempBuffers);
  1167. deleteTempChannels (doubleTempBuffers);
  1168. }
  1169. //==============================================================================
  1170. void findMaxTotalChannels (int& maxTotalIns, int& maxTotalOuts)
  1171. {
  1172. #ifdef JucePlugin_PreferredChannelConfigurations
  1173. int configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1174. maxTotalIns = maxTotalOuts = 0;
  1175. for (auto& config : configs)
  1176. {
  1177. maxTotalIns = jmax (maxTotalIns, config[0]);
  1178. maxTotalOuts = jmax (maxTotalOuts, config[1]);
  1179. }
  1180. #else
  1181. auto numInputBuses = processor->getBusCount (true);
  1182. auto numOutputBuses = processor->getBusCount (false);
  1183. if (numInputBuses > 1 || numOutputBuses > 1)
  1184. {
  1185. maxTotalIns = maxTotalOuts = 0;
  1186. for (int i = 0; i < numInputBuses; ++i)
  1187. maxTotalIns += processor->getChannelCountOfBus (true, i);
  1188. for (int i = 0; i < numOutputBuses; ++i)
  1189. maxTotalOuts += processor->getChannelCountOfBus (false, i);
  1190. }
  1191. else
  1192. {
  1193. maxTotalIns = numInputBuses > 0 ? processor->getBus (true, 0)->getMaxSupportedChannels (64) : 0;
  1194. maxTotalOuts = numOutputBuses > 0 ? processor->getBus (false, 0)->getMaxSupportedChannels (64) : 0;
  1195. }
  1196. #endif
  1197. }
  1198. bool pluginHasSidechainsOrAuxs() const { return (processor->getBusCount (true) > 1 || processor->getBusCount (false) > 1); }
  1199. //==============================================================================
  1200. /** Host to plug-in calls. */
  1201. pointer_sized_int handleOpen (VstOpCodeArguments)
  1202. {
  1203. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1204. setHasEditorFlag (processor->hasEditor());
  1205. return 0;
  1206. }
  1207. pointer_sized_int handleClose (VstOpCodeArguments)
  1208. {
  1209. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1210. stopTimer();
  1211. if (MessageManager::getInstance()->isThisTheMessageThread())
  1212. deleteEditor (false);
  1213. return 0;
  1214. }
  1215. pointer_sized_int handleSetCurrentProgram (VstOpCodeArguments args)
  1216. {
  1217. if (processor != nullptr && isPositiveAndBelow ((int) args.value, processor->getNumPrograms()))
  1218. processor->setCurrentProgram ((int) args.value);
  1219. return 0;
  1220. }
  1221. pointer_sized_int handleGetCurrentProgram (VstOpCodeArguments)
  1222. {
  1223. return (processor != nullptr && processor->getNumPrograms() > 0 ? processor->getCurrentProgram() : 0);
  1224. }
  1225. pointer_sized_int handleSetCurrentProgramName (VstOpCodeArguments args)
  1226. {
  1227. if (processor != nullptr && processor->getNumPrograms() > 0)
  1228. processor->changeProgramName (processor->getCurrentProgram(), (char*) args.ptr);
  1229. return 0;
  1230. }
  1231. pointer_sized_int handleGetCurrentProgramName (VstOpCodeArguments args)
  1232. {
  1233. if (processor != nullptr && processor->getNumPrograms() > 0)
  1234. processor->getProgramName (processor->getCurrentProgram()).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1235. return 0;
  1236. }
  1237. pointer_sized_int handleGetParameterLabel (VstOpCodeArguments args)
  1238. {
  1239. if (auto* param = juceParameters.getParamForIndex (args.index))
  1240. {
  1241. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1242. param->getLabel().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1243. }
  1244. return 0;
  1245. }
  1246. pointer_sized_int handleGetParameterText (VstOpCodeArguments args)
  1247. {
  1248. if (auto* param = juceParameters.getParamForIndex (args.index))
  1249. {
  1250. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1251. param->getCurrentValueAsText().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1252. }
  1253. return 0;
  1254. }
  1255. pointer_sized_int handleGetParameterName (VstOpCodeArguments args)
  1256. {
  1257. if (auto* param = juceParameters.getParamForIndex (args.index))
  1258. {
  1259. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1260. param->getName (32).copyToUTF8 ((char*) args.ptr, 32 + 1);
  1261. }
  1262. return 0;
  1263. }
  1264. pointer_sized_int handleSetSampleRate (VstOpCodeArguments args)
  1265. {
  1266. sampleRate = args.opt;
  1267. return 0;
  1268. }
  1269. pointer_sized_int handleSetBlockSize (VstOpCodeArguments args)
  1270. {
  1271. blockSize = (int32) args.value;
  1272. return 0;
  1273. }
  1274. pointer_sized_int handleResumeSuspend (VstOpCodeArguments args)
  1275. {
  1276. if (args.value)
  1277. resume();
  1278. else
  1279. suspend();
  1280. return 0;
  1281. }
  1282. pointer_sized_int handleGetEditorBounds (VstOpCodeArguments args)
  1283. {
  1284. checkWhetherMessageThreadIsCorrect();
  1285. const MessageManagerLock mmLock;
  1286. createEditorComp();
  1287. if (editorComp != nullptr)
  1288. {
  1289. editorComp->getEditorBounds (editorBounds);
  1290. *((Vst2::ERect**) args.ptr) = &editorBounds;
  1291. return (pointer_sized_int) &editorBounds;
  1292. }
  1293. return 0;
  1294. }
  1295. pointer_sized_int handleOpenEditor (VstOpCodeArguments args)
  1296. {
  1297. checkWhetherMessageThreadIsCorrect();
  1298. const MessageManagerLock mmLock;
  1299. jassert (! recursionCheck);
  1300. startTimerHz (4); // performs misc housekeeping chores
  1301. deleteEditor (true);
  1302. createEditorComp();
  1303. if (editorComp != nullptr)
  1304. {
  1305. editorComp->attachToHost (args);
  1306. return 1;
  1307. }
  1308. return 0;
  1309. }
  1310. pointer_sized_int handleCloseEditor (VstOpCodeArguments)
  1311. {
  1312. checkWhetherMessageThreadIsCorrect();
  1313. const MessageManagerLock mmLock;
  1314. deleteEditor (true);
  1315. return 0;
  1316. }
  1317. pointer_sized_int handleGetData (VstOpCodeArguments args)
  1318. {
  1319. if (processor == nullptr)
  1320. return 0;
  1321. auto data = (void**) args.ptr;
  1322. bool onlyStoreCurrentProgramData = (args.index != 0);
  1323. ScopedLock lock (stateInformationLock);
  1324. chunkMemory.reset();
  1325. if (onlyStoreCurrentProgramData)
  1326. processor->getCurrentProgramStateInformation (chunkMemory);
  1327. else
  1328. processor->getStateInformation (chunkMemory);
  1329. *data = (void*) chunkMemory.getData();
  1330. // because the chunk is only needed temporarily by the host (or at least you'd
  1331. // hope so) we'll give it a while and then free it in the timer callback.
  1332. chunkMemoryTime = juce::Time::getApproximateMillisecondCounter();
  1333. return (int32) chunkMemory.getSize();
  1334. }
  1335. pointer_sized_int handleSetData (VstOpCodeArguments args)
  1336. {
  1337. if (processor != nullptr)
  1338. {
  1339. void* data = args.ptr;
  1340. int32 byteSize = (int32) args.value;
  1341. bool onlyRestoreCurrentProgramData = (args.index != 0);
  1342. {
  1343. ScopedLock lock (stateInformationLock);
  1344. chunkMemory.reset();
  1345. chunkMemoryTime = 0;
  1346. if (byteSize > 0 && data != nullptr)
  1347. {
  1348. if (onlyRestoreCurrentProgramData)
  1349. processor->setCurrentProgramStateInformation (data, byteSize);
  1350. else
  1351. processor->setStateInformation (data, byteSize);
  1352. }
  1353. }
  1354. }
  1355. return 0;
  1356. }
  1357. pointer_sized_int handlePreAudioProcessingEvents (VstOpCodeArguments args)
  1358. {
  1359. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1360. VSTMidiEventList::addEventsToMidiBuffer ((Vst2::VstEvents*) args.ptr, midiEvents);
  1361. return 1;
  1362. #else
  1363. ignoreUnused (args);
  1364. return 0;
  1365. #endif
  1366. }
  1367. pointer_sized_int handleIsParameterAutomatable (VstOpCodeArguments args)
  1368. {
  1369. if (auto* param = juceParameters.getParamForIndex (args.index))
  1370. {
  1371. const bool isMeter = ((((unsigned int) param->getCategory() & 0xffff0000) >> 16) == 2);
  1372. return (param->isAutomatable() && (! isMeter) ? 1 : 0);
  1373. }
  1374. return 0;
  1375. }
  1376. pointer_sized_int handleParameterValueForText (VstOpCodeArguments args)
  1377. {
  1378. if (auto* param = juceParameters.getParamForIndex (args.index))
  1379. {
  1380. if (! LegacyAudioParameter::isLegacy (param))
  1381. {
  1382. auto value = param->getValueForText (String::fromUTF8 ((char*) args.ptr));
  1383. param->setValue (value);
  1384. inParameterChangedCallback = true;
  1385. param->sendValueChangedMessageToListeners (value);
  1386. return 1;
  1387. }
  1388. }
  1389. return 0;
  1390. }
  1391. pointer_sized_int handleGetProgramName (VstOpCodeArguments args)
  1392. {
  1393. if (processor != nullptr && isPositiveAndBelow (args.index, processor->getNumPrograms()))
  1394. {
  1395. processor->getProgramName (args.index).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1396. return 1;
  1397. }
  1398. return 0;
  1399. }
  1400. pointer_sized_int handleGetInputPinProperties (VstOpCodeArguments args)
  1401. {
  1402. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, true, args.index)) ? 1 : 0;
  1403. }
  1404. pointer_sized_int handleGetOutputPinProperties (VstOpCodeArguments args)
  1405. {
  1406. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, false, args.index)) ? 1 : 0;
  1407. }
  1408. pointer_sized_int handleGetPlugInCategory (VstOpCodeArguments)
  1409. {
  1410. return Vst2::JucePlugin_VSTCategory;
  1411. }
  1412. pointer_sized_int handleSetSpeakerConfiguration (VstOpCodeArguments args)
  1413. {
  1414. auto* pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.value);
  1415. auto* pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.ptr);
  1416. if (processor->isMidiEffect())
  1417. return 0;
  1418. auto numIns = processor->getBusCount (true);
  1419. auto numOuts = processor->getBusCount (false);
  1420. if (pluginInput != nullptr && pluginInput->type >= 0)
  1421. {
  1422. // inconsistent request?
  1423. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput).size() != pluginInput->numChannels)
  1424. return 0;
  1425. }
  1426. if (pluginOutput != nullptr && pluginOutput->type >= 0)
  1427. {
  1428. // inconsistent request?
  1429. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput).size() != pluginOutput->numChannels)
  1430. return 0;
  1431. }
  1432. if (pluginInput != nullptr && pluginInput->numChannels > 0 && numIns == 0)
  1433. return 0;
  1434. if (pluginOutput != nullptr && pluginOutput->numChannels > 0 && numOuts == 0)
  1435. return 0;
  1436. auto layouts = processor->getBusesLayout();
  1437. if (pluginInput != nullptr && pluginInput-> numChannels >= 0 && numIns > 0)
  1438. layouts.getChannelSet (true, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  1439. if (pluginOutput != nullptr && pluginOutput->numChannels >= 0 && numOuts > 0)
  1440. layouts.getChannelSet (false, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  1441. #ifdef JucePlugin_PreferredChannelConfigurations
  1442. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1443. if (! AudioProcessor::containsLayout (layouts, configs))
  1444. return 0;
  1445. #endif
  1446. return processor->setBusesLayout (layouts) ? 1 : 0;
  1447. }
  1448. pointer_sized_int handleSetBypass (VstOpCodeArguments args)
  1449. {
  1450. isBypassed = (args.value != 0);
  1451. if (auto* bypass = processor->getBypassParameter())
  1452. bypass->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  1453. return 1;
  1454. }
  1455. pointer_sized_int handleGetPlugInName (VstOpCodeArguments args)
  1456. {
  1457. String (JucePlugin_Name).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1458. return 1;
  1459. }
  1460. pointer_sized_int handleGetManufacturerName (VstOpCodeArguments args)
  1461. {
  1462. String (JucePlugin_Manufacturer).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1463. return 1;
  1464. }
  1465. pointer_sized_int handleGetManufacturerVersion (VstOpCodeArguments)
  1466. {
  1467. return convertHexVersionToDecimal (JucePlugin_VersionCode);
  1468. }
  1469. pointer_sized_int handleManufacturerSpecific (VstOpCodeArguments args)
  1470. {
  1471. if (handleManufacturerSpecificVST2Opcode (args.index, args.value, args.ptr, args.opt))
  1472. return 1;
  1473. if (args.index == (int32) JUCE_MULTICHAR_CONSTANT ('P', 'r', 'e', 'S')
  1474. && args.value == (int32) JUCE_MULTICHAR_CONSTANT ('A', 'e', 'C', 's'))
  1475. return handleSetContentScaleFactor (args.opt);
  1476. if (args.index == Vst2::effGetParamDisplay)
  1477. return handleCockosGetParameterText (args.value, args.ptr, args.opt);
  1478. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1479. return callbackHandler->handleVstManufacturerSpecific (args.index, args.value, args.ptr, args.opt);
  1480. return 0;
  1481. }
  1482. pointer_sized_int handleCanPlugInDo (VstOpCodeArguments args)
  1483. {
  1484. auto text = (const char*) args.ptr;
  1485. auto matches = [=](const char* s) { return strcmp (text, s) == 0; };
  1486. if (matches ("receiveVstEvents")
  1487. || matches ("receiveVstMidiEvent")
  1488. || matches ("receiveVstMidiEvents"))
  1489. {
  1490. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1491. return 1;
  1492. #else
  1493. return -1;
  1494. #endif
  1495. }
  1496. if (matches ("sendVstEvents")
  1497. || matches ("sendVstMidiEvent")
  1498. || matches ("sendVstMidiEvents"))
  1499. {
  1500. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1501. return 1;
  1502. #else
  1503. return -1;
  1504. #endif
  1505. }
  1506. if (matches ("receiveVstTimeInfo")
  1507. || matches ("conformsToWindowRules")
  1508. || matches ("supportsViewDpiScaling")
  1509. || matches ("bypass"))
  1510. {
  1511. return 1;
  1512. }
  1513. // This tells Wavelab to use the UI thread to invoke open/close,
  1514. // like all other hosts do.
  1515. if (matches ("openCloseAnyThread"))
  1516. return -1;
  1517. if (matches ("MPE"))
  1518. return processor->supportsMPE() ? 1 : 0;
  1519. #if JUCE_MAC
  1520. if (matches ("hasCockosViewAsConfig"))
  1521. {
  1522. useNSView = true;
  1523. return (int32) 0xbeef0000;
  1524. }
  1525. #endif
  1526. if (matches ("hasCockosExtensions"))
  1527. return (int32) 0xbeef0000;
  1528. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1529. return callbackHandler->handleVstPluginCanDo (args.index, args.value, args.ptr, args.opt);
  1530. return 0;
  1531. }
  1532. pointer_sized_int handleGetTailSize (VstOpCodeArguments)
  1533. {
  1534. if (processor != nullptr)
  1535. {
  1536. int32 result;
  1537. auto tailSeconds = processor->getTailLengthSeconds();
  1538. if (tailSeconds == std::numeric_limits<double>::infinity())
  1539. result = std::numeric_limits<int32>::max();
  1540. else
  1541. result = static_cast<int32> (tailSeconds * sampleRate);
  1542. return result; // Vst2 expects an int32 upcasted to a intptr_t here
  1543. }
  1544. return 0;
  1545. }
  1546. pointer_sized_int handleKeyboardFocusRequired (VstOpCodeArguments)
  1547. {
  1548. return (JucePlugin_EditorRequiresKeyboardFocus != 0) ? 1 : 0;
  1549. }
  1550. pointer_sized_int handleGetVstInterfaceVersion (VstOpCodeArguments)
  1551. {
  1552. return kVstVersion;
  1553. }
  1554. pointer_sized_int handleGetCurrentMidiProgram (VstOpCodeArguments)
  1555. {
  1556. return -1;
  1557. }
  1558. pointer_sized_int handleGetSpeakerConfiguration (VstOpCodeArguments args)
  1559. {
  1560. auto** pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.value);
  1561. auto** pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.ptr);
  1562. if (pluginHasSidechainsOrAuxs() || processor->isMidiEffect())
  1563. return false;
  1564. auto inputLayout = processor->getChannelLayoutOfBus (true, 0);
  1565. auto outputLayout = processor->getChannelLayoutOfBus (false, 0);
  1566. auto speakerBaseSize = sizeof (Vst2::VstSpeakerArrangement) - (sizeof (Vst2::VstSpeakerProperties) * 8);
  1567. cachedInArrangement .malloc (speakerBaseSize + (static_cast<std::size_t> (inputLayout. size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1568. cachedOutArrangement.malloc (speakerBaseSize + (static_cast<std::size_t> (outputLayout.size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1569. *pluginInput = cachedInArrangement. getData();
  1570. *pluginOutput = cachedOutArrangement.getData();
  1571. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (true, 0), **pluginInput);
  1572. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (false, 0), **pluginOutput);
  1573. return 1;
  1574. }
  1575. pointer_sized_int handleSetNumberOfSamplesToProcess (VstOpCodeArguments args)
  1576. {
  1577. return args.value;
  1578. }
  1579. pointer_sized_int handleSetSampleFloatType (VstOpCodeArguments args)
  1580. {
  1581. if (! isProcessing)
  1582. {
  1583. if (processor != nullptr)
  1584. {
  1585. processor->setProcessingPrecision ((args.value == Vst2::kVstProcessPrecision64
  1586. && processor->supportsDoublePrecisionProcessing())
  1587. ? AudioProcessor::doublePrecision
  1588. : AudioProcessor::singlePrecision);
  1589. return 1;
  1590. }
  1591. }
  1592. return 0;
  1593. }
  1594. pointer_sized_int handleSetContentScaleFactor (float scale)
  1595. {
  1596. #if ! JUCE_MAC
  1597. if (editorComp != nullptr)
  1598. editorComp->setContentScaleFactor (scale);
  1599. lastScaleFactorReceived = scale;
  1600. #else
  1601. ignoreUnused (scale);
  1602. #endif
  1603. return 1;
  1604. }
  1605. pointer_sized_int handleCockosGetParameterText (pointer_sized_int paramIndex,
  1606. void* dest,
  1607. float value)
  1608. {
  1609. if (processor != nullptr && dest != nullptr)
  1610. {
  1611. if (auto* param = juceParameters.getParamForIndex ((int) paramIndex))
  1612. {
  1613. if (! LegacyAudioParameter::isLegacy (param))
  1614. {
  1615. String text (param->getText (value, 1024));
  1616. memcpy (dest, text.toRawUTF8(), ((size_t) text.length()) + 1);
  1617. return 0xbeef;
  1618. }
  1619. }
  1620. }
  1621. return 0;
  1622. }
  1623. //==============================================================================
  1624. pointer_sized_int handleGetNumMidiInputChannels()
  1625. {
  1626. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1627. #ifdef JucePlugin_VSTNumMidiInputs
  1628. return JucePlugin_VSTNumMidiInputs;
  1629. #else
  1630. return 16;
  1631. #endif
  1632. #else
  1633. return 0;
  1634. #endif
  1635. }
  1636. pointer_sized_int handleGetNumMidiOutputChannels()
  1637. {
  1638. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1639. #ifdef JucePlugin_VSTNumMidiOutputs
  1640. return JucePlugin_VSTNumMidiOutputs;
  1641. #else
  1642. return 16;
  1643. #endif
  1644. #else
  1645. return 0;
  1646. #endif
  1647. }
  1648. //==============================================================================
  1649. Vst2::audioMasterCallback hostCallback;
  1650. AudioProcessor* processor = {};
  1651. double sampleRate = 44100.0;
  1652. int32 blockSize = 1024;
  1653. Vst2::AEffect vstEffect;
  1654. CriticalSection stateInformationLock;
  1655. juce::MemoryBlock chunkMemory;
  1656. uint32 chunkMemoryTime = 0;
  1657. std::unique_ptr<EditorCompWrapper> editorComp;
  1658. Vst2::ERect editorBounds;
  1659. MidiBuffer midiEvents;
  1660. VSTMidiEventList outgoingEvents;
  1661. #if ! JUCE_MAC
  1662. float lastScaleFactorReceived = 1.0f;
  1663. #endif
  1664. LegacyAudioParametersWrapper juceParameters;
  1665. bool isProcessing = false, isBypassed = false, hasShutdown = false;
  1666. bool firstProcessCallback = true, shouldDeleteEditor = false;
  1667. #if JUCE_MAC
  1668. #if JUCE_64BIT
  1669. bool useNSView = true;
  1670. #else
  1671. bool useNSView = false;
  1672. #endif
  1673. #endif
  1674. VstTempBuffers<float> floatTempBuffers;
  1675. VstTempBuffers<double> doubleTempBuffers;
  1676. int maxNumInChannels = 0, maxNumOutChannels = 0;
  1677. HeapBlock<Vst2::VstSpeakerArrangement> cachedInArrangement, cachedOutArrangement;
  1678. ThreadLocalValue<bool> inParameterChangedCallback;
  1679. //==============================================================================
  1680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1681. };
  1682. //==============================================================================
  1683. namespace
  1684. {
  1685. Vst2::AEffect* pluginEntryPoint (Vst2::audioMasterCallback audioMaster)
  1686. {
  1687. JUCE_AUTORELEASEPOOL
  1688. {
  1689. initialiseJuce_GUI();
  1690. try
  1691. {
  1692. if (audioMaster (nullptr, Vst2::audioMasterVersion, 0, 0, nullptr, 0) != 0)
  1693. {
  1694. #if JUCE_LINUX
  1695. MessageManagerLock mmLock;
  1696. #endif
  1697. auto* processor = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1698. auto* wrapper = new JuceVSTWrapper (audioMaster, processor);
  1699. auto* aEffect = wrapper->getAEffect();
  1700. if (auto* callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1701. {
  1702. callbackHandler->handleVstHostCallbackAvailable ([audioMaster, aEffect](int32 opcode, int32 index, pointer_sized_int value, void* ptr, float opt)
  1703. {
  1704. return audioMaster (aEffect, opcode, index, value, ptr, opt);
  1705. });
  1706. }
  1707. return aEffect;
  1708. }
  1709. }
  1710. catch (...)
  1711. {}
  1712. }
  1713. return nullptr;
  1714. }
  1715. }
  1716. #if ! JUCE_WINDOWS
  1717. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1718. #endif
  1719. //==============================================================================
  1720. // Mac startup code..
  1721. #if JUCE_MAC
  1722. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1723. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1724. {
  1725. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1726. initialiseMacVST();
  1727. return pluginEntryPoint (audioMaster);
  1728. }
  1729. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster);
  1730. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster)
  1731. {
  1732. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1733. initialiseMacVST();
  1734. return pluginEntryPoint (audioMaster);
  1735. }
  1736. //==============================================================================
  1737. // Linux startup code..
  1738. #elif JUCE_LINUX
  1739. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1740. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1741. {
  1742. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1743. SharedMessageThread::getInstance();
  1744. return pluginEntryPoint (audioMaster);
  1745. }
  1746. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster) asm ("main");
  1747. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster)
  1748. {
  1749. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1750. return VSTPluginMain (audioMaster);
  1751. }
  1752. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1753. __attribute__((constructor)) void myPluginInit() {}
  1754. __attribute__((destructor)) void myPluginFini() {}
  1755. //==============================================================================
  1756. // Win32 startup code..
  1757. #else
  1758. extern "C" __declspec (dllexport) Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1759. {
  1760. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1761. return pluginEntryPoint (audioMaster);
  1762. }
  1763. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1764. extern "C" __declspec (dllexport) int main (Vst2::audioMasterCallback audioMaster)
  1765. {
  1766. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1767. return (int) pluginEntryPoint (audioMaster);
  1768. }
  1769. #endif
  1770. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1771. {
  1772. if (reason == DLL_PROCESS_ATTACH)
  1773. Process::setCurrentModuleInstanceHandle (instance);
  1774. return true;
  1775. }
  1776. #endif
  1777. JUCE_END_IGNORE_WARNINGS_MSVC
  1778. #endif