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.

2401 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. HWND w = (HWND) getWindowHandle();
  1187. while (w != 0)
  1188. {
  1189. HWND parent = getWindowParent (w);
  1190. if (parent == 0)
  1191. break;
  1192. TCHAR windowType [32] = { 0 };
  1193. GetClassName (parent, windowType, 31);
  1194. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  1195. break;
  1196. RECT windowPos, parentPos;
  1197. GetWindowRect (w, &windowPos);
  1198. GetWindowRect (parent, &parentPos);
  1199. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1200. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1201. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1202. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1203. w = parent;
  1204. if (dw == 2 * frameThickness)
  1205. break;
  1206. if (dw > 100 || dh > 100)
  1207. w = 0;
  1208. }
  1209. if (w != 0)
  1210. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1211. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1212. #endif
  1213. }
  1214. if (auto* peer = getPeer())
  1215. {
  1216. peer->handleMovedOrResized();
  1217. repaint();
  1218. }
  1219. }
  1220. #if JUCE_WINDOWS
  1221. void mouseDown (const MouseEvent&) override
  1222. {
  1223. broughtToFront();
  1224. }
  1225. void broughtToFront() override
  1226. {
  1227. // for hosts like nuendo, need to also pop the MDI container to the
  1228. // front when our comp is clicked on.
  1229. if (! isCurrentlyBlockedByAnotherModalComponent())
  1230. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  1231. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1232. }
  1233. #endif
  1234. #if JUCE_MAC
  1235. bool keyPressed (const KeyPress&) override
  1236. {
  1237. // If we have an unused keypress, move the key-focus to a host window
  1238. // and re-inject the event..
  1239. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1240. }
  1241. #endif
  1242. //==============================================================================
  1243. JuceVSTWrapper& wrapper;
  1244. FakeMouseMoveGenerator fakeMouseGenerator;
  1245. bool isInSizeWindow = false;
  1246. bool shouldResizeEditor = true;
  1247. #if JUCE_MAC
  1248. void* hostWindow = {};
  1249. #elif JUCE_LINUX
  1250. ScopedXDisplay display;
  1251. Window hostWindow = {};
  1252. #else
  1253. HWND hostWindow = {};
  1254. WindowsHooks hooks;
  1255. #endif
  1256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1257. };
  1258. //==============================================================================
  1259. private:
  1260. static JuceVSTWrapper* getWrapper (Vst2::AEffect* v) noexcept { return static_cast<JuceVSTWrapper*> (v->object); }
  1261. bool isProcessLevelOffline()
  1262. {
  1263. return hostCallback != nullptr
  1264. && (int32) hostCallback (&vstEffect, Vst2::audioMasterGetCurrentProcessLevel, 0, 0, 0, 0) == 4;
  1265. }
  1266. static inline int32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1267. {
  1268. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1269. return (int32) hexVersion;
  1270. #else
  1271. // Currently, only Cubase displays the version number to the user
  1272. // We are hoping here that when other DAWs start to display the version
  1273. // number, that they do so according to yfede's encoding table in the link
  1274. // below. If not, then this code will need an if (isSteinberg()) in the
  1275. // future.
  1276. int major = (hexVersion >> 16) & 0xff;
  1277. int minor = (hexVersion >> 8) & 0xff;
  1278. int bugfix = hexVersion & 0xff;
  1279. // for details, see: https://forum.juce.com/t/issues-with-version-integer-reported-by-vst2/23867
  1280. // Encoding B
  1281. if (major < 1)
  1282. return major * 1000 + minor * 100 + bugfix * 10;
  1283. // Encoding E
  1284. if (major > 100)
  1285. return major * 10000000 + minor * 100000 + bugfix * 1000;
  1286. // Encoding D
  1287. return static_cast<int32> (hexVersion);
  1288. #endif
  1289. }
  1290. //==============================================================================
  1291. #if JUCE_WINDOWS
  1292. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1293. static void checkWhetherMessageThreadIsCorrect()
  1294. {
  1295. auto host = getHostType();
  1296. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1297. {
  1298. if (! messageThreadIsDefinitelyCorrect)
  1299. {
  1300. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1301. struct MessageThreadCallback : public CallbackMessage
  1302. {
  1303. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1304. void messageCallback() override { triggered = true; }
  1305. bool& triggered;
  1306. };
  1307. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1308. }
  1309. }
  1310. }
  1311. #else
  1312. static void checkWhetherMessageThreadIsCorrect() {}
  1313. #endif
  1314. //==============================================================================
  1315. template <typename FloatType>
  1316. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1317. {
  1318. tmpBuffers.release();
  1319. if (processor != nullptr)
  1320. tmpBuffers.tempChannels.insertMultiple (0, nullptr, vstEffect.numInputs
  1321. + vstEffect.numOutputs);
  1322. }
  1323. void deleteTempChannels()
  1324. {
  1325. deleteTempChannels (floatTempBuffers);
  1326. deleteTempChannels (doubleTempBuffers);
  1327. }
  1328. //==============================================================================
  1329. void findMaxTotalChannels (int& maxTotalIns, int& maxTotalOuts)
  1330. {
  1331. #ifdef JucePlugin_PreferredChannelConfigurations
  1332. int configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1333. maxTotalIns = maxTotalOuts = 0;
  1334. for (auto& config : configs)
  1335. {
  1336. maxTotalIns = jmax (maxTotalIns, config[0]);
  1337. maxTotalOuts = jmax (maxTotalOuts, config[1]);
  1338. }
  1339. #else
  1340. auto numInputBuses = processor->getBusCount (true);
  1341. auto numOutputBuses = processor->getBusCount (false);
  1342. if (numInputBuses > 1 || numOutputBuses > 1)
  1343. {
  1344. maxTotalIns = maxTotalOuts = 0;
  1345. for (int i = 0; i < numInputBuses; ++i)
  1346. maxTotalIns += processor->getChannelCountOfBus (true, i);
  1347. for (int i = 0; i < numOutputBuses; ++i)
  1348. maxTotalOuts += processor->getChannelCountOfBus (false, i);
  1349. }
  1350. else
  1351. {
  1352. maxTotalIns = numInputBuses > 0 ? processor->getBus (true, 0)->getMaxSupportedChannels (64) : 0;
  1353. maxTotalOuts = numOutputBuses > 0 ? processor->getBus (false, 0)->getMaxSupportedChannels (64) : 0;
  1354. }
  1355. #endif
  1356. }
  1357. bool pluginHasSidechainsOrAuxs() const { return (processor->getBusCount (true) > 1 || processor->getBusCount (false) > 1); }
  1358. //==============================================================================
  1359. /** Host to plug-in calls. */
  1360. pointer_sized_int handleOpen (VstOpCodeArguments)
  1361. {
  1362. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1363. if (processor->hasEditor())
  1364. vstEffect.flags |= Vst2::effFlagsHasEditor;
  1365. else
  1366. vstEffect.flags &= ~Vst2::effFlagsHasEditor;
  1367. return 0;
  1368. }
  1369. pointer_sized_int handleClose (VstOpCodeArguments)
  1370. {
  1371. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1372. stopTimer();
  1373. if (MessageManager::getInstance()->isThisTheMessageThread())
  1374. deleteEditor (false);
  1375. return 0;
  1376. }
  1377. pointer_sized_int handleSetCurrentProgram (VstOpCodeArguments args)
  1378. {
  1379. if (processor != nullptr && isPositiveAndBelow ((int) args.value, processor->getNumPrograms()))
  1380. processor->setCurrentProgram ((int) args.value);
  1381. return 0;
  1382. }
  1383. pointer_sized_int handleGetCurrentProgram (VstOpCodeArguments)
  1384. {
  1385. return (processor != nullptr && processor->getNumPrograms() > 0 ? processor->getCurrentProgram() : 0);
  1386. }
  1387. pointer_sized_int handleSetCurrentProgramName (VstOpCodeArguments args)
  1388. {
  1389. if (processor != nullptr && processor->getNumPrograms() > 0)
  1390. processor->changeProgramName (processor->getCurrentProgram(), (char*) args.ptr);
  1391. return 0;
  1392. }
  1393. pointer_sized_int handleGetCurrentProgramName (VstOpCodeArguments args)
  1394. {
  1395. if (processor != nullptr && processor->getNumPrograms() > 0)
  1396. processor->getProgramName (processor->getCurrentProgram()).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1397. return 0;
  1398. }
  1399. pointer_sized_int handleGetParameterLabel (VstOpCodeArguments args)
  1400. {
  1401. if (auto* param = juceParameters.getParamForIndex (args.index))
  1402. {
  1403. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1404. param->getLabel().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1405. }
  1406. return 0;
  1407. }
  1408. pointer_sized_int handleGetParameterText (VstOpCodeArguments args)
  1409. {
  1410. if (auto* param = juceParameters.getParamForIndex (args.index))
  1411. {
  1412. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1413. param->getCurrentValueAsText().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1414. }
  1415. return 0;
  1416. }
  1417. pointer_sized_int handleGetParameterName (VstOpCodeArguments args)
  1418. {
  1419. if (auto* param = juceParameters.getParamForIndex (args.index))
  1420. {
  1421. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1422. param->getName (32).copyToUTF8 ((char*) args.ptr, 32 + 1);
  1423. }
  1424. return 0;
  1425. }
  1426. pointer_sized_int handleSetSampleRate (VstOpCodeArguments args)
  1427. {
  1428. sampleRate = args.opt;
  1429. return 0;
  1430. }
  1431. pointer_sized_int handleSetBlockSize (VstOpCodeArguments args)
  1432. {
  1433. blockSize = (int32) args.value;
  1434. return 0;
  1435. }
  1436. pointer_sized_int handleResumeSuspend (VstOpCodeArguments args)
  1437. {
  1438. if (args.value)
  1439. resume();
  1440. else
  1441. suspend();
  1442. return 0;
  1443. }
  1444. pointer_sized_int handleGetEditorBounds (VstOpCodeArguments args)
  1445. {
  1446. checkWhetherMessageThreadIsCorrect();
  1447. const MessageManagerLock mmLock;
  1448. createEditorComp();
  1449. if (editorComp != nullptr)
  1450. {
  1451. editorComp->getEditorBounds (editorBounds);
  1452. *((Vst2::ERect**) args.ptr) = &editorBounds;
  1453. return (pointer_sized_int) &editorBounds;
  1454. }
  1455. return 0;
  1456. }
  1457. pointer_sized_int handleOpenEditor (VstOpCodeArguments args)
  1458. {
  1459. checkWhetherMessageThreadIsCorrect();
  1460. const MessageManagerLock mmLock;
  1461. jassert (! recursionCheck);
  1462. startTimerHz (4); // performs misc housekeeping chores
  1463. deleteEditor (true);
  1464. createEditorComp();
  1465. if (editorComp != nullptr)
  1466. {
  1467. editorComp->attachToHost (args);
  1468. return 1;
  1469. }
  1470. return 0;
  1471. }
  1472. pointer_sized_int handleCloseEditor (VstOpCodeArguments)
  1473. {
  1474. checkWhetherMessageThreadIsCorrect();
  1475. const MessageManagerLock mmLock;
  1476. deleteEditor (true);
  1477. return 0;
  1478. }
  1479. pointer_sized_int handleGetData (VstOpCodeArguments args)
  1480. {
  1481. if (processor == nullptr)
  1482. return 0;
  1483. auto data = (void**) args.ptr;
  1484. bool onlyStoreCurrentProgramData = (args.index != 0);
  1485. chunkMemory.reset();
  1486. if (onlyStoreCurrentProgramData)
  1487. processor->getCurrentProgramStateInformation (chunkMemory);
  1488. else
  1489. processor->getStateInformation (chunkMemory);
  1490. *data = (void*) chunkMemory.getData();
  1491. // because the chunk is only needed temporarily by the host (or at least you'd
  1492. // hope so) we'll give it a while and then free it in the timer callback.
  1493. chunkMemoryTime = juce::Time::getApproximateMillisecondCounter();
  1494. return (int32) chunkMemory.getSize();
  1495. }
  1496. pointer_sized_int handleSetData (VstOpCodeArguments args)
  1497. {
  1498. if (processor != nullptr)
  1499. {
  1500. void* data = args.ptr;
  1501. int32 byteSize = (int32) args.value;
  1502. bool onlyRestoreCurrentProgramData = (args.index != 0);
  1503. chunkMemory.reset();
  1504. chunkMemoryTime = 0;
  1505. if (byteSize > 0 && data != nullptr)
  1506. {
  1507. if (onlyRestoreCurrentProgramData)
  1508. processor->setCurrentProgramStateInformation (data, byteSize);
  1509. else
  1510. processor->setStateInformation (data, byteSize);
  1511. }
  1512. }
  1513. return 0;
  1514. }
  1515. pointer_sized_int handlePreAudioProcessingEvents (VstOpCodeArguments args)
  1516. {
  1517. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1518. VSTMidiEventList::addEventsToMidiBuffer ((Vst2::VstEvents*) args.ptr, midiEvents);
  1519. return 1;
  1520. #else
  1521. ignoreUnused (args);
  1522. return 0;
  1523. #endif
  1524. }
  1525. pointer_sized_int handleIsParameterAutomatable (VstOpCodeArguments args)
  1526. {
  1527. if (auto* param = juceParameters.getParamForIndex (args.index))
  1528. {
  1529. const bool isMeter = (((param->getCategory() & 0xffff0000) >> 16) == 2);
  1530. return (param->isAutomatable() && (! isMeter) ? 1 : 0);
  1531. }
  1532. return 0;
  1533. }
  1534. pointer_sized_int handleParameterValueForText (VstOpCodeArguments args)
  1535. {
  1536. if (auto* param = juceParameters.getParamForIndex (args.index))
  1537. {
  1538. if (! LegacyAudioParameter::isLegacy (param))
  1539. {
  1540. auto value = param->getValueForText (String::fromUTF8 ((char*) args.ptr));
  1541. param->setValue (value);
  1542. inParameterChangedCallback = true;
  1543. param->sendValueChangedMessageToListeners (value);
  1544. return 1;
  1545. }
  1546. }
  1547. return 0;
  1548. }
  1549. pointer_sized_int handleGetProgramName (VstOpCodeArguments args)
  1550. {
  1551. if (processor != nullptr && isPositiveAndBelow (args.index, processor->getNumPrograms()))
  1552. {
  1553. processor->getProgramName (args.index).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1554. return 1;
  1555. }
  1556. return 0;
  1557. }
  1558. pointer_sized_int handleGetInputPinProperties (VstOpCodeArguments args)
  1559. {
  1560. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, true, args.index)) ? 1 : 0;
  1561. }
  1562. pointer_sized_int handleGetOutputPinProperties (VstOpCodeArguments args)
  1563. {
  1564. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, false, args.index)) ? 1 : 0;
  1565. }
  1566. pointer_sized_int handleGetPlugInCategory (VstOpCodeArguments)
  1567. {
  1568. return Vst2::JucePlugin_VSTCategory;
  1569. }
  1570. pointer_sized_int handleSetSpeakerConfiguration (VstOpCodeArguments args)
  1571. {
  1572. auto* pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.value);
  1573. auto* pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.ptr);
  1574. if (processor->isMidiEffect())
  1575. return 0;
  1576. auto numIns = processor->getBusCount (true);
  1577. auto numOuts = processor->getBusCount (false);
  1578. if (pluginInput != nullptr && pluginInput->type >= 0)
  1579. {
  1580. // inconsistent request?
  1581. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput).size() != pluginInput->numChannels)
  1582. return 0;
  1583. }
  1584. if (pluginOutput != nullptr && pluginOutput->type >= 0)
  1585. {
  1586. // inconsistent request?
  1587. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput).size() != pluginOutput->numChannels)
  1588. return 0;
  1589. }
  1590. if (pluginInput != nullptr && pluginInput->numChannels > 0 && numIns == 0)
  1591. return 0;
  1592. if (pluginOutput != nullptr && pluginOutput->numChannels > 0 && numOuts == 0)
  1593. return 0;
  1594. auto layouts = processor->getBusesLayout();
  1595. if (pluginInput != nullptr && pluginInput-> numChannels >= 0 && numIns > 0)
  1596. layouts.getChannelSet (true, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  1597. if (pluginOutput != nullptr && pluginOutput->numChannels >= 0 && numOuts > 0)
  1598. layouts.getChannelSet (false, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  1599. #ifdef JucePlugin_PreferredChannelConfigurations
  1600. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1601. if (! AudioProcessor::containsLayout (layouts, configs))
  1602. return 0;
  1603. #endif
  1604. return processor->setBusesLayout (layouts) ? 1 : 0;
  1605. }
  1606. pointer_sized_int handleSetBypass (VstOpCodeArguments args)
  1607. {
  1608. isBypassed = (args.value != 0);
  1609. if (auto* bypass = processor->getBypassParameter())
  1610. bypass->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  1611. return 1;
  1612. }
  1613. pointer_sized_int handleGetPlugInName (VstOpCodeArguments args)
  1614. {
  1615. String (JucePlugin_Name).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1616. return 1;
  1617. }
  1618. pointer_sized_int handleGetManufacturerName (VstOpCodeArguments args)
  1619. {
  1620. String (JucePlugin_Manufacturer).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1621. return 1;
  1622. }
  1623. pointer_sized_int handleGetManufacturerVersion (VstOpCodeArguments)
  1624. {
  1625. return convertHexVersionToDecimal (JucePlugin_VersionCode);
  1626. }
  1627. pointer_sized_int handleManufacturerSpecific (VstOpCodeArguments args)
  1628. {
  1629. if (handleManufacturerSpecificVST2Opcode (args.index, args.value, args.ptr, args.opt))
  1630. return 1;
  1631. if (args.index == JUCE_MULTICHAR_CONSTANT ('P', 'r', 'e', 'S')
  1632. && args.value == JUCE_MULTICHAR_CONSTANT ('A', 'e', 'C', 's'))
  1633. return handleSetContentScaleFactor (args.opt);
  1634. if (args.index == Vst2::effGetParamDisplay)
  1635. return handleCockosGetParameterText (args.value, args.ptr, args.opt);
  1636. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1637. return callbackHandler->handleVstManufacturerSpecific (args.index, args.value, args.ptr, args.opt);
  1638. return 0;
  1639. }
  1640. pointer_sized_int handleCanPlugInDo (VstOpCodeArguments args)
  1641. {
  1642. auto text = (const char*) args.ptr;
  1643. auto matches = [=](const char* s) { return strcmp (text, s) == 0; };
  1644. if (matches ("receiveVstEvents")
  1645. || matches ("receiveVstMidiEvent")
  1646. || matches ("receiveVstMidiEvents"))
  1647. {
  1648. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1649. return 1;
  1650. #else
  1651. return -1;
  1652. #endif
  1653. }
  1654. if (matches ("sendVstEvents")
  1655. || matches ("sendVstMidiEvent")
  1656. || matches ("sendVstMidiEvents"))
  1657. {
  1658. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1659. return 1;
  1660. #else
  1661. return -1;
  1662. #endif
  1663. }
  1664. if (matches ("receiveVstTimeInfo")
  1665. || matches ("conformsToWindowRules")
  1666. || matches ("supportsViewDpiScaling")
  1667. || matches ("bypass"))
  1668. {
  1669. return 1;
  1670. }
  1671. // This tells Wavelab to use the UI thread to invoke open/close,
  1672. // like all other hosts do.
  1673. if (matches ("openCloseAnyThread"))
  1674. return -1;
  1675. if (matches ("MPE"))
  1676. return processor->supportsMPE() ? 1 : 0;
  1677. #if JUCE_MAC
  1678. if (matches ("hasCockosViewAsConfig"))
  1679. {
  1680. useNSView = true;
  1681. return (int32) 0xbeef0000;
  1682. }
  1683. #endif
  1684. if (matches ("hasCockosExtensions"))
  1685. return (int32) 0xbeef0000;
  1686. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1687. return callbackHandler->handleVstPluginCanDo (args.index, args.value, args.ptr, args.opt);
  1688. return 0;
  1689. }
  1690. pointer_sized_int handleGetTailSize (VstOpCodeArguments)
  1691. {
  1692. if (processor != nullptr)
  1693. {
  1694. int32 result;
  1695. auto tailSeconds = processor->getTailLengthSeconds();
  1696. if (tailSeconds == std::numeric_limits<double>::infinity())
  1697. result = std::numeric_limits<int32>::max();
  1698. else
  1699. result = static_cast<int32> (tailSeconds * sampleRate);
  1700. return result; // Vst2 expects an int32 upcasted to a intptr_t here
  1701. }
  1702. return 0;
  1703. }
  1704. pointer_sized_int handleKeyboardFocusRequired (VstOpCodeArguments)
  1705. {
  1706. return (JucePlugin_EditorRequiresKeyboardFocus != 0) ? 1 : 0;
  1707. }
  1708. pointer_sized_int handleGetVstInterfaceVersion (VstOpCodeArguments)
  1709. {
  1710. return kVstVersion;
  1711. }
  1712. pointer_sized_int handleGetCurrentMidiProgram (VstOpCodeArguments)
  1713. {
  1714. return -1;
  1715. }
  1716. pointer_sized_int handleGetSpeakerConfiguration (VstOpCodeArguments args)
  1717. {
  1718. auto** pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.value);
  1719. auto** pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.ptr);
  1720. if (pluginHasSidechainsOrAuxs() || processor->isMidiEffect())
  1721. return false;
  1722. auto inputLayout = processor->getChannelLayoutOfBus (true, 0);
  1723. auto outputLayout = processor->getChannelLayoutOfBus (false, 0);
  1724. auto speakerBaseSize = sizeof (Vst2::VstSpeakerArrangement) - (sizeof (Vst2::VstSpeakerProperties) * 8);
  1725. cachedInArrangement .malloc (speakerBaseSize + (static_cast<std::size_t> (inputLayout. size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1726. cachedOutArrangement.malloc (speakerBaseSize + (static_cast<std::size_t> (outputLayout.size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1727. *pluginInput = cachedInArrangement. getData();
  1728. *pluginOutput = cachedOutArrangement.getData();
  1729. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (true, 0), **pluginInput);
  1730. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (false, 0), **pluginOutput);
  1731. return 1;
  1732. }
  1733. pointer_sized_int handleSetNumberOfSamplesToProcess (VstOpCodeArguments args)
  1734. {
  1735. return args.value;
  1736. }
  1737. pointer_sized_int handleSetSampleFloatType (VstOpCodeArguments args)
  1738. {
  1739. if (! isProcessing)
  1740. {
  1741. if (processor != nullptr)
  1742. {
  1743. processor->setProcessingPrecision ((args.value == Vst2::kVstProcessPrecision64
  1744. && processor->supportsDoublePrecisionProcessing())
  1745. ? AudioProcessor::doublePrecision
  1746. : AudioProcessor::singlePrecision);
  1747. return 1;
  1748. }
  1749. }
  1750. return 0;
  1751. }
  1752. pointer_sized_int handleSetContentScaleFactor (float scale)
  1753. {
  1754. #if ! JUCE_MAC
  1755. if (! approximatelyEqual (scale, editorScaleFactor))
  1756. {
  1757. editorScaleFactor = scale;
  1758. if (editorComp != nullptr)
  1759. #if JUCE_WINDOWS && ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  1760. if (auto* ed = editorComp->getEditorComp())
  1761. ed->setScaleFactor (scale);
  1762. #else
  1763. editorComp->updateWindowSize (true);
  1764. #endif
  1765. }
  1766. #else
  1767. ignoreUnused (scale);
  1768. #endif
  1769. return 1;
  1770. }
  1771. pointer_sized_int handleCockosGetParameterText (pointer_sized_int paramIndex,
  1772. void* dest,
  1773. float value)
  1774. {
  1775. if (processor != nullptr && dest != nullptr)
  1776. {
  1777. if (auto* param = juceParameters.getParamForIndex ((int) paramIndex))
  1778. {
  1779. if (! LegacyAudioParameter::isLegacy (param))
  1780. {
  1781. String text (param->getText (value, 1024));
  1782. memcpy (dest, text.toRawUTF8(), ((size_t) text.length()) + 1);
  1783. return 0xbeef;
  1784. }
  1785. }
  1786. }
  1787. return 0;
  1788. }
  1789. //==============================================================================
  1790. pointer_sized_int handleGetNumMidiInputChannels()
  1791. {
  1792. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1793. return 16;
  1794. #else
  1795. return 0;
  1796. #endif
  1797. }
  1798. pointer_sized_int handleGetNumMidiOutputChannels()
  1799. {
  1800. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1801. return 16;
  1802. #else
  1803. return 0;
  1804. #endif
  1805. }
  1806. //==============================================================================
  1807. Vst2::audioMasterCallback hostCallback;
  1808. AudioProcessor* processor = {};
  1809. double sampleRate = 44100.0;
  1810. int32 blockSize = 1024;
  1811. Vst2::AEffect vstEffect;
  1812. juce::MemoryBlock chunkMemory;
  1813. juce::uint32 chunkMemoryTime = 0;
  1814. std::unique_ptr<EditorCompWrapper> editorComp;
  1815. Vst2::ERect editorBounds;
  1816. MidiBuffer midiEvents;
  1817. VSTMidiEventList outgoingEvents;
  1818. #if ! JUCE_MAC
  1819. float editorScaleFactor = 1.0f;
  1820. #endif
  1821. LegacyAudioParametersWrapper juceParameters;
  1822. bool isProcessing = false, isBypassed = false, hasShutdown = false;
  1823. bool firstProcessCallback = true, shouldDeleteEditor = false;
  1824. #if JUCE_64BIT
  1825. bool useNSView = true;
  1826. #else
  1827. bool useNSView = false;
  1828. #endif
  1829. VstTempBuffers<float> floatTempBuffers;
  1830. VstTempBuffers<double> doubleTempBuffers;
  1831. int maxNumInChannels = 0, maxNumOutChannels = 0;
  1832. HeapBlock<Vst2::VstSpeakerArrangement> cachedInArrangement, cachedOutArrangement;
  1833. ThreadLocalValue<bool> inParameterChangedCallback;
  1834. //==============================================================================
  1835. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1836. };
  1837. //==============================================================================
  1838. namespace
  1839. {
  1840. Vst2::AEffect* pluginEntryPoint (Vst2::audioMasterCallback audioMaster)
  1841. {
  1842. JUCE_AUTORELEASEPOOL
  1843. {
  1844. initialiseJuce_GUI();
  1845. try
  1846. {
  1847. if (audioMaster (0, Vst2::audioMasterVersion, 0, 0, 0, 0) != 0)
  1848. {
  1849. #if JUCE_LINUX
  1850. MessageManagerLock mmLock;
  1851. #endif
  1852. auto* processor = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1853. auto* wrapper = new JuceVSTWrapper (audioMaster, processor);
  1854. auto* aEffect = wrapper->getAEffect();
  1855. if (auto* callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1856. {
  1857. callbackHandler->handleVstHostCallbackAvailable ([audioMaster, aEffect](int32 opcode, int32 index, pointer_sized_int value, void* ptr, float opt)
  1858. {
  1859. return audioMaster (aEffect, opcode, index, value, ptr, opt);
  1860. });
  1861. }
  1862. return aEffect;
  1863. }
  1864. }
  1865. catch (...)
  1866. {}
  1867. }
  1868. return nullptr;
  1869. }
  1870. }
  1871. #if ! JUCE_WINDOWS
  1872. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1873. #endif
  1874. //==============================================================================
  1875. // Mac startup code..
  1876. #if JUCE_MAC
  1877. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1878. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1879. {
  1880. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1881. initialiseMacVST();
  1882. return pluginEntryPoint (audioMaster);
  1883. }
  1884. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster);
  1885. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster)
  1886. {
  1887. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1888. initialiseMacVST();
  1889. return pluginEntryPoint (audioMaster);
  1890. }
  1891. //==============================================================================
  1892. // Linux startup code..
  1893. #elif JUCE_LINUX
  1894. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1895. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1896. {
  1897. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1898. SharedMessageThread::getInstance();
  1899. return pluginEntryPoint (audioMaster);
  1900. }
  1901. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster) asm ("main");
  1902. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster)
  1903. {
  1904. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1905. return VSTPluginMain (audioMaster);
  1906. }
  1907. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1908. __attribute__((constructor)) void myPluginInit() {}
  1909. __attribute__((destructor)) void myPluginFini() {}
  1910. //==============================================================================
  1911. // Win32 startup code..
  1912. #else
  1913. extern "C" __declspec (dllexport) Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1914. {
  1915. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1916. return pluginEntryPoint (audioMaster);
  1917. }
  1918. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1919. extern "C" __declspec (dllexport) int main (Vst2::audioMasterCallback audioMaster)
  1920. {
  1921. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1922. return (int) pluginEntryPoint (audioMaster);
  1923. }
  1924. #endif
  1925. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1926. {
  1927. if (reason == DLL_PROCESS_ATTACH)
  1928. Process::setCurrentModuleInstanceHandle (instance);
  1929. return true;
  1930. }
  1931. #endif
  1932. #endif