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.

1586 lines
52KB

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