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.

1568 lines
51KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. // Your project must contain an AppConfig.h file with your project-specific settings in it,
  19. // and your header search path must make it accessible to the module's files.
  20. #include "AppConfig.h"
  21. #include "../utility/juce_CheckSettingMacros.h"
  22. #if JucePlugin_Build_VST
  23. #ifdef _MSC_VER
  24. #pragma warning (disable : 4996 4100)
  25. #endif
  26. #ifdef _WIN32
  27. #undef _WIN32_WINNT
  28. #define _WIN32_WINNT 0x500
  29. #undef STRICT
  30. #define STRICT 1
  31. #include <windows.h>
  32. #ifdef __MINGW32__
  33. struct MOUSEHOOKSTRUCTEX : public MOUSEHOOKSTRUCT
  34. {
  35. DWORD mouseData;
  36. };
  37. #endif
  38. #elif defined (LINUX)
  39. #include <X11/Xlib.h>
  40. #include <X11/Xutil.h>
  41. #include <X11/Xatom.h>
  42. #undef KeyPress
  43. #else
  44. #include <Carbon/Carbon.h>
  45. #endif
  46. #ifdef PRAGMA_ALIGN_SUPPORTED
  47. #undef PRAGMA_ALIGN_SUPPORTED
  48. #define PRAGMA_ALIGN_SUPPORTED 1
  49. #endif
  50. //==============================================================================
  51. /* These files come with the Steinberg VST SDK - to get them, you'll need to
  52. visit the Steinberg website and jump through some hoops to sign up as a
  53. VST developer.
  54. Then, you'll need to make sure your include path contains your "vstsdk2.4" directory.
  55. */
  56. #ifndef _MSC_VER
  57. #define __cdecl
  58. #endif
  59. #ifdef __clang__
  60. #pragma clang diagnostic push
  61. #pragma clang diagnostic ignored "-Wconversion"
  62. #pragma clang diagnostic ignored "-Wshadow"
  63. #endif
  64. // VSTSDK V2.4 includes..
  65. #include <public.sdk/source/vst2.x/audioeffectx.h>
  66. #include <public.sdk/source/vst2.x/aeffeditor.h>
  67. #include <public.sdk/source/vst2.x/audioeffectx.cpp>
  68. #include <public.sdk/source/vst2.x/audioeffect.cpp>
  69. #if ! VST_2_4_EXTENSIONS
  70. #error "It looks like you're trying to include an out-of-date VSTSDK version - make sure you have at least version 2.4"
  71. #endif
  72. #ifdef __clang__
  73. #pragma clang diagnostic pop
  74. #endif
  75. //==============================================================================
  76. #ifdef _MSC_VER
  77. #pragma pack (push, 8)
  78. #endif
  79. #include "../utility/juce_IncludeModuleHeaders.h"
  80. #include "../utility/juce_FakeMouseMoveGenerator.h"
  81. #include "../utility/juce_PluginHostType.h"
  82. #ifdef _MSC_VER
  83. #pragma pack (pop)
  84. #endif
  85. #undef MemoryBlock
  86. class JuceVSTWrapper;
  87. static bool recursionCheck = false;
  88. static juce::uint32 lastMasterIdleCall = 0;
  89. namespace juce
  90. {
  91. #if JUCE_MAC
  92. extern void initialiseMac();
  93. extern void* attachComponentToWindowRef (Component* component, void* windowRef);
  94. extern void detachComponentFromWindowRef (Component* component, void* nsWindow);
  95. extern void setNativeHostWindowSize (void* nsWindow, Component* editorComp, int newWidth, int newHeight, const PluginHostType& host);
  96. extern void checkWindowVisibility (void* nsWindow, Component* component);
  97. extern bool forwardCurrentKeyEventToHost (Component* component);
  98. #endif
  99. #if JUCE_LINUX
  100. extern Display* display;
  101. #endif
  102. }
  103. //==============================================================================
  104. #if JUCE_WINDOWS
  105. namespace
  106. {
  107. HWND findMDIParentOf (HWND w)
  108. {
  109. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  110. while (w != 0)
  111. {
  112. HWND parent = GetParent (w);
  113. if (parent == 0)
  114. break;
  115. TCHAR windowType[32] = { 0 };
  116. GetClassName (parent, windowType, 31);
  117. if (String (windowType).equalsIgnoreCase ("MDIClient"))
  118. return parent;
  119. RECT windowPos, parentPos;
  120. GetWindowRect (w, &windowPos);
  121. GetWindowRect (parent, &parentPos);
  122. const int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  123. const int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  124. if (dw > 100 || dh > 100)
  125. break;
  126. w = parent;
  127. if (dw == 2 * frameThickness)
  128. break;
  129. }
  130. return w;
  131. }
  132. //==============================================================================
  133. static HHOOK mouseWheelHook = 0;
  134. static int mouseHookUsers = 0;
  135. LRESULT CALLBACK mouseWheelHookCallback (int nCode, WPARAM wParam, LPARAM lParam)
  136. {
  137. if (nCode >= 0 && wParam == WM_MOUSEWHEEL)
  138. {
  139. const MOUSEHOOKSTRUCTEX& hs = *(MOUSEHOOKSTRUCTEX*) lParam;
  140. if (Component* const comp = Desktop::getInstance().findComponentAt (Point<int> (hs.pt.x, hs.pt.y)))
  141. if (comp->getWindowHandle() != 0)
  142. return PostMessage ((HWND) comp->getWindowHandle(), WM_MOUSEWHEEL,
  143. hs.mouseData & 0xffff0000, (hs.pt.x & 0xffff) | (hs.pt.y << 16));
  144. }
  145. return CallNextHookEx (mouseWheelHook, nCode, wParam, lParam);
  146. }
  147. void registerMouseWheelHook()
  148. {
  149. if (mouseHookUsers++ == 0)
  150. mouseWheelHook = SetWindowsHookEx (WH_MOUSE, mouseWheelHookCallback,
  151. (HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  152. GetCurrentThreadId());
  153. }
  154. void unregisterMouseWheelHook()
  155. {
  156. if (--mouseHookUsers == 0 && mouseWheelHook != 0)
  157. {
  158. UnhookWindowsHookEx (mouseWheelHook);
  159. mouseWheelHook = 0;
  160. }
  161. }
  162. #if JUCE_WINDOWS
  163. static bool messageThreadIsDefinitelyCorrect = false;
  164. #endif
  165. }
  166. //==============================================================================
  167. #elif JUCE_LINUX
  168. class SharedMessageThread : public Thread
  169. {
  170. public:
  171. SharedMessageThread()
  172. : Thread ("VstMessageThread"),
  173. initialised (false)
  174. {
  175. startThread (7);
  176. while (! initialised)
  177. sleep (1);
  178. }
  179. ~SharedMessageThread()
  180. {
  181. signalThreadShouldExit();
  182. JUCEApplication::quit();
  183. waitForThreadToExit (5000);
  184. clearSingletonInstance();
  185. }
  186. void run()
  187. {
  188. initialiseJuce_GUI();
  189. initialised = true;
  190. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  191. while ((! threadShouldExit()) && MessageManager::getInstance()->runDispatchLoopUntil (250))
  192. {}
  193. }
  194. juce_DeclareSingleton (SharedMessageThread, false);
  195. private:
  196. bool initialised;
  197. };
  198. juce_ImplementSingleton (SharedMessageThread)
  199. #endif
  200. static Array<void*> activePlugins;
  201. //==============================================================================
  202. /**
  203. This is an AudioEffectX object that holds and wraps our AudioProcessor...
  204. */
  205. class JuceVSTWrapper : public AudioEffectX,
  206. private Timer,
  207. public AudioProcessorListener,
  208. public AudioPlayHead
  209. {
  210. public:
  211. //==============================================================================
  212. JuceVSTWrapper (audioMasterCallback audioMaster, AudioProcessor* const af)
  213. : AudioEffectX (audioMaster, af->getNumPrograms(), af->getNumParameters()),
  214. filter (af),
  215. chunkMemoryTime (0),
  216. speakerIn (kSpeakerArrEmpty),
  217. speakerOut (kSpeakerArrEmpty),
  218. numInChans (JucePlugin_MaxNumInputChannels),
  219. numOutChans (JucePlugin_MaxNumOutputChannels),
  220. isProcessing (false),
  221. isBypassed (false),
  222. hasShutdown (false),
  223. firstProcessCallback (true),
  224. shouldDeleteEditor (false),
  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. AudioSampleBuffer temp (numIn, numSamples);
  400. for (int i = numIn; --i >= 0;)
  401. memcpy (temp.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, temp, 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()
  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, getHostType());
  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&) {}
  1057. void paintOverChildren (Graphics&)
  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&)
  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()
  1078. {
  1079. if (Component* const editor = getChildComponent(0))
  1080. editor->setBounds (getLocalBounds());
  1081. }
  1082. void childBoundsChanged (Component* child)
  1083. {
  1084. child->setTopLeftPosition (0, 0);
  1085. const int cw = child->getWidth();
  1086. const int ch = child->getHeight();
  1087. #if JUCE_MAC && JUCE_64BIT
  1088. setTopLeftPosition (0, getHeight() - ch);
  1089. #endif
  1090. wrapper.resizeHostWindow (cw, ch);
  1091. #if ! JUCE_LINUX // setSize() on linux causes renoise and energyxt to fail.
  1092. setSize (cw, ch);
  1093. #else
  1094. XResizeWindow (display, (Window) getWindowHandle(), cw, ch);
  1095. #endif
  1096. #if JUCE_MAC
  1097. wrapper.resizeHostWindow (cw, ch); // (doing this a second time seems to be necessary in tracktion)
  1098. #endif
  1099. }
  1100. void handleAsyncUpdate()
  1101. {
  1102. wrapper.tryMasterIdle();
  1103. }
  1104. #if JUCE_WINDOWS
  1105. void mouseDown (const MouseEvent&)
  1106. {
  1107. broughtToFront();
  1108. }
  1109. void broughtToFront()
  1110. {
  1111. // for hosts like nuendo, need to also pop the MDI container to the
  1112. // front when our comp is clicked on.
  1113. HWND parent = findMDIParentOf ((HWND) getWindowHandle());
  1114. if (parent != 0)
  1115. SetWindowPos (parent, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1116. }
  1117. #endif
  1118. private:
  1119. //==============================================================================
  1120. JuceVSTWrapper& wrapper;
  1121. FakeMouseMoveGenerator fakeMouseGenerator;
  1122. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EditorCompWrapper)
  1123. };
  1124. //==============================================================================
  1125. private:
  1126. AudioProcessor* filter;
  1127. juce::MemoryBlock chunkMemory;
  1128. juce::uint32 chunkMemoryTime;
  1129. ScopedPointer<EditorCompWrapper> editorComp;
  1130. ERect editorSize;
  1131. MidiBuffer midiEvents;
  1132. VSTMidiEventList outgoingEvents;
  1133. VstSpeakerArrangementType speakerIn, speakerOut;
  1134. int numInChans, numOutChans;
  1135. bool isProcessing, isBypassed, hasShutdown, firstProcessCallback, shouldDeleteEditor;
  1136. HeapBlock<float*> channels;
  1137. Array<float*> tempChannels; // see note in processReplacing()
  1138. #if JUCE_MAC
  1139. void* hostWindow;
  1140. #elif JUCE_LINUX
  1141. Window hostWindow;
  1142. #else
  1143. HWND hostWindow;
  1144. #endif
  1145. static inline VstInt32 convertHexVersionToDecimal (const unsigned int hexVersion)
  1146. {
  1147. #if JUCE_VST_RETURN_HEX_VERSION_NUMBER_DIRECTLY
  1148. return (VstInt32) hexVersion;
  1149. #else
  1150. return (VstInt32) (((hexVersion >> 24) & 0xff) * 1000
  1151. + ((hexVersion >> 16) & 0xff) * 100
  1152. + ((hexVersion >> 8) & 0xff) * 10
  1153. + (hexVersion & 0xff));
  1154. #endif
  1155. }
  1156. //==============================================================================
  1157. #if JUCE_WINDOWS
  1158. // Workarounds for hosts which attempt to open editor windows on a non-GUI thread.. (Grrrr...)
  1159. static void checkWhetherMessageThreadIsCorrect()
  1160. {
  1161. const PluginHostType host (getHostType());
  1162. if (host.isWavelab() || host.isCubaseBridged() || host.isPremiere())
  1163. {
  1164. if (! messageThreadIsDefinitelyCorrect)
  1165. {
  1166. MessageManager::getInstance()->setCurrentThreadAsMessageThread();
  1167. class MessageThreadCallback : public CallbackMessage
  1168. {
  1169. public:
  1170. MessageThreadCallback (bool& tr) : triggered (tr) {}
  1171. void messageCallback()
  1172. {
  1173. triggered = true;
  1174. }
  1175. private:
  1176. bool& triggered;
  1177. };
  1178. (new MessageThreadCallback (messageThreadIsDefinitelyCorrect))->post();
  1179. }
  1180. }
  1181. }
  1182. #else
  1183. static void checkWhetherMessageThreadIsCorrect() {}
  1184. #endif
  1185. //==============================================================================
  1186. void deleteTempChannels()
  1187. {
  1188. for (int i = tempChannels.size(); --i >= 0;)
  1189. delete[] (tempChannels.getUnchecked(i));
  1190. tempChannels.clear();
  1191. if (filter != nullptr)
  1192. tempChannels.insertMultiple (0, 0, filter->getNumInputChannels() + filter->getNumOutputChannels());
  1193. }
  1194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVSTWrapper)
  1195. };
  1196. //==============================================================================
  1197. namespace
  1198. {
  1199. AEffect* pluginEntryPoint (audioMasterCallback audioMaster)
  1200. {
  1201. JUCE_AUTORELEASEPOOL
  1202. {
  1203. initialiseJuce_GUI();
  1204. try
  1205. {
  1206. if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0)
  1207. {
  1208. #if JUCE_LINUX
  1209. MessageManagerLock mmLock;
  1210. #endif
  1211. AudioProcessor* const filter = createPluginFilterOfType (AudioProcessor::wrapperType_VST);
  1212. JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter);
  1213. return wrapper->getAeffect();
  1214. }
  1215. }
  1216. catch (...)
  1217. {}
  1218. }
  1219. return nullptr;
  1220. }
  1221. }
  1222. #if ! JUCE_WINDOWS
  1223. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  1224. #endif
  1225. //==============================================================================
  1226. // Mac startup code..
  1227. #if JUCE_MAC
  1228. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster);
  1229. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1230. {
  1231. initialiseMac();
  1232. return pluginEntryPoint (audioMaster);
  1233. }
  1234. JUCE_EXPORTED_FUNCTION AEffect* main_macho (audioMasterCallback audioMaster);
  1235. JUCE_EXPORTED_FUNCTION AEffect* main_macho (audioMasterCallback audioMaster)
  1236. {
  1237. initialiseMac();
  1238. return pluginEntryPoint (audioMaster);
  1239. }
  1240. //==============================================================================
  1241. // Linux startup code..
  1242. #elif JUCE_LINUX
  1243. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster);
  1244. JUCE_EXPORTED_FUNCTION AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1245. {
  1246. SharedMessageThread::getInstance();
  1247. return pluginEntryPoint (audioMaster);
  1248. }
  1249. JUCE_EXPORTED_FUNCTION AEffect* main_plugin (audioMasterCallback audioMaster) asm ("main");
  1250. JUCE_EXPORTED_FUNCTION AEffect* main_plugin (audioMasterCallback audioMaster)
  1251. {
  1252. return VSTPluginMain (audioMaster);
  1253. }
  1254. // don't put initialiseJuce_GUI or shutdownJuce_GUI in these... it will crash!
  1255. __attribute__((constructor)) void myPluginInit() {}
  1256. __attribute__((destructor)) void myPluginFini() {}
  1257. //==============================================================================
  1258. // Win32 startup code..
  1259. #else
  1260. extern "C" __declspec (dllexport) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1261. {
  1262. return pluginEntryPoint (audioMaster);
  1263. }
  1264. #ifndef JUCE_64BIT // (can't compile this on win64, but it's not needed anyway with VST2.4)
  1265. extern "C" __declspec (dllexport) int main (audioMasterCallback audioMaster)
  1266. {
  1267. return (int) pluginEntryPoint (audioMaster);
  1268. }
  1269. #endif
  1270. #endif
  1271. #endif