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.

2263 lines
82KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. updateCallbackContextInfo();
  295. int i;
  296. for (i = 0; i < numOut; ++i)
  297. {
  298. auto* chan = tmpBuffers.tempChannels.getUnchecked(i);
  299. if (chan == nullptr)
  300. {
  301. chan = outputs[i];
  302. bool bufferPointerReusedForOtherChannels = false;
  303. for (int j = i; --j >= 0;)
  304. {
  305. if (outputs[j] == chan)
  306. {
  307. bufferPointerReusedForOtherChannels = true;
  308. break;
  309. }
  310. }
  311. // if some output channels are disabled, some hosts supply the same buffer
  312. // for multiple channels or supply a nullptr - this buggers up our method
  313. // of copying the inputs over the outputs, so we need to create unique temp
  314. // buffers in this case..
  315. if (bufferPointerReusedForOtherChannels || chan == nullptr)
  316. {
  317. chan = new FloatType [(size_t) blockSize * 2];
  318. tmpBuffers.tempChannels.set (i, chan);
  319. }
  320. }
  321. if (i < numIn)
  322. {
  323. if (chan != inputs[i])
  324. memcpy (chan, inputs[i], (size_t) numSamples * sizeof (FloatType));
  325. }
  326. else
  327. {
  328. FloatVectorOperations::clear (chan, numSamples);
  329. }
  330. tmpBuffers.channels[i] = chan;
  331. }
  332. for (; i < numIn; ++i)
  333. tmpBuffers.channels[i] = inputs[i];
  334. {
  335. const int numChannels = jmax (numIn, numOut);
  336. AudioBuffer<FloatType> chans (tmpBuffers.channels, isMidiEffect ? 0 : numChannels, numSamples);
  337. if (isBypassed && processor->getBypassParameter() == nullptr)
  338. processor->processBlockBypassed (chans, midiEvents);
  339. else
  340. processor->processBlock (chans, midiEvents);
  341. }
  342. // copy back any temp channels that may have been used..
  343. for (i = 0; i < numOut; ++i)
  344. if (auto* chan = tmpBuffers.tempChannels.getUnchecked(i))
  345. if (auto* dest = outputs[i])
  346. memcpy (dest, chan, (size_t) numSamples * sizeof (FloatType));
  347. }
  348. }
  349. if (! midiEvents.isEmpty())
  350. {
  351. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  352. auto numEvents = midiEvents.getNumEvents();
  353. outgoingEvents.ensureSize (numEvents);
  354. outgoingEvents.clear();
  355. for (const auto metadata : midiEvents)
  356. {
  357. jassert (metadata.samplePosition >= 0 && metadata.samplePosition < numSamples);
  358. outgoingEvents.addEvent (metadata.data, metadata.numBytes, metadata.samplePosition);
  359. }
  360. // Send VST events to the host.
  361. if (hostCallback != nullptr)
  362. hostCallback (&vstEffect, Vst2::hostOpcodePreAudioProcessingEvents, 0, 0, outgoingEvents.events, 0);
  363. #elif JUCE_DEBUG
  364. /* This assertion is caused when you've added some events to the
  365. midiMessages array in your processBlock() method, which usually means
  366. that you're trying to send them somewhere. But in this case they're
  367. getting thrown away.
  368. If your plugin does want to send midi messages, you'll need to set
  369. the JucePlugin_ProducesMidiOutput macro to 1 in your
  370. JucePluginCharacteristics.h file.
  371. If you don't want to produce any midi output, then you should clear the
  372. midiMessages array at the end of your processBlock() method, to
  373. indicate that you don't want any of the events to be passed through
  374. to the output.
  375. */
  376. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  377. #endif
  378. midiEvents.clear();
  379. }
  380. }
  381. void processReplacing (float** inputs, float** outputs, int32 sampleFrames)
  382. {
  383. jassert (! processor->isUsingDoublePrecision());
  384. internalProcessReplacing (inputs, outputs, sampleFrames, floatTempBuffers);
  385. }
  386. static void processReplacingCB (Vst2::VstEffectInterface* vstInterface, float** inputs, float** outputs, int32 sampleFrames)
  387. {
  388. getWrapper (vstInterface)->processReplacing (inputs, outputs, sampleFrames);
  389. }
  390. void processDoubleReplacing (double** inputs, double** outputs, int32 sampleFrames)
  391. {
  392. jassert (processor->isUsingDoublePrecision());
  393. internalProcessReplacing (inputs, outputs, sampleFrames, doubleTempBuffers);
  394. }
  395. static void processDoubleReplacingCB (Vst2::VstEffectInterface* vstInterface, double** inputs, double** outputs, int32 sampleFrames)
  396. {
  397. getWrapper (vstInterface)->processDoubleReplacing (inputs, outputs, sampleFrames);
  398. }
  399. //==============================================================================
  400. void resume()
  401. {
  402. if (processor != nullptr)
  403. {
  404. isProcessing = true;
  405. auto numInAndOutChannels = static_cast<size_t> (vstEffect.numInputChannels + vstEffect.numOutputChannels);
  406. floatTempBuffers .channels.calloc (numInAndOutChannels);
  407. doubleTempBuffers.channels.calloc (numInAndOutChannels);
  408. auto currentRate = sampleRate;
  409. auto currentBlockSize = blockSize;
  410. firstProcessCallback = true;
  411. processor->setNonRealtime (isProcessLevelOffline());
  412. processor->setRateAndBufferSizeDetails (currentRate, currentBlockSize);
  413. deleteTempChannels();
  414. processor->prepareToPlay (currentRate, currentBlockSize);
  415. midiEvents.ensureSize (2048);
  416. midiEvents.clear();
  417. vstEffect.latency = processor->getLatencySamples();
  418. /** If this plug-in is a synth or it can receive midi events we need to tell the
  419. host that we want midi. In the SDK this method is marked as deprecated, but
  420. some hosts rely on this behaviour.
  421. */
  422. if (vstEffect.flags & Vst2::vstEffectFlagIsSynth || JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect)
  423. {
  424. if (hostCallback != nullptr)
  425. hostCallback (&vstEffect, Vst2::hostOpcodePlugInWantsMidi, 0, 1, nullptr, 0);
  426. }
  427. if (getHostType().isAbletonLive()
  428. && hostCallback != nullptr
  429. && processor->getTailLengthSeconds() == std::numeric_limits<double>::infinity())
  430. {
  431. AbletonLiveHostSpecific hostCmd;
  432. hostCmd.magic = 0x41624c69; // 'AbLi'
  433. hostCmd.cmd = 5;
  434. hostCmd.commandSize = sizeof (int);
  435. hostCmd.flags = AbletonLiveHostSpecific::KCantBeSuspended;
  436. hostCallback (&vstEffect, Vst2::hostOpcodeManufacturerSpecific, 0, 0, &hostCmd, 0.0f);
  437. }
  438. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  439. outgoingEvents.ensureSize (512);
  440. #endif
  441. }
  442. }
  443. void suspend()
  444. {
  445. if (processor != nullptr)
  446. {
  447. processor->releaseResources();
  448. outgoingEvents.freeEvents();
  449. isProcessing = false;
  450. floatTempBuffers.channels.free();
  451. doubleTempBuffers.channels.free();
  452. deleteTempChannels();
  453. }
  454. }
  455. void updateCallbackContextInfo()
  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 | Vst2::vstTimingInfoFlagNanosecondsValid;
  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. {
  469. currentPosition.reset();
  470. return;
  471. }
  472. auto& info = currentPosition.emplace();
  473. info.setBpm ((ti->flags & Vst2::vstTimingInfoFlagTempoValid) != 0 ? makeOptional (ti->tempoBPM) : nullopt);
  474. info.setTimeSignature ((ti->flags & Vst2::vstTimingInfoFlagTimeSignatureValid) != 0 ? makeOptional (TimeSignature { ti->timeSignatureNumerator, ti->timeSignatureDenominator })
  475. : nullopt);
  476. info.setTimeInSamples ((int64) (ti->samplePosition + 0.5));
  477. info.setTimeInSeconds (ti->samplePosition / ti->sampleRate);
  478. info.setPpqPosition ((ti->flags & Vst2::vstTimingInfoFlagMusicalPositionValid) != 0 ? makeOptional (ti->musicalPosition) : nullopt);
  479. info.setPpqPositionOfLastBarStart ((ti->flags & Vst2::vstTimingInfoFlagLastBarPositionValid) != 0 ? makeOptional (ti->lastBarPosition) : nullopt);
  480. if ((ti->flags & Vst2::vstTimingInfoFlagSmpteValid) != 0)
  481. {
  482. info.setFrameRate ([&]() -> Optional<FrameRate>
  483. {
  484. switch (ti->smpteRate)
  485. {
  486. case Vst2::vstSmpteRateFps24: return FrameRate().withBaseRate (24);
  487. case Vst2::vstSmpteRateFps239: return FrameRate().withBaseRate (24).withPullDown();
  488. case Vst2::vstSmpteRateFps25: return FrameRate().withBaseRate (25);
  489. case Vst2::vstSmpteRateFps249: return FrameRate().withBaseRate (25).withPullDown();
  490. case Vst2::vstSmpteRateFps30: return FrameRate().withBaseRate (30);
  491. case Vst2::vstSmpteRateFps30drop: return FrameRate().withBaseRate (30).withDrop();
  492. case Vst2::vstSmpteRateFps2997: return FrameRate().withBaseRate (30).withPullDown();
  493. case Vst2::vstSmpteRateFps2997drop: return FrameRate().withBaseRate (30).withPullDown().withDrop();
  494. case Vst2::vstSmpteRateFps60: return FrameRate().withBaseRate (60);
  495. case Vst2::vstSmpteRateFps599: return FrameRate().withBaseRate (60).withPullDown();
  496. case Vst2::vstSmpteRate16mmFilm:
  497. case Vst2::vstSmpteRate35mmFilm: return FrameRate().withBaseRate (24);
  498. }
  499. return nullopt;
  500. }());
  501. const auto effectiveRate = info.getFrameRate().hasValue() ? info.getFrameRate()->getEffectiveRate() : 0.0;
  502. info.setEditOriginTime (effectiveRate != 0.0 ? makeOptional (ti->smpteOffset / (80.0 * effectiveRate)) : nullopt);
  503. }
  504. info.setIsRecording ((ti->flags & Vst2::vstTimingInfoFlagCurrentlyRecording) != 0);
  505. info.setIsPlaying ((ti->flags & (Vst2::vstTimingInfoFlagCurrentlyRecording | Vst2::vstTimingInfoFlagCurrentlyPlaying)) != 0);
  506. info.setIsLooping ((ti->flags & Vst2::vstTimingInfoFlagLoopActive) != 0);
  507. info.setLoopPoints ((ti->flags & Vst2::vstTimingInfoFlagLoopPositionValid) != 0 ? makeOptional (LoopPoints { ti->loopStartPosition, ti->loopEndPosition })
  508. : nullopt);
  509. info.setHostTimeNs ((ti->flags & Vst2::vstTimingInfoFlagNanosecondsValid) != 0 ? makeOptional ((uint64_t) ti->systemTimeNanoseconds) : nullopt);
  510. }
  511. //==============================================================================
  512. Optional<PositionInfo> getPosition() const override
  513. {
  514. return currentPosition;
  515. }
  516. //==============================================================================
  517. float getParameter (int32 index) const
  518. {
  519. if (auto* param = juceParameters.getParamForIndex (index))
  520. return param->getValue();
  521. return 0.0f;
  522. }
  523. static float getParameterCB (Vst2::VstEffectInterface* vstInterface, int32 index)
  524. {
  525. return getWrapper (vstInterface)->getParameter (index);
  526. }
  527. void setParameter (int32 index, float value)
  528. {
  529. if (auto* param = juceParameters.getParamForIndex (index))
  530. setValueAndNotifyIfChanged (*param, value);
  531. }
  532. static void setParameterCB (Vst2::VstEffectInterface* vstInterface, int32 index, float value)
  533. {
  534. getWrapper (vstInterface)->setParameter (index, value);
  535. }
  536. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  537. {
  538. if (inParameterChangedCallback.get())
  539. {
  540. inParameterChangedCallback = false;
  541. return;
  542. }
  543. if (hostCallback != nullptr)
  544. hostCallback (&vstEffect, Vst2::hostOpcodeParameterChanged, index, 0, nullptr, newValue);
  545. }
  546. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override
  547. {
  548. if (hostCallback != nullptr)
  549. hostCallback (&vstEffect, Vst2::hostOpcodeParameterChangeGestureBegin, index, 0, nullptr, 0);
  550. }
  551. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override
  552. {
  553. if (hostCallback != nullptr)
  554. hostCallback (&vstEffect, Vst2::hostOpcodeParameterChangeGestureEnd, index, 0, nullptr, 0);
  555. }
  556. void parameterValueChanged (int, float newValue) override
  557. {
  558. // this can only come from the bypass parameter
  559. isBypassed = (newValue >= 0.5f);
  560. }
  561. void parameterGestureChanged (int, bool) override {}
  562. void audioProcessorChanged (AudioProcessor*, const ChangeDetails& details) override
  563. {
  564. hostChangeUpdater.update (details);
  565. }
  566. bool getPinProperties (Vst2::VstPinInfo& properties, bool direction, int index) const
  567. {
  568. if (processor->isMidiEffect())
  569. return false;
  570. int channelIdx, busIdx;
  571. // fill with default
  572. properties.flags = 0;
  573. properties.text[0] = 0;
  574. properties.shortText[0] = 0;
  575. properties.configurationType = Vst2::vstSpeakerConfigTypeEmpty;
  576. if ((channelIdx = processor->getOffsetInBusBufferForAbsoluteChannelIndex (direction, index, busIdx)) >= 0)
  577. {
  578. auto& bus = *processor->getBus (direction, busIdx);
  579. auto& channelSet = bus.getCurrentLayout();
  580. auto channelType = channelSet.getTypeOfChannel (channelIdx);
  581. properties.flags = Vst2::vstPinInfoFlagIsActive | Vst2::vstPinInfoFlagValid;
  582. properties.configurationType = SpeakerMappings::channelSetToVstArrangementType (channelSet);
  583. String label = bus.getName();
  584. #ifdef JucePlugin_PreferredChannelConfigurations
  585. label += " " + String (channelIdx);
  586. #else
  587. if (channelSet.size() > 1)
  588. label += " " + AudioChannelSet::getAbbreviatedChannelTypeName (channelType);
  589. #endif
  590. label.copyToUTF8 (properties.text, (size_t) (Vst2::vstMaxParameterOrPinLabelLength + 1));
  591. label.copyToUTF8 (properties.shortText, (size_t) (Vst2::vstMaxParameterOrPinShortLabelLength + 1));
  592. if (channelType == AudioChannelSet::left
  593. || channelType == AudioChannelSet::leftSurround
  594. || channelType == AudioChannelSet::leftCentre
  595. || channelType == AudioChannelSet::leftSurroundSide
  596. || channelType == AudioChannelSet::topFrontLeft
  597. || channelType == AudioChannelSet::topRearLeft
  598. || channelType == AudioChannelSet::leftSurroundRear
  599. || channelType == AudioChannelSet::wideLeft)
  600. properties.flags |= Vst2::vstPinInfoFlagIsStereo;
  601. return true;
  602. }
  603. return false;
  604. }
  605. //==============================================================================
  606. void timerCallback() override
  607. {
  608. if (shouldDeleteEditor)
  609. {
  610. shouldDeleteEditor = false;
  611. deleteEditor (true);
  612. }
  613. {
  614. ScopedLock lock (stateInformationLock);
  615. if (chunkMemoryTime > 0
  616. && chunkMemoryTime < juce::Time::getApproximateMillisecondCounter() - 2000
  617. && ! recursionCheck)
  618. {
  619. chunkMemory.reset();
  620. chunkMemoryTime = 0;
  621. }
  622. }
  623. if (editorComp != nullptr)
  624. editorComp->checkVisibility();
  625. }
  626. void setHasEditorFlag (bool shouldSetHasEditor)
  627. {
  628. auto hasEditor = (vstEffect.flags & Vst2::vstEffectFlagHasEditor) != 0;
  629. if (shouldSetHasEditor == hasEditor)
  630. return;
  631. if (shouldSetHasEditor)
  632. vstEffect.flags |= Vst2::vstEffectFlagHasEditor;
  633. else
  634. vstEffect.flags &= ~Vst2::vstEffectFlagHasEditor;
  635. }
  636. void createEditorComp()
  637. {
  638. if (hasShutdown || processor == nullptr)
  639. return;
  640. if (editorComp == nullptr)
  641. {
  642. if (auto* ed = processor->createEditorIfNeeded())
  643. {
  644. setHasEditorFlag (true);
  645. editorComp.reset (new EditorCompWrapper (*this, *ed, editorScaleFactor));
  646. }
  647. else
  648. {
  649. setHasEditorFlag (false);
  650. }
  651. }
  652. shouldDeleteEditor = false;
  653. }
  654. void deleteEditor (bool canDeleteLaterIfModal)
  655. {
  656. JUCE_AUTORELEASEPOOL
  657. {
  658. PopupMenu::dismissAllActiveMenus();
  659. jassert (! recursionCheck);
  660. ScopedValueSetter<bool> svs (recursionCheck, true, false);
  661. if (editorComp != nullptr)
  662. {
  663. if (auto* modalComponent = Component::getCurrentlyModalComponent())
  664. {
  665. modalComponent->exitModalState (0);
  666. if (canDeleteLaterIfModal)
  667. {
  668. shouldDeleteEditor = true;
  669. return;
  670. }
  671. }
  672. editorComp->detachHostWindow();
  673. if (auto* ed = editorComp->getEditorComp())
  674. processor->editorBeingDeleted (ed);
  675. editorComp = nullptr;
  676. // there's some kind of component currently modal, but the host
  677. // is trying to delete our plugin. You should try to avoid this happening..
  678. jassert (Component::getCurrentlyModalComponent() == nullptr);
  679. }
  680. }
  681. }
  682. pointer_sized_int dispatcher (int32 opCode, VstOpCodeArguments args)
  683. {
  684. if (hasShutdown)
  685. return 0;
  686. switch (opCode)
  687. {
  688. case Vst2::plugInOpcodeOpen: return handleOpen (args);
  689. case Vst2::plugInOpcodeClose: return handleClose (args);
  690. case Vst2::plugInOpcodeSetCurrentProgram: return handleSetCurrentProgram (args);
  691. case Vst2::plugInOpcodeGetCurrentProgram: return handleGetCurrentProgram (args);
  692. case Vst2::plugInOpcodeSetCurrentProgramName: return handleSetCurrentProgramName (args);
  693. case Vst2::plugInOpcodeGetCurrentProgramName: return handleGetCurrentProgramName (args);
  694. case Vst2::plugInOpcodeGetParameterLabel: return handleGetParameterLabel (args);
  695. case Vst2::plugInOpcodeGetParameterText: return handleGetParameterText (args);
  696. case Vst2::plugInOpcodeGetParameterName: return handleGetParameterName (args);
  697. case Vst2::plugInOpcodeSetSampleRate: return handleSetSampleRate (args);
  698. case Vst2::plugInOpcodeSetBlockSize: return handleSetBlockSize (args);
  699. case Vst2::plugInOpcodeResumeSuspend: return handleResumeSuspend (args);
  700. case Vst2::plugInOpcodeGetEditorBounds: return handleGetEditorBounds (args);
  701. case Vst2::plugInOpcodeOpenEditor: return handleOpenEditor (args);
  702. case Vst2::plugInOpcodeCloseEditor: return handleCloseEditor (args);
  703. case Vst2::plugInOpcodeIdentify: return (pointer_sized_int) ByteOrder::bigEndianInt ("NvEf");
  704. case Vst2::plugInOpcodeGetData: return handleGetData (args);
  705. case Vst2::plugInOpcodeSetData: return handleSetData (args);
  706. case Vst2::plugInOpcodePreAudioProcessingEvents: return handlePreAudioProcessingEvents (args);
  707. case Vst2::plugInOpcodeIsParameterAutomatable: return handleIsParameterAutomatable (args);
  708. case Vst2::plugInOpcodeParameterValueForText: return handleParameterValueForText (args);
  709. case Vst2::plugInOpcodeGetProgramName: return handleGetProgramName (args);
  710. case Vst2::plugInOpcodeGetInputPinProperties: return handleGetInputPinProperties (args);
  711. case Vst2::plugInOpcodeGetOutputPinProperties: return handleGetOutputPinProperties (args);
  712. case Vst2::plugInOpcodeGetPlugInCategory: return handleGetPlugInCategory (args);
  713. case Vst2::plugInOpcodeSetSpeakerConfiguration: return handleSetSpeakerConfiguration (args);
  714. case Vst2::plugInOpcodeSetBypass: return handleSetBypass (args);
  715. case Vst2::plugInOpcodeGetPlugInName: return handleGetPlugInName (args);
  716. case Vst2::plugInOpcodeGetManufacturerProductName: return handleGetPlugInName (args);
  717. case Vst2::plugInOpcodeGetManufacturerName: return handleGetManufacturerName (args);
  718. case Vst2::plugInOpcodeGetManufacturerVersion: return handleGetManufacturerVersion (args);
  719. case Vst2::plugInOpcodeManufacturerSpecific: return handleManufacturerSpecific (args);
  720. case Vst2::plugInOpcodeCanPlugInDo: return handleCanPlugInDo (args);
  721. case Vst2::plugInOpcodeGetTailSize: return handleGetTailSize (args);
  722. case Vst2::plugInOpcodeKeyboardFocusRequired: return handleKeyboardFocusRequired (args);
  723. case Vst2::plugInOpcodeGetVstInterfaceVersion: return handleGetVstInterfaceVersion (args);
  724. case Vst2::plugInOpcodeGetCurrentMidiProgram: return handleGetCurrentMidiProgram (args);
  725. case Vst2::plugInOpcodeGetSpeakerArrangement: return handleGetSpeakerConfiguration (args);
  726. case Vst2::plugInOpcodeSetNumberOfSamplesToProcess: return handleSetNumberOfSamplesToProcess (args);
  727. case Vst2::plugInOpcodeSetSampleFloatType: return handleSetSampleFloatType (args);
  728. case Vst2::pluginOpcodeGetNumMidiInputChannels: return handleGetNumMidiInputChannels();
  729. case Vst2::pluginOpcodeGetNumMidiOutputChannels: return handleGetNumMidiOutputChannels();
  730. case Vst2::plugInOpcodeEditorIdle: return handleEditIdle();
  731. default: return 0;
  732. }
  733. }
  734. static pointer_sized_int dispatcherCB (Vst2::VstEffectInterface* vstInterface, int32 opCode, int32 index,
  735. pointer_sized_int value, void* ptr, float opt)
  736. {
  737. auto* wrapper = getWrapper (vstInterface);
  738. VstOpCodeArguments args = { index, value, ptr, opt };
  739. if (opCode == Vst2::plugInOpcodeClose)
  740. {
  741. wrapper->dispatcher (opCode, args);
  742. delete wrapper;
  743. return 1;
  744. }
  745. return wrapper->dispatcher (opCode, args);
  746. }
  747. //==============================================================================
  748. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  749. // chores when it changes or repaints.
  750. struct EditorCompWrapper : public Component
  751. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  752. , public Timer
  753. #endif
  754. {
  755. EditorCompWrapper (JuceVSTWrapper& w, AudioProcessorEditor& editor, float initialScale)
  756. : wrapper (w)
  757. {
  758. editor.setOpaque (true);
  759. #if ! JUCE_MAC
  760. editor.setScaleFactor (initialScale);
  761. #else
  762. ignoreUnused (initialScale);
  763. #endif
  764. addAndMakeVisible (editor);
  765. auto editorBounds = getSizeToContainChild();
  766. setSize (editorBounds.getWidth(), editorBounds.getHeight());
  767. #if JUCE_WINDOWS
  768. if (! getHostType().isReceptor())
  769. addMouseListener (this, true);
  770. #endif
  771. setOpaque (true);
  772. }
  773. ~EditorCompWrapper() override
  774. {
  775. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  776. // have been transferred to another parent which takes over ownership.
  777. }
  778. void paint (Graphics& g) override
  779. {
  780. g.fillAll (Colours::black);
  781. }
  782. void getEditorBounds (Vst2::VstEditorBounds& bounds)
  783. {
  784. auto editorBounds = getSizeToContainChild();
  785. bounds = convertToHostBounds ({ 0, 0, (int16) editorBounds.getHeight(), (int16) editorBounds.getWidth() });
  786. }
  787. void attachToHost (VstOpCodeArguments args)
  788. {
  789. setVisible (false);
  790. #if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
  791. addToDesktop (0, args.ptr);
  792. hostWindow = (HostWindowType) args.ptr;
  793. #if JUCE_LINUX || JUCE_BSD
  794. X11Symbols::getInstance()->xReparentWindow (display,
  795. (Window) getWindowHandle(),
  796. (HostWindowType) hostWindow,
  797. 0, 0);
  798. // The host is likely to attempt to move/resize the window directly after this call,
  799. // and we need to ensure that the X server knows that our window has been attached
  800. // before that happens.
  801. X11Symbols::getInstance()->xFlush (display);
  802. #elif JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  803. checkHostWindowScaleFactor();
  804. startTimer (500);
  805. #endif
  806. #elif JUCE_MAC
  807. hostWindow = attachComponentToWindowRefVST (this, args.ptr, wrapper.useNSView);
  808. #endif
  809. setVisible (true);
  810. }
  811. void detachHostWindow()
  812. {
  813. #if JUCE_MAC
  814. if (hostWindow != nullptr)
  815. detachComponentFromWindowRefVST (this, hostWindow, wrapper.useNSView);
  816. #endif
  817. hostWindow = {};
  818. }
  819. void checkVisibility()
  820. {
  821. #if JUCE_MAC
  822. if (hostWindow != nullptr)
  823. checkWindowVisibilityVST (hostWindow, this, wrapper.useNSView);
  824. #endif
  825. }
  826. AudioProcessorEditor* getEditorComp() const noexcept
  827. {
  828. return dynamic_cast<AudioProcessorEditor*> (getChildComponent (0));
  829. }
  830. void resized() override
  831. {
  832. if (auto* pluginEditor = getEditorComp())
  833. {
  834. if (! resizingParent)
  835. {
  836. auto newBounds = getLocalBounds();
  837. {
  838. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  839. pluginEditor->setBounds (pluginEditor->getLocalArea (this, newBounds).withPosition (0, 0));
  840. }
  841. lastBounds = newBounds;
  842. }
  843. updateWindowSize();
  844. }
  845. #if JUCE_MAC && ! JUCE_64BIT
  846. if (! wrapper.useNSView)
  847. updateEditorCompBoundsVST (this);
  848. #endif
  849. }
  850. void parentSizeChanged() override
  851. {
  852. updateWindowSize();
  853. repaint();
  854. }
  855. void childBoundsChanged (Component*) override
  856. {
  857. if (resizingChild)
  858. return;
  859. auto newBounds = getSizeToContainChild();
  860. if (newBounds != lastBounds)
  861. {
  862. updateWindowSize();
  863. lastBounds = newBounds;
  864. }
  865. }
  866. juce::Rectangle<int> getSizeToContainChild()
  867. {
  868. if (auto* pluginEditor = getEditorComp())
  869. return getLocalArea (pluginEditor, pluginEditor->getLocalBounds());
  870. return {};
  871. }
  872. void resizeHostWindow (juce::Rectangle<int> bounds)
  873. {
  874. auto rect = convertToHostBounds ({ 0, 0, (int16) bounds.getHeight(), (int16) bounds.getWidth() });
  875. const auto newWidth = rect.rightmost - rect.leftmost;
  876. const auto newHeight = rect.lower - rect.upper;
  877. bool sizeWasSuccessful = false;
  878. if (auto host = wrapper.hostCallback)
  879. {
  880. auto status = host (wrapper.getAEffect(), Vst2::hostOpcodeCanHostDo, 0, 0, const_cast<char*> ("sizeWindow"), 0);
  881. if (status == (pointer_sized_int) 1 || getHostType().isAbletonLive())
  882. {
  883. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  884. sizeWasSuccessful = (host (wrapper.getAEffect(), Vst2::hostOpcodeWindowSize,
  885. newWidth, newHeight, nullptr, 0) != 0);
  886. }
  887. }
  888. // some hosts don't support the sizeWindow call, so do it manually..
  889. if (! sizeWasSuccessful)
  890. {
  891. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  892. #if JUCE_MAC
  893. setNativeHostWindowSizeVST (hostWindow, this, newWidth, newHeight, wrapper.useNSView);
  894. #elif JUCE_LINUX || JUCE_BSD
  895. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  896. setSize (newWidth, newHeight);
  897. #else
  898. int dw = 0;
  899. int dh = 0;
  900. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  901. HWND w = (HWND) getWindowHandle();
  902. while (w != nullptr)
  903. {
  904. HWND parent = getWindowParent (w);
  905. if (parent == nullptr)
  906. break;
  907. TCHAR windowType [32] = { 0 };
  908. GetClassName (parent, windowType, 31);
  909. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  910. break;
  911. RECT windowPos, parentPos;
  912. GetWindowRect (w, &windowPos);
  913. GetWindowRect (parent, &parentPos);
  914. if (w != (HWND) getWindowHandle())
  915. SetWindowPos (w, nullptr, 0, 0, newWidth + dw, newHeight + dh,
  916. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  917. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  918. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  919. w = parent;
  920. if (dw == 2 * frameThickness)
  921. break;
  922. if (dw > 100 || dh > 100)
  923. w = nullptr;
  924. }
  925. if (w != nullptr)
  926. SetWindowPos (w, nullptr, 0, 0, newWidth + dw, newHeight + dh,
  927. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  928. #endif
  929. }
  930. #if JUCE_LINUX || JUCE_BSD
  931. X11Symbols::getInstance()->xResizeWindow (display, (Window) getWindowHandle(),
  932. static_cast<unsigned int> (rect.rightmost - rect.leftmost),
  933. static_cast<unsigned int> (rect.lower - rect.upper));
  934. #endif
  935. }
  936. void setContentScaleFactor (float scale)
  937. {
  938. if (auto* pluginEditor = getEditorComp())
  939. {
  940. auto prevEditorBounds = pluginEditor->getLocalArea (this, lastBounds);
  941. {
  942. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  943. pluginEditor->setScaleFactor (scale);
  944. pluginEditor->setBounds (prevEditorBounds.withPosition (0, 0));
  945. }
  946. lastBounds = getSizeToContainChild();
  947. updateWindowSize();
  948. }
  949. }
  950. #if JUCE_WINDOWS
  951. void mouseDown (const MouseEvent&) override
  952. {
  953. broughtToFront();
  954. }
  955. void broughtToFront() override
  956. {
  957. // for hosts like nuendo, need to also pop the MDI container to the
  958. // front when our comp is clicked on.
  959. if (! isCurrentlyBlockedByAnotherModalComponent())
  960. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  961. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  962. }
  963. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  964. void checkHostWindowScaleFactor()
  965. {
  966. auto hostWindowScale = (float) getScaleFactorForWindow ((HostWindowType) hostWindow);
  967. if (hostWindowScale > 0.0f && ! approximatelyEqual (hostWindowScale, wrapper.editorScaleFactor))
  968. wrapper.handleSetContentScaleFactor (hostWindowScale);
  969. }
  970. void timerCallback() override
  971. {
  972. checkHostWindowScaleFactor();
  973. }
  974. #endif
  975. #endif
  976. #if JUCE_MAC
  977. bool keyPressed (const KeyPress&) override
  978. {
  979. // If we have an unused keypress, move the key-focus to a host window
  980. // and re-inject the event..
  981. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  982. }
  983. #endif
  984. private:
  985. void updateWindowSize()
  986. {
  987. if (! resizingParent
  988. && getEditorComp() != nullptr
  989. && hostWindow != HostWindowType{})
  990. {
  991. const auto editorBounds = getSizeToContainChild();
  992. resizeHostWindow (editorBounds);
  993. {
  994. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  995. // setSize() on linux causes renoise and energyxt to fail.
  996. // We'll resize our peer during resizeHostWindow() instead.
  997. #if ! (JUCE_LINUX || JUCE_BSD)
  998. setSize (editorBounds.getWidth(), editorBounds.getHeight());
  999. #endif
  1000. if (auto* p = getPeer())
  1001. p->updateBounds();
  1002. }
  1003. #if JUCE_MAC
  1004. resizeHostWindow (editorBounds); // (doing this a second time seems to be necessary in tracktion)
  1005. #endif
  1006. }
  1007. }
  1008. //==============================================================================
  1009. static Vst2::VstEditorBounds convertToHostBounds (const Vst2::VstEditorBounds& rect)
  1010. {
  1011. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1012. if (approximatelyEqual (desktopScale, 1.0f))
  1013. return rect;
  1014. return { (int16) roundToInt (rect.upper * desktopScale),
  1015. (int16) roundToInt (rect.leftmost * desktopScale),
  1016. (int16) roundToInt (rect.lower * desktopScale),
  1017. (int16) roundToInt (rect.rightmost * desktopScale)};
  1018. }
  1019. //==============================================================================
  1020. #if JUCE_LINUX || JUCE_BSD
  1021. SharedResourcePointer<HostDrivenEventLoop> hostEventLoop;
  1022. #endif
  1023. //==============================================================================
  1024. JuceVSTWrapper& wrapper;
  1025. bool resizingChild = false, resizingParent = false;
  1026. juce::Rectangle<int> lastBounds;
  1027. #if JUCE_LINUX || JUCE_BSD
  1028. using HostWindowType = ::Window;
  1029. ::Display* display = XWindowSystem::getInstance()->getDisplay();
  1030. #elif JUCE_WINDOWS
  1031. using HostWindowType = HWND;
  1032. WindowsHooks hooks;
  1033. #else
  1034. using HostWindowType = void*;
  1035. #endif
  1036. HostWindowType hostWindow = {};
  1037. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1038. };
  1039. //==============================================================================
  1040. private:
  1041. struct HostChangeUpdater : private AsyncUpdater
  1042. {
  1043. explicit HostChangeUpdater (JuceVSTWrapper& o) : owner (o) {}
  1044. ~HostChangeUpdater() override { cancelPendingUpdate(); }
  1045. void update (const ChangeDetails& details)
  1046. {
  1047. if (details.latencyChanged)
  1048. {
  1049. owner.vstEffect.latency = owner.processor->getLatencySamples();
  1050. callbackBits |= audioMasterIOChangedBit;
  1051. }
  1052. if (details.parameterInfoChanged || details.programChanged)
  1053. callbackBits |= audioMasterUpdateDisplayBit;
  1054. triggerAsyncUpdate();
  1055. }
  1056. private:
  1057. void handleAsyncUpdate() override
  1058. {
  1059. const auto callbacksToFire = callbackBits.exchange (0);
  1060. if (auto* callback = owner.hostCallback)
  1061. {
  1062. struct FlagPair
  1063. {
  1064. int32 opcode;
  1065. int bit;
  1066. };
  1067. constexpr FlagPair pairs[] { { Vst2::hostOpcodeUpdateView, audioMasterUpdateDisplayBit },
  1068. { Vst2::hostOpcodeIOModified, audioMasterIOChangedBit } };
  1069. for (const auto& pair : pairs)
  1070. if ((callbacksToFire & pair.bit) != 0)
  1071. callback (&owner.vstEffect, pair.opcode, 0, 0, nullptr, 0);
  1072. }
  1073. }
  1074. static constexpr auto audioMasterUpdateDisplayBit = 1 << 0;
  1075. static constexpr auto audioMasterIOChangedBit = 1 << 1;
  1076. JuceVSTWrapper& owner;
  1077. std::atomic<int> callbackBits { 0 };
  1078. };
  1079. static JuceVSTWrapper* getWrapper (Vst2::VstEffectInterface* v) noexcept { return static_cast<JuceVSTWrapper*> (v->effectPointer); }
  1080. bool isProcessLevelOffline()
  1081. {
  1082. return hostCallback != nullptr
  1083. && (int32) hostCallback (&vstEffect, Vst2::hostOpcodeGetCurrentAudioProcessingLevel, 0, 0, nullptr, 0) == 4;
  1084. }
  1085. static int32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1086. {
  1087. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1088. return (int32) hexVersion;
  1089. #else
  1090. // Currently, only Cubase displays the version number to the user
  1091. // We are hoping here that when other DAWs start to display the version
  1092. // number, that they do so according to yfede's encoding table in the link
  1093. // below. If not, then this code will need an if (isSteinberg()) in the
  1094. // future.
  1095. int major = (hexVersion >> 16) & 0xff;
  1096. int minor = (hexVersion >> 8) & 0xff;
  1097. int bugfix = hexVersion & 0xff;
  1098. // for details, see: https://forum.juce.com/t/issues-with-version-integer-reported-by-vst2/23867
  1099. // Encoding B
  1100. if (major < 1)
  1101. return major * 1000 + minor * 100 + bugfix * 10;
  1102. // Encoding E
  1103. if (major > 100)
  1104. return major * 10000000 + minor * 100000 + bugfix * 1000;
  1105. // Encoding D
  1106. return static_cast<int32> (hexVersion);
  1107. #endif
  1108. }
  1109. //==============================================================================
  1110. #if JUCE_WINDOWS
  1111. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1112. static void checkWhetherMessageThreadIsCorrect()
  1113. {
  1114. auto host = getHostType();
  1115. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1116. {
  1117. if (! messageThreadIsDefinitelyCorrect)
  1118. {
  1119. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1120. struct MessageThreadCallback : public CallbackMessage
  1121. {
  1122. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1123. void messageCallback() override { triggered = true; }
  1124. bool& triggered;
  1125. };
  1126. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1127. }
  1128. }
  1129. }
  1130. #else
  1131. static void checkWhetherMessageThreadIsCorrect() {}
  1132. #endif
  1133. void setValueAndNotifyIfChanged (AudioProcessorParameter& param, float newValue)
  1134. {
  1135. if (param.getValue() == newValue)
  1136. return;
  1137. inParameterChangedCallback = true;
  1138. param.setValueNotifyingHost (newValue);
  1139. }
  1140. //==============================================================================
  1141. template <typename FloatType>
  1142. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1143. {
  1144. tmpBuffers.release();
  1145. if (processor != nullptr)
  1146. tmpBuffers.tempChannels.insertMultiple (0, nullptr, vstEffect.numInputChannels
  1147. + vstEffect.numOutputChannels);
  1148. }
  1149. void deleteTempChannels()
  1150. {
  1151. deleteTempChannels (floatTempBuffers);
  1152. deleteTempChannels (doubleTempBuffers);
  1153. }
  1154. //==============================================================================
  1155. void findMaxTotalChannels (int& maxTotalIns, int& maxTotalOuts)
  1156. {
  1157. #ifdef JucePlugin_PreferredChannelConfigurations
  1158. int configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1159. maxTotalIns = maxTotalOuts = 0;
  1160. for (auto& config : configs)
  1161. {
  1162. maxTotalIns = jmax (maxTotalIns, config[0]);
  1163. maxTotalOuts = jmax (maxTotalOuts, config[1]);
  1164. }
  1165. #else
  1166. auto numInputBuses = processor->getBusCount (true);
  1167. auto numOutputBuses = processor->getBusCount (false);
  1168. if (numInputBuses > 1 || numOutputBuses > 1)
  1169. {
  1170. maxTotalIns = maxTotalOuts = 0;
  1171. for (int i = 0; i < numInputBuses; ++i)
  1172. maxTotalIns += processor->getChannelCountOfBus (true, i);
  1173. for (int i = 0; i < numOutputBuses; ++i)
  1174. maxTotalOuts += processor->getChannelCountOfBus (false, i);
  1175. }
  1176. else
  1177. {
  1178. maxTotalIns = numInputBuses > 0 ? processor->getBus (true, 0)->getMaxSupportedChannels (64) : 0;
  1179. maxTotalOuts = numOutputBuses > 0 ? processor->getBus (false, 0)->getMaxSupportedChannels (64) : 0;
  1180. }
  1181. #endif
  1182. }
  1183. bool pluginHasSidechainsOrAuxs() const { return (processor->getBusCount (true) > 1 || processor->getBusCount (false) > 1); }
  1184. //==============================================================================
  1185. /** Host to plug-in calls. */
  1186. pointer_sized_int handleOpen (VstOpCodeArguments)
  1187. {
  1188. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1189. setHasEditorFlag (processor->hasEditor());
  1190. return 0;
  1191. }
  1192. pointer_sized_int handleClose (VstOpCodeArguments)
  1193. {
  1194. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1195. stopTimer();
  1196. if (MessageManager::getInstance()->isThisTheMessageThread())
  1197. deleteEditor (false);
  1198. return 0;
  1199. }
  1200. pointer_sized_int handleSetCurrentProgram (VstOpCodeArguments args)
  1201. {
  1202. if (processor != nullptr && isPositiveAndBelow ((int) args.value, processor->getNumPrograms()))
  1203. processor->setCurrentProgram ((int) args.value);
  1204. return 0;
  1205. }
  1206. pointer_sized_int handleGetCurrentProgram (VstOpCodeArguments)
  1207. {
  1208. return (processor != nullptr && processor->getNumPrograms() > 0 ? processor->getCurrentProgram() : 0);
  1209. }
  1210. pointer_sized_int handleSetCurrentProgramName (VstOpCodeArguments args)
  1211. {
  1212. if (processor != nullptr && processor->getNumPrograms() > 0)
  1213. processor->changeProgramName (processor->getCurrentProgram(), (char*) args.ptr);
  1214. return 0;
  1215. }
  1216. pointer_sized_int handleGetCurrentProgramName (VstOpCodeArguments args)
  1217. {
  1218. if (processor != nullptr && processor->getNumPrograms() > 0)
  1219. processor->getProgramName (processor->getCurrentProgram()).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1220. return 0;
  1221. }
  1222. pointer_sized_int handleGetParameterLabel (VstOpCodeArguments args)
  1223. {
  1224. if (auto* param = juceParameters.getParamForIndex (args.index))
  1225. {
  1226. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1227. param->getLabel().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1228. }
  1229. return 0;
  1230. }
  1231. pointer_sized_int handleGetParameterText (VstOpCodeArguments args)
  1232. {
  1233. if (auto* param = juceParameters.getParamForIndex (args.index))
  1234. {
  1235. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1236. param->getCurrentValueAsText().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1237. }
  1238. return 0;
  1239. }
  1240. pointer_sized_int handleGetParameterName (VstOpCodeArguments args)
  1241. {
  1242. if (auto* param = juceParameters.getParamForIndex (args.index))
  1243. {
  1244. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1245. param->getName (32).copyToUTF8 ((char*) args.ptr, 32 + 1);
  1246. }
  1247. return 0;
  1248. }
  1249. pointer_sized_int handleSetSampleRate (VstOpCodeArguments args)
  1250. {
  1251. sampleRate = args.opt;
  1252. return 0;
  1253. }
  1254. pointer_sized_int handleSetBlockSize (VstOpCodeArguments args)
  1255. {
  1256. blockSize = (int32) args.value;
  1257. return 0;
  1258. }
  1259. pointer_sized_int handleResumeSuspend (VstOpCodeArguments args)
  1260. {
  1261. if (args.value)
  1262. resume();
  1263. else
  1264. suspend();
  1265. return 0;
  1266. }
  1267. pointer_sized_int handleGetEditorBounds (VstOpCodeArguments args)
  1268. {
  1269. checkWhetherMessageThreadIsCorrect();
  1270. #if JUCE_LINUX || JUCE_BSD
  1271. SharedResourcePointer<HostDrivenEventLoop> hostDrivenEventLoop;
  1272. #else
  1273. const MessageManagerLock mmLock;
  1274. #endif
  1275. createEditorComp();
  1276. if (editorComp != nullptr)
  1277. {
  1278. editorComp->getEditorBounds (editorRect);
  1279. *((Vst2::VstEditorBounds**) args.ptr) = &editorRect;
  1280. return (pointer_sized_int) &editorRect;
  1281. }
  1282. return 0;
  1283. }
  1284. pointer_sized_int handleOpenEditor (VstOpCodeArguments args)
  1285. {
  1286. checkWhetherMessageThreadIsCorrect();
  1287. #if JUCE_LINUX || JUCE_BSD
  1288. SharedResourcePointer<HostDrivenEventLoop> hostDrivenEventLoop;
  1289. #else
  1290. const MessageManagerLock mmLock;
  1291. #endif
  1292. jassert (! recursionCheck);
  1293. startTimerHz (4); // performs misc housekeeping chores
  1294. deleteEditor (true);
  1295. createEditorComp();
  1296. if (editorComp != nullptr)
  1297. {
  1298. editorComp->attachToHost (args);
  1299. return 1;
  1300. }
  1301. return 0;
  1302. }
  1303. pointer_sized_int handleCloseEditor (VstOpCodeArguments)
  1304. {
  1305. checkWhetherMessageThreadIsCorrect();
  1306. #if JUCE_LINUX || JUCE_BSD
  1307. SharedResourcePointer<HostDrivenEventLoop> hostDrivenEventLoop;
  1308. #else
  1309. const MessageManagerLock mmLock;
  1310. #endif
  1311. deleteEditor (true);
  1312. return 0;
  1313. }
  1314. pointer_sized_int handleGetData (VstOpCodeArguments args)
  1315. {
  1316. if (processor == nullptr)
  1317. return 0;
  1318. auto data = (void**) args.ptr;
  1319. bool onlyStoreCurrentProgramData = (args.index != 0);
  1320. MemoryBlock block;
  1321. if (onlyStoreCurrentProgramData)
  1322. processor->getCurrentProgramStateInformation (block);
  1323. else
  1324. processor->getStateInformation (block);
  1325. // IMPORTANT! Don't call getStateInfo while holding this lock!
  1326. const ScopedLock lock (stateInformationLock);
  1327. chunkMemory = std::move (block);
  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. const ScopedLock lock (stateInformationLock);
  1343. chunkMemory.reset();
  1344. chunkMemoryTime = 0;
  1345. }
  1346. if (byteSize > 0 && data != nullptr)
  1347. {
  1348. if (onlyRestoreCurrentProgramData)
  1349. processor->setCurrentProgramStateInformation (data, byteSize);
  1350. else
  1351. processor->setStateInformation (data, byteSize);
  1352. }
  1353. }
  1354. return 0;
  1355. }
  1356. pointer_sized_int handlePreAudioProcessingEvents (VstOpCodeArguments args)
  1357. {
  1358. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1359. VSTMidiEventList::addEventsToMidiBuffer ((Vst2::VstEventBlock*) 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. setValueAndNotifyIfChanged (*param, param->getValueForText (String::fromUTF8 ((char*) args.ptr)));
  1382. return 1;
  1383. }
  1384. }
  1385. return 0;
  1386. }
  1387. pointer_sized_int handleGetProgramName (VstOpCodeArguments args)
  1388. {
  1389. if (processor != nullptr && isPositiveAndBelow (args.index, processor->getNumPrograms()))
  1390. {
  1391. processor->getProgramName (args.index).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1392. return 1;
  1393. }
  1394. return 0;
  1395. }
  1396. pointer_sized_int handleGetInputPinProperties (VstOpCodeArguments args)
  1397. {
  1398. return (processor != nullptr && getPinProperties (*(Vst2::VstPinInfo*) args.ptr, true, args.index)) ? 1 : 0;
  1399. }
  1400. pointer_sized_int handleGetOutputPinProperties (VstOpCodeArguments args)
  1401. {
  1402. return (processor != nullptr && getPinProperties (*(Vst2::VstPinInfo*) args.ptr, false, args.index)) ? 1 : 0;
  1403. }
  1404. pointer_sized_int handleGetPlugInCategory (VstOpCodeArguments)
  1405. {
  1406. return Vst2::JucePlugin_VSTCategory;
  1407. }
  1408. pointer_sized_int handleSetSpeakerConfiguration (VstOpCodeArguments args)
  1409. {
  1410. auto* pluginInput = reinterpret_cast<Vst2::VstSpeakerConfiguration*> (args.value);
  1411. auto* pluginOutput = reinterpret_cast<Vst2::VstSpeakerConfiguration*> (args.ptr);
  1412. if (processor->isMidiEffect())
  1413. return 0;
  1414. auto numIns = processor->getBusCount (true);
  1415. auto numOuts = processor->getBusCount (false);
  1416. if (pluginInput != nullptr && pluginInput->type >= 0)
  1417. {
  1418. // inconsistent request?
  1419. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput).size() != pluginInput->numberOfChannels)
  1420. return 0;
  1421. }
  1422. if (pluginOutput != nullptr && pluginOutput->type >= 0)
  1423. {
  1424. // inconsistent request?
  1425. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput).size() != pluginOutput->numberOfChannels)
  1426. return 0;
  1427. }
  1428. if (pluginInput != nullptr && pluginInput->numberOfChannels > 0 && numIns == 0)
  1429. return 0;
  1430. if (pluginOutput != nullptr && pluginOutput->numberOfChannels > 0 && numOuts == 0)
  1431. return 0;
  1432. auto layouts = processor->getBusesLayout();
  1433. if (pluginInput != nullptr && pluginInput-> numberOfChannels >= 0 && numIns > 0)
  1434. layouts.getChannelSet (true, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  1435. if (pluginOutput != nullptr && pluginOutput->numberOfChannels >= 0 && numOuts > 0)
  1436. layouts.getChannelSet (false, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  1437. #ifdef JucePlugin_PreferredChannelConfigurations
  1438. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1439. if (! AudioProcessor::containsLayout (layouts, configs))
  1440. return 0;
  1441. #endif
  1442. return processor->setBusesLayout (layouts) ? 1 : 0;
  1443. }
  1444. pointer_sized_int handleSetBypass (VstOpCodeArguments args)
  1445. {
  1446. isBypassed = args.value != 0;
  1447. if (auto* param = processor->getBypassParameter())
  1448. param->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  1449. return 1;
  1450. }
  1451. pointer_sized_int handleGetPlugInName (VstOpCodeArguments args)
  1452. {
  1453. String (processor->getName()).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1454. return 1;
  1455. }
  1456. pointer_sized_int handleGetManufacturerName (VstOpCodeArguments args)
  1457. {
  1458. String (JucePlugin_Manufacturer).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1459. return 1;
  1460. }
  1461. pointer_sized_int handleGetManufacturerVersion (VstOpCodeArguments)
  1462. {
  1463. return convertHexVersionToDecimal (JucePlugin_VersionCode);
  1464. }
  1465. pointer_sized_int handleManufacturerSpecific (VstOpCodeArguments args)
  1466. {
  1467. if (handleManufacturerSpecificVST2Opcode (args.index, args.value, args.ptr, args.opt))
  1468. return 1;
  1469. if (args.index == (int32) ByteOrder::bigEndianInt ("PreS")
  1470. && args.value == (int32) ByteOrder::bigEndianInt ("AeCs"))
  1471. return handleSetContentScaleFactor (args.opt);
  1472. if (args.index == Vst2::plugInOpcodeGetParameterText)
  1473. return handleCockosGetParameterText (args.value, args.ptr, args.opt);
  1474. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor.get()))
  1475. return callbackHandler->handleVstManufacturerSpecific (args.index, args.value, args.ptr, args.opt);
  1476. return 0;
  1477. }
  1478. pointer_sized_int handleCanPlugInDo (VstOpCodeArguments args)
  1479. {
  1480. auto text = (const char*) args.ptr;
  1481. auto matches = [=] (const char* s) { return strcmp (text, s) == 0; };
  1482. if (matches ("receiveVstEvents")
  1483. || matches ("receiveVstMidiEvent")
  1484. || matches ("receiveVstMidiEvents"))
  1485. {
  1486. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1487. return 1;
  1488. #else
  1489. return -1;
  1490. #endif
  1491. }
  1492. if (matches ("sendVstEvents")
  1493. || matches ("sendVstMidiEvent")
  1494. || matches ("sendVstMidiEvents"))
  1495. {
  1496. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1497. return 1;
  1498. #else
  1499. return -1;
  1500. #endif
  1501. }
  1502. if (matches ("receiveVstTimeInfo")
  1503. || matches ("conformsToWindowRules")
  1504. || matches ("supportsViewDpiScaling")
  1505. || matches ("bypass"))
  1506. {
  1507. return 1;
  1508. }
  1509. // This tells Wavelab to use the UI thread to invoke open/close,
  1510. // like all other hosts do.
  1511. if (matches ("openCloseAnyThread"))
  1512. return -1;
  1513. if (matches ("MPE"))
  1514. return processor->supportsMPE() ? 1 : 0;
  1515. #if JUCE_MAC
  1516. if (matches ("hasCockosViewAsConfig"))
  1517. {
  1518. useNSView = true;
  1519. return (int32) 0xbeef0000;
  1520. }
  1521. #endif
  1522. if (matches ("hasCockosExtensions"))
  1523. return (int32) 0xbeef0000;
  1524. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor.get()))
  1525. return callbackHandler->handleVstPluginCanDo (args.index, args.value, args.ptr, args.opt);
  1526. return 0;
  1527. }
  1528. pointer_sized_int handleGetTailSize (VstOpCodeArguments)
  1529. {
  1530. if (processor != nullptr)
  1531. {
  1532. int32 result;
  1533. auto tailSeconds = processor->getTailLengthSeconds();
  1534. if (tailSeconds == std::numeric_limits<double>::infinity())
  1535. result = std::numeric_limits<int32>::max();
  1536. else
  1537. result = static_cast<int32> (tailSeconds * sampleRate);
  1538. return result; // Vst2 expects an int32 upcasted to a intptr_t here
  1539. }
  1540. return 0;
  1541. }
  1542. pointer_sized_int handleKeyboardFocusRequired (VstOpCodeArguments)
  1543. {
  1544. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6326)
  1545. return (JucePlugin_EditorRequiresKeyboardFocus != 0) ? 1 : 0;
  1546. JUCE_END_IGNORE_WARNINGS_MSVC
  1547. }
  1548. pointer_sized_int handleGetVstInterfaceVersion (VstOpCodeArguments)
  1549. {
  1550. return Vst2::juceVstInterfaceVersion;
  1551. }
  1552. pointer_sized_int handleGetCurrentMidiProgram (VstOpCodeArguments)
  1553. {
  1554. return -1;
  1555. }
  1556. pointer_sized_int handleGetSpeakerConfiguration (VstOpCodeArguments args)
  1557. {
  1558. auto** pluginInput = reinterpret_cast<Vst2::VstSpeakerConfiguration**> (args.value);
  1559. auto** pluginOutput = reinterpret_cast<Vst2::VstSpeakerConfiguration**> (args.ptr);
  1560. if (pluginHasSidechainsOrAuxs() || processor->isMidiEffect())
  1561. return false;
  1562. auto inputLayout = processor->getChannelLayoutOfBus (true, 0);
  1563. auto outputLayout = processor->getChannelLayoutOfBus (false, 0);
  1564. auto speakerBaseSize = sizeof (Vst2::VstSpeakerConfiguration) - (sizeof (Vst2::VstIndividualSpeakerInfo) * 8);
  1565. cachedInArrangement .malloc (speakerBaseSize + (static_cast<std::size_t> (inputLayout. size()) * sizeof (Vst2::VstSpeakerConfiguration)), 1);
  1566. cachedOutArrangement.malloc (speakerBaseSize + (static_cast<std::size_t> (outputLayout.size()) * sizeof (Vst2::VstSpeakerConfiguration)), 1);
  1567. *pluginInput = cachedInArrangement. getData();
  1568. *pluginOutput = cachedOutArrangement.getData();
  1569. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (true, 0), **pluginInput);
  1570. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (false, 0), **pluginOutput);
  1571. return 1;
  1572. }
  1573. pointer_sized_int handleSetNumberOfSamplesToProcess (VstOpCodeArguments args)
  1574. {
  1575. return args.value;
  1576. }
  1577. pointer_sized_int handleSetSampleFloatType (VstOpCodeArguments args)
  1578. {
  1579. if (! isProcessing)
  1580. {
  1581. if (processor != nullptr)
  1582. {
  1583. processor->setProcessingPrecision ((args.value == Vst2::vstProcessingSampleTypeDouble
  1584. && processor->supportsDoublePrecisionProcessing())
  1585. ? AudioProcessor::doublePrecision
  1586. : AudioProcessor::singlePrecision);
  1587. return 1;
  1588. }
  1589. }
  1590. return 0;
  1591. }
  1592. pointer_sized_int handleSetContentScaleFactor (float scale)
  1593. {
  1594. checkWhetherMessageThreadIsCorrect();
  1595. #if JUCE_LINUX || JUCE_BSD
  1596. SharedResourcePointer<HostDrivenEventLoop> hostDrivenEventLoop;
  1597. #else
  1598. const MessageManagerLock mmLock;
  1599. #endif
  1600. #if ! JUCE_MAC
  1601. if (! approximatelyEqual (scale, editorScaleFactor))
  1602. {
  1603. editorScaleFactor = scale;
  1604. if (editorComp != nullptr)
  1605. editorComp->setContentScaleFactor (editorScaleFactor);
  1606. }
  1607. #else
  1608. ignoreUnused (scale);
  1609. #endif
  1610. return 1;
  1611. }
  1612. pointer_sized_int handleCockosGetParameterText (pointer_sized_int paramIndex,
  1613. void* dest,
  1614. float value)
  1615. {
  1616. if (processor != nullptr && dest != nullptr)
  1617. {
  1618. if (auto* param = juceParameters.getParamForIndex ((int) paramIndex))
  1619. {
  1620. if (! LegacyAudioParameter::isLegacy (param))
  1621. {
  1622. String text (param->getText (value, 1024));
  1623. memcpy (dest, text.toRawUTF8(), ((size_t) text.length()) + 1);
  1624. return 0xbeef;
  1625. }
  1626. }
  1627. }
  1628. return 0;
  1629. }
  1630. //==============================================================================
  1631. pointer_sized_int handleGetNumMidiInputChannels()
  1632. {
  1633. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1634. #ifdef JucePlugin_VSTNumMidiInputs
  1635. return JucePlugin_VSTNumMidiInputs;
  1636. #else
  1637. return 16;
  1638. #endif
  1639. #else
  1640. return 0;
  1641. #endif
  1642. }
  1643. pointer_sized_int handleGetNumMidiOutputChannels()
  1644. {
  1645. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1646. #ifdef JucePlugin_VSTNumMidiOutputs
  1647. return JucePlugin_VSTNumMidiOutputs;
  1648. #else
  1649. return 16;
  1650. #endif
  1651. #else
  1652. return 0;
  1653. #endif
  1654. }
  1655. pointer_sized_int handleEditIdle()
  1656. {
  1657. #if JUCE_LINUX || JUCE_BSD
  1658. SharedResourcePointer<HostDrivenEventLoop> hostDrivenEventLoop;
  1659. hostDrivenEventLoop->processPendingEvents();
  1660. #endif
  1661. return 0;
  1662. }
  1663. //==============================================================================
  1664. ScopedJuceInitialiser_GUI libraryInitialiser;
  1665. #if JUCE_LINUX || JUCE_BSD
  1666. SharedResourcePointer<MessageThread> messageThread;
  1667. #endif
  1668. Vst2::VstHostCallback hostCallback;
  1669. std::unique_ptr<AudioProcessor> processor;
  1670. double sampleRate = 44100.0;
  1671. int32 blockSize = 1024;
  1672. Vst2::VstEffectInterface vstEffect;
  1673. CriticalSection stateInformationLock;
  1674. juce::MemoryBlock chunkMemory;
  1675. uint32 chunkMemoryTime = 0;
  1676. float editorScaleFactor = 1.0f;
  1677. std::unique_ptr<EditorCompWrapper> editorComp;
  1678. Vst2::VstEditorBounds editorRect;
  1679. MidiBuffer midiEvents;
  1680. VSTMidiEventList outgoingEvents;
  1681. Optional<PositionInfo> currentPosition;
  1682. LegacyAudioParametersWrapper juceParameters;
  1683. bool isProcessing = false, isBypassed = false, hasShutdown = false;
  1684. bool firstProcessCallback = true, shouldDeleteEditor = false;
  1685. #if JUCE_MAC
  1686. #if JUCE_64BIT
  1687. bool useNSView = true;
  1688. #else
  1689. bool useNSView = false;
  1690. #endif
  1691. #endif
  1692. VstTempBuffers<float> floatTempBuffers;
  1693. VstTempBuffers<double> doubleTempBuffers;
  1694. int maxNumInChannels = 0, maxNumOutChannels = 0;
  1695. HeapBlock<Vst2::VstSpeakerConfiguration> cachedInArrangement, cachedOutArrangement;
  1696. ThreadLocalValue<bool> inParameterChangedCallback;
  1697. HostChangeUpdater hostChangeUpdater { *this };
  1698. //==============================================================================
  1699. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1700. };
  1701. //==============================================================================
  1702. namespace
  1703. {
  1704. Vst2::VstEffectInterface* pluginEntryPoint (Vst2::VstHostCallback audioMaster)
  1705. {
  1706. JUCE_AUTORELEASEPOOL
  1707. {
  1708. ScopedJuceInitialiser_GUI libraryInitialiser;
  1709. #if JUCE_LINUX || JUCE_BSD
  1710. SharedResourcePointer<HostDrivenEventLoop> hostDrivenEventLoop;
  1711. #endif
  1712. try
  1713. {
  1714. if (audioMaster (nullptr, Vst2::hostOpcodeVstVersion, 0, 0, nullptr, 0) != 0)
  1715. {
  1716. std::unique_ptr<AudioProcessor> processor { createPluginFilterOfType (AudioProcessor::wrapperType_VST) };
  1717. auto* processorPtr = processor.get();
  1718. auto* wrapper = new JuceVSTWrapper (audioMaster, std::move (processor));
  1719. auto* aEffect = wrapper->getAEffect();
  1720. if (auto* callbackHandler = dynamic_cast<VSTCallbackHandler*> (processorPtr))
  1721. {
  1722. callbackHandler->handleVstHostCallbackAvailable ([audioMaster, aEffect] (int32 opcode, int32 index, pointer_sized_int value, void* ptr, float opt)
  1723. {
  1724. return audioMaster (aEffect, opcode, index, value, ptr, opt);
  1725. });
  1726. }
  1727. return aEffect;
  1728. }
  1729. }
  1730. catch (...)
  1731. {}
  1732. }
  1733. return nullptr;
  1734. }
  1735. }
  1736. #if ! JUCE_WINDOWS
  1737. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1738. #endif
  1739. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wmissing-prototypes")
  1740. //==============================================================================
  1741. // Mac startup code..
  1742. #if JUCE_MAC
  1743. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* VSTPluginMain (Vst2::VstHostCallback audioMaster);
  1744. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* VSTPluginMain (Vst2::VstHostCallback audioMaster)
  1745. {
  1746. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1747. initialiseMacVST();
  1748. return pluginEntryPoint (audioMaster);
  1749. }
  1750. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* main_macho (Vst2::VstHostCallback audioMaster);
  1751. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* main_macho (Vst2::VstHostCallback audioMaster)
  1752. {
  1753. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1754. initialiseMacVST();
  1755. return pluginEntryPoint (audioMaster);
  1756. }
  1757. //==============================================================================
  1758. // Linux startup code..
  1759. #elif JUCE_LINUX || JUCE_BSD
  1760. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* VSTPluginMain (Vst2::VstHostCallback audioMaster);
  1761. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* VSTPluginMain (Vst2::VstHostCallback audioMaster)
  1762. {
  1763. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1764. return pluginEntryPoint (audioMaster);
  1765. }
  1766. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* main_plugin (Vst2::VstHostCallback audioMaster) asm ("main");
  1767. JUCE_EXPORTED_FUNCTION Vst2::VstEffectInterface* main_plugin (Vst2::VstHostCallback audioMaster)
  1768. {
  1769. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1770. return VSTPluginMain (audioMaster);
  1771. }
  1772. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1773. __attribute__((constructor)) void myPluginInit() {}
  1774. __attribute__((destructor)) void myPluginFini() {}
  1775. //==============================================================================
  1776. // Win32 startup code..
  1777. #else
  1778. extern "C" __declspec (dllexport) Vst2::VstEffectInterface* VSTPluginMain (Vst2::VstHostCallback audioMaster)
  1779. {
  1780. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1781. return pluginEntryPoint (audioMaster);
  1782. }
  1783. #if ! defined (JUCE_64BIT) && JUCE_MSVC // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1784. extern "C" __declspec (dllexport) int main (Vst2::VstHostCallback audioMaster)
  1785. {
  1786. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1787. return (int) pluginEntryPoint (audioMaster);
  1788. }
  1789. #endif
  1790. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1791. {
  1792. if (reason == DLL_PROCESS_ATTACH)
  1793. Process::setCurrentModuleInstanceHandle (instance);
  1794. return true;
  1795. }
  1796. #endif
  1797. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1798. JUCE_END_IGNORE_WARNINGS_MSVC
  1799. #endif