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.

2127 lines
82KB

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