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.

1496 lines
43KB

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