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.

1822 lines
64KB

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