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.

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