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.

2293 lines
87KB

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