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.

1901 lines
67KB

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