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.

1353 lines
39KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. *** DON't EDIT THIS FILE!! ***
  25. The idea is that everyone's plugins should share this same wrapper
  26. code, so if you start hacking around in here you're missing the point!
  27. If there's a bug or a function you need that can't be done without changing
  28. some of the code in here, give me a shout so we can add it to the library,
  29. rather than branching off and going it alone!
  30. */
  31. //==============================================================================
  32. #ifdef _MSC_VER
  33. #pragma warning (disable : 4996)
  34. #endif
  35. #ifdef _WIN32
  36. #include <windows.h>
  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. #include "../../juce_IncludeCharacteristics.h"
  50. //==============================================================================
  51. /* These files come with the Steinberg VST SDK - to get them, you'll need to
  52. visit the Steinberg website and jump through some hoops to sign up as a
  53. VST developer.
  54. Then, you'll need to make sure your include path contains your "vstsdk2.3" or
  55. "vstsdk2.4" directory.
  56. Note that the JUCE_USE_VSTSDK_2_4 macro should be defined in JucePluginCharacteristics.h
  57. */
  58. #if JUCE_USE_VSTSDK_2_4
  59. // VSTSDK V2.4 includes..
  60. #include "public.sdk/source/vst2.x/audioeffectx.h"
  61. #include "public.sdk/source/vst2.x/aeffeditor.h"
  62. #include "public.sdk/source/vst2.x/audioeffectx.cpp"
  63. #include "public.sdk/source/vst2.x/audioeffect.cpp"
  64. #else
  65. // VSTSDK V2.3 includes..
  66. #include "source/common/audioeffectx.h"
  67. #include "source/common/AEffEditor.hpp"
  68. #include "source/common/audioeffectx.cpp"
  69. #include "source/common/AudioEffect.cpp"
  70. typedef long VstInt32;
  71. typedef long VstIntPtr;
  72. #endif
  73. //==============================================================================
  74. #include "../../juce_AudioFilterBase.h"
  75. #undef MemoryBlock
  76. class JuceVSTWrapper;
  77. static bool recursionCheck = false;
  78. static uint32 lastMasterIdleCall = 0;
  79. BEGIN_JUCE_NAMESPACE
  80. extern void juce_callAnyTimersSynchronously();
  81. #if JUCE_LINUX
  82. extern Display* display;
  83. extern bool juce_postMessageToSystemQueue (void* message);
  84. #endif
  85. END_JUCE_NAMESPACE
  86. //==============================================================================
  87. #if JUCE_WIN32
  88. static HWND findMDIParentOf (HWND w)
  89. {
  90. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  91. while (w != 0)
  92. {
  93. HWND parent = GetParent (w);
  94. if (parent == 0)
  95. break;
  96. TCHAR windowType [32];
  97. zeromem (windowType, sizeof (windowType));
  98. GetClassName (parent, windowType, 31);
  99. if (String (windowType).equalsIgnoreCase (T("MDIClient")))
  100. {
  101. w = parent;
  102. break;
  103. }
  104. RECT windowPos;
  105. GetWindowRect (w, &windowPos);
  106. RECT parentPos;
  107. GetWindowRect (parent, &parentPos);
  108. int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  109. int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  110. if (dw > 100 || dh > 100)
  111. break;
  112. w = parent;
  113. if (dw == 2 * frameThickness)
  114. break;
  115. }
  116. return w;
  117. }
  118. //==============================================================================
  119. #elif JUCE_LINUX
  120. class SharedMessageThread : public Thread
  121. {
  122. public:
  123. SharedMessageThread()
  124. : Thread (T("VstMessageThread"))
  125. {
  126. startThread (7);
  127. }
  128. ~SharedMessageThread()
  129. {
  130. signalThreadShouldExit();
  131. const int quitMessageId = 0xfffff321;
  132. Message* const m = new Message (quitMessageId, 1, 0, 0);
  133. if (! juce_postMessageToSystemQueue (m))
  134. delete m;
  135. clearSingletonInstance();
  136. }
  137. void run()
  138. {
  139. MessageManager* const messageManager = MessageManager::getInstance();
  140. const int originalThreadId = messageManager->getCurrentMessageThread();
  141. messageManager->setCurrentMessageThread (getThreadId());
  142. while (! threadShouldExit()
  143. && messageManager->dispatchNextMessage())
  144. {
  145. }
  146. messageManager->setCurrentMessageThread (originalThreadId);
  147. }
  148. juce_DeclareSingleton (SharedMessageThread, false)
  149. };
  150. juce_ImplementSingleton (SharedMessageThread);
  151. #endif
  152. //==============================================================================
  153. // A component to hold the AudioFilterEditor, and cope with some housekeeping
  154. // chores when it changes or repaints.
  155. class EditorCompWrapper : public Component,
  156. public AsyncUpdater
  157. {
  158. JuceVSTWrapper* wrapper;
  159. public:
  160. EditorCompWrapper (JuceVSTWrapper* const wrapper_,
  161. AudioFilterEditor* const editor)
  162. : wrapper (wrapper_)
  163. {
  164. setOpaque (true);
  165. editor->setOpaque (true);
  166. setBounds (editor->getBounds());
  167. editor->setTopLeftPosition (0, 0);
  168. addAndMakeVisible (editor);
  169. #if JUCE_WIN32
  170. addMouseListener (this, true);
  171. #endif
  172. }
  173. ~EditorCompWrapper()
  174. {
  175. deleteAllChildren();
  176. }
  177. void paint (Graphics& g)
  178. {
  179. }
  180. void paintOverChildren (Graphics& g)
  181. {
  182. // this causes an async call to masterIdle() to help
  183. // creaky old DAWs like Nuendo repaint themselves while we're
  184. // repainting. Otherwise they just seem to give up and sit there
  185. // waiting.
  186. triggerAsyncUpdate();
  187. }
  188. AudioFilterEditor* getEditorComp() const
  189. {
  190. return dynamic_cast <AudioFilterEditor*> (getChildComponent (0));
  191. }
  192. void resized()
  193. {
  194. Component* const c = getChildComponent (0);
  195. if (c != 0)
  196. {
  197. #if JUCE_LINUX
  198. const MessageManagerLock mml;
  199. #endif
  200. c->setBounds (0, 0, getWidth(), getHeight());
  201. }
  202. }
  203. void childBoundsChanged (Component* child);
  204. void handleAsyncUpdate();
  205. #if JUCE_WIN32
  206. void mouseDown (const MouseEvent&)
  207. {
  208. broughtToFront();
  209. }
  210. void broughtToFront()
  211. {
  212. // for hosts like nuendo, need to also pop the MDI container to the
  213. // front when our comp is clicked on.
  214. HWND parent = findMDIParentOf ((HWND) getWindowHandle());
  215. if (parent != 0)
  216. {
  217. SetWindowPos (parent,
  218. HWND_TOP,
  219. 0, 0, 0, 0,
  220. SWP_NOMOVE | SWP_NOSIZE);
  221. }
  222. }
  223. #endif
  224. //==============================================================================
  225. juce_UseDebuggingNewOperator
  226. };
  227. static VoidArray activePlugins;
  228. //==============================================================================
  229. /**
  230. This wraps an AudioFilterBase as an AudioEffectX...
  231. */
  232. class JuceVSTWrapper : public AudioEffectX,
  233. private Timer,
  234. public AudioFilterBase::HostCallbacks
  235. {
  236. public:
  237. //==============================================================================
  238. JuceVSTWrapper (audioMasterCallback audioMaster,
  239. AudioFilterBase* const filter_)
  240. : AudioEffectX (audioMaster,
  241. filter_->getNumPrograms(),
  242. filter_->getNumParameters()),
  243. filter (filter_)
  244. {
  245. filter->setPlayConfigDetails (JucePlugin_MaxNumInputChannels,
  246. JucePlugin_MaxNumOutputChannels,
  247. 0, 0);
  248. filter_->setHostCallbacks (this);
  249. editorComp = 0;
  250. outgoingEvents = 0;
  251. outgoingEventSize = 0;
  252. chunkMemoryTime = 0;
  253. isProcessing = false;
  254. firstResize = true;
  255. channels = 0;
  256. #if JUCE_MAC || JUCE_LINUX
  257. hostWindow = 0;
  258. #endif
  259. cEffect.flags |= effFlagsHasEditor;
  260. setUniqueID ((int) (JucePlugin_VSTUniqueID));
  261. getAeffect()->version = (long) (JucePlugin_VersionCode);
  262. #if JucePlugin_WantsMidiInput && ! JUCE_USE_VSTSDK_2_4
  263. wantEvents();
  264. #endif
  265. setNumInputs (filter->getNumInputChannels());
  266. setNumOutputs (filter->getNumOutputChannels());
  267. canProcessReplacing (true);
  268. #if ! JUCE_USE_VSTSDK_2_4
  269. hasVu (false);
  270. hasClip (false);
  271. #endif
  272. isSynth ((JucePlugin_IsSynth) != 0);
  273. noTail ((JucePlugin_SilenceInProducesSilenceOut) != 0);
  274. setInitialDelay (JucePlugin_Latency);
  275. programsAreChunks (true);
  276. activePlugins.add (this);
  277. }
  278. ~JuceVSTWrapper()
  279. {
  280. stopTimer();
  281. deleteEditor();
  282. delete filter;
  283. filter = 0;
  284. if (outgoingEvents != 0)
  285. {
  286. for (int i = outgoingEventSize; --i >= 0;)
  287. juce_free (outgoingEvents->events[i]);
  288. juce_free (outgoingEvents);
  289. outgoingEvents = 0;
  290. }
  291. jassert (editorComp == 0);
  292. jassert (activePlugins.contains (this));
  293. activePlugins.removeValue (this);
  294. juce_free (channels);
  295. #if JUCE_MAC || JUCE_LINUX
  296. if (activePlugins.size() == 0)
  297. {
  298. #if JUCE_LINUX
  299. SharedMessageThread::deleteInstance();
  300. #endif
  301. shutdownJuce_GUI();
  302. }
  303. #endif
  304. }
  305. void open()
  306. {
  307. startTimer (1000 / 4);
  308. }
  309. void close()
  310. {
  311. jassert (! recursionCheck);
  312. stopTimer();
  313. deleteEditor();
  314. }
  315. //==============================================================================
  316. bool getEffectName (char* name)
  317. {
  318. String (JucePlugin_Name).copyToBuffer (name, 64);
  319. return true;
  320. }
  321. bool getVendorString (char* text)
  322. {
  323. String (JucePlugin_Manufacturer).copyToBuffer (text, 64);
  324. return true;
  325. }
  326. bool getProductString (char* text)
  327. {
  328. return getEffectName (text);
  329. }
  330. VstInt32 getVendorVersion()
  331. {
  332. return JucePlugin_VersionCode;
  333. }
  334. VstPlugCategory getPlugCategory()
  335. {
  336. return JucePlugin_VSTCategory;
  337. }
  338. VstInt32 canDo (char* text)
  339. {
  340. VstInt32 result = 0;
  341. if (strcmp (text, "receiveVstEvents") == 0
  342. || strcmp (text, "receiveVstMidiEvent") == 0
  343. || strcmp (text, "receiveVstMidiEvents") == 0)
  344. {
  345. #if JucePlugin_WantsMidiInput
  346. result = 1;
  347. #else
  348. result = -1;
  349. #endif
  350. }
  351. else if (strcmp (text, "sendVstEvents") == 0
  352. || strcmp (text, "sendVstMidiEvent") == 0
  353. || strcmp (text, "sendVstMidiEvents") == 0)
  354. {
  355. #if JucePlugin_ProducesMidiOutput
  356. result = 1;
  357. #else
  358. result = -1;
  359. #endif
  360. }
  361. else if (strcmp (text, "receiveVstTimeInfo") == 0)
  362. {
  363. result = 1;
  364. }
  365. else if (strcmp (text, "conformsToWindowRules") == 0)
  366. {
  367. result = 1;
  368. }
  369. return result;
  370. }
  371. bool keysRequired()
  372. {
  373. return (JucePlugin_EditorRequiresKeyboardFocus) != 0;
  374. }
  375. bool getInputProperties (VstInt32 index, VstPinProperties* properties)
  376. {
  377. const String name (filter->getInputChannelName ((int) index));
  378. name.copyToBuffer (properties->label, kVstMaxLabelLen - 1);
  379. name.copyToBuffer (properties->shortLabel, kVstMaxShortLabelLen - 1);
  380. properties->flags = kVstPinIsActive;
  381. if (filter->isInputChannelStereoPair ((int) index))
  382. properties->flags |= kVstPinIsStereo;
  383. properties->arrangementType = 0;
  384. return true;
  385. }
  386. bool getOutputProperties (VstInt32 index, VstPinProperties* properties)
  387. {
  388. const String name (filter->getOutputChannelName ((int) index));
  389. name.copyToBuffer (properties->label, kVstMaxLabelLen - 1);
  390. name.copyToBuffer (properties->shortLabel, kVstMaxShortLabelLen - 1);
  391. properties->flags = kVstPinIsActive;
  392. if (filter->isOutputChannelStereoPair ((int) index))
  393. properties->flags |= kVstPinIsStereo;
  394. properties->arrangementType = 0;
  395. return true;
  396. }
  397. //==============================================================================
  398. VstInt32 processEvents (VstEvents* events)
  399. {
  400. #if JucePlugin_WantsMidiInput
  401. for (int i = 0; i < events->numEvents; ++i)
  402. {
  403. const VstEvent* const e = events->events[i];
  404. if (e != 0 && e->type == kVstMidiType)
  405. {
  406. const VstMidiEvent* const vme = (const VstMidiEvent*) e;
  407. midiEvents.addEvent ((const uint8*) vme->midiData,
  408. 4,
  409. vme->deltaFrames);
  410. }
  411. }
  412. return 1;
  413. #else
  414. return 0;
  415. #endif
  416. }
  417. void process (float** inputs, float** outputs, VstInt32 numSamples)
  418. {
  419. const int numIn = filter->getNumInputChannels();
  420. const int numOut = filter->getNumOutputChannels();
  421. AudioSampleBuffer temp (numIn, numSamples);
  422. int i;
  423. for (i = numIn; --i >= 0;)
  424. memcpy (temp.getSampleData (i), outputs[i], sizeof (float) * numSamples);
  425. processReplacing (inputs, outputs, numSamples);
  426. AudioSampleBuffer dest (outputs, numOut, numSamples);
  427. for (i = jmin (numIn, numOut); --i >= 0;)
  428. dest.addFrom (i, 0, temp, i, 0, numSamples);
  429. }
  430. void processReplacing (float** inputs, float** outputs, VstInt32 numSamples)
  431. {
  432. //process (inputs, outputs, numSamples, false);
  433. // if this fails, the host hasn't called resume() before processing
  434. jassert (isProcessing);
  435. // (tragically, some hosts actually need this, although it's stupid to have
  436. // to do it here..)
  437. if (! isProcessing)
  438. resume();
  439. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  440. const int numMidiEventsComingIn = midiEvents.getNumEvents();
  441. #endif
  442. jassert (activePlugins.contains (this));
  443. {
  444. const ScopedLock sl (filter->getCallbackLock());
  445. const int numIn = filter->getNumInputChannels();
  446. const int numOut = filter->getNumOutputChannels();
  447. const int totalChans = jmax (numIn, numOut);
  448. if (filter->isSuspended())
  449. {
  450. for (int i = 0; i < numOut; ++i)
  451. zeromem (outputs [i], sizeof (float) * numSamples);
  452. }
  453. else
  454. {
  455. {
  456. int i;
  457. for (i = 0; i < numOut; ++i)
  458. {
  459. channels[i] = outputs [i];
  460. if (i < numIn && inputs != outputs)
  461. memcpy (outputs [i], inputs[i], sizeof (float) * numSamples);
  462. }
  463. for (; i < numIn; ++i)
  464. channels [i] = inputs [i];
  465. }
  466. AudioSampleBuffer chans (channels, totalChans, numSamples);
  467. filter->processBlock (chans, midiEvents);
  468. }
  469. }
  470. if (! midiEvents.isEmpty())
  471. {
  472. #if JucePlugin_ProducesMidiOutput
  473. const int numEvents = midiEvents.getNumEvents();
  474. ensureOutgoingEventSize (numEvents);
  475. outgoingEvents->numEvents = 0;
  476. const uint8* midiEventData;
  477. int midiEventSize, midiEventPosition;
  478. MidiBuffer::Iterator i (midiEvents);
  479. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  480. {
  481. if (midiEventSize <= 4)
  482. {
  483. VstMidiEvent* const vme = (VstMidiEvent*) outgoingEvents->events [outgoingEvents->numEvents++];
  484. memcpy (vme->midiData, midiEventData, midiEventSize);
  485. vme->deltaFrames = midiEventPosition;
  486. jassert (vme->deltaFrames >= 0 && vme->deltaFrames < numSamples);
  487. }
  488. }
  489. sendVstEventsToHost (outgoingEvents);
  490. #else
  491. /* This assertion is caused when you've added some events to the
  492. midiMessages array in your processBlock() method, which usually means
  493. that you're trying to send them somewhere. But in this case they're
  494. getting thrown away.
  495. If your plugin does want to send midi messages, you'll need to set
  496. the JucePlugin_ProducesMidiOutput macro to 1 in your
  497. JucePluginCharacteristics.h file.
  498. If you don't want to produce any midi output, then you should clear the
  499. midiMessages array at the end of your processBlock() method, to
  500. indicate that you don't want any of the events to be passed through
  501. to the output.
  502. */
  503. jassert (midiEvents.getNumEvents() <= numMidiEventsComingIn);
  504. #endif
  505. midiEvents.clear();
  506. }
  507. }
  508. //==============================================================================
  509. void resume()
  510. {
  511. isProcessing = true;
  512. juce_free (channels);
  513. channels = (float**) juce_calloc (sizeof (float*) * jmax (filter->getNumInputChannels(), filter->getNumOutputChannels()));
  514. double rate = getSampleRate();
  515. jassert (rate > 0);
  516. if (rate <= 0.0)
  517. rate = 44100.0;
  518. const int blockSize = getBlockSize();
  519. jassert (blockSize > 0);
  520. filter->setPlayConfigDetails (JucePlugin_MaxNumInputChannels,
  521. JucePlugin_MaxNumOutputChannels,
  522. rate, blockSize);
  523. filter->prepareToPlay (rate, blockSize);
  524. midiEvents.clear();
  525. AudioEffectX::resume();
  526. #if JucePlugin_ProducesMidiOutput
  527. ensureOutgoingEventSize (64);
  528. #endif
  529. #if JucePlugin_WantsMidiInput && ! JUCE_USE_VSTSDK_2_4
  530. wantEvents();
  531. #endif
  532. }
  533. void suspend()
  534. {
  535. AudioEffectX::suspend();
  536. filter->releaseResources();
  537. midiEvents.clear();
  538. isProcessing = false;
  539. juce_free (channels);
  540. channels = 0;
  541. }
  542. bool JUCE_CALLTYPE getCurrentPositionInfo (AudioFilterBase::CurrentPositionInfo& info)
  543. {
  544. const VstTimeInfo* const ti = getTimeInfo (kVstPpqPosValid
  545. | kVstTempoValid
  546. | kVstBarsValid
  547. //| kVstCyclePosValid
  548. | kVstTimeSigValid
  549. | kVstSmpteValid
  550. | kVstClockValid);
  551. if (ti == 0 || ti->sampleRate <= 0)
  552. return false;
  553. if ((ti->flags & kVstTempoValid) != 0)
  554. info.bpm = ti->tempo;
  555. else
  556. info.bpm = 0.0;
  557. if ((ti->flags & kVstTimeSigValid) != 0)
  558. {
  559. info.timeSigNumerator = ti->timeSigNumerator;
  560. info.timeSigDenominator = ti->timeSigDenominator;
  561. }
  562. else
  563. {
  564. info.timeSigNumerator = 4;
  565. info.timeSigDenominator = 4;
  566. }
  567. info.timeInSeconds = ti->samplePos / ti->sampleRate;
  568. if ((ti->flags & kVstPpqPosValid) != 0)
  569. info.ppqPosition = ti->ppqPos;
  570. else
  571. info.ppqPosition = 0.0;
  572. if ((ti->flags & kVstBarsValid) != 0)
  573. info.ppqPositionOfLastBarStart = ti->barStartPos;
  574. else
  575. info.ppqPositionOfLastBarStart = 0.0;
  576. if ((ti->flags & kVstSmpteValid) != 0)
  577. {
  578. info.frameRate = (AudioFilterBase::CurrentPositionInfo::FrameRateType) (int) ti->smpteFrameRate;
  579. const double fpsDivisors[] = { 24.0, 25.0, 30.0, 30.0, 30.0, 30.0, 1.0 };
  580. info.editOriginTime = (ti->smpteOffset / (80.0 * fpsDivisors [(int) info.frameRate]));
  581. }
  582. else
  583. {
  584. info.frameRate = AudioFilterBase::CurrentPositionInfo::fpsUnknown;
  585. info.editOriginTime = 0;
  586. }
  587. info.isRecording = (ti->flags & kVstTransportRecording) != 0;
  588. info.isPlaying = (ti->flags & kVstTransportPlaying) != 0 || info.isRecording;
  589. return true;
  590. }
  591. //==============================================================================
  592. VstInt32 getProgram()
  593. {
  594. return filter->getCurrentProgram();
  595. }
  596. void setProgram (VstInt32 program)
  597. {
  598. filter->setCurrentProgram (program);
  599. }
  600. void setProgramName (char* name)
  601. {
  602. filter->changeProgramName (filter->getCurrentProgram(), name);
  603. }
  604. void getProgramName (char* name)
  605. {
  606. filter->getProgramName (filter->getCurrentProgram()).copyToBuffer (name, 24);
  607. }
  608. bool getProgramNameIndexed (VstInt32 category, VstInt32 index, char* text)
  609. {
  610. if (index >= 0 && index < filter->getNumPrograms())
  611. {
  612. filter->getProgramName (index).copyToBuffer (text, 24);
  613. return true;
  614. }
  615. return false;
  616. }
  617. //==============================================================================
  618. float getParameter (VstInt32 index)
  619. {
  620. jassert (index >= 0 && index < filter->getNumParameters());
  621. return filter->getParameter (index);
  622. }
  623. void setParameter (VstInt32 index, float value)
  624. {
  625. jassert (index >= 0 && index < filter->getNumParameters());
  626. filter->setParameter (index, value);
  627. }
  628. void getParameterDisplay (VstInt32 index, char* text)
  629. {
  630. jassert (index >= 0 && index < filter->getNumParameters());
  631. filter->getParameterText (index).copyToBuffer (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  632. }
  633. void getParameterName (VstInt32 index, char* text)
  634. {
  635. jassert (index >= 0 && index < filter->getNumParameters());
  636. filter->getParameterName (index).copyToBuffer (text, 16); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  637. }
  638. void JUCE_CALLTYPE informHostOfParameterChange (int index, float newValue)
  639. {
  640. setParameterAutomated (index, newValue);
  641. }
  642. void JUCE_CALLTYPE informHostOfStateChange()
  643. {
  644. updateDisplay();
  645. }
  646. bool canParameterBeAutomated (VstInt32 index)
  647. {
  648. return filter->isParameterAutomatable ((int) index);
  649. }
  650. //==============================================================================
  651. VstInt32 getChunk (void** data, bool onlyStoreCurrentProgramData)
  652. {
  653. chunkMemory.setSize (0);
  654. if (onlyStoreCurrentProgramData)
  655. filter->getCurrentProgramStateInformation (chunkMemory);
  656. else
  657. filter->getStateInformation (chunkMemory);
  658. *data = (void*) chunkMemory;
  659. // because the chunk is only needed temporarily by the host (or at least you'd
  660. // hope so) we'll give it a while and then free it in the timer callback.
  661. chunkMemoryTime = JUCE_NAMESPACE::Time::getApproximateMillisecondCounter();
  662. return chunkMemory.getSize();
  663. }
  664. VstInt32 setChunk (void* data, VstInt32 byteSize, bool onlyRestoreCurrentProgramData)
  665. {
  666. chunkMemory.setSize (0);
  667. chunkMemoryTime = 0;
  668. if (byteSize > 0 && data != 0)
  669. {
  670. if (onlyRestoreCurrentProgramData)
  671. filter->setCurrentProgramStateInformation (data, byteSize);
  672. else
  673. filter->setStateInformation (data, byteSize);
  674. }
  675. return 0;
  676. }
  677. void timerCallback()
  678. {
  679. if (chunkMemoryTime > 0
  680. && chunkMemoryTime < JUCE_NAMESPACE::Time::getApproximateMillisecondCounter() - 2000
  681. && ! recursionCheck)
  682. {
  683. chunkMemoryTime = 0;
  684. chunkMemory.setSize (0);
  685. }
  686. tryMasterIdle();
  687. }
  688. void tryMasterIdle()
  689. {
  690. if (Component::isMouseButtonDownAnywhere()
  691. && ! recursionCheck)
  692. {
  693. const uint32 now = JUCE_NAMESPACE::Time::getMillisecondCounter();
  694. if (now > lastMasterIdleCall + 20 && editorComp != 0)
  695. {
  696. lastMasterIdleCall = now;
  697. recursionCheck = true;
  698. masterIdle();
  699. recursionCheck = false;
  700. }
  701. }
  702. }
  703. void doIdleCallback()
  704. {
  705. // (wavelab calls this on a separate thread and causes a deadlock)..
  706. if (MessageManager::getInstance()->isThisTheMessageThread())
  707. {
  708. if (! recursionCheck)
  709. {
  710. const MessageManagerLock mml;
  711. recursionCheck = true;
  712. juce_callAnyTimersSynchronously();
  713. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  714. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  715. recursionCheck = false;
  716. }
  717. }
  718. }
  719. void createEditorComp()
  720. {
  721. if (editorComp == 0)
  722. {
  723. #if JUCE_LINUX
  724. const MessageManagerLock mml;
  725. #endif
  726. AudioFilterEditor* const ed = filter->createEditorIfNeeded();
  727. if (ed != 0)
  728. {
  729. ed->setOpaque (true);
  730. ed->setVisible (true);
  731. editorComp = new EditorCompWrapper (this, ed);
  732. }
  733. }
  734. }
  735. void deleteEditor()
  736. {
  737. PopupMenu::dismissAllActiveMenus();
  738. jassert (! recursionCheck);
  739. recursionCheck = true;
  740. #if JUCE_LINUX
  741. const MessageManagerLock mml;
  742. #endif
  743. if (editorComp != 0)
  744. {
  745. Component* const modalComponent = Component::getCurrentlyModalComponent();
  746. if (modalComponent != 0)
  747. modalComponent->exitModalState (0);
  748. filter->editorBeingDeleted (editorComp->getEditorComp());
  749. deleteAndZero (editorComp);
  750. // there's some kind of component currently modal, but the host
  751. // is trying to delete our plugin. You should try to avoid this happening..
  752. jassert (Component::getCurrentlyModalComponent() == 0);
  753. }
  754. #if JUCE_MAC || JUCE_LINUX
  755. hostWindow = 0;
  756. #endif
  757. recursionCheck = false;
  758. }
  759. VstIntPtr dispatcher (VstInt32 opCode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  760. {
  761. if (opCode == effEditIdle)
  762. {
  763. doIdleCallback();
  764. return 0;
  765. }
  766. else if (opCode == effEditOpen)
  767. {
  768. jassert (! recursionCheck);
  769. deleteEditor();
  770. createEditorComp();
  771. if (editorComp != 0)
  772. {
  773. #if JUCE_LINUX
  774. const MessageManagerLock mml;
  775. #endif
  776. editorComp->setOpaque (true);
  777. editorComp->setVisible (false);
  778. #if JUCE_WIN32
  779. editorComp->addToDesktop (0);
  780. hostWindow = (HWND) ptr;
  781. HWND editorWnd = (HWND) editorComp->getWindowHandle();
  782. SetParent (editorWnd, hostWindow);
  783. DWORD val = GetWindowLong (editorWnd, GWL_STYLE);
  784. val = (val & ~WS_POPUP) | WS_CHILD;
  785. SetWindowLong (editorWnd, GWL_STYLE, val);
  786. editorComp->setVisible (true);
  787. #elif JUCE_LINUX
  788. editorComp->addToDesktop (0);
  789. hostWindow = (Window) ptr;
  790. Window editorWnd = (Window) editorComp->getWindowHandle();
  791. XReparentWindow (display, editorWnd, hostWindow, 0, 0);
  792. editorComp->setVisible (true);
  793. #else
  794. hostWindow = (WindowRef) ptr;
  795. firstResize = true;
  796. SetAutomaticControlDragTrackingEnabledForWindow (hostWindow, true);
  797. WindowAttributes attributes;
  798. GetWindowAttributes (hostWindow, &attributes);
  799. HIViewRef parentView = 0;
  800. if ((attributes & kWindowCompositingAttribute) != 0)
  801. {
  802. HIViewRef root = HIViewGetRoot (hostWindow);
  803. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  804. if (parentView == 0)
  805. parentView = root;
  806. }
  807. else
  808. {
  809. GetRootControl (hostWindow, (ControlRef*) &parentView);
  810. if (parentView == 0)
  811. CreateRootControl (hostWindow, (ControlRef*) &parentView);
  812. }
  813. jassert (parentView != 0); // agh - the host has to provide a compositing window..
  814. editorComp->setVisible (true);
  815. editorComp->addToDesktop (0, (void*) parentView);
  816. #endif
  817. return 1;
  818. }
  819. }
  820. else if (opCode == effEditClose)
  821. {
  822. deleteEditor();
  823. return 0;
  824. }
  825. else if (opCode == effEditGetRect)
  826. {
  827. createEditorComp();
  828. if (editorComp != 0)
  829. {
  830. editorSize.left = 0;
  831. editorSize.top = 0;
  832. editorSize.right = editorComp->getWidth();
  833. editorSize.bottom = editorComp->getHeight();
  834. *((ERect**) ptr) = &editorSize;
  835. return (VstIntPtr) &editorSize;
  836. }
  837. else
  838. {
  839. return 0;
  840. }
  841. }
  842. return AudioEffectX::dispatcher (opCode, index, value, ptr, opt);
  843. }
  844. void resizeHostWindow (int newWidth, int newHeight)
  845. {
  846. if (editorComp != 0)
  847. {
  848. #if ! JUCE_LINUX // linux hosts shouldn't be trusted!
  849. if (! (canHostDo ("sizeWindow") && sizeWindow (newWidth, newHeight)))
  850. #endif
  851. {
  852. // some hosts don't support the sizeWindow call, so do it manually..
  853. #if JUCE_MAC
  854. Rect r;
  855. GetWindowBounds (hostWindow, kWindowContentRgn, &r);
  856. if (firstResize)
  857. {
  858. diffW = (r.right - r.left) - editorComp->getWidth();
  859. diffH = (r.bottom - r.top) - editorComp->getHeight();
  860. firstResize = false;
  861. }
  862. r.right = r.left + newWidth + diffW;
  863. r.bottom = r.top + newHeight + diffH;
  864. SetWindowBounds (hostWindow, kWindowContentRgn, &r);
  865. r.bottom -= r.top;
  866. r.right -= r.left;
  867. r.left = r.top = 0;
  868. InvalWindowRect (hostWindow, &r);
  869. #elif JUCE_LINUX
  870. Window root;
  871. int x, y;
  872. unsigned int width, height, border, depth;
  873. XGetGeometry (display, hostWindow, &root,
  874. &x, &y, &width, &height, &border, &depth);
  875. newWidth += (width + border) - editorComp->getWidth();
  876. newHeight += (height + border) - editorComp->getHeight();
  877. XResizeWindow (display, hostWindow, newWidth, newHeight);
  878. #else
  879. int dw = 0;
  880. int dh = 0;
  881. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  882. HWND w = (HWND) editorComp->getWindowHandle();
  883. while (w != 0)
  884. {
  885. HWND parent = GetParent (w);
  886. if (parent == 0)
  887. break;
  888. TCHAR windowType [32];
  889. zeromem (windowType, sizeof (windowType));
  890. GetClassName (parent, windowType, 31);
  891. if (String (windowType).equalsIgnoreCase (T("MDIClient")))
  892. break;
  893. RECT windowPos;
  894. GetWindowRect (w, &windowPos);
  895. RECT parentPos;
  896. GetWindowRect (parent, &parentPos);
  897. SetWindowPos (w, 0, 0, 0,
  898. newWidth + dw,
  899. newHeight + dh,
  900. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  901. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  902. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  903. w = parent;
  904. if (dw == 2 * frameThickness)
  905. break;
  906. if (dw > 100 || dh > 100)
  907. w = 0;
  908. }
  909. if (w != 0)
  910. SetWindowPos (w, 0, 0, 0,
  911. newWidth + dw,
  912. newHeight + dh,
  913. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  914. #endif
  915. }
  916. if (editorComp->getPeer() != 0)
  917. editorComp->getPeer()->handleMovedOrResized();
  918. }
  919. }
  920. //==============================================================================
  921. juce_UseDebuggingNewOperator
  922. private:
  923. AudioFilterBase* filter;
  924. juce::MemoryBlock chunkMemory;
  925. uint32 chunkMemoryTime;
  926. EditorCompWrapper* editorComp;
  927. ERect editorSize;
  928. MidiBuffer midiEvents;
  929. VstEvents* outgoingEvents;
  930. int outgoingEventSize;
  931. bool isProcessing;
  932. bool firstResize;
  933. int diffW, diffH;
  934. float** channels;
  935. void ensureOutgoingEventSize (int numEvents)
  936. {
  937. if (outgoingEventSize < numEvents)
  938. {
  939. numEvents += 32;
  940. const int size = 16 + sizeof (VstEvent*) * numEvents;
  941. if (outgoingEvents == 0)
  942. outgoingEvents = (VstEvents*) juce_calloc (size);
  943. else
  944. outgoingEvents = (VstEvents*) juce_realloc (outgoingEvents, size);
  945. for (int i = outgoingEventSize; i < numEvents; ++i)
  946. {
  947. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  948. e->type = kVstMidiType;
  949. e->byteSize = 24;
  950. outgoingEvents->events[i] = (VstEvent*) e;
  951. }
  952. outgoingEventSize = numEvents;
  953. }
  954. }
  955. const String getHostName()
  956. {
  957. char host[256];
  958. zeromem (host, sizeof (host));
  959. getHostProductString (host);
  960. return host;
  961. }
  962. #if JUCE_MAC
  963. WindowRef hostWindow;
  964. #elif JUCE_LINUX
  965. Window hostWindow;
  966. #else
  967. HWND hostWindow;
  968. #endif
  969. };
  970. //==============================================================================
  971. void EditorCompWrapper::childBoundsChanged (Component* child)
  972. {
  973. child->setTopLeftPosition (0, 0);
  974. const int cw = child->getWidth();
  975. const int ch = child->getHeight();
  976. wrapper->resizeHostWindow (cw, ch);
  977. setSize (cw, ch);
  978. #if JUCE_MAC
  979. wrapper->resizeHostWindow (cw, ch); // (doing this a second time seems to be necessary in tracktion)
  980. #endif
  981. }
  982. void EditorCompWrapper::handleAsyncUpdate()
  983. {
  984. wrapper->tryMasterIdle();
  985. }
  986. //==============================================================================
  987. static AEffect* pluginEntryPoint (audioMasterCallback audioMaster)
  988. {
  989. #if JUCE_MAC || JUCE_LINUX
  990. initialiseJuce_GUI();
  991. #endif
  992. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  993. try
  994. {
  995. if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0)
  996. {
  997. AudioFilterBase* const filter = createPluginFilter();
  998. if (filter != 0)
  999. {
  1000. JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter);
  1001. return wrapper->getAeffect();
  1002. }
  1003. }
  1004. }
  1005. catch (...)
  1006. {}
  1007. return 0;
  1008. }
  1009. //==============================================================================
  1010. // Mac startup code..
  1011. #if JUCE_MAC
  1012. extern "C" __attribute__ ((visibility("default"))) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1013. {
  1014. return pluginEntryPoint (audioMaster);
  1015. }
  1016. extern "C" __attribute__ ((visibility("default"))) AEffect* main_macho (audioMasterCallback audioMaster)
  1017. {
  1018. return pluginEntryPoint (audioMaster);
  1019. }
  1020. //==============================================================================
  1021. // Linux startup code..
  1022. #elif JUCE_LINUX
  1023. extern "C" AEffect* main_plugin (audioMasterCallback audioMaster) asm ("main");
  1024. extern "C" AEffect* main_plugin (audioMasterCallback audioMaster)
  1025. {
  1026. initialiseJuce_GUI();
  1027. SharedMessageThread::getInstance();
  1028. return pluginEntryPoint (audioMaster);
  1029. }
  1030. __attribute__((constructor)) void myPluginInit()
  1031. {
  1032. // don't put initialiseJuce_GUI here... it will crash !
  1033. }
  1034. __attribute__((destructor)) void myPluginFini()
  1035. {
  1036. // don't put shutdownJuce_GUI here... it will crash !
  1037. }
  1038. //==============================================================================
  1039. // Win32 startup code..
  1040. #else
  1041. extern "C" __declspec (dllexport) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1042. {
  1043. return pluginEntryPoint (audioMaster);
  1044. }
  1045. extern "C" __declspec (dllexport) void* main (audioMasterCallback audioMaster)
  1046. {
  1047. return (void*) pluginEntryPoint (audioMaster);
  1048. }
  1049. BOOL WINAPI DllMain (HINSTANCE instance, DWORD dwReason, LPVOID)
  1050. {
  1051. if (dwReason == DLL_PROCESS_ATTACH)
  1052. {
  1053. PlatformUtilities::setCurrentModuleInstanceHandle (instance);
  1054. initialiseJuce_GUI();
  1055. }
  1056. else if (dwReason == DLL_PROCESS_DETACH)
  1057. {
  1058. shutdownJuce_GUI();
  1059. }
  1060. return TRUE;
  1061. }
  1062. #endif