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.

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