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.

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