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.

1374 lines
40KB

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