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.

2307 lines
88KB

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