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.

2223 lines
80KB

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