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.

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