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.

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