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.

2159 lines
84KB

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