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.

1573 lines
51KB

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