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.

2091 lines
81KB

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