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.

2151 lines
83KB

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