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.

1882 lines
66KB

  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. /* These files come with the Steinberg VST SDK - to get them, you'll need to
  45. visit the Steinberg website and agree to whatever is currently required to
  46. get them. The best version to get is the VST3 SDK, which also contains
  47. the older VST2.4 files.
  48. Then, you'll need to make sure your include path contains your "VST SDK3"
  49. directory (or whatever you've named it on your machine). The introjucer has
  50. a special box for setting this path.
  51. */
  52. #include <public.sdk/source/vst2.x/audioeffectx.h>
  53. #include <public.sdk/source/vst2.x/aeffeditor.h>
  54. #include <public.sdk/source/vst2.x/audioeffectx.cpp>
  55. #include <public.sdk/source/vst2.x/audioeffect.cpp>
  56. #if ! VST_2_4_EXTENSIONS
  57. #error "It looks like you're trying to include an out-of-date VSTSDK version - make sure you have at least version 2.4"
  58. #endif
  59. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  60. #define JUCE_VST3_CAN_REPLACE_VST2 1
  61. #endif
  62. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  63. #include <pluginterfaces/base/funknown.h>
  64. namespace juce { extern Steinberg::FUID getJuceVST3ComponentIID(); }
  65. #endif
  66. #ifdef _MSC_VER
  67. #pragma warning (pop)
  68. #endif
  69. #ifdef __clang__
  70. #pragma clang diagnostic pop
  71. #endif
  72. //==============================================================================
  73. #ifdef _MSC_VER
  74. #pragma pack (push, 8)
  75. #endif
  76. #include "../utility/juce_IncludeModuleHeaders.h"
  77. #include "../utility/juce_FakeMouseMoveGenerator.h"
  78. #include "../utility/juce_WindowsHooks.h"
  79. #include "../utility/juce_PluginBusUtilities.h"
  80. #ifdef _MSC_VER
  81. #pragma pack (pop)
  82. #endif
  83. #undef MemoryBlock
  84. class JuceVSTWrapper;
  85. static bool recursionCheck = false;
  86. namespace juce
  87. {
  88. #if JUCE_MAC
  89. extern void initialiseMacVST();
  90. extern void* attachComponentToWindowRefVST (Component*, void* parent, bool isNSView);
  91. extern void detachComponentFromWindowRefVST (Component*, void* window, bool isNSView);
  92. extern void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  93. extern void checkWindowVisibilityVST (void* window, Component*, bool isNSView);
  94. extern bool forwardCurrentKeyEventToHostVST (Component*, bool isNSView);
  95. #if ! JUCE_64BIT
  96. extern void updateEditorCompBoundsVST (Component*);
  97. #endif
  98. #endif
  99. #if JUCE_LINUX
  100. extern Display* display;
  101. #endif
  102. }
  103. //==============================================================================
  104. #if JUCE_WINDOWS
  105. namespace
  106. {
  107. // Returns the actual container window, unlike GetParent, which can also return a separate owner window.
  108. static HWND getWindowParent (HWND w) noexcept { return GetAncestor (w, GA_PARENT); }
  109. static HWND findMDIParentOf (HWND w)
  110. {
  111. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  112. while (w != 0)
  113. {
  114. HWND parent = getWindowParent (w);
  115. if (parent == 0)
  116. break;
  117. TCHAR windowType[32] = { 0 };
  118. GetClassName (parent, windowType, 31);
  119. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  120. return parent;
  121. RECT windowPos, parentPos;
  122. GetWindowRect (w, &windowPos);
  123. GetWindowRect (parent, &parentPos);
  124. const int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  125. const int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  126. if (dw > 100 || dh > 100)
  127. break;
  128. w = parent;
  129. if (dw == 2 * frameThickness)
  130. break;
  131. }
  132. return w;
  133. }
  134. static bool messageThreadIsDefinitelyCorrect = false;
  135. }
  136. //==============================================================================
  137. #elif JUCE_LINUX
  138. class SharedMessageThread : public Thread
  139. {
  140. public:
  141. SharedMessageThread()
  142. : Thread ("VstMessageThread"),
  143. initialised (false)
  144. {
  145. startThread (7);
  146. while (! initialised)
  147. sleep (1);
  148. }
  149. ~SharedMessageThread()
  150. {
  151. signalThreadShouldExit();
  152. JUCEApplicationBase::quit();
  153. waitForThreadToExit (5000);
  154. clearSingletonInstance();
  155. }
  156. void run() override
  157. {
  158. initialiseJuce_GUI();
  159. initialised = true;
  160. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  161. while ((! threadShouldExit()) && MessageManager::getInstance()->runDispatchLoopUntil (250))
  162. {}
  163. }
  164. juce_DeclareSingleton (SharedMessageThread, false)
  165. private:
  166. bool initialised;
  167. };
  168. juce_ImplementSingleton (SharedMessageThread)
  169. #endif
  170. static Array<void*> activePlugins;
  171. //==============================================================================
  172. /**
  173. This is an AudioEffectX object that holds and wraps our AudioProcessor...
  174. */
  175. class JuceVSTWrapper : public AudioEffectX,
  176. public AudioProcessorListener,
  177. public AudioPlayHead,
  178. private Timer,
  179. private AsyncUpdater
  180. {
  181. private:
  182. //==============================================================================
  183. template <typename FloatType>
  184. struct VstTempBuffers
  185. {
  186. VstTempBuffers() {}
  187. ~VstTempBuffers() { release(); }
  188. void release() noexcept
  189. {
  190. for (int i = tempChannels.size(); --i >= 0;)
  191. delete[] (tempChannels.getUnchecked(i));
  192. tempChannels.clear();
  193. }
  194. HeapBlock<FloatType*> channels;
  195. Array<FloatType*> tempChannels; // see note in processReplacing()
  196. juce::AudioBuffer<FloatType> processTempBuffer;
  197. };
  198. public:
  199. //==============================================================================
  200. JuceVSTWrapper (audioMasterCallback audioMasterCB, AudioProcessor* const af)
  201. : AudioEffectX (audioMasterCB, af->getNumPrograms(), af->getNumParameters()),
  202. filter (af),
  203. busUtils (*filter, false),
  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. int maxNumInChannels, maxNumOutChannels;
  219. busUtils.findAllCompatibleLayouts();
  220. // VST-2 does not support disabling buses: so always enable all of them
  221. if (busUtils.hasDynamicInBuses() || busUtils.hasDynamicOutBuses())
  222. busUtils.enableAllBuses();
  223. {
  224. PluginBusUtilities::ScopedBusRestorer busRestorer (busUtils);
  225. maxNumInChannels = busUtils.getBusCount (true) > 0 ? busUtils.getSupportedBusLayouts (true, 0).maxNumberOfChannels() : 0;
  226. maxNumOutChannels = busUtils.getBusCount (false) > 0 ? busUtils.getSupportedBusLayouts (false, 0).maxNumberOfChannels() : 0;
  227. if (hostOnlySupportsStereo())
  228. {
  229. maxNumInChannels = jmin (maxNumInChannels, 2);
  230. maxNumOutChannels = jmin (maxNumOutChannels, 2);
  231. }
  232. // try setting the number of channels
  233. if (maxNumInChannels > 0)
  234. filter->setPreferredBusArrangement (true, 0, busUtils.getDefaultLayoutForChannelNumAndBus (true, 0, maxNumInChannels));
  235. if (maxNumOutChannels > 0)
  236. filter->setPreferredBusArrangement (false, 0, busUtils.getDefaultLayoutForChannelNumAndBus (false, 0, maxNumOutChannels));
  237. resetAuxChannelsToDefaultLayout (true);
  238. resetAuxChannelsToDefaultLayout (false);
  239. maxNumInChannels = busUtils.findTotalNumChannels (true);
  240. maxNumOutChannels = busUtils.findTotalNumChannels (false);
  241. if ((busUtils.getBusCount (true) > 0 && busUtils.getDefaultLayoutForBus (true, 0) .size() > maxNumInChannels)
  242. || (busUtils.getBusCount (false) > 0 && busUtils.getDefaultLayoutForBus (false, 0).size() > maxNumOutChannels))
  243. busRestorer.release();
  244. }
  245. filter->setRateAndBufferSizeDetails (0, 0);
  246. filter->setPlayHead (this);
  247. filter->addListener (this);
  248. cEffect.flags |= effFlagsHasEditor;
  249. cEffect.version = convertHexVersionToDecimal (JucePlugin_VersionCode);
  250. setUniqueID ((int) (JucePlugin_VSTUniqueID));
  251. setNumInputs (maxNumInChannels);
  252. setNumOutputs (maxNumOutChannels);
  253. canProcessReplacing (true);
  254. canDoubleReplacing (filter->supportsDoublePrecisionProcessing());
  255. isSynth ((JucePlugin_IsSynth) != 0);
  256. setInitialDelay (filter->getLatencySamples());
  257. programsAreChunks (true);
  258. // NB: For reasons best known to themselves, some hosts fail to load/save plugin
  259. // state correctly if the plugin doesn't report that it has at least 1 program.
  260. jassert (af->getNumPrograms() > 0);
  261. activePlugins.add (this);
  262. }
  263. ~JuceVSTWrapper()
  264. {
  265. JUCE_AUTORELEASEPOOL
  266. {
  267. {
  268. #if JUCE_LINUX
  269. MessageManagerLock mmLock;
  270. #endif
  271. stopTimer();
  272. deleteEditor (false);
  273. hasShutdown = true;
  274. delete filter;
  275. filter = nullptr;
  276. jassert (editorComp == 0);
  277. deleteTempChannels();
  278. jassert (activePlugins.contains (this));
  279. activePlugins.removeFirstMatchingValue (this);
  280. }
  281. if (activePlugins.size() == 0)
  282. {
  283. #if JUCE_LINUX
  284. SharedMessageThread::deleteInstance();
  285. #endif
  286. shutdownJuce_GUI();
  287. #if JUCE_WINDOWS
  288. messageThreadIsDefinitelyCorrect = false;
  289. #endif
  290. }
  291. }
  292. }
  293. void open() override
  294. {
  295. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  296. if (filter->hasEditor())
  297. cEffect.flags |= effFlagsHasEditor;
  298. else
  299. cEffect.flags &= ~effFlagsHasEditor;
  300. }
  301. void close() override
  302. {
  303. // Note: most hosts call this on the UI thread, but wavelab doesn't, so be careful in here.
  304. stopTimer();
  305. if (MessageManager::getInstance()->isThisTheMessageThread())
  306. deleteEditor (false);
  307. }
  308. //==============================================================================
  309. bool getEffectName (char* name) override
  310. {
  311. String (JucePlugin_Name).copyToUTF8 (name, 64);
  312. return true;
  313. }
  314. bool getVendorString (char* text) override
  315. {
  316. String (JucePlugin_Manufacturer).copyToUTF8 (text, 64);
  317. return true;
  318. }
  319. bool getProductString (char* text) override { return getEffectName (text); }
  320. VstInt32 getVendorVersion() override { return convertHexVersionToDecimal (JucePlugin_VersionCode); }
  321. VstPlugCategory getPlugCategory() override { return JucePlugin_VSTCategory; }
  322. bool keysRequired() { return (JucePlugin_EditorRequiresKeyboardFocus) != 0; }
  323. VstInt32 canDo (char* text) override
  324. {
  325. if (strcmp (text, "receiveVstEvents") == 0
  326. || strcmp (text, "receiveVstMidiEvent") == 0
  327. || strcmp (text, "receiveVstMidiEvents") == 0)
  328. {
  329. #if JucePlugin_WantsMidiInput
  330. return 1;
  331. #else
  332. return -1;
  333. #endif
  334. }
  335. if (strcmp (text, "sendVstEvents") == 0
  336. || strcmp (text, "sendVstMidiEvent") == 0
  337. || strcmp (text, "sendVstMidiEvents") == 0)
  338. {
  339. #if JucePlugin_ProducesMidiOutput
  340. return 1;
  341. #else
  342. return -1;
  343. #endif
  344. }
  345. if (strcmp (text, "receiveVstTimeInfo") == 0
  346. || strcmp (text, "conformsToWindowRules") == 0
  347. || strcmp (text, "bypass") == 0)
  348. {
  349. return 1;
  350. }
  351. // This tells Wavelab to use the UI thread to invoke open/close,
  352. // like all other hosts do.
  353. if (strcmp (text, "openCloseAnyThread") == 0)
  354. return -1;
  355. if (strcmp (text, "MPE") == 0)
  356. return filter->supportsMPE() ? 1 : 0;
  357. #if JUCE_MAC
  358. if (strcmp (text, "hasCockosViewAsConfig") == 0)
  359. {
  360. useNSView = true;
  361. return (VstInt32) 0xbeef0000;
  362. }
  363. #endif
  364. return 0;
  365. }
  366. VstIntPtr vendorSpecific (VstInt32 lArg, VstIntPtr lArg2, void* ptrArg, float floatArg) override
  367. {
  368. ignoreUnused (lArg, lArg2, ptrArg, floatArg);
  369. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  370. if ((lArg == 'stCA' || lArg == 'stCa') && lArg2 == 'FUID' && ptrArg != nullptr)
  371. {
  372. memcpy (ptrArg, getJuceVST3ComponentIID(), 16);
  373. return 1;
  374. }
  375. #endif
  376. return 0;
  377. }
  378. bool setBypass (bool b) override
  379. {
  380. isBypassed = b;
  381. return true;
  382. }
  383. VstInt32 getGetTailSize() override
  384. {
  385. if (filter != nullptr)
  386. return (VstInt32) (filter->getTailLengthSeconds() * getSampleRate());
  387. return 0;
  388. }
  389. //==============================================================================
  390. VstInt32 processEvents (VstEvents* events) override
  391. {
  392. #if JucePlugin_WantsMidiInput
  393. VSTMidiEventList::addEventsToMidiBuffer (events, midiEvents);
  394. return 1;
  395. #else
  396. ignoreUnused (events);
  397. return 0;
  398. #endif
  399. }
  400. template <typename FloatType>
  401. void internalProcessReplacing (FloatType** inputs, FloatType** outputs,
  402. VstInt32 numSamples, VstTempBuffers<FloatType>& tmpBuffers)
  403. {
  404. if (firstProcessCallback)
  405. {
  406. firstProcessCallback = false;
  407. // if this fails, the host hasn't called resume() before processing
  408. jassert (isProcessing);
  409. // (tragically, some hosts actually need this, although it's stupid to have
  410. // to do it here..)
  411. if (! isProcessing)
  412. resume();
  413. filter->setNonRealtime (getCurrentProcessLevel() == 4 /* kVstProcessLevelOffline */);
  414. }
  415. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  416. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  417. #endif
  418. jassert (activePlugins.contains (this));
  419. {
  420. const int numIn = cEffect.numInputs;
  421. const int numOut = cEffect.numOutputs;
  422. const ScopedLock sl (filter->getCallbackLock());
  423. if (filter->isSuspended())
  424. {
  425. for (int i = 0; i < numOut; ++i)
  426. FloatVectorOperations::clear (outputs[i], numSamples);
  427. }
  428. else
  429. {
  430. int i;
  431. for (i = 0; i < numOut; ++i)
  432. {
  433. FloatType* chan = tmpBuffers.tempChannels.getUnchecked(i);
  434. if (chan == nullptr)
  435. {
  436. chan = outputs[i];
  437. // if some output channels are disabled, some hosts supply the same buffer
  438. // for multiple channels - this buggers up our method of copying the
  439. // inputs over the outputs, so we need to create unique temp buffers in this case..
  440. for (int j = i; --j >= 0;)
  441. {
  442. if (outputs[j] == chan)
  443. {
  444. chan = new FloatType [blockSize * 2];
  445. tmpBuffers.tempChannels.set (i, chan);
  446. break;
  447. }
  448. }
  449. }
  450. if (i < numIn && chan != inputs[i])
  451. memcpy (chan, inputs[i], sizeof (FloatType) * (size_t) numSamples);
  452. tmpBuffers.channels[i] = chan;
  453. }
  454. for (; i < numIn; ++i)
  455. tmpBuffers.channels[i] = inputs[i];
  456. {
  457. const int numChannels = jmax (filter->getTotalNumInputChannels(), filter->getTotalNumOutputChannels());
  458. AudioBuffer<FloatType> chans (tmpBuffers.channels, numChannels, numSamples);
  459. if (isBypassed)
  460. filter->processBlockBypassed (chans, midiEvents);
  461. else
  462. filter->processBlock (chans, midiEvents);
  463. }
  464. // copy back any temp channels that may have been used..
  465. for (i = 0; i < numOut; ++i)
  466. if (const FloatType* const chan = tmpBuffers.tempChannels.getUnchecked(i))
  467. memcpy (outputs[i], chan, sizeof (FloatType) * (size_t) numSamples);
  468. }
  469. }
  470. if (! midiEvents.isEmpty())
  471. {
  472. #if JucePlugin_ProducesMidiOutput
  473. const int numEvents = midiEvents.getNumEvents();
  474. outgoingEvents.ensureSize (numEvents);
  475. outgoingEvents.clear();
  476. const juce::uint8* midiEventData;
  477. int midiEventSize, midiEventPosition;
  478. MidiBuffer::Iterator i (midiEvents);
  479. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  480. {
  481. jassert (midiEventPosition >= 0 && midiEventPosition < numSamples);
  482. outgoingEvents.addEvent (midiEventData, midiEventSize, midiEventPosition);
  483. }
  484. sendVstEventsToHost (outgoingEvents.events);
  485. #elif JUCE_DEBUG
  486. /* This assertion is caused when you've added some events to the
  487. midiMessages array in your processBlock() method, which usually means
  488. that you're trying to send them somewhere. But in this case they're
  489. getting thrown away.
  490. If your plugin does want to send midi messages, you'll need to set
  491. the JucePlugin_ProducesMidiOutput macro to 1 in your
  492. JucePluginCharacteristics.h file.
  493. If you don't want to produce any midi output, then you should clear the
  494. midiMessages array at the end of your processBlock() method, to
  495. indicate that you don't want any of the events to be passed through
  496. to the output.
  497. */
  498. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  499. #endif
  500. midiEvents.clear();
  501. }
  502. }
  503. void processReplacing (float** inputs, float** outputs, VstInt32 sampleFrames) override
  504. {
  505. jassert (! filter->isUsingDoublePrecision());
  506. internalProcessReplacing (inputs, outputs, sampleFrames, floatTempBuffers);
  507. }
  508. void processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames) override
  509. {
  510. jassert (filter->isUsingDoublePrecision());
  511. internalProcessReplacing (inputs, outputs, sampleFrames, doubleTempBuffers);
  512. }
  513. //==============================================================================
  514. VstInt32 startProcess() override { return 0; }
  515. VstInt32 stopProcess() override { return 0; }
  516. //==============================================================================
  517. bool setProcessPrecision (VstInt32 vstPrecision) override
  518. {
  519. if (! isProcessing)
  520. {
  521. if (filter != nullptr)
  522. {
  523. filter->setProcessingPrecision (vstPrecision == kVstProcessPrecision64 && filter->supportsDoublePrecisionProcessing()
  524. ? AudioProcessor::doublePrecision
  525. : AudioProcessor::singlePrecision);
  526. return true;
  527. }
  528. }
  529. return false;
  530. }
  531. void resume() override
  532. {
  533. if (filter != nullptr)
  534. {
  535. isProcessing = true;
  536. floatTempBuffers.channels.calloc ((size_t) (cEffect.numInputs + cEffect.numOutputs));
  537. doubleTempBuffers.channels.calloc ((size_t) (cEffect.numInputs + cEffect.numOutputs));
  538. double rate = getSampleRate();
  539. jassert (rate > 0);
  540. if (rate <= 0.0)
  541. rate = 44100.0;
  542. const int currentBlockSize = getBlockSize();
  543. jassert (currentBlockSize > 0);
  544. firstProcessCallback = true;
  545. filter->setNonRealtime (getCurrentProcessLevel() == 4 /* kVstProcessLevelOffline */);
  546. filter->setRateAndBufferSizeDetails (rate, currentBlockSize);
  547. deleteTempChannels();
  548. filter->prepareToPlay (rate, currentBlockSize);
  549. midiEvents.ensureSize (2048);
  550. midiEvents.clear();
  551. setInitialDelay (filter->getLatencySamples());
  552. AudioEffectX::resume();
  553. #if JucePlugin_ProducesMidiOutput
  554. outgoingEvents.ensureSize (512);
  555. #endif
  556. }
  557. }
  558. void suspend() override
  559. {
  560. if (filter != nullptr)
  561. {
  562. AudioEffectX::suspend();
  563. filter->releaseResources();
  564. outgoingEvents.freeEvents();
  565. isProcessing = false;
  566. floatTempBuffers.channels.free();
  567. doubleTempBuffers.channels.free();
  568. deleteTempChannels();
  569. }
  570. }
  571. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info) override
  572. {
  573. const VstTimeInfo* const ti = getTimeInfo (kVstPpqPosValid | kVstTempoValid | kVstBarsValid | kVstCyclePosValid
  574. | kVstTimeSigValid | kVstSmpteValid | kVstClockValid);
  575. if (ti == nullptr || ti->sampleRate <= 0)
  576. return false;
  577. info.bpm = (ti->flags & kVstTempoValid) != 0 ? ti->tempo : 0.0;
  578. if ((ti->flags & kVstTimeSigValid) != 0)
  579. {
  580. info.timeSigNumerator = ti->timeSigNumerator;
  581. info.timeSigDenominator = ti->timeSigDenominator;
  582. }
  583. else
  584. {
  585. info.timeSigNumerator = 4;
  586. info.timeSigDenominator = 4;
  587. }
  588. info.timeInSamples = (int64) (ti->samplePos + 0.5);
  589. info.timeInSeconds = ti->samplePos / ti->sampleRate;
  590. info.ppqPosition = (ti->flags & kVstPpqPosValid) != 0 ? ti->ppqPos : 0.0;
  591. info.ppqPositionOfLastBarStart = (ti->flags & kVstBarsValid) != 0 ? ti->barStartPos : 0.0;
  592. if ((ti->flags & kVstSmpteValid) != 0)
  593. {
  594. AudioPlayHead::FrameRateType rate = AudioPlayHead::fpsUnknown;
  595. double fps = 1.0;
  596. switch (ti->smpteFrameRate)
  597. {
  598. case kVstSmpte24fps: rate = AudioPlayHead::fps24; fps = 24.0; break;
  599. case kVstSmpte25fps: rate = AudioPlayHead::fps25; fps = 25.0; break;
  600. case kVstSmpte2997fps: rate = AudioPlayHead::fps2997; fps = 29.97; break;
  601. case kVstSmpte30fps: rate = AudioPlayHead::fps30; fps = 30.0; break;
  602. case kVstSmpte2997dfps: rate = AudioPlayHead::fps2997drop; fps = 29.97; break;
  603. case kVstSmpte30dfps: rate = AudioPlayHead::fps30drop; fps = 30.0; break;
  604. case kVstSmpteFilm16mm:
  605. case kVstSmpteFilm35mm: fps = 24.0; break;
  606. case kVstSmpte239fps: fps = 23.976; break;
  607. case kVstSmpte249fps: fps = 24.976; break;
  608. case kVstSmpte599fps: fps = 59.94; break;
  609. case kVstSmpte60fps: fps = 60; break;
  610. default: jassertfalse; // unknown frame-rate..
  611. }
  612. info.frameRate = rate;
  613. info.editOriginTime = ti->smpteOffset / (80.0 * fps);
  614. }
  615. else
  616. {
  617. info.frameRate = AudioPlayHead::fpsUnknown;
  618. info.editOriginTime = 0;
  619. }
  620. info.isRecording = (ti->flags & kVstTransportRecording) != 0;
  621. info.isPlaying = (ti->flags & (kVstTransportRecording | kVstTransportPlaying)) != 0;
  622. info.isLooping = (ti->flags & kVstTransportCycleActive) != 0;
  623. if ((ti->flags & kVstCyclePosValid) != 0)
  624. {
  625. info.ppqLoopStart = ti->cycleStartPos;
  626. info.ppqLoopEnd = ti->cycleEndPos;
  627. }
  628. else
  629. {
  630. info.ppqLoopStart = 0;
  631. info.ppqLoopEnd = 0;
  632. }
  633. return true;
  634. }
  635. //==============================================================================
  636. VstInt32 getProgram() override
  637. {
  638. return filter != nullptr ? filter->getCurrentProgram() : 0;
  639. }
  640. void setProgram (VstInt32 program) override
  641. {
  642. if (filter != nullptr)
  643. filter->setCurrentProgram (program);
  644. }
  645. void setProgramName (char* name) override
  646. {
  647. if (filter != nullptr)
  648. filter->changeProgramName (filter->getCurrentProgram(), name);
  649. }
  650. void getProgramName (char* name) override
  651. {
  652. if (filter != nullptr)
  653. filter->getProgramName (filter->getCurrentProgram()).copyToUTF8 (name, 24);
  654. }
  655. bool getProgramNameIndexed (VstInt32 /*category*/, VstInt32 index, char* text) override
  656. {
  657. if (filter != nullptr && isPositiveAndBelow (index, filter->getNumPrograms()))
  658. {
  659. filter->getProgramName (index).copyToUTF8 (text, 24);
  660. return true;
  661. }
  662. return false;
  663. }
  664. //==============================================================================
  665. float getParameter (VstInt32 index) override
  666. {
  667. if (filter == nullptr)
  668. return 0.0f;
  669. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  670. return filter->getParameter (index);
  671. }
  672. void setParameter (VstInt32 index, float value) override
  673. {
  674. if (filter != nullptr)
  675. {
  676. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  677. filter->setParameter (index, value);
  678. }
  679. }
  680. void getParameterDisplay (VstInt32 index, char* text) override
  681. {
  682. if (filter != nullptr)
  683. {
  684. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  685. filter->getParameterText (index, 24).copyToUTF8 (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  686. }
  687. }
  688. bool string2parameter (VstInt32 index, char* text) override
  689. {
  690. if (filter != nullptr)
  691. {
  692. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  693. if (AudioProcessorParameter* p = filter->getParameters()[index])
  694. {
  695. filter->setParameter (index, p->getValueForText (String::fromUTF8 (text)));
  696. return true;
  697. }
  698. }
  699. return false;
  700. }
  701. void getParameterName (VstInt32 index, char* text) override
  702. {
  703. if (filter != nullptr)
  704. {
  705. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  706. filter->getParameterName (index, 16).copyToUTF8 (text, 16); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  707. }
  708. }
  709. void getParameterLabel (VstInt32 index, char* text) override
  710. {
  711. if (filter != nullptr)
  712. {
  713. jassert (isPositiveAndBelow (index, filter->getNumParameters()));
  714. filter->getParameterLabel (index).copyToUTF8 (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  715. }
  716. }
  717. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  718. {
  719. if (audioMaster != nullptr)
  720. audioMaster (&cEffect, audioMasterAutomate, index, 0, 0, newValue);
  721. }
  722. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit (index); }
  723. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit (index); }
  724. void audioProcessorChanged (AudioProcessor*) override
  725. {
  726. setInitialDelay (filter->getLatencySamples());
  727. updateDisplay();
  728. triggerAsyncUpdate();
  729. }
  730. void handleAsyncUpdate() override
  731. {
  732. ioChanged();
  733. }
  734. bool canParameterBeAutomated (VstInt32 index) override
  735. {
  736. return filter != nullptr && filter->isParameterAutomatable ((int) index);
  737. }
  738. bool setSpeakerArrangement (VstSpeakerArrangement* pluginInput,
  739. VstSpeakerArrangement* pluginOutput) override
  740. {
  741. if (pluginInput != nullptr && filter->busArrangement.inputBuses.size() == 0)
  742. return false;
  743. if (pluginOutput != nullptr && filter->busArrangement.outputBuses.size() == 0)
  744. return false;
  745. PluginBusUtilities::ScopedBusRestorer busRestorer (busUtils);
  746. resetAuxChannelsToDefaultLayout (true);
  747. resetAuxChannelsToDefaultLayout (false);
  748. if (pluginInput != nullptr && pluginInput->numChannels >= 0)
  749. {
  750. AudioChannelSet newType;
  751. // subtract the number of channels which are used by the aux channels
  752. int mainNumChannels = pluginInput->numChannels - busUtils.findTotalNumChannels (true, 1);
  753. if (mainNumChannels <= 0)
  754. return false;
  755. if (mainNumChannels > busUtils.getSupportedBusLayouts (true, 0).maxNumberOfChannels())
  756. return false;
  757. newType = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginInput);
  758. if (mainNumChannels != newType.size())
  759. newType = AudioChannelSet::canonicalChannelSet(mainNumChannels);
  760. if (busUtils.getChannelSet (true, 0) != newType)
  761. if (! filter->setPreferredBusArrangement (true, 0, newType))
  762. return false;
  763. }
  764. if (pluginOutput != nullptr && pluginOutput->numChannels >= 0)
  765. {
  766. AudioChannelSet newType;
  767. // subtract the number of channels which are used by the aux channels
  768. int mainNumChannels = pluginOutput->numChannels - busUtils.findTotalNumChannels (false, 1);
  769. if (mainNumChannels <= 0)
  770. return false;
  771. if (mainNumChannels > busUtils.getSupportedBusLayouts (false, 0).maxNumberOfChannels())
  772. return false;
  773. newType = SpeakerMappings::vstArrangementTypeToChannelSet (*pluginOutput);
  774. if (mainNumChannels != newType.size())
  775. newType = AudioChannelSet::canonicalChannelSet(mainNumChannels);
  776. AudioChannelSet oldOutputLayout = busUtils.getChannelSet (false, 0);
  777. AudioChannelSet oldInputLayout = busUtils.getChannelSet (true, 0);
  778. if (busUtils.getChannelSet (false, 0) != newType)
  779. if (! filter->setPreferredBusArrangement (false, 0, newType))
  780. return false;
  781. // did this change the input layout?
  782. if (oldInputLayout != busUtils.getChannelSet (true, 0) && pluginInput != nullptr)
  783. return false;
  784. }
  785. busRestorer.release();
  786. filter->setRateAndBufferSizeDetails(0, 0);
  787. return true;
  788. }
  789. bool getSpeakerArrangement (VstSpeakerArrangement** pluginInput, VstSpeakerArrangement** pluginOutput) override
  790. {
  791. *pluginInput = 0;
  792. *pluginOutput = 0;
  793. if (! AudioEffectX::allocateArrangement (pluginInput, busUtils.findTotalNumChannels (true)))
  794. return false;
  795. if (! AudioEffectX::allocateArrangement (pluginOutput, busUtils.findTotalNumChannels (false)))
  796. {
  797. AudioEffectX::deallocateArrangement (pluginInput);
  798. *pluginInput = 0;
  799. return false;
  800. }
  801. if (busUtils.getBusCount (true) > 1)
  802. {
  803. AudioChannelSet layout = AudioChannelSet::canonicalChannelSet (busUtils.findTotalNumChannels(true));
  804. SpeakerMappings::channelSetToVstArrangement (layout, **pluginInput);
  805. }
  806. else
  807. {
  808. SpeakerMappings::channelSetToVstArrangement (busUtils.getChannelSet (true, 0), **pluginInput);
  809. }
  810. if (busUtils.getBusCount (false) > 1)
  811. {
  812. AudioChannelSet layout = AudioChannelSet::canonicalChannelSet (busUtils.findTotalNumChannels(false));
  813. SpeakerMappings::channelSetToVstArrangement (layout, **pluginOutput);
  814. }
  815. else
  816. {
  817. SpeakerMappings::channelSetToVstArrangement (busUtils.getChannelSet (false, 0), **pluginOutput);
  818. }
  819. return true;
  820. }
  821. bool getInputProperties (VstInt32 index, VstPinProperties* properties) override
  822. {
  823. return filter != nullptr
  824. && getPinProperties (*properties, true, (int) index);
  825. }
  826. bool getOutputProperties (VstInt32 index, VstPinProperties* properties) override
  827. {
  828. return filter != nullptr
  829. && getPinProperties (*properties, false, (int) index);
  830. }
  831. bool getPinProperties (VstPinProperties& properties, bool direction, int index) const
  832. {
  833. // index refers to the absolute index when combining all channels of every bus
  834. if (index >= (direction ? cEffect.numInputs : cEffect.numOutputs))
  835. return false;
  836. const int n = busUtils.getBusCount(direction);
  837. int busIdx;
  838. for (busIdx = 0; busIdx < n; ++busIdx)
  839. {
  840. const int numChans = busUtils.getNumChannels (direction, busIdx);
  841. if (index < numChans)
  842. break;
  843. index -= numChans;
  844. }
  845. if (busIdx >= n)
  846. {
  847. properties.flags = kVstPinUseSpeaker;
  848. properties.label[0] = 0;
  849. properties.shortLabel[0] = 0;
  850. properties.arrangementType = kSpeakerArrEmpty;
  851. return true;
  852. }
  853. const AudioProcessor::AudioProcessorBus& busInfo = busUtils.getFilterBus (direction).getReference (busIdx);
  854. String channelName = busInfo.name;
  855. channelName +=
  856. String (" ") + AudioChannelSet::getAbbreviatedChannelTypeName (busInfo.channels.getTypeOfChannel(index));
  857. channelName.copyToUTF8 (properties.label, (size_t) (kVstMaxLabelLen - 1));
  858. channelName.copyToUTF8 (properties.shortLabel, (size_t) (kVstMaxShortLabelLen - 1));
  859. properties.flags = kVstPinUseSpeaker | kVstPinIsActive;
  860. properties.arrangementType = SpeakerMappings::channelSetToVstArrangementType (busInfo.channels);
  861. if (properties.arrangementType == kSpeakerArrEmpty)
  862. properties.flags &= ~kVstPinIsActive;
  863. if (busInfo.channels.size() == 2)
  864. properties.flags |= kVstPinIsStereo;
  865. return true;
  866. }
  867. //==============================================================================
  868. struct SpeakerMappings : private AudioChannelSet // (inheritance only to give easier access to items in the namespace)
  869. {
  870. struct Mapping
  871. {
  872. VstInt32 vst2;
  873. ChannelType channels[13];
  874. bool matches (const Array<ChannelType>& chans) const noexcept
  875. {
  876. const int n = sizeof (channels) / sizeof (ChannelType);
  877. for (int i = 0; i < n; ++i)
  878. {
  879. if (channels[i] == unknown) return (i == chans.size());
  880. if (i == chans.size()) return (channels[i] == unknown);
  881. if (channels[i] != chans.getUnchecked(i))
  882. return false;
  883. }
  884. return true;
  885. }
  886. };
  887. static AudioChannelSet vstArrangementTypeToChannelSet (const VstSpeakerArrangement& arr)
  888. {
  889. for (const Mapping* m = getMappings(); m->vst2 != kSpeakerArrEmpty; ++m)
  890. {
  891. if (m->vst2 == arr.type)
  892. {
  893. AudioChannelSet s;
  894. for (int i = 0; m->channels[i] != 0; ++i)
  895. s.addChannel (m->channels[i]);
  896. return s;
  897. }
  898. }
  899. return AudioChannelSet::discreteChannels (arr.numChannels);
  900. }
  901. static VstInt32 channelSetToVstArrangementType (AudioChannelSet channels)
  902. {
  903. Array<AudioChannelSet::ChannelType> chans (channels.getChannelTypes());
  904. if (channels == AudioChannelSet::disabled())
  905. return kSpeakerArrEmpty;
  906. for (const Mapping* m = getMappings(); m->vst2 != kSpeakerArrEmpty; ++m)
  907. if (m->matches (chans))
  908. return m->vst2;
  909. return kSpeakerArrUserDefined;
  910. }
  911. static void channelSetToVstArrangement (const AudioChannelSet& channels, VstSpeakerArrangement& result)
  912. {
  913. result.type = channelSetToVstArrangementType (channels);
  914. result.numChannels = channels.size();
  915. for (int i = 0; i < result.numChannels; ++i)
  916. {
  917. VstSpeakerProperties& speaker = result.speakers[i];
  918. zeromem (&speaker, sizeof (VstSpeakerProperties));
  919. speaker.type = getSpeakerType (channels.getTypeOfChannel (i));
  920. }
  921. }
  922. static const Mapping* getMappings() noexcept
  923. {
  924. static const Mapping mappings[] =
  925. {
  926. { kSpeakerArrMono, { centre, unknown } },
  927. { kSpeakerArrStereo, { left, right, unknown } },
  928. { kSpeakerArrStereoSurround, { surroundLeft, surroundRight, unknown } },
  929. { kSpeakerArrStereoCenter, { centreLeft, centreRight, unknown } },
  930. { kSpeakerArrStereoSide, { sideLeft, sideRight, unknown } },
  931. { kSpeakerArrStereoCLfe, { centre, subbass, unknown } },
  932. { kSpeakerArr30Cine, { left, right, centre, unknown } },
  933. { kSpeakerArr30Music, { left, right, surround, unknown } },
  934. { kSpeakerArr31Cine, { left, right, centre, subbass, unknown } },
  935. { kSpeakerArr31Music, { left, right, subbass, surround, unknown } },
  936. { kSpeakerArr40Cine, { left, right, centre, surround, unknown } },
  937. { kSpeakerArr40Music, { left, right, surroundLeft, surroundRight, unknown } },
  938. { kSpeakerArr41Cine, { left, right, centre, subbass, surround, unknown } },
  939. { kSpeakerArr41Music, { left, right, subbass, surroundLeft, surroundRight, unknown } },
  940. { kSpeakerArr50, { left, right, centre, surroundLeft, surroundRight, unknown } },
  941. { kSpeakerArr51, { left, right, centre, subbass, surroundLeft, surroundRight, unknown } },
  942. { kSpeakerArr60Cine, { left, right, centre, surroundLeft, surroundRight, surround, unknown } },
  943. { kSpeakerArr60Music, { left, right, surroundLeft, surroundRight, sideLeft, sideRight, unknown } },
  944. { kSpeakerArr61Cine, { left, right, centre, subbass, surroundLeft, surroundRight, surround, unknown } },
  945. { kSpeakerArr61Music, { left, right, subbass, surroundLeft, surroundRight, sideLeft, sideRight, unknown } },
  946. { kSpeakerArr70Cine, { left, right, centre, surroundLeft, surroundRight, topFrontLeft, topFrontRight, unknown } },
  947. { kSpeakerArr70Music, { left, right, centre, surroundLeft, surroundRight, sideLeft, sideRight, unknown } },
  948. { kSpeakerArr71Cine, { left, right, centre, subbass, surroundLeft, surroundRight, topFrontLeft, topFrontRight, unknown } },
  949. { kSpeakerArr71Music, { left, right, centre, subbass, surroundLeft, surroundRight, sideLeft, sideRight, unknown } },
  950. { kSpeakerArr80Cine, { left, right, centre, surroundLeft, surroundRight, topFrontLeft, topFrontRight, surround, unknown } },
  951. { kSpeakerArr80Music, { left, right, centre, surroundLeft, surroundRight, surround, sideLeft, sideRight, unknown } },
  952. { kSpeakerArr81Cine, { left, right, centre, subbass, surroundLeft, surroundRight, topFrontLeft, topFrontRight, surround, unknown } },
  953. { kSpeakerArr81Music, { left, right, centre, subbass, surroundLeft, surroundRight, surround, sideLeft, sideRight, unknown } },
  954. { kSpeakerArr102, { left, right, centre, subbass, surroundLeft, surroundRight, topFrontLeft, topFrontCentre, topFrontRight, topRearLeft, topRearRight, subbass2, unknown } },
  955. { kSpeakerArrEmpty, { unknown } }
  956. };
  957. return mappings;
  958. }
  959. static inline VstInt32 getSpeakerType (AudioChannelSet::ChannelType type) noexcept
  960. {
  961. switch (type)
  962. {
  963. case AudioChannelSet::left: return kSpeakerL;
  964. case AudioChannelSet::right: return kSpeakerR;
  965. case AudioChannelSet::centre: return kSpeakerC;
  966. case AudioChannelSet::subbass: return kSpeakerLfe;
  967. case AudioChannelSet::surroundLeft: return kSpeakerLs;
  968. case AudioChannelSet::surroundRight: return kSpeakerRs;
  969. case AudioChannelSet::centreLeft: return kSpeakerLc;
  970. case AudioChannelSet::centreRight: return kSpeakerRc;
  971. case AudioChannelSet::surround: return kSpeakerS;
  972. case AudioChannelSet::sideLeft: return kSpeakerSl;
  973. case AudioChannelSet::sideRight: return kSpeakerSr;
  974. case AudioChannelSet::topMiddle: return kSpeakerTm;
  975. case AudioChannelSet::topFrontLeft: return kSpeakerTfl;
  976. case AudioChannelSet::topFrontCentre: return kSpeakerTfc;
  977. case AudioChannelSet::topFrontRight: return kSpeakerTfr;
  978. case AudioChannelSet::topRearLeft: return kSpeakerTrl;
  979. case AudioChannelSet::topRearCentre: return kSpeakerTrc;
  980. case AudioChannelSet::topRearRight: return kSpeakerTrr;
  981. case AudioChannelSet::subbass2: return kSpeakerLfe2;
  982. default: break;
  983. }
  984. return 0;
  985. }
  986. static inline AudioChannelSet::ChannelType getChannelType (VstInt32 type) noexcept
  987. {
  988. switch (type)
  989. {
  990. case kSpeakerL: return AudioChannelSet::left;
  991. case kSpeakerR: return AudioChannelSet::right;
  992. case kSpeakerC: return AudioChannelSet::centre;
  993. case kSpeakerLfe: return AudioChannelSet::subbass;
  994. case kSpeakerLs: return AudioChannelSet::surroundLeft;
  995. case kSpeakerRs: return AudioChannelSet::surroundRight;
  996. case kSpeakerLc: return AudioChannelSet::centreLeft;
  997. case kSpeakerRc: return AudioChannelSet::centreRight;
  998. case kSpeakerS: return AudioChannelSet::surround;
  999. case kSpeakerSl: return AudioChannelSet::sideLeft;
  1000. case kSpeakerSr: return AudioChannelSet::sideRight;
  1001. case kSpeakerTm: return AudioChannelSet::topMiddle;
  1002. case kSpeakerTfl: return AudioChannelSet::topFrontLeft;
  1003. case kSpeakerTfc: return AudioChannelSet::topFrontCentre;
  1004. case kSpeakerTfr: return AudioChannelSet::topFrontRight;
  1005. case kSpeakerTrl: return AudioChannelSet::topRearLeft;
  1006. case kSpeakerTrc: return AudioChannelSet::topRearCentre;
  1007. case kSpeakerTrr: return AudioChannelSet::topRearRight;
  1008. case kSpeakerLfe2: return AudioChannelSet::subbass2;
  1009. default: break;
  1010. }
  1011. return AudioChannelSet::unknown;
  1012. }
  1013. };
  1014. //==============================================================================
  1015. VstInt32 getChunk (void** data, bool onlyStoreCurrentProgramData) override
  1016. {
  1017. if (filter == nullptr)
  1018. return 0;
  1019. chunkMemory.reset();
  1020. if (onlyStoreCurrentProgramData)
  1021. filter->getCurrentProgramStateInformation (chunkMemory);
  1022. else
  1023. filter->getStateInformation (chunkMemory);
  1024. *data = (void*) chunkMemory.getData();
  1025. // because the chunk is only needed temporarily by the host (or at least you'd
  1026. // hope so) we'll give it a while and then free it in the timer callback.
  1027. chunkMemoryTime = juce::Time::getApproximateMillisecondCounter();
  1028. return (VstInt32) chunkMemory.getSize();
  1029. }
  1030. VstInt32 setChunk (void* data, VstInt32 byteSize, bool onlyRestoreCurrentProgramData) override
  1031. {
  1032. if (filter != nullptr)
  1033. {
  1034. chunkMemory.reset();
  1035. chunkMemoryTime = 0;
  1036. if (byteSize > 0 && data != nullptr)
  1037. {
  1038. if (onlyRestoreCurrentProgramData)
  1039. filter->setCurrentProgramStateInformation (data, byteSize);
  1040. else
  1041. filter->setStateInformation (data, byteSize);
  1042. }
  1043. }
  1044. return 0;
  1045. }
  1046. void timerCallback() override
  1047. {
  1048. if (shouldDeleteEditor)
  1049. {
  1050. shouldDeleteEditor = false;
  1051. deleteEditor (true);
  1052. }
  1053. if (chunkMemoryTime > 0
  1054. && chunkMemoryTime < juce::Time::getApproximateMillisecondCounter() - 2000
  1055. && ! recursionCheck)
  1056. {
  1057. chunkMemory.reset();
  1058. chunkMemoryTime = 0;
  1059. }
  1060. #if JUCE_MAC
  1061. if (hostWindow != 0)
  1062. checkWindowVisibilityVST (hostWindow, editorComp, useNSView);
  1063. #endif
  1064. }
  1065. void doIdleCallback()
  1066. {
  1067. // (wavelab calls this on a separate thread and causes a deadlock)..
  1068. if (MessageManager::getInstance()->isThisTheMessageThread()
  1069. && ! recursionCheck)
  1070. {
  1071. ScopedValueSetter<bool> svs (recursionCheck, true, false);
  1072. JUCE_AUTORELEASEPOOL
  1073. {
  1074. Timer::callPendingTimersSynchronously();
  1075. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1076. if (ComponentPeer* p = ComponentPeer::getPeer(i))
  1077. p->performAnyPendingRepaintsNow();
  1078. }
  1079. }
  1080. }
  1081. void createEditorComp()
  1082. {
  1083. if (hasShutdown || filter == nullptr)
  1084. return;
  1085. if (editorComp == nullptr)
  1086. {
  1087. if (AudioProcessorEditor* const ed = filter->createEditorIfNeeded())
  1088. {
  1089. cEffect.flags |= effFlagsHasEditor;
  1090. ed->setOpaque (true);
  1091. ed->setVisible (true);
  1092. editorComp = new EditorCompWrapper (*this, ed);
  1093. }
  1094. else
  1095. {
  1096. cEffect.flags &= ~effFlagsHasEditor;
  1097. }
  1098. }
  1099. shouldDeleteEditor = false;
  1100. }
  1101. void deleteEditor (bool canDeleteLaterIfModal)
  1102. {
  1103. JUCE_AUTORELEASEPOOL
  1104. {
  1105. PopupMenu::dismissAllActiveMenus();
  1106. jassert (! recursionCheck);
  1107. ScopedValueSetter<bool> svs (recursionCheck, true, false);
  1108. if (editorComp != nullptr)
  1109. {
  1110. if (Component* const modalComponent = Component::getCurrentlyModalComponent())
  1111. {
  1112. modalComponent->exitModalState (0);
  1113. if (canDeleteLaterIfModal)
  1114. {
  1115. shouldDeleteEditor = true;
  1116. return;
  1117. }
  1118. }
  1119. #if JUCE_MAC
  1120. if (hostWindow != 0)
  1121. {
  1122. detachComponentFromWindowRefVST (editorComp, hostWindow, useNSView);
  1123. hostWindow = 0;
  1124. }
  1125. #endif
  1126. filter->editorBeingDeleted (editorComp->getEditorComp());
  1127. editorComp = nullptr;
  1128. // there's some kind of component currently modal, but the host
  1129. // is trying to delete our plugin. You should try to avoid this happening..
  1130. jassert (Component::getCurrentlyModalComponent() == nullptr);
  1131. }
  1132. #if JUCE_LINUX
  1133. hostWindow = 0;
  1134. #endif
  1135. }
  1136. }
  1137. VstIntPtr dispatcher (VstInt32 opCode, VstInt32 index, VstIntPtr value, void* ptr, float opt) override
  1138. {
  1139. if (hasShutdown)
  1140. return 0;
  1141. if (opCode == effEditIdle)
  1142. {
  1143. doIdleCallback();
  1144. return 0;
  1145. }
  1146. else if (opCode == effEditOpen)
  1147. {
  1148. checkWhetherMessageThreadIsCorrect();
  1149. const MessageManagerLock mmLock;
  1150. jassert (! recursionCheck);
  1151. startTimer (1000 / 4); // performs misc housekeeping chores
  1152. deleteEditor (true);
  1153. createEditorComp();
  1154. if (editorComp != nullptr)
  1155. {
  1156. editorComp->setOpaque (true);
  1157. editorComp->setVisible (false);
  1158. #if JUCE_WINDOWS
  1159. editorComp->addToDesktop (0, ptr);
  1160. hostWindow = (HWND) ptr;
  1161. #elif JUCE_LINUX
  1162. editorComp->addToDesktop (0, ptr);
  1163. hostWindow = (Window) ptr;
  1164. Window editorWnd = (Window) editorComp->getWindowHandle();
  1165. XReparentWindow (display, editorWnd, hostWindow, 0, 0);
  1166. #else
  1167. hostWindow = attachComponentToWindowRefVST (editorComp, ptr, useNSView);
  1168. #endif
  1169. editorComp->setVisible (true);
  1170. return 1;
  1171. }
  1172. }
  1173. else if (opCode == effEditClose)
  1174. {
  1175. checkWhetherMessageThreadIsCorrect();
  1176. const MessageManagerLock mmLock;
  1177. deleteEditor (true);
  1178. return 0;
  1179. }
  1180. else if (opCode == effEditGetRect)
  1181. {
  1182. checkWhetherMessageThreadIsCorrect();
  1183. const MessageManagerLock mmLock;
  1184. createEditorComp();
  1185. if (editorComp != nullptr)
  1186. {
  1187. editorSize.left = 0;
  1188. editorSize.top = 0;
  1189. editorSize.right = (VstInt16) editorComp->getWidth();
  1190. editorSize.bottom = (VstInt16) editorComp->getHeight();
  1191. *((ERect**) ptr) = &editorSize;
  1192. return (VstIntPtr) (pointer_sized_int) &editorSize;
  1193. }
  1194. return 0;
  1195. }
  1196. return AudioEffectX::dispatcher (opCode, index, value, ptr, opt);
  1197. }
  1198. void resizeHostWindow (int newWidth, int newHeight)
  1199. {
  1200. if (editorComp != nullptr)
  1201. {
  1202. bool sizeWasSuccessful = false;
  1203. if (canHostDo (const_cast<char*> ("sizeWindow")))
  1204. {
  1205. isInSizeWindow = true;
  1206. sizeWasSuccessful = sizeWindow (newWidth, newHeight);
  1207. isInSizeWindow = false;
  1208. }
  1209. if (! sizeWasSuccessful)
  1210. {
  1211. // some hosts don't support the sizeWindow call, so do it manually..
  1212. #if JUCE_MAC
  1213. setNativeHostWindowSizeVST (hostWindow, editorComp, newWidth, newHeight, useNSView);
  1214. #elif JUCE_LINUX
  1215. // (Currently, all linux hosts support sizeWindow, so this should never need to happen)
  1216. editorComp->setSize (newWidth, newHeight);
  1217. #else
  1218. int dw = 0;
  1219. int dh = 0;
  1220. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  1221. HWND w = (HWND) editorComp->getWindowHandle();
  1222. while (w != 0)
  1223. {
  1224. HWND parent = getWindowParent (w);
  1225. if (parent == 0)
  1226. break;
  1227. TCHAR windowType [32] = { 0 };
  1228. GetClassName (parent, windowType, 31);
  1229. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  1230. break;
  1231. RECT windowPos, parentPos;
  1232. GetWindowRect (w, &windowPos);
  1233. GetWindowRect (parent, &parentPos);
  1234. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1235. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1236. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1237. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1238. w = parent;
  1239. if (dw == 2 * frameThickness)
  1240. break;
  1241. if (dw > 100 || dh > 100)
  1242. w = 0;
  1243. }
  1244. if (w != 0)
  1245. SetWindowPos (w, 0, 0, 0, newWidth + dw, newHeight + dh,
  1246. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1247. #endif
  1248. }
  1249. if (ComponentPeer* peer = editorComp->getPeer())
  1250. {
  1251. peer->handleMovedOrResized();
  1252. peer->getComponent().repaint();
  1253. }
  1254. }
  1255. }
  1256. //==============================================================================
  1257. // A component to hold the AudioProcessorEditor, and cope with some housekeeping
  1258. // chores when it changes or repaints.
  1259. class EditorCompWrapper : public Component
  1260. {
  1261. public:
  1262. EditorCompWrapper (JuceVSTWrapper& w, AudioProcessorEditor* editor)
  1263. : wrapper (w)
  1264. {
  1265. setOpaque (true);
  1266. editor->setOpaque (true);
  1267. setBounds (editor->getBounds());
  1268. editor->setTopLeftPosition (0, 0);
  1269. addAndMakeVisible (editor);
  1270. #if JUCE_WINDOWS
  1271. if (! getHostType().isReceptor())
  1272. addMouseListener (this, true);
  1273. #endif
  1274. ignoreUnused (fakeMouseGenerator);
  1275. }
  1276. ~EditorCompWrapper()
  1277. {
  1278. deleteAllChildren(); // note that we can't use a ScopedPointer because the editor may
  1279. // have been transferred to another parent which takes over ownership.
  1280. }
  1281. void paint (Graphics&) override {}
  1282. #if JUCE_MAC
  1283. bool keyPressed (const KeyPress&) override
  1284. {
  1285. // If we have an unused keypress, move the key-focus to a host window
  1286. // and re-inject the event..
  1287. return forwardCurrentKeyEventToHostVST (this, wrapper.useNSView);
  1288. }
  1289. #endif
  1290. AudioProcessorEditor* getEditorComp() const
  1291. {
  1292. return dynamic_cast<AudioProcessorEditor*> (getChildComponent(0));
  1293. }
  1294. void resized() override
  1295. {
  1296. if (Component* const editorChildComp = getChildComponent(0))
  1297. editorChildComp->setBounds (getLocalBounds());
  1298. #if JUCE_MAC && ! JUCE_64BIT
  1299. if (! wrapper.useNSView)
  1300. updateEditorCompBoundsVST (this);
  1301. #endif
  1302. }
  1303. void childBoundsChanged (Component* child) override
  1304. {
  1305. if (! wrapper.isInSizeWindow)
  1306. {
  1307. child->setTopLeftPosition (0, 0);
  1308. const int cw = child->getWidth();
  1309. const int ch = child->getHeight();
  1310. #if JUCE_MAC
  1311. if (wrapper.useNSView)
  1312. setTopLeftPosition (0, getHeight() - ch);
  1313. #endif
  1314. wrapper.resizeHostWindow (cw, ch);
  1315. #if ! JUCE_LINUX // setSize() on linux causes renoise and energyxt to fail.
  1316. setSize (cw, ch);
  1317. #else
  1318. XResizeWindow (display, (Window) getWindowHandle(), (unsigned int) cw, (unsigned int) ch);
  1319. #endif
  1320. #if JUCE_MAC
  1321. wrapper.resizeHostWindow (cw, ch); // (doing this a second time seems to be necessary in tracktion)
  1322. #endif
  1323. }
  1324. }
  1325. #if JUCE_WINDOWS
  1326. void mouseDown (const MouseEvent&) override
  1327. {
  1328. broughtToFront();
  1329. }
  1330. void broughtToFront() override
  1331. {
  1332. // for hosts like nuendo, need to also pop the MDI container to the
  1333. // front when our comp is clicked on.
  1334. if (! isCurrentlyBlockedByAnotherModalComponent())
  1335. if (HWND parent = findMDIParentOf ((HWND) getWindowHandle()))
  1336. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1337. }
  1338. #endif
  1339. private:
  1340. //==============================================================================
  1341. JuceVSTWrapper& wrapper;
  1342. FakeMouseMoveGenerator fakeMouseGenerator;
  1343. #if JUCE_WINDOWS
  1344. WindowsHooks hooks;
  1345. #endif
  1346. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1347. };
  1348. //==============================================================================
  1349. private:
  1350. AudioProcessor* filter;
  1351. PluginBusUtilities busUtils;
  1352. juce::MemoryBlock chunkMemory;
  1353. juce::uint32 chunkMemoryTime;
  1354. ScopedPointer<EditorCompWrapper> editorComp;
  1355. ERect editorSize;
  1356. MidiBuffer midiEvents;
  1357. VSTMidiEventList outgoingEvents;
  1358. bool isProcessing, isBypassed, hasShutdown, isInSizeWindow, firstProcessCallback;
  1359. bool shouldDeleteEditor, useNSView;
  1360. VstTempBuffers<float> floatTempBuffers;
  1361. VstTempBuffers<double> doubleTempBuffers;
  1362. #if JUCE_MAC
  1363. void* hostWindow;
  1364. #elif JUCE_LINUX
  1365. Window hostWindow;
  1366. #else
  1367. HWND hostWindow;
  1368. #endif
  1369. static inline VstInt32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1370. {
  1371. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1372. return (VstInt32) hexVersion;
  1373. #else
  1374. return (VstInt32) (((hexVersion >> 24) & 0xff) * 1000
  1375. + ((hexVersion >> 16) & 0xff) * 100
  1376. + ((hexVersion >> 8) & 0xff) * 10
  1377. + (hexVersion & 0xff));
  1378. #endif
  1379. }
  1380. //==============================================================================
  1381. #if JUCE_WINDOWS
  1382. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1383. static void checkWhetherMessageThreadIsCorrect()
  1384. {
  1385. const PluginHostType host (getHostType());
  1386. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1387. {
  1388. if (! messageThreadIsDefinitelyCorrect)
  1389. {
  1390. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1391. struct MessageThreadCallback : public CallbackMessage
  1392. {
  1393. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1394. void messageCallback() override { triggered = true; }
  1395. bool& triggered;
  1396. };
  1397. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1398. }
  1399. }
  1400. }
  1401. #else
  1402. static void checkWhetherMessageThreadIsCorrect() {}
  1403. #endif
  1404. //==============================================================================
  1405. template <typename FloatType>
  1406. void deleteTempChannels (VstTempBuffers<FloatType>& tmpBuffers)
  1407. {
  1408. tmpBuffers.release();
  1409. if (filter != nullptr)
  1410. {
  1411. int numChannels = cEffect.numInputs + cEffect.numOutputs;
  1412. tmpBuffers.tempChannels.insertMultiple (0, nullptr, numChannels);
  1413. }
  1414. }
  1415. void deleteTempChannels()
  1416. {
  1417. deleteTempChannels (floatTempBuffers);
  1418. deleteTempChannels (doubleTempBuffers);
  1419. }
  1420. //==============================================================================
  1421. void resetAuxChannelsToDefaultLayout (bool isInput) const
  1422. {
  1423. // set side-chain and aux channels to their default layout
  1424. for (int busIdx = 1; busIdx < busUtils.getBusCount (isInput); ++busIdx)
  1425. {
  1426. bool success = filter->setPreferredBusArrangement (isInput, busIdx, busUtils.getDefaultLayoutForBus (isInput, busIdx));
  1427. // VST 2 only supports a static channel layout on aux/sidechain channels
  1428. // You must at least support the default layout regardless of the layout of the main bus.
  1429. // If this is a problem for your plug-in, then consider using VST-3.
  1430. jassert (success);
  1431. ignoreUnused (success);
  1432. }
  1433. }
  1434. bool hostOnlySupportsStereo () const
  1435. {
  1436. const PluginHostType host (getHostType ());
  1437. // there are probably more hosts that need listing here
  1438. return host.isAbletonLive();
  1439. }
  1440. //==============================================================================
  1441. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1442. };
  1443. //==============================================================================
  1444. namespace
  1445. {
  1446. AEffect* pluginEntryPoint (audioMasterCallback audioMaster)
  1447. {
  1448. JUCE_AUTORELEASEPOOL
  1449. {
  1450. initialiseJuce_GUI();
  1451. try
  1452. {
  1453. if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0)
  1454. {
  1455. #if JUCE_LINUX
  1456. MessageManagerLock mmLock;
  1457. #endif
  1458. AudioProcessor* const filter = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1459. JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter);
  1460. return wrapper->getAeffect();
  1461. }
  1462. }
  1463. catch (...)
  1464. {}
  1465. }
  1466. return nullptr;
  1467. }
  1468. }
  1469. #if ! JUCE_WINDOWS
  1470. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1471. #endif
  1472. //==============================================================================
  1473. // Mac startup code..
  1474. #if JUCE_MAC
  1475. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster);
  1476. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1477. {
  1478. initialiseMacVST();
  1479. return pluginEntryPoint (audioMaster);
  1480. }
  1481. JUCE_EXPORTED_FUNCTION AEffect* main_macho (audioMasterCallback audioMaster);
  1482. JUCE_EXPORTED_FUNCTION AEffect* main_macho (audioMasterCallback audioMaster)
  1483. {
  1484. initialiseMacVST();
  1485. return pluginEntryPoint (audioMaster);
  1486. }
  1487. //==============================================================================
  1488. // Linux startup code..
  1489. #elif JUCE_LINUX
  1490. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster);
  1491. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1492. {
  1493. SharedMessageThread::getInstance();
  1494. return pluginEntryPoint (audioMaster);
  1495. }
  1496. JUCE_EXPORTED_FUNCTION AEffect* main_plugin (audioMasterCallback audioMaster) asm ("main");
  1497. JUCE_EXPORTED_FUNCTION AEffect* main_plugin (audioMasterCallback audioMaster)
  1498. {
  1499. return VSTPluginMain (audioMaster);
  1500. }
  1501. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1502. __attribute__((constructor)) void myPluginInit() {}
  1503. __attribute__((destructor)) void myPluginFini() {}
  1504. //==============================================================================
  1505. // Win32 startup code..
  1506. #else
  1507. extern "C" __declspec (dllexport) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1508. {
  1509. return pluginEntryPoint (audioMaster);
  1510. }
  1511. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1512. extern "C" __declspec (dllexport) int main (audioMasterCallback audioMaster)
  1513. {
  1514. return (int) pluginEntryPoint (audioMaster);
  1515. }
  1516. #endif
  1517. #endif
  1518. #endif