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.

1579 lines
46KB

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