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.

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