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.

1552 lines
51KB

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