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.

467 lines
18KB

  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: AUv3SynthPlugin
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: AUv3 synthesiser audio 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_mac, xcode_iphone
  29. type: AudioProcessor
  30. mainClass: AUv3SynthProcessor
  31. useLocalCopy: 1
  32. END_JUCE_PIP_METADATA
  33. *******************************************************************************/
  34. #pragma once
  35. #include "../Assets/DemoUtilities.h"
  36. //==============================================================================
  37. class MaterialLookAndFeel : public LookAndFeel_V4
  38. {
  39. public:
  40. //==============================================================================
  41. MaterialLookAndFeel()
  42. {
  43. setColour (ResizableWindow::backgroundColourId, windowBackgroundColour);
  44. setColour (TextButton::buttonOnColourId, brightButtonColour);
  45. setColour (TextButton::buttonColourId, disabledButtonColour);
  46. }
  47. //==============================================================================
  48. void drawButtonBackground (Graphics& g,
  49. Button& button,
  50. const Colour& /*backgroundColour*/,
  51. bool /*isMouseOverButton*/,
  52. bool isButtonDown) override
  53. {
  54. auto buttonRect = button.getLocalBounds().toFloat();
  55. if (isButtonDown)
  56. g.setColour (brightButtonColour.withAlpha (0.7f));
  57. else if (! button.isEnabled())
  58. g.setColour (disabledButtonColour);
  59. else
  60. g.setColour (brightButtonColour);
  61. g.fillRoundedRectangle (buttonRect, 5.0f);
  62. }
  63. //==============================================================================
  64. void drawButtonText (Graphics& g, TextButton& button, bool isMouseOverButton, bool isButtonDown) override
  65. {
  66. ignoreUnused (isMouseOverButton, isButtonDown);
  67. Font font (getTextButtonFont (button, button.getHeight()));
  68. g.setFont (font);
  69. if (button.isEnabled())
  70. g.setColour (Colours::white);
  71. else
  72. g.setColour (backgroundColour);
  73. g.drawFittedText (button.getButtonText(), 0, 0,
  74. button.getWidth(),
  75. button.getHeight(),
  76. Justification::centred, 2);
  77. }
  78. //==============================================================================
  79. void drawLinearSlider (Graphics& g, int x, int y, int width, int height,
  80. float sliderPos, float minSliderPos, float maxSliderPos,
  81. const Slider::SliderStyle style, Slider& slider) override
  82. {
  83. ignoreUnused (style, minSliderPos, maxSliderPos);
  84. auto r = Rectangle<int> (x + haloRadius, y, width - (haloRadius * 2), height);
  85. auto backgroundBar = r.withSizeKeepingCentre(r.getWidth(), 2);
  86. sliderPos = (sliderPos - minSliderPos) / static_cast<float> (width);
  87. auto knobPos = static_cast<int> (sliderPos * r.getWidth());
  88. g.setColour (sliderActivePart);
  89. g.fillRect (backgroundBar.removeFromLeft (knobPos));
  90. g.setColour (sliderInactivePart);
  91. g.fillRect (backgroundBar);
  92. if (slider.isMouseOverOrDragging())
  93. {
  94. auto haloBounds = r.withTrimmedLeft (knobPos - haloRadius)
  95. .withWidth (haloRadius * 2)
  96. .withSizeKeepingCentre (haloRadius * 2, haloRadius * 2);
  97. g.setColour (sliderActivePart.withAlpha (0.5f));
  98. g.fillEllipse (haloBounds.toFloat());
  99. }
  100. auto knobRadius = slider.isMouseOverOrDragging() ? knobActiveRadius : knobInActiveRadius;
  101. auto knobBounds = r.withTrimmedLeft (knobPos - knobRadius)
  102. .withWidth (knobRadius * 2)
  103. .withSizeKeepingCentre (knobRadius * 2, knobRadius * 2);
  104. g.setColour (sliderActivePart);
  105. g.fillEllipse (knobBounds.toFloat());
  106. }
  107. //==============================================================================
  108. Font getTextButtonFont (TextButton& button, int buttonHeight) override
  109. {
  110. return LookAndFeel_V3::getTextButtonFont (button, buttonHeight).withHeight (buttonFontSize);
  111. }
  112. Font getLabelFont (Label& label) override
  113. {
  114. return LookAndFeel_V3::getLabelFont (label).withHeight (labelFontSize);
  115. }
  116. //==============================================================================
  117. enum
  118. {
  119. labelFontSize = 12,
  120. buttonFontSize = 15
  121. };
  122. //==============================================================================
  123. enum
  124. {
  125. knobActiveRadius = 12,
  126. knobInActiveRadius = 8,
  127. haloRadius = 18
  128. };
  129. //==============================================================================
  130. const Colour windowBackgroundColour = Colour (0xff262328);
  131. const Colour backgroundColour = Colour (0xff4d4d4d);
  132. const Colour brightButtonColour = Colour (0xff80cbc4);
  133. const Colour disabledButtonColour = Colour (0xffe4e4e4);
  134. const Colour sliderInactivePart = Colour (0xff545d62);
  135. const Colour sliderActivePart = Colour (0xff80cbc4);
  136. };
  137. //==============================================================================
  138. class AUv3SynthEditor : public AudioProcessorEditor,
  139. private Timer
  140. {
  141. public:
  142. //==============================================================================
  143. AUv3SynthEditor (AudioProcessor& processor)
  144. : AudioProcessorEditor (processor),
  145. roomSizeSlider (Slider::LinearHorizontal, Slider::NoTextBox)
  146. {
  147. LookAndFeel::setDefaultLookAndFeel (&materialLookAndFeel);
  148. roomSizeSlider.setValue (getParameterValue ("roomSize"), NotificationType::dontSendNotification);
  149. recordButton.onClick = [this] { startRecording(); };
  150. addAndMakeVisible (recordButton);
  151. roomSizeSlider.onValueChange = [this] { setParameterValue ("roomSize", roomSizeSlider.getValue()); };
  152. roomSizeSlider.setRange (0.0, 1.0);
  153. addAndMakeVisible (roomSizeSlider);
  154. if (auto* assetStream = createAssetInputStream ("proaudio.path"))
  155. {
  156. std::unique_ptr<InputStream> fileStream (assetStream);
  157. Path proAudioPath;
  158. proAudioPath.loadPathFromStream (*fileStream);
  159. proAudioIcon.setPath (proAudioPath);
  160. addAndMakeVisible (proAudioIcon);
  161. auto proAudioIconColour = findColour (TextButton::buttonOnColourId);
  162. proAudioIcon.setFill (FillType (proAudioIconColour));
  163. }
  164. setSize (600, 400);
  165. startTimer (100);
  166. }
  167. //==============================================================================
  168. void paint (Graphics& g) override
  169. {
  170. g.fillAll (findColour (ResizableWindow::backgroundColourId));
  171. }
  172. void resized() override
  173. {
  174. auto r = getLocalBounds();
  175. auto guiElementAreaHeight = r.getHeight() / 3;
  176. proAudioIcon.setTransformToFit (r.removeFromLeft (proportionOfWidth (0.25))
  177. .withSizeKeepingCentre (guiElementAreaHeight, guiElementAreaHeight)
  178. .toFloat(),
  179. RectanglePlacement::fillDestination);
  180. auto margin = guiElementAreaHeight / 4;
  181. r.reduce (margin, margin);
  182. auto buttonHeight = guiElementAreaHeight - margin;
  183. recordButton .setBounds (r.removeFromTop (guiElementAreaHeight).withSizeKeepingCentre (r.getWidth(), buttonHeight));
  184. roomSizeSlider.setBounds (r.removeFromTop (guiElementAreaHeight).withSizeKeepingCentre (r.getWidth(), buttonHeight));
  185. }
  186. //==============================================================================
  187. void startRecording()
  188. {
  189. recordButton.setEnabled (false);
  190. setParameterValue ("isRecording", 1.0f);
  191. }
  192. private:
  193. //==============================================================================
  194. void timerCallback() override
  195. {
  196. auto isRecordingNow = (getParameterValue ("isRecording") >= 0.5f);
  197. recordButton.setEnabled (! isRecordingNow);
  198. roomSizeSlider.setValue (getParameterValue ("roomSize"), NotificationType::dontSendNotification);
  199. }
  200. //==============================================================================
  201. AudioProcessorParameter* getParameter (const String& paramId)
  202. {
  203. if (auto* processor = getAudioProcessor())
  204. {
  205. const OwnedArray<AudioProcessorParameter>& params = processor->getParameters();
  206. for (auto p : params)
  207. {
  208. if (auto* param = dynamic_cast<AudioProcessorParameterWithID*> (p))
  209. {
  210. if (param->paramID == paramId)
  211. return param;
  212. }
  213. }
  214. }
  215. return nullptr;
  216. }
  217. //==============================================================================
  218. float getParameterValue (const String& paramId)
  219. {
  220. if (auto* param = getParameter (paramId))
  221. return param->getValue();
  222. return 0.0f;
  223. }
  224. void setParameterValue (const String& paramId, float value)
  225. {
  226. if (auto* param = getParameter (paramId))
  227. param->setValueNotifyingHost (value);
  228. }
  229. //==============================================================================
  230. MaterialLookAndFeel materialLookAndFeel;
  231. //==============================================================================
  232. TextButton recordButton { "Record" };
  233. Slider roomSizeSlider;
  234. DrawablePath proAudioIcon;
  235. //==============================================================================
  236. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AUv3SynthEditor)
  237. };
  238. //==============================================================================
  239. class AUv3SynthProcessor : public AudioProcessor
  240. {
  241. public:
  242. AUv3SynthProcessor ()
  243. : AudioProcessor (BusesProperties().withOutput ("Output", AudioChannelSet::stereo(), true)),
  244. currentRecording (1, 1), currentProgram (0)
  245. {
  246. // initialize parameters
  247. addParameter (isRecordingParam = new AudioParameterBool ("isRecording", "Is Recording", false));
  248. addParameter (roomSizeParam = new AudioParameterFloat ("roomSize", "Room Size", 0.0f, 1.0f, 0.5f));
  249. formatManager.registerBasicFormats();
  250. for (auto i = 0; i < maxNumVoices; ++i)
  251. synth.addVoice (new SamplerVoice());
  252. loadNewSample (createAssetInputStream ("singing.ogg"), "ogg");
  253. }
  254. //==============================================================================
  255. bool isBusesLayoutSupported (const BusesLayout& layouts) const override
  256. {
  257. return (layouts.getMainOutputChannels() <= 2);
  258. }
  259. void prepareToPlay (double sampleRate, int estimatedMaxSizeOfBuffer) override
  260. {
  261. ignoreUnused (estimatedMaxSizeOfBuffer);
  262. lastSampleRate = sampleRate;
  263. currentRecording.setSize (1, static_cast<int> (std::ceil (maxDurationOfRecording * lastSampleRate)));
  264. samplesRecorded = 0;
  265. synth.setCurrentPlaybackSampleRate (lastSampleRate);
  266. reverb.setSampleRate (lastSampleRate);
  267. }
  268. void processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiMessages) override
  269. {
  270. Reverb::Parameters reverbParameters;
  271. reverbParameters.roomSize = roomSizeParam->get();
  272. reverb.setParameters (reverbParameters);
  273. synth.renderNextBlock (buffer, midiMessages, 0, buffer.getNumSamples());
  274. if (getMainBusNumOutputChannels() == 1)
  275. reverb.processMono (buffer.getWritePointer (0), buffer.getNumSamples());
  276. else if (getMainBusNumOutputChannels() == 2)
  277. reverb.processStereo (buffer.getWritePointer (0), buffer.getWritePointer (1), buffer.getNumSamples());
  278. }
  279. //==============================================================================
  280. void releaseResources() override { currentRecording.setSize (1, 1); }
  281. //==============================================================================
  282. bool acceptsMidi() const override { return true; }
  283. bool producesMidi() const override { return false; }
  284. bool silenceInProducesSilenceOut() const override { return false; }
  285. double getTailLengthSeconds() const override { return 0.0; }
  286. //==============================================================================
  287. AudioProcessorEditor* createEditor() override { return new AUv3SynthEditor (*this); }
  288. bool hasEditor() const override { return true; }
  289. //==============================================================================
  290. const String getName() const override { return "AUv3 Synth"; }
  291. int getNumPrograms() override { return 4; }
  292. int getCurrentProgram() override { return currentProgram; }
  293. void setCurrentProgram (int index) override { currentProgram = index; }
  294. const String getProgramName (int index) override
  295. {
  296. switch (index)
  297. {
  298. case 0: return "Piano";
  299. case 1: return "Singing";
  300. case 2: return "Pinched Balloon";
  301. case 3: return "Gazeebo";
  302. }
  303. return "<Unknown>";
  304. }
  305. //==============================================================================
  306. void changeProgramName (int /*index*/, const String& /*name*/) override {}
  307. //==============================================================================
  308. void getStateInformation (MemoryBlock& destData) override
  309. {
  310. MemoryOutputStream stream (destData, true);
  311. stream.writeFloat (*isRecordingParam);
  312. stream.writeFloat (*roomSizeParam);
  313. }
  314. void setStateInformation (const void* data, int sizeInBytes) override
  315. {
  316. MemoryInputStream stream (data, static_cast<size_t> (sizeInBytes), false);
  317. isRecordingParam->setValueNotifyingHost (stream.readFloat());
  318. roomSizeParam->setValueNotifyingHost (stream.readFloat());
  319. }
  320. private:
  321. //==============================================================================
  322. void loadNewSampleBinary (const void* data, int dataSize, const char* format)
  323. {
  324. auto* soundBuffer = new MemoryInputStream (data, static_cast<std::size_t> (dataSize), false);
  325. loadNewSample (soundBuffer, format);
  326. }
  327. void loadNewSample (InputStream* soundBuffer, const char* format)
  328. {
  329. std::unique_ptr<AudioFormatReader> formatReader (formatManager.findFormatForFileExtension (format)->createReaderFor (soundBuffer, true));
  330. BigInteger midiNotes;
  331. midiNotes.setRange (0, 126, true);
  332. SynthesiserSound::Ptr newSound = new SamplerSound ("Voice", *formatReader, midiNotes, 0x40, 0.0, 0.0, 10.0);
  333. synth.removeSound (0);
  334. sound = newSound;
  335. synth.addSound (sound);
  336. }
  337. void swapSamples()
  338. {
  339. MemoryBlock mb;
  340. auto* stream = new MemoryOutputStream (mb, true);
  341. {
  342. std::unique_ptr<AudioFormatWriter> writer (formatManager.findFormatForFileExtension ("wav")->createWriterFor (stream, lastSampleRate, 1, 16,
  343. StringPairArray(), 0));
  344. writer->writeFromAudioSampleBuffer (currentRecording, 0, currentRecording.getNumSamples());
  345. writer->flush();
  346. stream->flush();
  347. }
  348. loadNewSampleBinary (mb.getData(), static_cast<int> (mb.getSize()), "wav");
  349. }
  350. //==============================================================================
  351. static constexpr int maxNumVoices = 5;
  352. static constexpr double maxDurationOfRecording = 1.0;
  353. //==============================================================================
  354. AudioFormatManager formatManager;
  355. int samplesRecorded;
  356. double lastSampleRate;
  357. AudioBuffer<float> currentRecording;
  358. Reverb reverb;
  359. Synthesiser synth;
  360. SynthesiserSound::Ptr sound;
  361. AudioParameterBool* isRecordingParam;
  362. AudioParameterFloat* roomSizeParam;
  363. int currentProgram;
  364. //==============================================================================
  365. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AUv3SynthProcessor)
  366. };