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.

2255 lines
86KB

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