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.

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