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.

2428 lines
91KB

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