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.

2237 lines
79KB

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