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.

1553 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. numInChans = JucePlugin_MaxNumInputChannels;
  284. numOutChans = JucePlugin_MaxNumOutputChannels;
  285. #if JUCE_MAC || JUCE_LINUX
  286. hostWindow = 0;
  287. #endif
  288. filter->setPlayConfigDetails (numInChans, numOutChans, 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 (numInChans);
  298. setNumOutputs (numOutChans);
  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 = numInChans;
  454. const int numOut = numOutChans;
  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 = numInChans;
  479. const int numOut = numOutChans;
  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. VstInt32 startProcess () { return 0; }
  568. VstInt32 stopProcess () { return 0;}
  569. void resume()
  570. {
  571. if (filter == 0)
  572. return;
  573. isProcessing = true;
  574. juce_free (channels);
  575. channels = (float**) juce_calloc (sizeof (float*) * (numInChans + numOutChans));
  576. double rate = getSampleRate();
  577. jassert (rate > 0);
  578. if (rate <= 0.0)
  579. rate = 44100.0;
  580. const int blockSize = getBlockSize();
  581. jassert (blockSize > 0);
  582. filter->setPlayConfigDetails (numInChans, numOutChans,
  583. rate, blockSize);
  584. deleteTempChannels();
  585. filter->prepareToPlay (rate, blockSize);
  586. midiEvents.clear();
  587. setInitialDelay (filter->getLatencySamples());
  588. AudioEffectX::resume();
  589. #if JucePlugin_ProducesMidiOutput
  590. ensureOutgoingEventSize (64);
  591. #endif
  592. #if JucePlugin_WantsMidiInput && ! JUCE_USE_VSTSDK_2_4
  593. wantEvents();
  594. #endif
  595. }
  596. void suspend()
  597. {
  598. if (filter == 0)
  599. return;
  600. AudioEffectX::suspend();
  601. filter->releaseResources();
  602. midiEvents.clear();
  603. isProcessing = false;
  604. juce_free (channels);
  605. channels = 0;
  606. deleteTempChannels();
  607. }
  608. bool getCurrentPosition (AudioPlayHead::CurrentPositionInfo& info)
  609. {
  610. const VstTimeInfo* const ti = getTimeInfo (kVstPpqPosValid
  611. | kVstTempoValid
  612. | kVstBarsValid
  613. //| kVstCyclePosValid
  614. | kVstTimeSigValid
  615. | kVstSmpteValid
  616. | kVstClockValid);
  617. if (ti == 0 || ti->sampleRate <= 0)
  618. return false;
  619. if ((ti->flags & kVstTempoValid) != 0)
  620. info.bpm = ti->tempo;
  621. else
  622. info.bpm = 0.0;
  623. if ((ti->flags & kVstTimeSigValid) != 0)
  624. {
  625. info.timeSigNumerator = ti->timeSigNumerator;
  626. info.timeSigDenominator = ti->timeSigDenominator;
  627. }
  628. else
  629. {
  630. info.timeSigNumerator = 4;
  631. info.timeSigDenominator = 4;
  632. }
  633. info.timeInSeconds = ti->samplePos / ti->sampleRate;
  634. if ((ti->flags & kVstPpqPosValid) != 0)
  635. info.ppqPosition = ti->ppqPos;
  636. else
  637. info.ppqPosition = 0.0;
  638. if ((ti->flags & kVstBarsValid) != 0)
  639. info.ppqPositionOfLastBarStart = ti->barStartPos;
  640. else
  641. info.ppqPositionOfLastBarStart = 0.0;
  642. if ((ti->flags & kVstSmpteValid) != 0)
  643. {
  644. AudioPlayHead::FrameRateType rate = AudioPlayHead::fpsUnknown;
  645. double fps = 1.0;
  646. switch (ti->smpteFrameRate)
  647. {
  648. case kVstSmpte24fps:
  649. rate = AudioPlayHead::fps24;
  650. fps = 24.0;
  651. break;
  652. case kVstSmpte25fps:
  653. rate = AudioPlayHead::fps25;
  654. fps = 25.0;
  655. break;
  656. case kVstSmpte2997fps:
  657. rate = AudioPlayHead::fps2997;
  658. fps = 29.97;
  659. break;
  660. case kVstSmpte30fps:
  661. rate = AudioPlayHead::fps30;
  662. fps = 30.0;
  663. break;
  664. case kVstSmpte2997dfps:
  665. rate = AudioPlayHead::fps2997drop;
  666. fps = 29.97;
  667. break;
  668. case kVstSmpte30dfps:
  669. rate = AudioPlayHead::fps30drop;
  670. fps = 30.0;
  671. break;
  672. case kVstSmpteFilm16mm:
  673. case kVstSmpteFilm35mm:
  674. fps = 24.0;
  675. break;
  676. case kVstSmpte239fps: fps = 23.976; break;
  677. case kVstSmpte249fps: fps = 24.976; break;
  678. case kVstSmpte599fps: fps = 59.94; break;
  679. case kVstSmpte60fps: fps = 60; break;
  680. default:
  681. jassertfalse // unknown frame-rate..
  682. }
  683. info.frameRate = rate;
  684. info.editOriginTime = ti->smpteOffset / (80.0 * fps);
  685. }
  686. else
  687. {
  688. info.frameRate = AudioPlayHead::fpsUnknown;
  689. info.editOriginTime = 0;
  690. }
  691. info.isRecording = (ti->flags & kVstTransportRecording) != 0;
  692. info.isPlaying = (ti->flags & kVstTransportPlaying) != 0 || info.isRecording;
  693. return true;
  694. }
  695. //==============================================================================
  696. VstInt32 getProgram()
  697. {
  698. return filter != 0 ? filter->getCurrentProgram() : 0;
  699. }
  700. void setProgram (VstInt32 program)
  701. {
  702. if (filter != 0)
  703. filter->setCurrentProgram (program);
  704. }
  705. void setProgramName (char* name)
  706. {
  707. if (filter != 0)
  708. filter->changeProgramName (filter->getCurrentProgram(), name);
  709. }
  710. void getProgramName (char* name)
  711. {
  712. if (filter != 0)
  713. filter->getProgramName (filter->getCurrentProgram()).copyToBuffer (name, 24);
  714. }
  715. bool getProgramNameIndexed (VstInt32 category, VstInt32 index, char* text)
  716. {
  717. if (filter != 0 && ((unsigned int) index) < (unsigned int) filter->getNumPrograms())
  718. {
  719. filter->getProgramName (index).copyToBuffer (text, 24);
  720. return true;
  721. }
  722. return false;
  723. }
  724. //==============================================================================
  725. float getParameter (VstInt32 index)
  726. {
  727. if (filter == 0)
  728. return 0.0f;
  729. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  730. return filter->getParameter (index);
  731. }
  732. void setParameter (VstInt32 index, float value)
  733. {
  734. if (filter != 0)
  735. {
  736. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  737. filter->setParameter (index, value);
  738. }
  739. }
  740. void getParameterDisplay (VstInt32 index, char* text)
  741. {
  742. if (filter != 0)
  743. {
  744. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  745. filter->getParameterText (index).copyToBuffer (text, 24); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  746. }
  747. }
  748. void getParameterName (VstInt32 index, char* text)
  749. {
  750. if (filter != 0)
  751. {
  752. jassert (((unsigned int) index) < (unsigned int) filter->getNumParameters());
  753. filter->getParameterName (index).copyToBuffer (text, 16); // length should technically be kVstMaxParamStrLen, which is 8, but hosts will normally allow a bit more.
  754. }
  755. }
  756. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue)
  757. {
  758. setParameterAutomated (index, newValue);
  759. }
  760. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index)
  761. {
  762. beginEdit (index);
  763. }
  764. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index)
  765. {
  766. endEdit (index);
  767. }
  768. void audioProcessorChanged (AudioProcessor*)
  769. {
  770. updateDisplay();
  771. }
  772. bool canParameterBeAutomated (VstInt32 index)
  773. {
  774. return filter != 0 && filter->isParameterAutomatable ((int) index);
  775. }
  776. bool setSpeakerArrangement (VstSpeakerArrangement* pluginInput,
  777. VstSpeakerArrangement* pluginOutput)
  778. {
  779. // if this method isn't implemented, nuendo4 + cubase4 crash when you've got multiple channels..
  780. numInChans = pluginInput->numChannels;
  781. numOutChans = pluginOutput->numChannels;
  782. filter->setPlayConfigDetails (numInChans, numOutChans,
  783. filter->getSampleRate(),
  784. filter->getBlockSize());
  785. return true;
  786. }
  787. //==============================================================================
  788. VstInt32 getChunk (void** data, bool onlyStoreCurrentProgramData)
  789. {
  790. if (filter == 0)
  791. return 0;
  792. chunkMemory.setSize (0);
  793. if (onlyStoreCurrentProgramData)
  794. filter->getCurrentProgramStateInformation (chunkMemory);
  795. else
  796. filter->getStateInformation (chunkMemory);
  797. *data = (void*) chunkMemory;
  798. // because the chunk is only needed temporarily by the host (or at least you'd
  799. // hope so) we'll give it a while and then free it in the timer callback.
  800. chunkMemoryTime = JUCE_NAMESPACE::Time::getApproximateMillisecondCounter();
  801. return chunkMemory.getSize();
  802. }
  803. VstInt32 setChunk (void* data, VstInt32 byteSize, bool onlyRestoreCurrentProgramData)
  804. {
  805. if (filter == 0)
  806. return 0;
  807. chunkMemory.setSize (0);
  808. chunkMemoryTime = 0;
  809. if (byteSize > 0 && data != 0)
  810. {
  811. if (onlyRestoreCurrentProgramData)
  812. filter->setCurrentProgramStateInformation (data, byteSize);
  813. else
  814. filter->setStateInformation (data, byteSize);
  815. }
  816. return 0;
  817. }
  818. void timerCallback()
  819. {
  820. if (chunkMemoryTime > 0
  821. && chunkMemoryTime < JUCE_NAMESPACE::Time::getApproximateMillisecondCounter() - 2000
  822. && ! recursionCheck)
  823. {
  824. chunkMemoryTime = 0;
  825. chunkMemory.setSize (0);
  826. }
  827. tryMasterIdle();
  828. }
  829. void tryMasterIdle()
  830. {
  831. if (Component::isMouseButtonDownAnywhere()
  832. && ! recursionCheck)
  833. {
  834. const uint32 now = JUCE_NAMESPACE::Time::getMillisecondCounter();
  835. if (now > lastMasterIdleCall + 20 && editorComp != 0)
  836. {
  837. lastMasterIdleCall = now;
  838. recursionCheck = true;
  839. masterIdle();
  840. recursionCheck = false;
  841. }
  842. }
  843. }
  844. void doIdleCallback()
  845. {
  846. // (wavelab calls this on a separate thread and causes a deadlock)..
  847. if (MessageManager::getInstance()->isThisTheMessageThread()
  848. && ! recursionCheck)
  849. {
  850. const MessageManagerLock mml;
  851. recursionCheck = true;
  852. juce_callAnyTimersSynchronously();
  853. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  854. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  855. recursionCheck = false;
  856. }
  857. }
  858. void createEditorComp()
  859. {
  860. if (hasShutdown || filter == 0)
  861. return;
  862. if (editorComp == 0)
  863. {
  864. #if JUCE_LINUX
  865. const MessageManagerLock mml;
  866. #endif
  867. AudioProcessorEditor* const ed = filter->createEditorIfNeeded();
  868. if (ed != 0)
  869. {
  870. ed->setOpaque (true);
  871. ed->setVisible (true);
  872. editorComp = new EditorCompWrapper (this, ed);
  873. }
  874. }
  875. }
  876. void deleteEditor()
  877. {
  878. PopupMenu::dismissAllActiveMenus();
  879. jassert (! recursionCheck);
  880. recursionCheck = true;
  881. #if JUCE_LINUX
  882. const MessageManagerLock mml;
  883. #endif
  884. if (editorComp != 0)
  885. {
  886. Component* const modalComponent = Component::getCurrentlyModalComponent();
  887. if (modalComponent != 0)
  888. modalComponent->exitModalState (0);
  889. filter->editorBeingDeleted (editorComp->getEditorComp());
  890. deleteAndZero (editorComp);
  891. // there's some kind of component currently modal, but the host
  892. // is trying to delete our plugin. You should try to avoid this happening..
  893. jassert (Component::getCurrentlyModalComponent() == 0);
  894. }
  895. #if JUCE_MAC || JUCE_LINUX
  896. hostWindow = 0;
  897. #endif
  898. recursionCheck = false;
  899. }
  900. VstIntPtr dispatcher (VstInt32 opCode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  901. {
  902. if (hasShutdown)
  903. return 0;
  904. if (opCode == effEditIdle)
  905. {
  906. doIdleCallback();
  907. return 0;
  908. }
  909. else if (opCode == effEditOpen)
  910. {
  911. jassert (! recursionCheck);
  912. deleteEditor();
  913. createEditorComp();
  914. if (editorComp != 0)
  915. {
  916. #if JUCE_LINUX
  917. const MessageManagerLock mml;
  918. #endif
  919. editorComp->setOpaque (true);
  920. editorComp->setVisible (false);
  921. #if JUCE_WIN32
  922. editorComp->addToDesktop (0);
  923. hostWindow = (HWND) ptr;
  924. HWND editorWnd = (HWND) editorComp->getWindowHandle();
  925. SetParent (editorWnd, hostWindow);
  926. DWORD val = GetWindowLong (editorWnd, GWL_STYLE);
  927. val = (val & ~WS_POPUP) | WS_CHILD;
  928. SetWindowLong (editorWnd, GWL_STYLE, val);
  929. editorComp->setVisible (true);
  930. #elif JUCE_LINUX
  931. editorComp->addToDesktop (0);
  932. hostWindow = (Window) ptr;
  933. Window editorWnd = (Window) editorComp->getWindowHandle();
  934. XReparentWindow (display, editorWnd, hostWindow, 0, 0);
  935. editorComp->setVisible (true);
  936. #else
  937. hostWindow = (WindowRef) ptr;
  938. firstResize = true;
  939. SetAutomaticControlDragTrackingEnabledForWindow (hostWindow, true);
  940. WindowAttributes attributes;
  941. GetWindowAttributes (hostWindow, &attributes);
  942. HIViewRef parentView = 0;
  943. if ((attributes & kWindowCompositingAttribute) != 0)
  944. {
  945. HIViewRef root = HIViewGetRoot (hostWindow);
  946. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  947. if (parentView == 0)
  948. parentView = root;
  949. }
  950. else
  951. {
  952. GetRootControl (hostWindow, (ControlRef*) &parentView);
  953. if (parentView == 0)
  954. CreateRootControl (hostWindow, (ControlRef*) &parentView);
  955. }
  956. jassert (parentView != 0); // agh - the host has to provide a compositing window..
  957. editorComp->setVisible (true);
  958. editorComp->addToDesktop (0, (void*) parentView);
  959. #endif
  960. return 1;
  961. }
  962. }
  963. else if (opCode == effEditClose)
  964. {
  965. deleteEditor();
  966. return 0;
  967. }
  968. else if (opCode == effEditGetRect)
  969. {
  970. createEditorComp();
  971. if (editorComp != 0)
  972. {
  973. editorSize.left = 0;
  974. editorSize.top = 0;
  975. editorSize.right = editorComp->getWidth();
  976. editorSize.bottom = editorComp->getHeight();
  977. *((ERect**) ptr) = &editorSize;
  978. return (VstIntPtr) &editorSize;
  979. }
  980. else
  981. {
  982. return 0;
  983. }
  984. }
  985. return AudioEffectX::dispatcher (opCode, index, value, ptr, opt);
  986. }
  987. void resizeHostWindow (int newWidth, int newHeight)
  988. {
  989. if (editorComp != 0)
  990. {
  991. #if ! JUCE_LINUX // linux hosts shouldn't be trusted!
  992. if (! (canHostDo ("sizeWindow") && sizeWindow (newWidth, newHeight)))
  993. #endif
  994. {
  995. // some hosts don't support the sizeWindow call, so do it manually..
  996. #if JUCE_MAC
  997. Rect r;
  998. GetWindowBounds (hostWindow, kWindowContentRgn, &r);
  999. if (firstResize)
  1000. {
  1001. diffW = (r.right - r.left) - editorComp->getWidth();
  1002. diffH = (r.bottom - r.top) - editorComp->getHeight();
  1003. firstResize = false;
  1004. }
  1005. r.right = r.left + newWidth + diffW;
  1006. r.bottom = r.top + newHeight + diffH;
  1007. SetWindowBounds (hostWindow, kWindowContentRgn, &r);
  1008. r.bottom -= r.top;
  1009. r.right -= r.left;
  1010. r.left = r.top = 0;
  1011. InvalWindowRect (hostWindow, &r);
  1012. #elif JUCE_LINUX
  1013. Window root;
  1014. int x, y;
  1015. unsigned int width, height, border, depth;
  1016. XGetGeometry (display, hostWindow, &root,
  1017. &x, &y, &width, &height, &border, &depth);
  1018. newWidth += (width + border) - editorComp->getWidth();
  1019. newHeight += (height + border) - editorComp->getHeight();
  1020. XResizeWindow (display, hostWindow, newWidth, newHeight);
  1021. #else
  1022. int dw = 0;
  1023. int dh = 0;
  1024. const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);
  1025. HWND w = (HWND) editorComp->getWindowHandle();
  1026. while (w != 0)
  1027. {
  1028. HWND parent = GetParent (w);
  1029. if (parent == 0)
  1030. break;
  1031. TCHAR windowType [32];
  1032. zeromem (windowType, sizeof (windowType));
  1033. GetClassName (parent, windowType, 31);
  1034. if (String (windowType).equalsIgnoreCase (T("MDIClient")))
  1035. break;
  1036. RECT windowPos;
  1037. GetWindowRect (w, &windowPos);
  1038. RECT parentPos;
  1039. GetWindowRect (parent, &parentPos);
  1040. SetWindowPos (w, 0, 0, 0,
  1041. newWidth + dw,
  1042. newHeight + dh,
  1043. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1044. dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
  1045. dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);
  1046. w = parent;
  1047. if (dw == 2 * frameThickness)
  1048. break;
  1049. if (dw > 100 || dh > 100)
  1050. w = 0;
  1051. }
  1052. if (w != 0)
  1053. SetWindowPos (w, 0, 0, 0,
  1054. newWidth + dw,
  1055. newHeight + dh,
  1056. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  1057. #endif
  1058. }
  1059. if (editorComp->getPeer() != 0)
  1060. editorComp->getPeer()->handleMovedOrResized();
  1061. }
  1062. }
  1063. //==============================================================================
  1064. juce_UseDebuggingNewOperator
  1065. private:
  1066. AudioProcessor* filter;
  1067. juce::MemoryBlock chunkMemory;
  1068. uint32 chunkMemoryTime;
  1069. EditorCompWrapper* editorComp;
  1070. ERect editorSize;
  1071. MidiBuffer midiEvents;
  1072. VstEvents* outgoingEvents;
  1073. int outgoingEventSize;
  1074. bool isProcessing;
  1075. bool firstResize;
  1076. bool hasShutdown;
  1077. int diffW, diffH;
  1078. int numInChans, numOutChans;
  1079. float** channels;
  1080. VoidArray tempChannels; // see note in processReplacing()
  1081. bool hasCreatedTempChannels;
  1082. void deleteTempChannels()
  1083. {
  1084. int i;
  1085. for (i = tempChannels.size(); --i >= 0;)
  1086. juce_free (tempChannels.getUnchecked(i));
  1087. tempChannels.clear();
  1088. if (filter != 0)
  1089. tempChannels.insertMultiple (0, 0, filter->getNumInputChannels() + filter->getNumOutputChannels());
  1090. hasCreatedTempChannels = false;
  1091. }
  1092. void ensureOutgoingEventSize (int numEvents)
  1093. {
  1094. if (outgoingEventSize < numEvents)
  1095. {
  1096. numEvents += 32;
  1097. const int size = 16 + sizeof (VstEvent*) * numEvents;
  1098. if (outgoingEvents == 0)
  1099. outgoingEvents = (VstEvents*) juce_calloc (size);
  1100. else
  1101. outgoingEvents = (VstEvents*) juce_realloc (outgoingEvents, size);
  1102. for (int i = outgoingEventSize; i < numEvents; ++i)
  1103. {
  1104. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  1105. e->type = kVstMidiType;
  1106. e->byteSize = 24;
  1107. outgoingEvents->events[i] = (VstEvent*) e;
  1108. }
  1109. outgoingEventSize = numEvents;
  1110. }
  1111. }
  1112. const String getHostName()
  1113. {
  1114. char host[256];
  1115. zeromem (host, sizeof (host));
  1116. getHostProductString (host);
  1117. return host;
  1118. }
  1119. #if JUCE_MAC
  1120. WindowRef hostWindow;
  1121. #elif JUCE_LINUX
  1122. Window hostWindow;
  1123. #else
  1124. HWND hostWindow;
  1125. #endif
  1126. };
  1127. //==============================================================================
  1128. void EditorCompWrapper::childBoundsChanged (Component* child)
  1129. {
  1130. child->setTopLeftPosition (0, 0);
  1131. const int cw = child->getWidth();
  1132. const int ch = child->getHeight();
  1133. wrapper->resizeHostWindow (cw, ch);
  1134. setSize (cw, ch);
  1135. #if JUCE_MAC
  1136. wrapper->resizeHostWindow (cw, ch); // (doing this a second time seems to be necessary in tracktion)
  1137. #endif
  1138. }
  1139. void EditorCompWrapper::handleAsyncUpdate()
  1140. {
  1141. wrapper->tryMasterIdle();
  1142. }
  1143. //==============================================================================
  1144. /** Somewhere in the codebase of your plugin, you need to implement this function
  1145. and make it create an instance of the filter subclass that you're building.
  1146. */
  1147. extern AudioProcessor* JUCE_CALLTYPE createPluginFilter();
  1148. //==============================================================================
  1149. static AEffect* pluginEntryPoint (audioMasterCallback audioMaster)
  1150. {
  1151. initialiseJuce_GUI();
  1152. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  1153. try
  1154. {
  1155. if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0)
  1156. {
  1157. AudioProcessor* const filter = createPluginFilter();
  1158. if (filter != 0)
  1159. {
  1160. JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter);
  1161. return wrapper->getAeffect();
  1162. }
  1163. }
  1164. }
  1165. catch (...)
  1166. {}
  1167. return 0;
  1168. }
  1169. //==============================================================================
  1170. // Mac startup code..
  1171. #if JUCE_MAC
  1172. extern "C" __attribute__ ((visibility("default"))) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1173. {
  1174. return pluginEntryPoint (audioMaster);
  1175. }
  1176. extern "C" __attribute__ ((visibility("default"))) AEffect* main_macho (audioMasterCallback audioMaster)
  1177. {
  1178. return pluginEntryPoint (audioMaster);
  1179. }
  1180. //==============================================================================
  1181. // Linux startup code..
  1182. #elif JUCE_LINUX
  1183. extern "C" AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1184. {
  1185. initialiseJuce_GUI();
  1186. SharedMessageThread::getInstance();
  1187. return pluginEntryPoint (audioMaster);
  1188. }
  1189. extern "C" AEffect* main_plugin (audioMasterCallback audioMaster) asm ("main");
  1190. extern "C" AEffect* main_plugin (audioMasterCallback audioMaster)
  1191. {
  1192. return VSTPluginMain (audioMaster);
  1193. }
  1194. __attribute__((constructor)) void myPluginInit()
  1195. {
  1196. // don't put initialiseJuce_GUI here... it will crash !
  1197. }
  1198. __attribute__((destructor)) void myPluginFini()
  1199. {
  1200. // don't put shutdownJuce_GUI here... it will crash !
  1201. }
  1202. //==============================================================================
  1203. // Win32 startup code..
  1204. #else
  1205. extern "C" __declspec (dllexport) AEffect* VSTPluginMain (audioMasterCallback audioMaster)
  1206. {
  1207. return pluginEntryPoint (audioMaster);
  1208. }
  1209. extern "C" __declspec (dllexport) void* main (audioMasterCallback audioMaster)
  1210. {
  1211. return (void*) pluginEntryPoint (audioMaster);
  1212. }
  1213. BOOL WINAPI DllMain (HINSTANCE instance, DWORD dwReason, LPVOID)
  1214. {
  1215. if (dwReason == DLL_PROCESS_ATTACH)
  1216. PlatformUtilities::setCurrentModuleInstanceHandle (instance);
  1217. return TRUE;
  1218. }
  1219. #endif