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.

2204 lines
84KB

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