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.

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