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.

1537 lines
45KB

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