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.

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