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.

2118 lines
82KB

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