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.

1617 lines
53KB

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