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.

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