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.

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