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.

1618 lines
53KB

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