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.

478 lines
19KB

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