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.

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