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.

1512 lines
44KB

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