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.

2418 lines
91KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../../juce_core/system/juce_TargetPlatform.h"
  20. #include "../utility/juce_CheckSettingMacros.h"
  21. #if JucePlugin_Build_VST
  22. #ifdef _MSC_VER
  23. #pragma warning (disable : 4996 4100)
  24. #endif
  25. #include "../utility/juce_IncludeSystemHeaders.h"
  26. #include <juce_core/juce_core.h>
  27. #if JucePlugin_VersionCode < 0x010000 // Major < 0
  28. #if (JucePlugin_VersionCode & 0x00FF00) > (9 * 0x100) // check if Minor number exceeeds 9
  29. JUCE_COMPILER_WARNING ("When version has 'major' = 0, VST2 has trouble displaying 'minor' exceeding 9")
  30. #endif
  31. #if (JucePlugin_VersionCode & 0xFF) > 9 // check if Bugfix number exceeeds 9
  32. JUCE_COMPILER_WARNING ("When version has 'major' = 0, VST2 has trouble displaying 'bugfix' exceeding 9")
  33. #endif
  34. #elif JucePlugin_VersionCode >= 0x650000 // Major >= 101
  35. #if (JucePlugin_VersionCode & 0x00FF00) > (99 * 0x100) // check if Minor number exceeeds 99
  36. JUCE_COMPILER_WARNING ("When version has 'major' > 100, VST2 has trouble displaying 'minor' exceeding 99")
  37. #endif
  38. #if (JucePlugin_VersionCode & 0xFF) > 99 // check if Bugfix number exceeeds 99
  39. JUCE_COMPILER_WARNING ("When version has 'major' > 100, VST2 has trouble displaying 'bugfix' exceeding 99")
  40. #endif
  41. #endif
  42. #ifdef PRAGMA_ALIGN_SUPPORTED
  43. #undef PRAGMA_ALIGN_SUPPORTED
  44. #define PRAGMA_ALIGN_SUPPORTED 1
  45. #endif
  46. #ifndef _MSC_VER
  47. #define __cdecl
  48. #endif
  49. #if JUCE_CLANG
  50. #pragma clang diagnostic push
  51. #pragma clang diagnostic ignored "-Wconversion"
  52. #pragma clang diagnostic ignored "-Wshadow"
  53. #pragma clang diagnostic ignored "-Wdeprecated-register"
  54. #pragma clang diagnostic ignored "-Wunused-parameter"
  55. #pragma clang diagnostic ignored "-Wdeprecated-writable-strings"
  56. #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  57. #endif
  58. #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. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1022. wrapper.editorScaleFactor = static_cast<float> (Desktop::getInstance().getDisplays().getMainDisplay().scale);
  1023. #endif
  1024. #endif
  1025. ignoreUnused (fakeMouseGenerator);
  1026. }
  1027. ~EditorCompWrapper()
  1028. {
  1029. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  1030. // have been transferred to another parent which takes over ownership.
  1031. }
  1032. void paint (Graphics&) override {}
  1033. void getEditorBounds (Vst2::ERect& bounds)
  1034. {
  1035. auto b = getSizeToContainChild();
  1036. bounds.top = 0;
  1037. bounds.left = 0;
  1038. bounds.bottom = (int16) b.getHeight();
  1039. bounds.right = (int16) b.getWidth();
  1040. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1041. bounds.bottom = (int16) roundToInt (bounds.bottom * wrapper.editorScaleFactor);
  1042. bounds.right = (int16) roundToInt (bounds.right * wrapper.editorScaleFactor);
  1043. #endif
  1044. }
  1045. void attachToHost (VstOpCodeArguments args)
  1046. {
  1047. setOpaque (true);
  1048. setVisible (false);
  1049. #if JUCE_WINDOWS
  1050. addToDesktop (0, args.ptr);
  1051. hostWindow = (HWND) args.ptr;
  1052. if (auto* ed = getEditorComp())
  1053. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1054. if (auto* peer = ed->getPeer())
  1055. wrapper.editorScaleFactor = (float) peer->getPlatformScaleFactor();
  1056. #else
  1057. ed->setScaleFactor (wrapper.editorScaleFactor);
  1058. #endif
  1059. #elif JUCE_LINUX
  1060. addToDesktop (0, args.ptr);
  1061. hostWindow = (Window) args.ptr;
  1062. XReparentWindow (display.display, (Window) getWindowHandle(), hostWindow, 0, 0);
  1063. #else
  1064. hostWindow = attachComponentToWindowRefVST (this, args.ptr, wrapper.useNSView);
  1065. #endif
  1066. setVisible (true);
  1067. }
  1068. void detachHostWindow()
  1069. {
  1070. #if JUCE_MAC
  1071. if (hostWindow != 0)
  1072. {
  1073. detachComponentFromWindowRefVST (this, hostWindow, wrapper.useNSView);
  1074. hostWindow = 0;
  1075. }
  1076. #endif
  1077. #if JUCE_LINUX
  1078. hostWindow = 0;
  1079. #endif
  1080. }
  1081. void checkVisibility()
  1082. {
  1083. #if JUCE_MAC
  1084. if (hostWindow != 0)
  1085. checkWindowVisibilityVST (hostWindow, this, wrapper.useNSView);
  1086. #endif
  1087. }
  1088. AudioProcessorEditor* getEditorComp() const noexcept
  1089. {
  1090. return dynamic_cast<AudioProcessorEditor*> (getChildComponent(0));
  1091. }
  1092. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1093. void checkScaleFactorIsCorrect()
  1094. {
  1095. if (auto* peer = getEditorComp()->getPeer())
  1096. {
  1097. auto peerScaleFactor = (float) peer->getPlatformScaleFactor();
  1098. if (! approximatelyEqual (peerScaleFactor, wrapper.editorScaleFactor))
  1099. wrapper.handleSetContentScaleFactor (peerScaleFactor);
  1100. }
  1101. }
  1102. #endif
  1103. void resized() override
  1104. {
  1105. if (auto* ed = getEditorComp())
  1106. {
  1107. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1108. checkScaleFactorIsCorrect();
  1109. #endif
  1110. ed->setTopLeftPosition (0, 0);
  1111. if (shouldResizeEditor)
  1112. ed->setBounds (ed->getLocalArea (this, getLocalBounds()));
  1113. updateWindowSize (false);
  1114. }
  1115. #if JUCE_MAC && ! JUCE_64BIT
  1116. if (! wrapper.useNSView)
  1117. updateEditorCompBoundsVST (this);
  1118. #endif
  1119. }
  1120. void childBoundsChanged (Component*) override
  1121. {
  1122. updateWindowSize (false);
  1123. }
  1124. juce::Rectangle<int> getSizeToContainChild()
  1125. {
  1126. if (auto* ed = getEditorComp())
  1127. return getLocalArea (ed, ed->getLocalBounds());
  1128. return {};
  1129. }
  1130. void updateWindowSize (bool resizeEditor)
  1131. {
  1132. if (! isInSizeWindow)
  1133. {
  1134. if (auto* ed = getEditorComp())
  1135. {
  1136. ed->setTopLeftPosition (0, 0);
  1137. auto pos = getSizeToContainChild();
  1138. #if JUCE_MAC
  1139. if (wrapper.useNSView)
  1140. setTopLeftPosition (0, getHeight() - pos.getHeight());
  1141. #endif
  1142. resizeHostWindow (pos.getWidth(), pos.getHeight());
  1143. #if ! JUCE_LINUX // setSize() on linux causes renoise and energyxt to fail.
  1144. if (! resizeEditor) // this is needed to prevent an infinite resizing loop due to coordinate rounding
  1145. shouldResizeEditor = false;
  1146. setSize (pos.getWidth(), pos.getHeight());
  1147. shouldResizeEditor = true;
  1148. #else
  1149. ignoreUnused (resizeEditor);
  1150. XResizeWindow (display.display, (Window) getWindowHandle(),
  1151. static_cast<unsigned int> (roundToInt (pos.getWidth() * wrapper.editorScaleFactor)),
  1152. static_cast<unsigned int> (roundToInt (pos.getHeight() * wrapper.editorScaleFactor)));
  1153. #endif
  1154. #if JUCE_MAC
  1155. resizeHostWindow (pos.getWidth(), pos.getHeight()); // (doing this a second time seems to be necessary in tracktion)
  1156. #endif
  1157. }
  1158. }
  1159. }
  1160. void resizeHostWindow (int newWidth, int newHeight)
  1161. {
  1162. bool sizeWasSuccessful = false;
  1163. if (auto host = wrapper.hostCallback)
  1164. {
  1165. auto status = host (wrapper.getAEffect(), Vst2::audioMasterCanDo, 0, 0, const_cast<char*> ("sizeWindow"), 0);
  1166. if (status == (pointer_sized_int) 1 || getHostType().isAbletonLive())
  1167. {
  1168. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1169. newWidth = roundToInt (newWidth * wrapper.editorScaleFactor);
  1170. newHeight = roundToInt (newHeight * wrapper.editorScaleFactor);
  1171. #endif
  1172. const ScopedValueSetter<bool> inSizeWindowSetter (isInSizeWindow, true);
  1173. sizeWasSuccessful = (host (wrapper.getAEffect(), Vst2::audioMasterSizeWindow,
  1174. newWidth, newHeight, 0, 0) != 0);
  1175. }
  1176. }
  1177. if (! sizeWasSuccessful)
  1178. {
  1179. // some hosts don't support the sizeWindow call, so do it manually..
  1180. #if JUCE_MAC
  1181. setNativeHostWindowSizeVST (hostWindow, this, newWidth, newHeight, wrapper.useNSView);
  1182. #elif JUCE_LINUX
  1183. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  1184. setSize (newWidth, newHeight);
  1185. #else
  1186. int dw = 0;
  1187. int dh = 0;
  1188. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  1189. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1190. newWidth = roundToInt (newWidth * wrapper.editorScaleFactor);
  1191. newHeight = roundToInt (newHeight * wrapper.editorScaleFactor);
  1192. #endif
  1193. HWND w = (HWND) getWindowHandle();
  1194. while (w != 0)
  1195. {
  1196. HWND parent = getWindowParent (w);
  1197. if (parent == 0)
  1198. break;
  1199. TCHAR windowType [32] = { 0 };
  1200. GetClassName (parent, windowType, 31);
  1201. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  1202. break;
  1203. RECT windowPos, parentPos;
  1204. GetWindowRect (w, &windowPos);
  1205. GetWindowRect (parent, &parentPos);
  1206. if (w != (HWND) getWindowHandle())
  1207. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1208. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1209. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1210. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1211. w = parent;
  1212. if (dw == 2 * frameThickness)
  1213. break;
  1214. if (dw > 100 || dh > 100)
  1215. w = 0;
  1216. }
  1217. if (w != 0)
  1218. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1219. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1220. #endif
  1221. }
  1222. if (auto* peer = getPeer())
  1223. {
  1224. peer->handleMovedOrResized();
  1225. repaint();
  1226. }
  1227. }
  1228. #if JUCE_WINDOWS
  1229. void mouseDown (const MouseEvent&) override
  1230. {
  1231. broughtToFront();
  1232. }
  1233. void broughtToFront() override
  1234. {
  1235. // for hosts like nuendo, need to also pop the MDI container to the
  1236. // front when our comp is clicked on.
  1237. if (! isCurrentlyBlockedByAnotherModalComponent())
  1238. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  1239. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1240. }
  1241. #endif
  1242. #if JUCE_MAC
  1243. bool keyPressed (const KeyPress&) override
  1244. {
  1245. // If we have an unused keypress, move the key-focus to a host window
  1246. // and re-inject the event..
  1247. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1248. }
  1249. #endif
  1250. //==============================================================================
  1251. JuceVSTWrapper& wrapper;
  1252. FakeMouseMoveGenerator fakeMouseGenerator;
  1253. bool isInSizeWindow = false;
  1254. bool shouldResizeEditor = true;
  1255. #if JUCE_MAC
  1256. void* hostWindow = {};
  1257. #elif JUCE_LINUX
  1258. ScopedXDisplay display;
  1259. Window hostWindow = {};
  1260. #else
  1261. HWND hostWindow = {};
  1262. WindowsHooks hooks;
  1263. #endif
  1264. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1265. };
  1266. //==============================================================================
  1267. private:
  1268. static JuceVSTWrapper* getWrapper (Vst2::AEffect* v) noexcept { return static_cast<JuceVSTWrapper*> (v->object); }
  1269. bool isProcessLevelOffline()
  1270. {
  1271. return hostCallback != nullptr
  1272. && (int32) hostCallback (&vstEffect, Vst2::audioMasterGetCurrentProcessLevel, 0, 0, 0, 0) == 4;
  1273. }
  1274. static inline int32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1275. {
  1276. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1277. return (int32) hexVersion;
  1278. #else
  1279. // Currently, only Cubase displays the version number to the user
  1280. // We are hoping here that when other DAWs start to display the version
  1281. // number, that they do so according to yfede's encoding table in the link
  1282. // below. If not, then this code will need an if (isSteinberg()) in the
  1283. // future.
  1284. int major = (hexVersion >> 16) & 0xff;
  1285. int minor = (hexVersion >> 8) & 0xff;
  1286. int bugfix = hexVersion & 0xff;
  1287. // for details, see: https://forum.juce.com/t/issues-with-version-integer-reported-by-vst2/23867
  1288. // Encoding B
  1289. if (major < 1)
  1290. return major * 1000 + minor * 100 + bugfix * 10;
  1291. // Encoding E
  1292. if (major > 100)
  1293. return major * 10000000 + minor * 100000 + bugfix * 1000;
  1294. // Encoding D
  1295. return static_cast<int32> (hexVersion);
  1296. #endif
  1297. }
  1298. //==============================================================================
  1299. #if JUCE_WINDOWS
  1300. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1301. static void checkWhetherMessageThreadIsCorrect()
  1302. {
  1303. auto host = getHostType();
  1304. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1305. {
  1306. if (! messageThreadIsDefinitelyCorrect)
  1307. {
  1308. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1309. struct MessageThreadCallback : public CallbackMessage
  1310. {
  1311. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1312. void messageCallback() override { triggered = true; }
  1313. bool& triggered;
  1314. };
  1315. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1316. }
  1317. }
  1318. }
  1319. #else
  1320. static void checkWhetherMessageThreadIsCorrect() {}
  1321. #endif
  1322. //==============================================================================
  1323. template <typename FloatType>
  1324. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1325. {
  1326. tmpBuffers.release();
  1327. if (processor != nullptr)
  1328. tmpBuffers.tempChannels.insertMultiple (0, nullptr, vstEffect.numInputs
  1329. + vstEffect.numOutputs);
  1330. }
  1331. void deleteTempChannels()
  1332. {
  1333. deleteTempChannels (floatTempBuffers);
  1334. deleteTempChannels (doubleTempBuffers);
  1335. }
  1336. //==============================================================================
  1337. void findMaxTotalChannels (int& maxTotalIns, int& maxTotalOuts)
  1338. {
  1339. #ifdef JucePlugin_PreferredChannelConfigurations
  1340. int configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1341. maxTotalIns = maxTotalOuts = 0;
  1342. for (auto& config : configs)
  1343. {
  1344. maxTotalIns = jmax (maxTotalIns, config[0]);
  1345. maxTotalOuts = jmax (maxTotalOuts, config[1]);
  1346. }
  1347. #else
  1348. auto numInputBuses = processor->getBusCount (true);
  1349. auto numOutputBuses = processor->getBusCount (false);
  1350. if (numInputBuses > 1 || numOutputBuses > 1)
  1351. {
  1352. maxTotalIns = maxTotalOuts = 0;
  1353. for (int i = 0; i < numInputBuses; ++i)
  1354. maxTotalIns += processor->getChannelCountOfBus (true, i);
  1355. for (int i = 0; i < numOutputBuses; ++i)
  1356. maxTotalOuts += processor->getChannelCountOfBus (false, i);
  1357. }
  1358. else
  1359. {
  1360. maxTotalIns = numInputBuses > 0 ? processor->getBus (true, 0)->getMaxSupportedChannels (64) : 0;
  1361. maxTotalOuts = numOutputBuses > 0 ? processor->getBus (false, 0)->getMaxSupportedChannels (64) : 0;
  1362. }
  1363. #endif
  1364. }
  1365. bool pluginHasSidechainsOrAuxs() const { return (processor->getBusCount (true) > 1 || processor->getBusCount (false) > 1); }
  1366. //==============================================================================
  1367. /** Host to plug-in calls. */
  1368. pointer_sized_int handleOpen (VstOpCodeArguments)
  1369. {
  1370. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1371. if (processor->hasEditor())
  1372. vstEffect.flags |= Vst2::effFlagsHasEditor;
  1373. else
  1374. vstEffect.flags &= ~Vst2::effFlagsHasEditor;
  1375. return 0;
  1376. }
  1377. pointer_sized_int handleClose (VstOpCodeArguments)
  1378. {
  1379. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1380. stopTimer();
  1381. if (MessageManager::getInstance()->isThisTheMessageThread())
  1382. deleteEditor (false);
  1383. return 0;
  1384. }
  1385. pointer_sized_int handleSetCurrentProgram (VstOpCodeArguments args)
  1386. {
  1387. if (processor != nullptr && isPositiveAndBelow ((int) args.value, processor->getNumPrograms()))
  1388. processor->setCurrentProgram ((int) args.value);
  1389. return 0;
  1390. }
  1391. pointer_sized_int handleGetCurrentProgram (VstOpCodeArguments)
  1392. {
  1393. return (processor != nullptr && processor->getNumPrograms() > 0 ? processor->getCurrentProgram() : 0);
  1394. }
  1395. pointer_sized_int handleSetCurrentProgramName (VstOpCodeArguments args)
  1396. {
  1397. if (processor != nullptr && processor->getNumPrograms() > 0)
  1398. processor->changeProgramName (processor->getCurrentProgram(), (char*) args.ptr);
  1399. return 0;
  1400. }
  1401. pointer_sized_int handleGetCurrentProgramName (VstOpCodeArguments args)
  1402. {
  1403. if (processor != nullptr && processor->getNumPrograms() > 0)
  1404. processor->getProgramName (processor->getCurrentProgram()).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1405. return 0;
  1406. }
  1407. pointer_sized_int handleGetParameterLabel (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->getLabel().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1413. }
  1414. return 0;
  1415. }
  1416. pointer_sized_int handleGetParameterText (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->getCurrentValueAsText().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1422. }
  1423. return 0;
  1424. }
  1425. pointer_sized_int handleGetParameterName (VstOpCodeArguments args)
  1426. {
  1427. if (auto* param = juceParameters.getParamForIndex (args.index))
  1428. {
  1429. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1430. param->getName (32).copyToUTF8 ((char*) args.ptr, 32 + 1);
  1431. }
  1432. return 0;
  1433. }
  1434. pointer_sized_int handleSetSampleRate (VstOpCodeArguments args)
  1435. {
  1436. sampleRate = args.opt;
  1437. return 0;
  1438. }
  1439. pointer_sized_int handleSetBlockSize (VstOpCodeArguments args)
  1440. {
  1441. blockSize = (int32) args.value;
  1442. return 0;
  1443. }
  1444. pointer_sized_int handleResumeSuspend (VstOpCodeArguments args)
  1445. {
  1446. if (args.value)
  1447. resume();
  1448. else
  1449. suspend();
  1450. return 0;
  1451. }
  1452. pointer_sized_int handleGetEditorBounds (VstOpCodeArguments args)
  1453. {
  1454. checkWhetherMessageThreadIsCorrect();
  1455. const MessageManagerLock mmLock;
  1456. createEditorComp();
  1457. if (editorComp != nullptr)
  1458. {
  1459. editorComp->getEditorBounds (editorBounds);
  1460. *((Vst2::ERect**) args.ptr) = &editorBounds;
  1461. return (pointer_sized_int) &editorBounds;
  1462. }
  1463. return 0;
  1464. }
  1465. pointer_sized_int handleOpenEditor (VstOpCodeArguments args)
  1466. {
  1467. checkWhetherMessageThreadIsCorrect();
  1468. const MessageManagerLock mmLock;
  1469. jassert (! recursionCheck);
  1470. startTimerHz (4); // performs misc housekeeping chores
  1471. deleteEditor (true);
  1472. createEditorComp();
  1473. if (editorComp != nullptr)
  1474. {
  1475. editorComp->attachToHost (args);
  1476. return 1;
  1477. }
  1478. return 0;
  1479. }
  1480. pointer_sized_int handleCloseEditor (VstOpCodeArguments)
  1481. {
  1482. checkWhetherMessageThreadIsCorrect();
  1483. const MessageManagerLock mmLock;
  1484. deleteEditor (true);
  1485. return 0;
  1486. }
  1487. pointer_sized_int handleGetData (VstOpCodeArguments args)
  1488. {
  1489. if (processor == nullptr)
  1490. return 0;
  1491. auto data = (void**) args.ptr;
  1492. bool onlyStoreCurrentProgramData = (args.index != 0);
  1493. chunkMemory.reset();
  1494. if (onlyStoreCurrentProgramData)
  1495. processor->getCurrentProgramStateInformation (chunkMemory);
  1496. else
  1497. processor->getStateInformation (chunkMemory);
  1498. *data = (void*) chunkMemory.getData();
  1499. // because the chunk is only needed temporarily by the host (or at least you'd
  1500. // hope so) we'll give it a while and then free it in the timer callback.
  1501. chunkMemoryTime = juce::Time::getApproximateMillisecondCounter();
  1502. return (int32) chunkMemory.getSize();
  1503. }
  1504. pointer_sized_int handleSetData (VstOpCodeArguments args)
  1505. {
  1506. if (processor != nullptr)
  1507. {
  1508. void* data = args.ptr;
  1509. int32 byteSize = (int32) args.value;
  1510. bool onlyRestoreCurrentProgramData = (args.index != 0);
  1511. chunkMemory.reset();
  1512. chunkMemoryTime = 0;
  1513. if (byteSize > 0 && data != nullptr)
  1514. {
  1515. if (onlyRestoreCurrentProgramData)
  1516. processor->setCurrentProgramStateInformation (data, byteSize);
  1517. else
  1518. processor->setStateInformation (data, byteSize);
  1519. }
  1520. }
  1521. return 0;
  1522. }
  1523. pointer_sized_int handlePreAudioProcessingEvents (VstOpCodeArguments args)
  1524. {
  1525. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1526. VSTMidiEventList::addEventsToMidiBuffer ((Vst2::VstEvents*) args.ptr, midiEvents);
  1527. return 1;
  1528. #else
  1529. ignoreUnused (args);
  1530. return 0;
  1531. #endif
  1532. }
  1533. pointer_sized_int handleIsParameterAutomatable (VstOpCodeArguments args)
  1534. {
  1535. if (auto* param = juceParameters.getParamForIndex (args.index))
  1536. {
  1537. const bool isMeter = (((param->getCategory() & 0xffff0000) >> 16) == 2);
  1538. return (param->isAutomatable() && (! isMeter) ? 1 : 0);
  1539. }
  1540. return 0;
  1541. }
  1542. pointer_sized_int handleParameterValueForText (VstOpCodeArguments args)
  1543. {
  1544. if (auto* param = juceParameters.getParamForIndex (args.index))
  1545. {
  1546. if (! LegacyAudioParameter::isLegacy (param))
  1547. {
  1548. auto value = param->getValueForText (String::fromUTF8 ((char*) args.ptr));
  1549. param->setValue (value);
  1550. inParameterChangedCallback = true;
  1551. param->sendValueChangedMessageToListeners (value);
  1552. return 1;
  1553. }
  1554. }
  1555. return 0;
  1556. }
  1557. pointer_sized_int handleGetProgramName (VstOpCodeArguments args)
  1558. {
  1559. if (processor != nullptr && isPositiveAndBelow (args.index, processor->getNumPrograms()))
  1560. {
  1561. processor->getProgramName (args.index).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1562. return 1;
  1563. }
  1564. return 0;
  1565. }
  1566. pointer_sized_int handleGetInputPinProperties (VstOpCodeArguments args)
  1567. {
  1568. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, true, args.index)) ? 1 : 0;
  1569. }
  1570. pointer_sized_int handleGetOutputPinProperties (VstOpCodeArguments args)
  1571. {
  1572. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, false, args.index)) ? 1 : 0;
  1573. }
  1574. pointer_sized_int handleGetPlugInCategory (VstOpCodeArguments)
  1575. {
  1576. return Vst2::JucePlugin_VSTCategory;
  1577. }
  1578. pointer_sized_int handleSetSpeakerConfiguration (VstOpCodeArguments args)
  1579. {
  1580. auto* pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.value);
  1581. auto* pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.ptr);
  1582. if (processor->isMidiEffect())
  1583. return 0;
  1584. auto numIns = processor->getBusCount (true);
  1585. auto numOuts = processor->getBusCount (false);
  1586. if (pluginInput != nullptr && pluginInput->type >= 0)
  1587. {
  1588. // inconsistent request?
  1589. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput).size() != pluginInput->numChannels)
  1590. return 0;
  1591. }
  1592. if (pluginOutput != nullptr && pluginOutput->type >= 0)
  1593. {
  1594. // inconsistent request?
  1595. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput).size() != pluginOutput->numChannels)
  1596. return 0;
  1597. }
  1598. if (pluginInput != nullptr && pluginInput->numChannels > 0 && numIns == 0)
  1599. return 0;
  1600. if (pluginOutput != nullptr && pluginOutput->numChannels > 0 && numOuts == 0)
  1601. return 0;
  1602. auto layouts = processor->getBusesLayout();
  1603. if (pluginInput != nullptr && pluginInput-> numChannels >= 0 && numIns > 0)
  1604. layouts.getChannelSet (true, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  1605. if (pluginOutput != nullptr && pluginOutput->numChannels >= 0 && numOuts > 0)
  1606. layouts.getChannelSet (false, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  1607. #ifdef JucePlugin_PreferredChannelConfigurations
  1608. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1609. if (! AudioProcessor::containsLayout (layouts, configs))
  1610. return 0;
  1611. #endif
  1612. return processor->setBusesLayout (layouts) ? 1 : 0;
  1613. }
  1614. pointer_sized_int handleSetBypass (VstOpCodeArguments args)
  1615. {
  1616. isBypassed = (args.value != 0);
  1617. if (auto* bypass = processor->getBypassParameter())
  1618. bypass->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  1619. return 1;
  1620. }
  1621. pointer_sized_int handleGetPlugInName (VstOpCodeArguments args)
  1622. {
  1623. String (JucePlugin_Name).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1624. return 1;
  1625. }
  1626. pointer_sized_int handleGetManufacturerName (VstOpCodeArguments args)
  1627. {
  1628. String (JucePlugin_Manufacturer).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1629. return 1;
  1630. }
  1631. pointer_sized_int handleGetManufacturerVersion (VstOpCodeArguments)
  1632. {
  1633. return convertHexVersionToDecimal (JucePlugin_VersionCode);
  1634. }
  1635. pointer_sized_int handleManufacturerSpecific (VstOpCodeArguments args)
  1636. {
  1637. if (handleManufacturerSpecificVST2Opcode (args.index, args.value, args.ptr, args.opt))
  1638. return 1;
  1639. if (args.index == JUCE_MULTICHAR_CONSTANT ('P', 'r', 'e', 'S')
  1640. && args.value == JUCE_MULTICHAR_CONSTANT ('A', 'e', 'C', 's'))
  1641. return handleSetContentScaleFactor (args.opt);
  1642. if (args.index == Vst2::effGetParamDisplay)
  1643. return handleCockosGetParameterText (args.value, args.ptr, args.opt);
  1644. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1645. return callbackHandler->handleVstManufacturerSpecific (args.index, args.value, args.ptr, args.opt);
  1646. return 0;
  1647. }
  1648. pointer_sized_int handleCanPlugInDo (VstOpCodeArguments args)
  1649. {
  1650. auto text = (const char*) args.ptr;
  1651. auto matches = [=](const char* s) { return strcmp (text, s) == 0; };
  1652. if (matches ("receiveVstEvents")
  1653. || matches ("receiveVstMidiEvent")
  1654. || matches ("receiveVstMidiEvents"))
  1655. {
  1656. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1657. return 1;
  1658. #else
  1659. return -1;
  1660. #endif
  1661. }
  1662. if (matches ("sendVstEvents")
  1663. || matches ("sendVstMidiEvent")
  1664. || matches ("sendVstMidiEvents"))
  1665. {
  1666. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1667. return 1;
  1668. #else
  1669. return -1;
  1670. #endif
  1671. }
  1672. if (matches ("receiveVstTimeInfo")
  1673. || matches ("conformsToWindowRules")
  1674. || matches ("supportsViewDpiScaling")
  1675. || matches ("bypass"))
  1676. {
  1677. return 1;
  1678. }
  1679. // This tells Wavelab to use the UI thread to invoke open/close,
  1680. // like all other hosts do.
  1681. if (matches ("openCloseAnyThread"))
  1682. return -1;
  1683. if (matches ("MPE"))
  1684. return processor->supportsMPE() ? 1 : 0;
  1685. #if JUCE_MAC
  1686. if (matches ("hasCockosViewAsConfig"))
  1687. {
  1688. useNSView = true;
  1689. return (int32) 0xbeef0000;
  1690. }
  1691. #endif
  1692. if (matches ("hasCockosExtensions"))
  1693. return (int32) 0xbeef0000;
  1694. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1695. return callbackHandler->handleVstPluginCanDo (args.index, args.value, args.ptr, args.opt);
  1696. return 0;
  1697. }
  1698. pointer_sized_int handleGetTailSize (VstOpCodeArguments)
  1699. {
  1700. if (processor != nullptr)
  1701. {
  1702. int32 result;
  1703. auto tailSeconds = processor->getTailLengthSeconds();
  1704. if (tailSeconds == std::numeric_limits<double>::infinity())
  1705. result = std::numeric_limits<int32>::max();
  1706. else
  1707. result = static_cast<int32> (tailSeconds * sampleRate);
  1708. return result; // Vst2 expects an int32 upcasted to a intptr_t here
  1709. }
  1710. return 0;
  1711. }
  1712. pointer_sized_int handleKeyboardFocusRequired (VstOpCodeArguments)
  1713. {
  1714. return (JucePlugin_EditorRequiresKeyboardFocus != 0) ? 1 : 0;
  1715. }
  1716. pointer_sized_int handleGetVstInterfaceVersion (VstOpCodeArguments)
  1717. {
  1718. return kVstVersion;
  1719. }
  1720. pointer_sized_int handleGetCurrentMidiProgram (VstOpCodeArguments)
  1721. {
  1722. return -1;
  1723. }
  1724. pointer_sized_int handleGetSpeakerConfiguration (VstOpCodeArguments args)
  1725. {
  1726. auto** pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.value);
  1727. auto** pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.ptr);
  1728. if (pluginHasSidechainsOrAuxs() || processor->isMidiEffect())
  1729. return false;
  1730. auto inputLayout = processor->getChannelLayoutOfBus (true, 0);
  1731. auto outputLayout = processor->getChannelLayoutOfBus (false, 0);
  1732. auto speakerBaseSize = sizeof (Vst2::VstSpeakerArrangement) - (sizeof (Vst2::VstSpeakerProperties) * 8);
  1733. cachedInArrangement .malloc (speakerBaseSize + (static_cast<std::size_t> (inputLayout. size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1734. cachedOutArrangement.malloc (speakerBaseSize + (static_cast<std::size_t> (outputLayout.size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1735. *pluginInput = cachedInArrangement. getData();
  1736. *pluginOutput = cachedOutArrangement.getData();
  1737. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (true, 0), **pluginInput);
  1738. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (false, 0), **pluginOutput);
  1739. return 1;
  1740. }
  1741. pointer_sized_int handleSetNumberOfSamplesToProcess (VstOpCodeArguments args)
  1742. {
  1743. return args.value;
  1744. }
  1745. pointer_sized_int handleSetSampleFloatType (VstOpCodeArguments args)
  1746. {
  1747. if (! isProcessing)
  1748. {
  1749. if (processor != nullptr)
  1750. {
  1751. processor->setProcessingPrecision ((args.value == Vst2::kVstProcessPrecision64
  1752. && processor->supportsDoublePrecisionProcessing())
  1753. ? AudioProcessor::doublePrecision
  1754. : AudioProcessor::singlePrecision);
  1755. return 1;
  1756. }
  1757. }
  1758. return 0;
  1759. }
  1760. pointer_sized_int handleSetContentScaleFactor (float scale)
  1761. {
  1762. #if ! JUCE_MAC
  1763. if (! approximatelyEqual (scale, editorScaleFactor))
  1764. {
  1765. editorScaleFactor = scale;
  1766. if (editorComp != nullptr)
  1767. #if JUCE_WINDOWS && ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  1768. if (auto* ed = editorComp->getEditorComp())
  1769. ed->setScaleFactor (scale);
  1770. #else
  1771. editorComp->updateWindowSize (true);
  1772. #endif
  1773. }
  1774. #else
  1775. ignoreUnused (scale);
  1776. #endif
  1777. return 1;
  1778. }
  1779. pointer_sized_int handleCockosGetParameterText (pointer_sized_int paramIndex,
  1780. void* dest,
  1781. float value)
  1782. {
  1783. if (processor != nullptr && dest != nullptr)
  1784. {
  1785. if (auto* param = juceParameters.getParamForIndex ((int) paramIndex))
  1786. {
  1787. if (! LegacyAudioParameter::isLegacy (param))
  1788. {
  1789. String text (param->getText (value, 1024));
  1790. memcpy (dest, text.toRawUTF8(), ((size_t) text.length()) + 1);
  1791. return 0xbeef;
  1792. }
  1793. }
  1794. }
  1795. return 0;
  1796. }
  1797. //==============================================================================
  1798. pointer_sized_int handleGetNumMidiInputChannels()
  1799. {
  1800. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1801. #ifdef JucePlugin_VSTNumMidiInputs
  1802. return JucePlugin_VSTNumMidiInputs;
  1803. #else
  1804. return 16;
  1805. #endif
  1806. #else
  1807. return 0;
  1808. #endif
  1809. }
  1810. pointer_sized_int handleGetNumMidiOutputChannels()
  1811. {
  1812. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1813. #ifdef JucePlugin_VSTNumMidiOutputs
  1814. return JucePlugin_VSTNumMidiOutputs;
  1815. #else
  1816. return 16;
  1817. #endif
  1818. #else
  1819. return 0;
  1820. #endif
  1821. }
  1822. //==============================================================================
  1823. Vst2::audioMasterCallback hostCallback;
  1824. AudioProcessor* processor = {};
  1825. double sampleRate = 44100.0;
  1826. int32 blockSize = 1024;
  1827. Vst2::AEffect vstEffect;
  1828. juce::MemoryBlock chunkMemory;
  1829. juce::uint32 chunkMemoryTime = 0;
  1830. std::unique_ptr<EditorCompWrapper> editorComp;
  1831. Vst2::ERect editorBounds;
  1832. MidiBuffer midiEvents;
  1833. VSTMidiEventList outgoingEvents;
  1834. #if ! JUCE_MAC
  1835. float editorScaleFactor = 1.0f;
  1836. #endif
  1837. LegacyAudioParametersWrapper juceParameters;
  1838. bool isProcessing = false, isBypassed = false, hasShutdown = false;
  1839. bool firstProcessCallback = true, shouldDeleteEditor = false;
  1840. #if JUCE_64BIT
  1841. bool useNSView = true;
  1842. #else
  1843. bool useNSView = false;
  1844. #endif
  1845. VstTempBuffers<float> floatTempBuffers;
  1846. VstTempBuffers<double> doubleTempBuffers;
  1847. int maxNumInChannels = 0, maxNumOutChannels = 0;
  1848. HeapBlock<Vst2::VstSpeakerArrangement> cachedInArrangement, cachedOutArrangement;
  1849. ThreadLocalValue<bool> inParameterChangedCallback;
  1850. //==============================================================================
  1851. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1852. };
  1853. //==============================================================================
  1854. namespace
  1855. {
  1856. Vst2::AEffect* pluginEntryPoint (Vst2::audioMasterCallback audioMaster)
  1857. {
  1858. JUCE_AUTORELEASEPOOL
  1859. {
  1860. initialiseJuce_GUI();
  1861. try
  1862. {
  1863. if (audioMaster (0, Vst2::audioMasterVersion, 0, 0, 0, 0) != 0)
  1864. {
  1865. #if JUCE_LINUX
  1866. MessageManagerLock mmLock;
  1867. #endif
  1868. auto* processor = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1869. auto* wrapper = new JuceVSTWrapper (audioMaster, processor);
  1870. auto* aEffect = wrapper->getAEffect();
  1871. if (auto* callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1872. {
  1873. callbackHandler->handleVstHostCallbackAvailable ([audioMaster, aEffect](int32 opcode, int32 index, pointer_sized_int value, void* ptr, float opt)
  1874. {
  1875. return audioMaster (aEffect, opcode, index, value, ptr, opt);
  1876. });
  1877. }
  1878. return aEffect;
  1879. }
  1880. }
  1881. catch (...)
  1882. {}
  1883. }
  1884. return nullptr;
  1885. }
  1886. }
  1887. #if ! JUCE_WINDOWS
  1888. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1889. #endif
  1890. //==============================================================================
  1891. // Mac startup code..
  1892. #if JUCE_MAC
  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. initialiseMacVST();
  1898. return pluginEntryPoint (audioMaster);
  1899. }
  1900. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster);
  1901. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster)
  1902. {
  1903. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1904. initialiseMacVST();
  1905. return pluginEntryPoint (audioMaster);
  1906. }
  1907. //==============================================================================
  1908. // Linux startup code..
  1909. #elif JUCE_LINUX
  1910. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1911. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1912. {
  1913. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1914. SharedMessageThread::getInstance();
  1915. return pluginEntryPoint (audioMaster);
  1916. }
  1917. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster) asm ("main");
  1918. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster)
  1919. {
  1920. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1921. return VSTPluginMain (audioMaster);
  1922. }
  1923. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1924. __attribute__((constructor)) void myPluginInit() {}
  1925. __attribute__((destructor)) void myPluginFini() {}
  1926. //==============================================================================
  1927. // Win32 startup code..
  1928. #else
  1929. extern "C" __declspec (dllexport) Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1930. {
  1931. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1932. return pluginEntryPoint (audioMaster);
  1933. }
  1934. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1935. extern "C" __declspec (dllexport) int main (Vst2::audioMasterCallback audioMaster)
  1936. {
  1937. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1938. return (int) pluginEntryPoint (audioMaster);
  1939. }
  1940. #endif
  1941. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1942. {
  1943. if (reason == DLL_PROCESS_ATTACH)
  1944. Process::setCurrentModuleInstanceHandle (instance);
  1945. return true;
  1946. }
  1947. #endif
  1948. #endif