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.

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