The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2255 lines
84KB

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