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.

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