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.

561 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: InterAppAudioEffectPlugin
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Inter-app audio effect plugin.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_plugin_client, juce_audio_processors,
  26. juce_audio_utils, juce_core, juce_data_structures,
  27. juce_events, juce_graphics, juce_gui_basics, juce_gui_extra
  28. exporters: xcode_iphone
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: AudioProcessor
  31. mainClass: IAAEffectProcessor
  32. useLocalCopy: 1
  33. extraPluginFormats: IAA
  34. END_JUCE_PIP_METADATA
  35. *******************************************************************************/
  36. #pragma once
  37. #include <array>
  38. //==============================================================================
  39. // A very simple decaying meter.
  40. class SimpleMeter : public Component,
  41. private Timer
  42. {
  43. public:
  44. SimpleMeter()
  45. {
  46. startTimerHz (30);
  47. }
  48. //==============================================================================
  49. void paint (Graphics& g) override
  50. {
  51. g.fillAll (Colours::transparentBlack);
  52. auto area = g.getClipBounds();
  53. g.setColour (getLookAndFeel().findColour (Slider::thumbColourId));
  54. g.fillRoundedRectangle (area.toFloat(), 6.0);
  55. auto unfilledHeight = area.getHeight() * (1.0 - level);
  56. g.reduceClipRegion (area.getX(), area.getY(),
  57. area.getWidth(), (int) unfilledHeight);
  58. g.setColour (getLookAndFeel().findColour (Slider::trackColourId));
  59. g.fillRoundedRectangle (area.toFloat(), 6.0);
  60. }
  61. void resized() override {}
  62. //==============================================================================
  63. // Called from the audio thread.
  64. void update (float newLevel)
  65. {
  66. // We don't care if maxLevel gets set to zero (in timerCallback) between the
  67. // load and the assignment.
  68. maxLevel = jmax (maxLevel.load(), newLevel);
  69. }
  70. private:
  71. //==============================================================================
  72. void timerCallback() override
  73. {
  74. auto callbackLevel = maxLevel.exchange (0.0);
  75. float decayFactor = 0.95f;
  76. if (callbackLevel > level)
  77. level = callbackLevel;
  78. else if (level > 0.001)
  79. level *= decayFactor;
  80. else
  81. level = 0;
  82. repaint();
  83. }
  84. std::atomic<float> maxLevel {0.0};
  85. float level = 0;
  86. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SimpleMeter)
  87. };
  88. #if JUCE_PROJUCER_LIVE_BUILD
  89. // Animate the meter in the Projucer live build.
  90. struct MockSimpleMeter : public Component,
  91. private Timer
  92. {
  93. MockSimpleMeter()
  94. {
  95. addAndMakeVisible (meter);
  96. resized();
  97. startTimerHz (100);
  98. }
  99. void paint (Graphics&) override {}
  100. void resized() override
  101. {
  102. meter.setBounds (getBounds());
  103. }
  104. void timerCallback() override
  105. {
  106. meter.update (std::pow (randomNumberGenerator.nextFloat(), 2));
  107. }
  108. SimpleMeter meter;
  109. Random randomNumberGenerator;
  110. };
  111. #endif
  112. //==============================================================================
  113. // A simple Inter-App Audio plug-in with a gain control and some meters.
  114. class IAAEffectProcessor : public AudioProcessor
  115. {
  116. public:
  117. IAAEffectProcessor()
  118. : AudioProcessor (BusesProperties()
  119. .withInput ("Input", AudioChannelSet::stereo(), true)
  120. .withOutput ("Output", AudioChannelSet::stereo(), true)),
  121. parameters (*this, nullptr, "InterAppAudioEffect",
  122. { std::make_unique<AudioParameterFloat> ("gain", "Gain", NormalisableRange<float> (0.0f, 1.0f), 1.0f / 3.14f) })
  123. {
  124. }
  125. //==============================================================================
  126. void prepareToPlay (double, int) override
  127. {
  128. previousGain = *parameters.getRawParameterValue ("gain");
  129. }
  130. void releaseResources() override {}
  131. bool isBusesLayoutSupported (const BusesLayout& layouts) const override
  132. {
  133. if (layouts.getMainInputChannels() > 2)
  134. return false;
  135. if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
  136. return false;
  137. return true;
  138. }
  139. void processBlock (AudioBuffer<float>& buffer, MidiBuffer&) override
  140. {
  141. float gain = *parameters.getRawParameterValue ("gain");
  142. auto totalNumInputChannels = getTotalNumInputChannels();
  143. auto totalNumOutputChannels = getTotalNumOutputChannels();
  144. auto numSamples = buffer.getNumSamples();
  145. for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
  146. buffer.clear (i, 0, buffer.getNumSamples());
  147. // Apply the gain to the samples using a ramp to avoid discontinuities in
  148. // the audio between processed buffers.
  149. for (auto channel = 0; channel < totalNumInputChannels; ++channel)
  150. {
  151. buffer.applyGainRamp (channel, 0, numSamples, previousGain, gain);
  152. auto newLevel = buffer.getMagnitude (channel, 0, numSamples);
  153. meterListeners.call ([=] (MeterListener& l) { l.handleNewMeterValue (channel, newLevel); });
  154. }
  155. previousGain = gain;
  156. // Now ask the host for the current time so we can store it to be displayed later.
  157. updateCurrentTimeInfoFromHost (lastPosInfo);
  158. }
  159. //==============================================================================
  160. AudioProcessorEditor* createEditor() override
  161. {
  162. return new IAAEffectEditor (*this, parameters);
  163. }
  164. bool hasEditor() const override { return true; }
  165. //==============================================================================
  166. const String getName() const override { return JucePlugin_Name; }
  167. bool acceptsMidi() const override { return false; }
  168. bool producesMidi() const override { return false; }
  169. double getTailLengthSeconds() const override { return 0.0; }
  170. //==============================================================================
  171. int getNumPrograms() override { return 1; }
  172. int getCurrentProgram() override { return 0; }
  173. void setCurrentProgram (int) override {}
  174. const String getProgramName (int) override { return {}; }
  175. void changeProgramName (int, const String&) override {}
  176. //==============================================================================
  177. void getStateInformation (MemoryBlock& destData) override
  178. {
  179. if (auto xml = parameters.state.createXml())
  180. copyXmlToBinary (*xml, destData);
  181. }
  182. void setStateInformation (const void* data, int sizeInBytes) override
  183. {
  184. if (auto xmlState = getXmlFromBinary (data, sizeInBytes))
  185. if (xmlState->hasTagName (parameters.state.getType()))
  186. parameters.state = ValueTree::fromXml (*xmlState);
  187. }
  188. //==============================================================================
  189. bool updateCurrentTimeInfoFromHost (AudioPlayHead::CurrentPositionInfo& posInfo)
  190. {
  191. if (auto* ph = getPlayHead())
  192. {
  193. AudioPlayHead::CurrentPositionInfo newTime;
  194. if (ph->getCurrentPosition (newTime))
  195. {
  196. posInfo = newTime; // Successfully got the current time from the host.
  197. return true;
  198. }
  199. }
  200. // If the host fails to provide the current time, we'll just reset our copy to a default.
  201. lastPosInfo.resetToDefault();
  202. return false;
  203. }
  204. // Allow an IAAAudioProcessorEditor to register as a listener to receive new
  205. // meter values directly from the audio thread.
  206. struct MeterListener
  207. {
  208. virtual ~MeterListener() {}
  209. virtual void handleNewMeterValue (int, float) = 0;
  210. };
  211. void addMeterListener (MeterListener& listener) { meterListeners.add (&listener); }
  212. void removeMeterListener (MeterListener& listener) { meterListeners.remove (&listener); }
  213. private:
  214. //==============================================================================
  215. class IAAEffectEditor : public AudioProcessorEditor,
  216. private IAAEffectProcessor::MeterListener,
  217. private Timer
  218. {
  219. public:
  220. IAAEffectEditor (IAAEffectProcessor& p,
  221. AudioProcessorValueTreeState& vts)
  222. : AudioProcessorEditor (p),
  223. iaaEffectProcessor (p),
  224. parameters (vts)
  225. {
  226. // Register for meter value updates.
  227. iaaEffectProcessor.addMeterListener (*this);
  228. gainSlider.setSliderStyle (Slider::SliderStyle::LinearVertical);
  229. gainSlider.setTextBoxStyle (Slider::TextEntryBoxPosition::TextBoxAbove, false, 60, 20);
  230. addAndMakeVisible (gainSlider);
  231. for (auto& meter : meters)
  232. addAndMakeVisible (meter);
  233. // Configure all the graphics for the transport control.
  234. transportText.setFont (Font (Font::getDefaultMonospacedFontName(), 18.0f, Font::plain));
  235. transportText.setJustificationType (Justification::topLeft);
  236. addChildComponent (transportText);
  237. Path rewindShape;
  238. rewindShape.addRectangle (0.0, 0.0, 5.0, buttonSize);
  239. rewindShape.addTriangle (0.0, buttonSize / 2, buttonSize, 0.0, buttonSize, buttonSize);
  240. rewindButton.setShape (rewindShape, true, true, false);
  241. rewindButton.onClick = [this]
  242. {
  243. if (transportControllable())
  244. iaaEffectProcessor.getPlayHead()->transportRewind();
  245. };
  246. addChildComponent (rewindButton);
  247. Path playShape;
  248. playShape.addTriangle (0.0, 0.0, 0.0, buttonSize, buttonSize, buttonSize / 2);
  249. playButton.setShape (playShape, true, true, false);
  250. playButton.onClick = [this]
  251. {
  252. if (transportControllable())
  253. iaaEffectProcessor.getPlayHead()->transportPlay (! lastPosInfo.isPlaying);
  254. };
  255. addChildComponent (playButton);
  256. Path recordShape;
  257. recordShape.addEllipse (0.0, 0.0, buttonSize, buttonSize);
  258. recordButton.setShape (recordShape, true, true, false);
  259. recordButton.onClick = [this]
  260. {
  261. if (transportControllable())
  262. iaaEffectProcessor.getPlayHead()->transportRecord (! lastPosInfo.isRecording);
  263. };
  264. addChildComponent (recordButton);
  265. // Configure the switch to host button.
  266. switchToHostButtonLabel.setFont (Font (Font::getDefaultMonospacedFontName(), 18.0f, Font::plain));
  267. switchToHostButtonLabel.setJustificationType (Justification::centredRight);
  268. switchToHostButtonLabel.setText ("Switch to\nhost app:", dontSendNotification);
  269. addChildComponent (switchToHostButtonLabel);
  270. switchToHostButton.onClick = [this]
  271. {
  272. if (transportControllable())
  273. {
  274. PluginHostType hostType;
  275. hostType.switchToHostApplication();
  276. }
  277. };
  278. addChildComponent (switchToHostButton);
  279. auto screenSize = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  280. setSize (screenSize.getWidth(), screenSize.getHeight());
  281. resized();
  282. startTimerHz (60);
  283. }
  284. ~IAAEffectEditor() override
  285. {
  286. iaaEffectProcessor.removeMeterListener (*this);
  287. }
  288. //==============================================================================
  289. void paint (Graphics& g) override
  290. {
  291. g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
  292. }
  293. void resized() override
  294. {
  295. auto area = getBounds().reduced (20);
  296. gainSlider.setBounds (area.removeFromLeft (60));
  297. for (auto& meter : meters)
  298. {
  299. area.removeFromLeft (10);
  300. meter.setBounds (area.removeFromLeft (20));
  301. }
  302. area.removeFromLeft (20);
  303. transportText.setBounds (area.removeFromTop (120));
  304. auto navigationArea = area.removeFromTop (buttonSize);
  305. rewindButton.setTopLeftPosition (navigationArea.getPosition());
  306. navigationArea.removeFromLeft (buttonSize + 10);
  307. playButton.setTopLeftPosition (navigationArea.getPosition());
  308. navigationArea.removeFromLeft (buttonSize + 10);
  309. recordButton.setTopLeftPosition (navigationArea.getPosition());
  310. area.removeFromTop (30);
  311. auto appSwitchArea = area.removeFromTop (buttonSize);
  312. switchToHostButtonLabel.setBounds (appSwitchArea.removeFromLeft (100));
  313. appSwitchArea.removeFromLeft (5);
  314. switchToHostButton.setBounds (appSwitchArea.removeFromLeft (buttonSize));
  315. }
  316. private:
  317. //==============================================================================
  318. // Called from the audio thread.
  319. void handleNewMeterValue (int channel, float value) override
  320. {
  321. meters[(size_t) channel].update (value);
  322. }
  323. //==============================================================================
  324. void timerCallback () override
  325. {
  326. auto timeInfoSuccess = iaaEffectProcessor.updateCurrentTimeInfoFromHost (lastPosInfo);
  327. transportText.setVisible (timeInfoSuccess);
  328. if (timeInfoSuccess)
  329. updateTransportTextDisplay();
  330. updateTransportButtonsDisplay();
  331. updateSwitchToHostDisplay();
  332. }
  333. //==============================================================================
  334. bool transportControllable()
  335. {
  336. auto playHead = iaaEffectProcessor.getPlayHead();
  337. return playHead != nullptr && playHead->canControlTransport();
  338. }
  339. //==============================================================================
  340. // quick-and-dirty function to format a timecode string
  341. String timeToTimecodeString (double seconds)
  342. {
  343. auto millisecs = roundToInt (seconds * 1000.0);
  344. auto absMillisecs = std::abs (millisecs);
  345. return String::formatted ("%02d:%02d:%02d.%03d",
  346. millisecs / 360000,
  347. (absMillisecs / 60000) % 60,
  348. (absMillisecs / 1000) % 60,
  349. absMillisecs % 1000);
  350. }
  351. // A quick-and-dirty function to format a bars/beats string.
  352. String quarterNotePositionToBarsBeatsString (double quarterNotes, int numerator, int denominator)
  353. {
  354. if (numerator == 0 || denominator == 0)
  355. return "1|1|000";
  356. auto quarterNotesPerBar = (numerator * 4 / denominator);
  357. auto beats = (fmod (quarterNotes, quarterNotesPerBar) / quarterNotesPerBar) * numerator;
  358. auto bar = ((int) quarterNotes) / quarterNotesPerBar + 1;
  359. auto beat = ((int) beats) + 1;
  360. auto ticks = ((int) (fmod (beats, 1.0) * 960.0 + 0.5));
  361. return String::formatted ("%d|%d|%03d", bar, beat, ticks);
  362. }
  363. void updateTransportTextDisplay()
  364. {
  365. MemoryOutputStream displayText;
  366. displayText << "[" << SystemStats::getJUCEVersion() << "]\n"
  367. << String (lastPosInfo.bpm, 2) << " bpm\n"
  368. << lastPosInfo.timeSigNumerator << '/' << lastPosInfo.timeSigDenominator << "\n"
  369. << timeToTimecodeString (lastPosInfo.timeInSeconds) << "\n"
  370. << quarterNotePositionToBarsBeatsString (lastPosInfo.ppqPosition,
  371. lastPosInfo.timeSigNumerator,
  372. lastPosInfo.timeSigDenominator) << "\n";
  373. if (lastPosInfo.isRecording)
  374. displayText << "(recording)";
  375. else if (lastPosInfo.isPlaying)
  376. displayText << "(playing)";
  377. transportText.setText (displayText.toString(), dontSendNotification);
  378. }
  379. void updateTransportButtonsDisplay()
  380. {
  381. auto visible = iaaEffectProcessor.getPlayHead() != nullptr
  382. && iaaEffectProcessor.getPlayHead()->canControlTransport();
  383. if (rewindButton.isVisible() != visible)
  384. {
  385. rewindButton.setVisible (visible);
  386. playButton.setVisible (visible);
  387. recordButton.setVisible (visible);
  388. }
  389. if (visible)
  390. {
  391. auto playColour = lastPosInfo.isPlaying ? Colours::green : defaultButtonColour;
  392. playButton.setColours (playColour, playColour, playColour);
  393. playButton.repaint();
  394. auto recordColour = lastPosInfo.isRecording ? Colours::red : defaultButtonColour;
  395. recordButton.setColours (recordColour, recordColour, recordColour);
  396. recordButton.repaint();
  397. }
  398. }
  399. void updateSwitchToHostDisplay()
  400. {
  401. PluginHostType hostType;
  402. auto visible = hostType.isInterAppAudioConnected();
  403. if (switchToHostButtonLabel.isVisible() != visible)
  404. {
  405. switchToHostButtonLabel.setVisible (visible);
  406. switchToHostButton.setVisible (visible);
  407. if (visible)
  408. {
  409. auto icon = hostType.getHostIcon (buttonSize);
  410. switchToHostButton.setImages(false, true, true,
  411. icon, 1.0, Colours::transparentBlack,
  412. icon, 1.0, Colours::transparentBlack,
  413. icon, 1.0, Colours::transparentBlack);
  414. }
  415. }
  416. }
  417. IAAEffectProcessor& iaaEffectProcessor;
  418. AudioProcessorValueTreeState& parameters;
  419. const int buttonSize = 30;
  420. const Colour defaultButtonColour = Colours::darkgrey;
  421. ShapeButton rewindButton {"Rewind", defaultButtonColour, defaultButtonColour, defaultButtonColour};
  422. ShapeButton playButton {"Play", defaultButtonColour, defaultButtonColour, defaultButtonColour};
  423. ShapeButton recordButton {"Record", defaultButtonColour, defaultButtonColour, defaultButtonColour};
  424. Slider gainSlider;
  425. AudioProcessorValueTreeState::SliderAttachment gainAttachment = { parameters, "gain", gainSlider };
  426. std::array<SimpleMeter, 2> meters;
  427. ImageButton switchToHostButton;
  428. Label transportText, switchToHostButtonLabel;
  429. AudioPlayHead::CurrentPositionInfo lastPosInfo;
  430. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IAAEffectEditor)
  431. };
  432. //==============================================================================
  433. AudioProcessorValueTreeState parameters;
  434. float previousGain = 0.0f;
  435. // This keeps a copy of the last set of timing info that was acquired during an
  436. // audio callback - the UI component will display this.
  437. AudioPlayHead::CurrentPositionInfo lastPosInfo;
  438. ListenerList<MeterListener> meterListeners;
  439. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IAAEffectProcessor)
  440. };