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.

1613 lines
53KB

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