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.

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