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.

2406 lines
90KB

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