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.

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