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.

2425 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. #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. {
  885. editorComp->checkVisibility();
  886. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  887. if (getHostType().isWavelab())
  888. if (auto* peer = editorComp->getTopLevelComponent()->getPeer())
  889. handleSetContentScaleFactor ((float) peer->getPlatformScaleFactor());
  890. #endif
  891. }
  892. }
  893. void createEditorComp()
  894. {
  895. if (hasShutdown || processor == nullptr)
  896. return;
  897. if (editorComp == nullptr)
  898. {
  899. if (auto* ed = processor->createEditorIfNeeded())
  900. {
  901. vstEffect.flags |= Vst2::effFlagsHasEditor;
  902. editorComp.reset (new EditorCompWrapper (*this, *ed));
  903. }
  904. else
  905. {
  906. vstEffect.flags &= ~Vst2::effFlagsHasEditor;
  907. }
  908. }
  909. shouldDeleteEditor = false;
  910. }
  911. void deleteEditor (bool canDeleteLaterIfModal)
  912. {
  913. JUCE_AUTORELEASEPOOL
  914. {
  915. PopupMenu::dismissAllActiveMenus();
  916. jassert (! recursionCheck);
  917. ScopedValueSetter<bool> svs (recursionCheck, true, false);
  918. if (editorComp != nullptr)
  919. {
  920. if (auto* modalComponent = Component::getCurrentlyModalComponent())
  921. {
  922. modalComponent->exitModalState (0);
  923. if (canDeleteLaterIfModal)
  924. {
  925. shouldDeleteEditor = true;
  926. return;
  927. }
  928. }
  929. editorComp->detachHostWindow();
  930. if (auto* ed = editorComp->getEditorComp())
  931. processor->editorBeingDeleted (ed);
  932. editorComp = nullptr;
  933. // there's some kind of component currently modal, but the host
  934. // is trying to delete our plugin. You should try to avoid this happening..
  935. jassert (Component::getCurrentlyModalComponent() == nullptr);
  936. }
  937. }
  938. }
  939. pointer_sized_int dispatcher (int32 opCode, VstOpCodeArguments args)
  940. {
  941. if (hasShutdown)
  942. return 0;
  943. switch (opCode)
  944. {
  945. case Vst2::effOpen: return handleOpen (args);
  946. case Vst2::effClose: return handleClose (args);
  947. case Vst2::effSetProgram: return handleSetCurrentProgram (args);
  948. case Vst2::effGetProgram: return handleGetCurrentProgram (args);
  949. case Vst2::effSetProgramName: return handleSetCurrentProgramName (args);
  950. case Vst2::effGetProgramName: return handleGetCurrentProgramName (args);
  951. case Vst2::effGetParamLabel: return handleGetParameterLabel (args);
  952. case Vst2::effGetParamDisplay: return handleGetParameterText (args);
  953. case Vst2::effGetParamName: return handleGetParameterName (args);
  954. case Vst2::effSetSampleRate: return handleSetSampleRate (args);
  955. case Vst2::effSetBlockSize: return handleSetBlockSize (args);
  956. case Vst2::effMainsChanged: return handleResumeSuspend (args);
  957. case Vst2::effEditGetRect: return handleGetEditorBounds (args);
  958. case Vst2::effEditOpen: return handleOpenEditor (args);
  959. case Vst2::effEditClose: return handleCloseEditor (args);
  960. case Vst2::effIdentify: return (pointer_sized_int) ByteOrder::bigEndianInt ("NvEf");
  961. case Vst2::effGetChunk: return handleGetData (args);
  962. case Vst2::effSetChunk: return handleSetData (args);
  963. case Vst2::effProcessEvents: return handlePreAudioProcessingEvents (args);
  964. case Vst2::effCanBeAutomated: return handleIsParameterAutomatable (args);
  965. case Vst2::effString2Parameter: return handleParameterValueForText (args);
  966. case Vst2::effGetProgramNameIndexed: return handleGetProgramName (args);
  967. case Vst2::effGetInputProperties: return handleGetInputPinProperties (args);
  968. case Vst2::effGetOutputProperties: return handleGetOutputPinProperties (args);
  969. case Vst2::effGetPlugCategory: return handleGetPlugInCategory (args);
  970. case Vst2::effSetSpeakerArrangement: return handleSetSpeakerConfiguration (args);
  971. case Vst2::effSetBypass: return handleSetBypass (args);
  972. case Vst2::effGetEffectName: return handleGetPlugInName (args);
  973. case Vst2::effGetProductString: return handleGetPlugInName (args);
  974. case Vst2::effGetVendorString: return handleGetManufacturerName (args);
  975. case Vst2::effGetVendorVersion: return handleGetManufacturerVersion (args);
  976. case Vst2::effVendorSpecific: return handleManufacturerSpecific (args);
  977. case Vst2::effCanDo: return handleCanPlugInDo (args);
  978. case Vst2::effGetTailSize: return handleGetTailSize (args);
  979. case Vst2::effKeysRequired: return handleKeyboardFocusRequired (args);
  980. case Vst2::effGetVstVersion: return handleGetVstInterfaceVersion (args);
  981. case Vst2::effGetCurrentMidiProgram: return handleGetCurrentMidiProgram (args);
  982. case Vst2::effGetSpeakerArrangement: return handleGetSpeakerConfiguration (args);
  983. case Vst2::effSetTotalSampleToProcess: return handleSetNumberOfSamplesToProcess (args);
  984. case Vst2::effSetProcessPrecision: return handleSetSampleFloatType (args);
  985. case Vst2::effGetNumMidiInputChannels: return handleGetNumMidiInputChannels();
  986. case Vst2::effGetNumMidiOutputChannels: return handleGetNumMidiOutputChannels();
  987. default: return 0;
  988. }
  989. }
  990. static pointer_sized_int dispatcherCB (Vst2::AEffect* vstInterface, int32 opCode, int32 index,
  991. pointer_sized_int value, void* ptr, float opt)
  992. {
  993. auto* wrapper = getWrapper (vstInterface);
  994. VstOpCodeArguments args = { index, value, ptr, opt };
  995. if (opCode == Vst2::effClose)
  996. {
  997. wrapper->dispatcher (opCode, args);
  998. delete wrapper;
  999. return 1;
  1000. }
  1001. return wrapper->dispatcher (opCode, args);
  1002. }
  1003. //==============================================================================
  1004. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  1005. // chores when it changes or repaints.
  1006. struct EditorCompWrapper : public Component
  1007. #if ! JUCE_MAC
  1008. , public ComponentPeer::ScaleFactorListener,
  1009. public ComponentMovementWatcher
  1010. #endif
  1011. {
  1012. EditorCompWrapper (JuceVSTWrapper& w, AudioProcessorEditor& editor)
  1013. :
  1014. #if ! JUCE_MAC
  1015. ComponentMovementWatcher (this),
  1016. #endif
  1017. wrapper (w)
  1018. {
  1019. editor.setOpaque (true);
  1020. editor.setVisible (true);
  1021. setOpaque (true);
  1022. setTopLeftPosition (editor.getPosition());
  1023. editor.setTopLeftPosition (0, 0);
  1024. auto b = getLocalArea (&editor, editor.getLocalBounds());
  1025. setSize (b.getWidth(), b.getHeight());
  1026. addAndMakeVisible (editor);
  1027. #if JUCE_WINDOWS
  1028. if (! getHostType().isReceptor())
  1029. addMouseListener (this, true);
  1030. #endif
  1031. ignoreUnused (fakeMouseGenerator);
  1032. }
  1033. ~EditorCompWrapper()
  1034. {
  1035. deleteAllChildren(); // note that we can't use a std::unique_ptr because the editor may
  1036. // have been transferred to another parent which takes over ownership.
  1037. #if ! JUCE_MAC
  1038. for (int i = 0; i < ComponentPeer::getNumPeers(); ++i)
  1039. if (auto* peer = ComponentPeer::getPeer (i))
  1040. peer->removeScaleFactorListener (this);
  1041. #endif
  1042. }
  1043. void paint (Graphics&) override {}
  1044. void getEditorBounds (Vst2::ERect& bounds)
  1045. {
  1046. auto b = getSizeToContainChild();
  1047. bounds.top = 0;
  1048. bounds.left = 0;
  1049. bounds.bottom = (int16) b.getHeight();
  1050. bounds.right = (int16) b.getWidth();
  1051. }
  1052. void attachToHost (VstOpCodeArguments args)
  1053. {
  1054. setOpaque (true);
  1055. setVisible (false);
  1056. #if JUCE_WINDOWS
  1057. addToDesktop (0, args.ptr);
  1058. hostWindow = (HWND) args.ptr;
  1059. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1060. // workaround for plug-ins opening on an auxiliary monitor
  1061. Timer::callAfterDelay (250, [this] { updateWindowSize (false); });
  1062. #endif
  1063. #elif JUCE_LINUX
  1064. addToDesktop (0, args.ptr);
  1065. hostWindow = (Window) args.ptr;
  1066. XReparentWindow (display.display, (Window) getWindowHandle(), hostWindow, 0, 0);
  1067. #else
  1068. hostWindow = attachComponentToWindowRefVST (this, args.ptr, wrapper.useNSView);
  1069. #endif
  1070. setVisible (true);
  1071. }
  1072. void detachHostWindow()
  1073. {
  1074. #if JUCE_MAC
  1075. if (hostWindow != 0)
  1076. {
  1077. detachComponentFromWindowRefVST (this, hostWindow, wrapper.useNSView);
  1078. hostWindow = 0;
  1079. }
  1080. #endif
  1081. #if JUCE_LINUX
  1082. hostWindow = 0;
  1083. #endif
  1084. }
  1085. void checkVisibility()
  1086. {
  1087. #if JUCE_MAC
  1088. if (hostWindow != 0)
  1089. checkWindowVisibilityVST (hostWindow, this, wrapper.useNSView);
  1090. #endif
  1091. }
  1092. AudioProcessorEditor* getEditorComp() const noexcept
  1093. {
  1094. return dynamic_cast<AudioProcessorEditor*> (getChildComponent(0));
  1095. }
  1096. float getNativeEditorScaleFactor() const noexcept { return nativeScaleFactor; }
  1097. #if ! JUCE_MAC
  1098. void componentMovedOrResized (bool, bool) override {}
  1099. void componentPeerChanged() override
  1100. {
  1101. if (auto* peer = getTopLevelComponent()->getPeer())
  1102. peer->addScaleFactorListener (this);
  1103. }
  1104. void componentVisibilityChanged() override
  1105. {
  1106. if (auto* peer = getTopLevelComponent()->getPeer())
  1107. nativeScaleFactorChanged (peer->getPlatformScaleFactor());
  1108. }
  1109. void nativeScaleFactorChanged (double newScaleFactor) override
  1110. {
  1111. nativeScaleFactor = (float) newScaleFactor;
  1112. if (getHostType().isBitwigStudio())
  1113. updateWindowSize (true);
  1114. }
  1115. #endif
  1116. void resized() override
  1117. {
  1118. if (auto* ed = getEditorComp())
  1119. {
  1120. ed->setTopLeftPosition (0, 0);
  1121. if (shouldResizeEditor)
  1122. ed->setBounds (ed->getLocalArea (this, getLocalBounds()));
  1123. if (! getHostType().isBitwigStudio())
  1124. updateWindowSize (false);
  1125. }
  1126. #if JUCE_MAC && ! JUCE_64BIT
  1127. if (! wrapper.useNSView)
  1128. updateEditorCompBoundsVST (this);
  1129. #endif
  1130. }
  1131. void childBoundsChanged (Component*) override
  1132. {
  1133. updateWindowSize (false);
  1134. }
  1135. juce::Rectangle<int> getSizeToContainChild()
  1136. {
  1137. if (auto* ed = getEditorComp())
  1138. return getLocalArea (ed, ed->getLocalBounds());
  1139. return {};
  1140. }
  1141. void updateWindowSize (bool resizeEditor)
  1142. {
  1143. if (! isInSizeWindow)
  1144. {
  1145. if (auto* ed = getEditorComp())
  1146. {
  1147. ed->setTopLeftPosition (0, 0);
  1148. auto pos = getSizeToContainChild();
  1149. #if JUCE_MAC
  1150. if (wrapper.useNSView)
  1151. setTopLeftPosition (0, getHeight() - pos.getHeight());
  1152. #endif
  1153. resizeHostWindow (pos.getWidth(), pos.getHeight());
  1154. #if ! JUCE_LINUX // setSize() on linux causes renoise and energyxt to fail.
  1155. if (! resizeEditor) // this is needed to prevent an infinite resizing loop due to coordinate rounding
  1156. shouldResizeEditor = false;
  1157. setSize (pos.getWidth(), pos.getHeight());
  1158. shouldResizeEditor = true;
  1159. #else
  1160. ignoreUnused (resizeEditor);
  1161. XResizeWindow (display.display, (Window) getWindowHandle(),
  1162. static_cast<unsigned int> (roundToInt (pos.getWidth() * nativeScaleFactor)),
  1163. static_cast<unsigned int> (roundToInt (pos.getHeight() * nativeScaleFactor)));
  1164. #endif
  1165. #if JUCE_MAC
  1166. resizeHostWindow (pos.getWidth(), pos.getHeight()); // (doing this a second time seems to be necessary in tracktion)
  1167. #endif
  1168. }
  1169. }
  1170. }
  1171. void resizeHostWindow (int newWidth, int newHeight)
  1172. {
  1173. bool sizeWasSuccessful = false;
  1174. if (auto host = wrapper.hostCallback)
  1175. {
  1176. auto status = host (wrapper.getAEffect(), Vst2::audioMasterCanDo, 0, 0, const_cast<char*> ("sizeWindow"), 0);
  1177. if (status == (pointer_sized_int) 1 || getHostType().isAbletonLive())
  1178. {
  1179. isInSizeWindow = true;
  1180. sizeWasSuccessful = (host (wrapper.getAEffect(), Vst2::audioMasterSizeWindow,
  1181. roundToInt (newWidth * nativeScaleFactor),
  1182. roundToInt (newHeight * nativeScaleFactor), 0, 0) != 0);
  1183. isInSizeWindow = false;
  1184. }
  1185. }
  1186. if (! sizeWasSuccessful)
  1187. {
  1188. // some hosts don't support the sizeWindow call, so do it manually..
  1189. #if JUCE_MAC
  1190. setNativeHostWindowSizeVST (hostWindow, this, newWidth, newHeight, wrapper.useNSView);
  1191. #elif JUCE_LINUX
  1192. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  1193. setSize (newWidth, newHeight);
  1194. #else
  1195. int dw = 0;
  1196. int dh = 0;
  1197. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  1198. HWND w = (HWND) getWindowHandle();
  1199. while (w != 0)
  1200. {
  1201. HWND parent = getWindowParent (w);
  1202. if (parent == 0)
  1203. break;
  1204. TCHAR windowType [32] = { 0 };
  1205. GetClassName (parent, windowType, 31);
  1206. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  1207. break;
  1208. RECT windowPos, parentPos;
  1209. GetWindowRect (w, &windowPos);
  1210. GetWindowRect (parent, &parentPos);
  1211. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1212. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1213. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1214. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1215. w = parent;
  1216. if (dw == 2 * frameThickness)
  1217. break;
  1218. if (dw > 100 || dh > 100)
  1219. w = 0;
  1220. }
  1221. if (w != 0)
  1222. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1223. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1224. #endif
  1225. }
  1226. if (auto* peer = getPeer())
  1227. {
  1228. peer->handleMovedOrResized();
  1229. repaint();
  1230. }
  1231. }
  1232. #if JUCE_WINDOWS
  1233. void mouseDown (const MouseEvent&) override
  1234. {
  1235. broughtToFront();
  1236. }
  1237. void broughtToFront() override
  1238. {
  1239. // for hosts like nuendo, need to also pop the MDI container to the
  1240. // front when our comp is clicked on.
  1241. if (! isCurrentlyBlockedByAnotherModalComponent())
  1242. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  1243. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1244. }
  1245. #endif
  1246. #if JUCE_MAC
  1247. bool keyPressed (const KeyPress&) override
  1248. {
  1249. // If we have an unused keypress, move the key-focus to a host window
  1250. // and re-inject the event..
  1251. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1252. }
  1253. #endif
  1254. //==============================================================================
  1255. JuceVSTWrapper& wrapper;
  1256. FakeMouseMoveGenerator fakeMouseGenerator;
  1257. bool isInSizeWindow = false;
  1258. bool shouldResizeEditor = true;
  1259. float nativeScaleFactor = 1.0f;
  1260. #if JUCE_MAC
  1261. void* hostWindow = {};
  1262. #elif JUCE_LINUX
  1263. ScopedXDisplay display;
  1264. Window hostWindow = {};
  1265. #else
  1266. HWND hostWindow = {};
  1267. WindowsHooks hooks;
  1268. #endif
  1269. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1270. };
  1271. //==============================================================================
  1272. private:
  1273. static JuceVSTWrapper* getWrapper (Vst2::AEffect* v) noexcept { return static_cast<JuceVSTWrapper*> (v->object); }
  1274. bool isProcessLevelOffline()
  1275. {
  1276. return hostCallback != nullptr
  1277. && (int32) hostCallback (&vstEffect, Vst2::audioMasterGetCurrentProcessLevel, 0, 0, 0, 0) == 4;
  1278. }
  1279. static inline int32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1280. {
  1281. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1282. return (int32) hexVersion;
  1283. #else
  1284. // Currently, only Cubase displays the version number to the user
  1285. // We are hoping here that when other DAWs start to display the version
  1286. // number, that they do so according to yfede's encoding table in the link
  1287. // below. If not, then this code will need an if (isSteinberg()) in the
  1288. // future.
  1289. int major = (hexVersion >> 16) & 0xff;
  1290. int minor = (hexVersion >> 8) & 0xff;
  1291. int bugfix = hexVersion & 0xff;
  1292. // for details, see: https://forum.juce.com/t/issues-with-version-integer-reported-by-vst2/23867
  1293. // Encoding B
  1294. if (major < 1)
  1295. return major * 1000 + minor * 100 + bugfix * 10;
  1296. // Encoding E
  1297. if (major > 100)
  1298. return major * 10000000 + minor * 100000 + bugfix * 1000;
  1299. // Encoding D
  1300. return static_cast<int32> (hexVersion);
  1301. #endif
  1302. }
  1303. //==============================================================================
  1304. #if JUCE_WINDOWS
  1305. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1306. static void checkWhetherMessageThreadIsCorrect()
  1307. {
  1308. auto host = getHostType();
  1309. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1310. {
  1311. if (! messageThreadIsDefinitelyCorrect)
  1312. {
  1313. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1314. struct MessageThreadCallback : public CallbackMessage
  1315. {
  1316. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1317. void messageCallback() override { triggered = true; }
  1318. bool& triggered;
  1319. };
  1320. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1321. }
  1322. }
  1323. }
  1324. #else
  1325. static void checkWhetherMessageThreadIsCorrect() {}
  1326. #endif
  1327. //==============================================================================
  1328. template <typename FloatType>
  1329. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1330. {
  1331. tmpBuffers.release();
  1332. if (processor != nullptr)
  1333. tmpBuffers.tempChannels.insertMultiple (0, nullptr, vstEffect.numInputs
  1334. + vstEffect.numOutputs);
  1335. }
  1336. void deleteTempChannels()
  1337. {
  1338. deleteTempChannels (floatTempBuffers);
  1339. deleteTempChannels (doubleTempBuffers);
  1340. }
  1341. //==============================================================================
  1342. void findMaxTotalChannels (int& maxTotalIns, int& maxTotalOuts)
  1343. {
  1344. #ifdef JucePlugin_PreferredChannelConfigurations
  1345. int configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1346. maxTotalIns = maxTotalOuts = 0;
  1347. for (auto& config : configs)
  1348. {
  1349. maxTotalIns = jmax (maxTotalIns, config[0]);
  1350. maxTotalOuts = jmax (maxTotalOuts, config[1]);
  1351. }
  1352. #else
  1353. auto numInputBuses = processor->getBusCount (true);
  1354. auto numOutputBuses = processor->getBusCount (false);
  1355. if (numInputBuses > 1 || numOutputBuses > 1)
  1356. {
  1357. maxTotalIns = maxTotalOuts = 0;
  1358. for (int i = 0; i < numInputBuses; ++i)
  1359. maxTotalIns += processor->getChannelCountOfBus (true, i);
  1360. for (int i = 0; i < numOutputBuses; ++i)
  1361. maxTotalOuts += processor->getChannelCountOfBus (false, i);
  1362. }
  1363. else
  1364. {
  1365. maxTotalIns = numInputBuses > 0 ? processor->getBus (true, 0)->getMaxSupportedChannels (64) : 0;
  1366. maxTotalOuts = numOutputBuses > 0 ? processor->getBus (false, 0)->getMaxSupportedChannels (64) : 0;
  1367. }
  1368. #endif
  1369. }
  1370. bool pluginHasSidechainsOrAuxs() const { return (processor->getBusCount (true) > 1 || processor->getBusCount (false) > 1); }
  1371. //==============================================================================
  1372. /** Host to plug-in calls. */
  1373. pointer_sized_int handleOpen (VstOpCodeArguments)
  1374. {
  1375. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1376. if (processor->hasEditor())
  1377. vstEffect.flags |= Vst2::effFlagsHasEditor;
  1378. else
  1379. vstEffect.flags &= ~Vst2::effFlagsHasEditor;
  1380. return 0;
  1381. }
  1382. pointer_sized_int handleClose (VstOpCodeArguments)
  1383. {
  1384. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  1385. stopTimer();
  1386. if (MessageManager::getInstance()->isThisTheMessageThread())
  1387. deleteEditor (false);
  1388. return 0;
  1389. }
  1390. pointer_sized_int handleSetCurrentProgram (VstOpCodeArguments args)
  1391. {
  1392. if (processor != nullptr && isPositiveAndBelow ((int) args.value, processor->getNumPrograms()))
  1393. processor->setCurrentProgram ((int) args.value);
  1394. return 0;
  1395. }
  1396. pointer_sized_int handleGetCurrentProgram (VstOpCodeArguments)
  1397. {
  1398. return (processor != nullptr && processor->getNumPrograms() > 0 ? processor->getCurrentProgram() : 0);
  1399. }
  1400. pointer_sized_int handleSetCurrentProgramName (VstOpCodeArguments args)
  1401. {
  1402. if (processor != nullptr && processor->getNumPrograms() > 0)
  1403. processor->changeProgramName (processor->getCurrentProgram(), (char*) args.ptr);
  1404. return 0;
  1405. }
  1406. pointer_sized_int handleGetCurrentProgramName (VstOpCodeArguments args)
  1407. {
  1408. if (processor != nullptr && processor->getNumPrograms() > 0)
  1409. processor->getProgramName (processor->getCurrentProgram()).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1410. return 0;
  1411. }
  1412. pointer_sized_int handleGetParameterLabel (VstOpCodeArguments args)
  1413. {
  1414. if (auto* param = juceParameters.getParamForIndex (args.index))
  1415. {
  1416. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1417. param->getLabel().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1418. }
  1419. return 0;
  1420. }
  1421. pointer_sized_int handleGetParameterText (VstOpCodeArguments args)
  1422. {
  1423. if (auto* param = juceParameters.getParamForIndex (args.index))
  1424. {
  1425. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1426. param->getCurrentValueAsText().copyToUTF8 ((char*) args.ptr, 24 + 1);
  1427. }
  1428. return 0;
  1429. }
  1430. pointer_sized_int handleGetParameterName (VstOpCodeArguments args)
  1431. {
  1432. if (auto* param = juceParameters.getParamForIndex (args.index))
  1433. {
  1434. // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  1435. param->getName (32).copyToUTF8 ((char*) args.ptr, 32 + 1);
  1436. }
  1437. return 0;
  1438. }
  1439. pointer_sized_int handleSetSampleRate (VstOpCodeArguments args)
  1440. {
  1441. sampleRate = args.opt;
  1442. return 0;
  1443. }
  1444. pointer_sized_int handleSetBlockSize (VstOpCodeArguments args)
  1445. {
  1446. blockSize = (int32) args.value;
  1447. return 0;
  1448. }
  1449. pointer_sized_int handleResumeSuspend (VstOpCodeArguments args)
  1450. {
  1451. if (args.value)
  1452. resume();
  1453. else
  1454. suspend();
  1455. return 0;
  1456. }
  1457. pointer_sized_int handleGetEditorBounds (VstOpCodeArguments args)
  1458. {
  1459. checkWhetherMessageThreadIsCorrect();
  1460. const MessageManagerLock mmLock;
  1461. createEditorComp();
  1462. if (editorComp != nullptr)
  1463. {
  1464. editorComp->getEditorBounds (editorBounds);
  1465. *((Vst2::ERect**) args.ptr) = &editorBounds;
  1466. return (pointer_sized_int) &editorBounds;
  1467. }
  1468. return 0;
  1469. }
  1470. pointer_sized_int handleOpenEditor (VstOpCodeArguments args)
  1471. {
  1472. checkWhetherMessageThreadIsCorrect();
  1473. const MessageManagerLock mmLock;
  1474. jassert (! recursionCheck);
  1475. startTimerHz (4); // performs misc housekeeping chores
  1476. deleteEditor (true);
  1477. createEditorComp();
  1478. if (editorComp != nullptr)
  1479. {
  1480. editorComp->attachToHost (args);
  1481. return 1;
  1482. }
  1483. return 0;
  1484. }
  1485. pointer_sized_int handleCloseEditor (VstOpCodeArguments)
  1486. {
  1487. checkWhetherMessageThreadIsCorrect();
  1488. const MessageManagerLock mmLock;
  1489. deleteEditor (true);
  1490. return 0;
  1491. }
  1492. pointer_sized_int handleGetData (VstOpCodeArguments args)
  1493. {
  1494. if (processor == nullptr)
  1495. return 0;
  1496. auto data = (void**) args.ptr;
  1497. bool onlyStoreCurrentProgramData = (args.index != 0);
  1498. chunkMemory.reset();
  1499. if (onlyStoreCurrentProgramData)
  1500. processor->getCurrentProgramStateInformation (chunkMemory);
  1501. else
  1502. processor->getStateInformation (chunkMemory);
  1503. *data = (void*) chunkMemory.getData();
  1504. // because the chunk is only needed temporarily by the host (or at least you'd
  1505. // hope so) we'll give it a while and then free it in the timer callback.
  1506. chunkMemoryTime = juce::Time::getApproximateMillisecondCounter();
  1507. return (int32) chunkMemory.getSize();
  1508. }
  1509. pointer_sized_int handleSetData (VstOpCodeArguments args)
  1510. {
  1511. if (processor != nullptr)
  1512. {
  1513. void* data = args.ptr;
  1514. int32 byteSize = (int32) args.value;
  1515. bool onlyRestoreCurrentProgramData = (args.index != 0);
  1516. chunkMemory.reset();
  1517. chunkMemoryTime = 0;
  1518. if (byteSize > 0 && data != nullptr)
  1519. {
  1520. if (onlyRestoreCurrentProgramData)
  1521. processor->setCurrentProgramStateInformation (data, byteSize);
  1522. else
  1523. processor->setStateInformation (data, byteSize);
  1524. }
  1525. }
  1526. return 0;
  1527. }
  1528. pointer_sized_int handlePreAudioProcessingEvents (VstOpCodeArguments args)
  1529. {
  1530. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1531. VSTMidiEventList::addEventsToMidiBuffer ((Vst2::VstEvents*) args.ptr, midiEvents);
  1532. return 1;
  1533. #else
  1534. ignoreUnused (args);
  1535. return 0;
  1536. #endif
  1537. }
  1538. pointer_sized_int handleIsParameterAutomatable (VstOpCodeArguments args)
  1539. {
  1540. if (auto* param = juceParameters.getParamForIndex (args.index))
  1541. {
  1542. const bool isMeter = (((param->getCategory() & 0xffff0000) >> 16) == 2);
  1543. return (param->isAutomatable() && (! isMeter) ? 1 : 0);
  1544. }
  1545. return 0;
  1546. }
  1547. pointer_sized_int handleParameterValueForText (VstOpCodeArguments args)
  1548. {
  1549. if (auto* param = juceParameters.getParamForIndex (args.index))
  1550. {
  1551. if (! LegacyAudioParameter::isLegacy (param))
  1552. {
  1553. auto value = param->getValueForText (String::fromUTF8 ((char*) args.ptr));
  1554. param->setValue (value);
  1555. inParameterChangedCallback = true;
  1556. param->sendValueChangedMessageToListeners (value);
  1557. return 1;
  1558. }
  1559. }
  1560. return 0;
  1561. }
  1562. pointer_sized_int handleGetProgramName (VstOpCodeArguments args)
  1563. {
  1564. if (processor != nullptr && isPositiveAndBelow (args.index, processor->getNumPrograms()))
  1565. {
  1566. processor->getProgramName (args.index).copyToUTF8 ((char*) args.ptr, 24 + 1);
  1567. return 1;
  1568. }
  1569. return 0;
  1570. }
  1571. pointer_sized_int handleGetInputPinProperties (VstOpCodeArguments args)
  1572. {
  1573. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, true, args.index)) ? 1 : 0;
  1574. }
  1575. pointer_sized_int handleGetOutputPinProperties (VstOpCodeArguments args)
  1576. {
  1577. return (processor != nullptr && getPinProperties (*(Vst2::VstPinProperties*) args.ptr, false, args.index)) ? 1 : 0;
  1578. }
  1579. pointer_sized_int handleGetPlugInCategory (VstOpCodeArguments)
  1580. {
  1581. return Vst2::JucePlugin_VSTCategory;
  1582. }
  1583. pointer_sized_int handleSetSpeakerConfiguration (VstOpCodeArguments args)
  1584. {
  1585. auto* pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.value);
  1586. auto* pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement*> (args.ptr);
  1587. if (processor->isMidiEffect())
  1588. return 0;
  1589. auto numIns = processor->getBusCount (true);
  1590. auto numOuts = processor->getBusCount (false);
  1591. if (pluginInput != nullptr && pluginInput->type >= 0)
  1592. {
  1593. // inconsistent request?
  1594. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput).size() != pluginInput->numChannels)
  1595. return 0;
  1596. }
  1597. if (pluginOutput != nullptr && pluginOutput->type >= 0)
  1598. {
  1599. // inconsistent request?
  1600. if (SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput).size() != pluginOutput->numChannels)
  1601. return 0;
  1602. }
  1603. if (pluginInput != nullptr && pluginInput->numChannels > 0 && numIns == 0)
  1604. return 0;
  1605. if (pluginOutput != nullptr && pluginOutput->numChannels > 0 && numOuts == 0)
  1606. return 0;
  1607. auto layouts = processor->getBusesLayout();
  1608. if (pluginInput != nullptr && pluginInput-> numChannels >= 0 && numIns > 0)
  1609. layouts.getChannelSet (true, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  1610. if (pluginOutput != nullptr && pluginOutput->numChannels >= 0 && numOuts > 0)
  1611. layouts.getChannelSet (false, 0) = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  1612. #ifdef JucePlugin_PreferredChannelConfigurations
  1613. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1614. if (! AudioProcessor::containsLayout (layouts, configs))
  1615. return 0;
  1616. #endif
  1617. return processor->setBusesLayout (layouts) ? 1 : 0;
  1618. }
  1619. pointer_sized_int handleSetBypass (VstOpCodeArguments args)
  1620. {
  1621. isBypassed = (args.value != 0);
  1622. if (auto* bypass = processor->getBypassParameter())
  1623. bypass->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  1624. return 1;
  1625. }
  1626. pointer_sized_int handleGetPlugInName (VstOpCodeArguments args)
  1627. {
  1628. String (JucePlugin_Name).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1629. return 1;
  1630. }
  1631. pointer_sized_int handleGetManufacturerName (VstOpCodeArguments args)
  1632. {
  1633. String (JucePlugin_Manufacturer).copyToUTF8 ((char*) args.ptr, 64 + 1);
  1634. return 1;
  1635. }
  1636. pointer_sized_int handleGetManufacturerVersion (VstOpCodeArguments)
  1637. {
  1638. return convertHexVersionToDecimal (JucePlugin_VersionCode);
  1639. }
  1640. pointer_sized_int handleManufacturerSpecific (VstOpCodeArguments args)
  1641. {
  1642. if (handleManufacturerSpecificVST2Opcode (args.index, args.value, args.ptr, args.opt))
  1643. return 1;
  1644. if (args.index == JUCE_MULTICHAR_CONSTANT ('P', 'r', 'e', 'S')
  1645. && args.value == JUCE_MULTICHAR_CONSTANT ('A', 'e', 'C', 's'))
  1646. return handleSetContentScaleFactor (args.opt);
  1647. if (args.index == Vst2::effGetParamDisplay)
  1648. return handleCockosGetParameterText (args.value, args.ptr, args.opt);
  1649. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1650. return callbackHandler->handleVstManufacturerSpecific (args.index, args.value, args.ptr, args.opt);
  1651. return 0;
  1652. }
  1653. pointer_sized_int handleCanPlugInDo (VstOpCodeArguments args)
  1654. {
  1655. auto text = (const char*) args.ptr;
  1656. auto matches = [=](const char* s) { return strcmp (text, s) == 0; };
  1657. if (matches ("receiveVstEvents")
  1658. || matches ("receiveVstMidiEvent")
  1659. || matches ("receiveVstMidiEvents"))
  1660. {
  1661. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1662. return 1;
  1663. #else
  1664. return -1;
  1665. #endif
  1666. }
  1667. if (matches ("sendVstEvents")
  1668. || matches ("sendVstMidiEvent")
  1669. || matches ("sendVstMidiEvents"))
  1670. {
  1671. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1672. return 1;
  1673. #else
  1674. return -1;
  1675. #endif
  1676. }
  1677. if (matches ("receiveVstTimeInfo")
  1678. || matches ("conformsToWindowRules")
  1679. || matches ("supportsViewDpiScaling")
  1680. || matches ("bypass"))
  1681. {
  1682. return 1;
  1683. }
  1684. // This tells Wavelab to use the UI thread to invoke open/close,
  1685. // like all other hosts do.
  1686. if (matches ("openCloseAnyThread"))
  1687. return -1;
  1688. if (matches ("MPE"))
  1689. return processor->supportsMPE() ? 1 : 0;
  1690. #if JUCE_MAC
  1691. if (matches ("hasCockosViewAsConfig"))
  1692. {
  1693. useNSView = true;
  1694. return (int32) 0xbeef0000;
  1695. }
  1696. #endif
  1697. if (matches ("hasCockosExtensions"))
  1698. return (int32) 0xbeef0000;
  1699. if (auto callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1700. return callbackHandler->handleVstPluginCanDo (args.index, args.value, args.ptr, args.opt);
  1701. return 0;
  1702. }
  1703. pointer_sized_int handleGetTailSize (VstOpCodeArguments)
  1704. {
  1705. if (processor != nullptr)
  1706. {
  1707. int32 result;
  1708. auto tailSeconds = processor->getTailLengthSeconds();
  1709. if (tailSeconds == std::numeric_limits<double>::infinity())
  1710. result = std::numeric_limits<int32>::max();
  1711. else
  1712. result = static_cast<int32> (tailSeconds * sampleRate);
  1713. return result; // Vst2 expects an int32 upcasted to a intptr_t here
  1714. }
  1715. return 0;
  1716. }
  1717. pointer_sized_int handleKeyboardFocusRequired (VstOpCodeArguments)
  1718. {
  1719. return (JucePlugin_EditorRequiresKeyboardFocus != 0) ? 1 : 0;
  1720. }
  1721. pointer_sized_int handleGetVstInterfaceVersion (VstOpCodeArguments)
  1722. {
  1723. return kVstVersion;
  1724. }
  1725. pointer_sized_int handleGetCurrentMidiProgram (VstOpCodeArguments)
  1726. {
  1727. return -1;
  1728. }
  1729. pointer_sized_int handleGetSpeakerConfiguration (VstOpCodeArguments args)
  1730. {
  1731. auto** pluginInput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.value);
  1732. auto** pluginOutput = reinterpret_cast<Vst2::VstSpeakerArrangement**> (args.ptr);
  1733. if (pluginHasSidechainsOrAuxs() || processor->isMidiEffect())
  1734. return false;
  1735. auto inputLayout = processor->getChannelLayoutOfBus (true, 0);
  1736. auto outputLayout = processor->getChannelLayoutOfBus (false, 0);
  1737. auto speakerBaseSize = sizeof (Vst2::VstSpeakerArrangement) - (sizeof (Vst2::VstSpeakerProperties) * 8);
  1738. cachedInArrangement .malloc (speakerBaseSize + (static_cast<std::size_t> (inputLayout. size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1739. cachedOutArrangement.malloc (speakerBaseSize + (static_cast<std::size_t> (outputLayout.size()) * sizeof (Vst2::VstSpeakerArrangement)), 1);
  1740. *pluginInput = cachedInArrangement. getData();
  1741. *pluginOutput = cachedOutArrangement.getData();
  1742. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (true, 0), **pluginInput);
  1743. SpeakerMappings::channelSetToVstArrangement (processor->getChannelLayoutOfBus (false, 0), **pluginOutput);
  1744. return 1;
  1745. }
  1746. pointer_sized_int handleSetNumberOfSamplesToProcess (VstOpCodeArguments args)
  1747. {
  1748. return args.value;
  1749. }
  1750. pointer_sized_int handleSetSampleFloatType (VstOpCodeArguments args)
  1751. {
  1752. if (! isProcessing)
  1753. {
  1754. if (processor != nullptr)
  1755. {
  1756. processor->setProcessingPrecision ((args.value == Vst2::kVstProcessPrecision64
  1757. && processor->supportsDoublePrecisionProcessing())
  1758. ? AudioProcessor::doublePrecision
  1759. : AudioProcessor::singlePrecision);
  1760. return 1;
  1761. }
  1762. }
  1763. return 0;
  1764. }
  1765. pointer_sized_int handleSetContentScaleFactor (float scale)
  1766. {
  1767. #if ! JUCE_MAC
  1768. if (editorComp != nullptr)
  1769. {
  1770. #if JUCE_WINDOWS && ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  1771. if (auto* ed = editorComp->getEditorComp())
  1772. {
  1773. ed->setScaleFactor (scale);
  1774. editorComp->updateWindowSize (true);
  1775. }
  1776. #else
  1777. if (! approximatelyEqual (scale, (float) editorComp->getNativeEditorScaleFactor()))
  1778. {
  1779. editorComp->nativeScaleFactorChanged ((double) scale);
  1780. #if JUCE_LINUX
  1781. MessageManager::callAsync ([this] { if (editorComp != nullptr) editorComp->updateWindowSize (true); });
  1782. #else
  1783. editorComp->updateWindowSize (true);
  1784. #endif
  1785. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1786. if (getHostType().isStudioOne())
  1787. Timer::callAfterDelay (100, [this] { if (editorComp != nullptr) editorComp->updateWindowSize (false); });
  1788. #endif
  1789. }
  1790. #endif
  1791. }
  1792. #else
  1793. ignoreUnused (scale);
  1794. #endif
  1795. return 1;
  1796. }
  1797. pointer_sized_int handleCockosGetParameterText (pointer_sized_int paramIndex,
  1798. void* dest,
  1799. float value)
  1800. {
  1801. if (processor != nullptr && dest != nullptr)
  1802. {
  1803. if (auto* param = juceParameters.getParamForIndex ((int) paramIndex))
  1804. {
  1805. if (! LegacyAudioParameter::isLegacy (param))
  1806. {
  1807. String text (param->getText (value, 1024));
  1808. memcpy (dest, text.toRawUTF8(), ((size_t) text.length()) + 1);
  1809. return 0xbeef;
  1810. }
  1811. }
  1812. }
  1813. return 0;
  1814. }
  1815. //==============================================================================
  1816. pointer_sized_int handleGetNumMidiInputChannels()
  1817. {
  1818. #if JucePlugin_WantsMidiInput || JucePlugin_IsMidiEffect
  1819. return 16;
  1820. #else
  1821. return 0;
  1822. #endif
  1823. }
  1824. pointer_sized_int handleGetNumMidiOutputChannels()
  1825. {
  1826. #if JucePlugin_ProducesMidiOutput || JucePlugin_IsMidiEffect
  1827. return 16;
  1828. #else
  1829. return 0;
  1830. #endif
  1831. }
  1832. //==============================================================================
  1833. Vst2::audioMasterCallback hostCallback;
  1834. AudioProcessor* processor = {};
  1835. double sampleRate = 44100.0;
  1836. int32 blockSize = 1024;
  1837. Vst2::AEffect vstEffect;
  1838. juce::MemoryBlock chunkMemory;
  1839. juce::uint32 chunkMemoryTime = 0;
  1840. std::unique_ptr<EditorCompWrapper> editorComp;
  1841. Vst2::ERect editorBounds;
  1842. MidiBuffer midiEvents;
  1843. VSTMidiEventList outgoingEvents;
  1844. LegacyAudioParametersWrapper juceParameters;
  1845. bool isProcessing = false, isBypassed = false, hasShutdown = false;
  1846. bool firstProcessCallback = true, shouldDeleteEditor = false;
  1847. #if JUCE_64BIT
  1848. bool useNSView = true;
  1849. #else
  1850. bool useNSView = false;
  1851. #endif
  1852. VstTempBuffers<float> floatTempBuffers;
  1853. VstTempBuffers<double> doubleTempBuffers;
  1854. int maxNumInChannels = 0, maxNumOutChannels = 0;
  1855. HeapBlock<Vst2::VstSpeakerArrangement> cachedInArrangement, cachedOutArrangement;
  1856. ThreadLocalValue<bool> inParameterChangedCallback;
  1857. //==============================================================================
  1858. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1859. };
  1860. //==============================================================================
  1861. namespace
  1862. {
  1863. Vst2::AEffect* pluginEntryPoint (Vst2::audioMasterCallback audioMaster)
  1864. {
  1865. JUCE_AUTORELEASEPOOL
  1866. {
  1867. initialiseJuce_GUI();
  1868. try
  1869. {
  1870. if (audioMaster (0, Vst2::audioMasterVersion, 0, 0, 0, 0) != 0)
  1871. {
  1872. #if JUCE_LINUX
  1873. MessageManagerLock mmLock;
  1874. #endif
  1875. auto* processor = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1876. auto* wrapper = new JuceVSTWrapper (audioMaster, processor);
  1877. auto* aEffect = wrapper->getAEffect();
  1878. if (auto* callbackHandler = dynamic_cast<VSTCallbackHandler*> (processor))
  1879. {
  1880. callbackHandler->handleVstHostCallbackAvailable ([audioMaster, aEffect](int32 opcode, int32 index, pointer_sized_int value, void* ptr, float opt)
  1881. {
  1882. return audioMaster (aEffect, opcode, index, value, ptr, opt);
  1883. });
  1884. }
  1885. return aEffect;
  1886. }
  1887. }
  1888. catch (...)
  1889. {}
  1890. }
  1891. return nullptr;
  1892. }
  1893. }
  1894. #if ! JUCE_WINDOWS
  1895. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1896. #endif
  1897. //==============================================================================
  1898. // Mac startup code..
  1899. #if JUCE_MAC
  1900. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1901. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1902. {
  1903. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1904. initialiseMacVST();
  1905. return pluginEntryPoint (audioMaster);
  1906. }
  1907. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster);
  1908. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_macho (Vst2::audioMasterCallback audioMaster)
  1909. {
  1910. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1911. initialiseMacVST();
  1912. return pluginEntryPoint (audioMaster);
  1913. }
  1914. //==============================================================================
  1915. // Linux startup code..
  1916. #elif JUCE_LINUX
  1917. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster);
  1918. JUCE_EXPORTED_FUNCTION Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1919. {
  1920. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1921. SharedMessageThread::getInstance();
  1922. return pluginEntryPoint (audioMaster);
  1923. }
  1924. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster) asm ("main");
  1925. JUCE_EXPORTED_FUNCTION Vst2::AEffect* main_plugin (Vst2::audioMasterCallback audioMaster)
  1926. {
  1927. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1928. return VSTPluginMain (audioMaster);
  1929. }
  1930. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1931. __attribute__((constructor)) void myPluginInit() {}
  1932. __attribute__((destructor)) void myPluginFini() {}
  1933. //==============================================================================
  1934. // Win32 startup code..
  1935. #else
  1936. extern "C" __declspec (dllexport) Vst2::AEffect* VSTPluginMain (Vst2::audioMasterCallback audioMaster)
  1937. {
  1938. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1939. return pluginEntryPoint (audioMaster);
  1940. }
  1941. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1942. extern "C" __declspec (dllexport) int main (Vst2::audioMasterCallback audioMaster)
  1943. {
  1944. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST;
  1945. return (int) pluginEntryPoint (audioMaster);
  1946. }
  1947. #endif
  1948. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1949. {
  1950. if (reason == DLL_PROCESS_ATTACH)
  1951. Process::setCurrentModuleInstanceHandle (instance);
  1952. return true;
  1953. }
  1954. #endif
  1955. #endif