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.

2129 lines
82KB

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