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.

2096 lines
81KB

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