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.

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