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.

559 lines
21KB

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