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.

568 lines
25KB

  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: DSPModulePluginDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Audio plugin using the DSP module.
  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, juce_dsp,
  27. juce_events, juce_graphics, juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2017
  29. type: AudioProcessor
  30. mainClass: DspModulePluginDemoAudioProcessor
  31. useLocalCopy: 1
  32. END_JUCE_PIP_METADATA
  33. *******************************************************************************/
  34. #pragma once
  35. #include "../Assets/DemoUtilities.h"
  36. //==============================================================================
  37. struct ParameterSlider : public Slider,
  38. public Timer
  39. {
  40. ParameterSlider (AudioProcessorParameter& p)
  41. : Slider (p.getName (256)), param (p)
  42. {
  43. setRange (0.0, 1.0, 0.0);
  44. startTimerHz (30);
  45. updateSliderPos();
  46. }
  47. void valueChanged() override
  48. {
  49. if (isMouseButtonDown())
  50. param.setValueNotifyingHost ((float) Slider::getValue());
  51. else
  52. param.setValue ((float) Slider::getValue());
  53. }
  54. void timerCallback() override { updateSliderPos(); }
  55. void startedDragging() override { param.beginChangeGesture(); }
  56. void stoppedDragging() override { param.endChangeGesture(); }
  57. double getValueFromText (const String& text) override { return param.getValueForText (text); }
  58. String getTextFromValue (double value) override { return param.getText ((float) value, 1024) + " " + param.getLabel(); }
  59. void updateSliderPos()
  60. {
  61. auto newValue = param.getValue();
  62. if (newValue != (float) Slider::getValue() && ! isMouseButtonDown())
  63. Slider::setValue (newValue);
  64. }
  65. AudioProcessorParameter& param;
  66. };
  67. //==============================================================================
  68. /**
  69. This class handles the audio processing for the DSP module plugin demo.
  70. */
  71. class DspModulePluginDemoAudioProcessor : public AudioProcessor
  72. {
  73. public:
  74. //==============================================================================
  75. DspModulePluginDemoAudioProcessor()
  76. : AudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::stereo(), true)
  77. .withOutput ("Output", AudioChannelSet::stereo(), true)),
  78. lowPassFilter (dsp::IIR::Coefficients<float>::makeFirstOrderLowPass (48000.0, 20000.0f)),
  79. highPassFilter (dsp::IIR::Coefficients<float>::makeFirstOrderHighPass (48000.0, 20.0f)),
  80. waveShapers { { std::tanh }, { dsp::FastMathApproximations::tanh } },
  81. clipping { clip }
  82. {
  83. // Oversampling 2 times with IIR filtering
  84. oversampling.reset (new dsp::Oversampling<float> (2, 1, dsp::Oversampling<float>::filterHalfBandPolyphaseIIR, false));
  85. addParameter (inputVolumeParam = new AudioParameterFloat ("INPUT", "Input Volume", { 0.0f, 60.0f, 0.0f, 1.0f }, 0.0f, "dB"));
  86. addParameter (highPassFilterFreqParam = new AudioParameterFloat ("HPFREQ", "Pre Highpass Freq.", { 20.0f, 20000.0f, 0.0f, 0.5f }, 20.0f, "Hz"));
  87. addParameter (lowPassFilterFreqParam = new AudioParameterFloat ("LPFREQ", "Post Lowpass Freq.", { 20.0f, 20000.0f, 0.0f, 0.5f }, 20000.0f, "Hz"));
  88. addParameter (stereoParam = new AudioParameterChoice ("STEREO", "Stereo Processing", { "Always mono", "Yes" }, 1));
  89. addParameter (slopeParam = new AudioParameterChoice ("SLOPE", "Slope", { "-6 dB / octave", "-12 dB / octave" }, 0));
  90. addParameter (waveshaperParam = new AudioParameterChoice ("WVSHP", "Waveshaper", { "std::tanh", "Fast tanh approx." }, 0));
  91. addParameter (cabinetTypeParam = new AudioParameterChoice ("CABTYPE", "Cabinet Type", { "Guitar amplifier 8'' cabinet ",
  92. "Cassette recorder cabinet" }, 0));
  93. addParameter (cabinetSimParam = new AudioParameterBool ("CABSIM", "Cabinet Sim", false));
  94. addParameter (oversamplingParam = new AudioParameterBool ("OVERS", "Oversampling", false));
  95. addParameter (outputVolumeParam = new AudioParameterFloat ("OUTPUT", "Output Volume", { -40.0f, 40.0f, 0.0f, 1.0f }, 0.0f, "dB"));
  96. cabinetType.set (0);
  97. }
  98. ~DspModulePluginDemoAudioProcessor() {}
  99. //==============================================================================
  100. bool isBusesLayoutSupported (const BusesLayout& layouts) const override
  101. {
  102. // This is the place where you check if the layout is supported.
  103. // In this template code we only support mono or stereo.
  104. if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono() && layouts.getMainOutputChannelSet() != AudioChannelSet::stereo())
  105. return false;
  106. // This checks if the input layout matches the output layout
  107. if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
  108. return false;
  109. return true;
  110. }
  111. void prepareToPlay (double sampleRate, int samplesPerBlock) override
  112. {
  113. auto channels = static_cast<uint32> (jmin (getMainBusNumInputChannels(), getMainBusNumOutputChannels()));
  114. dsp::ProcessSpec spec { sampleRate, static_cast<uint32> (samplesPerBlock), channels };
  115. lowPassFilter .prepare (spec);
  116. highPassFilter.prepare (spec);
  117. inputVolume .prepare (spec);
  118. outputVolume.prepare (spec);
  119. convolution.prepare (spec);
  120. cabinetType.set (-1);
  121. oversampling->initProcessing (static_cast<size_t> (samplesPerBlock));
  122. updateParameters();
  123. reset();
  124. }
  125. void releaseResources() override {}
  126. void processBlock (AudioBuffer<float>& inoutBuffer, MidiBuffer&) override
  127. {
  128. auto totalNumInputChannels = getTotalNumInputChannels();
  129. auto totalNumOutputChannels = getTotalNumOutputChannels();
  130. auto numSamples = inoutBuffer.getNumSamples();
  131. for (auto i = jmin (2, totalNumInputChannels); i < totalNumOutputChannels; ++i)
  132. inoutBuffer.clear (i, 0, numSamples);
  133. updateParameters();
  134. dsp::AudioBlock<float> block (inoutBuffer);
  135. if (stereoParam->getIndex() == 1)
  136. {
  137. // Stereo processing mode:
  138. if (block.getNumChannels() > 2)
  139. block = block.getSubsetChannelBlock (0, 2);
  140. process (dsp::ProcessContextReplacing<float> (block));
  141. }
  142. else
  143. {
  144. // Mono processing mode:
  145. auto firstChan = block.getSingleChannelBlock (0);
  146. process (dsp::ProcessContextReplacing<float> (firstChan));
  147. for (size_t chan = 1; chan < block.getNumChannels(); ++chan)
  148. block.getSingleChannelBlock (chan).copy (firstChan);
  149. }
  150. }
  151. void reset() override
  152. {
  153. lowPassFilter .reset();
  154. highPassFilter.reset();
  155. convolution .reset();
  156. oversampling->reset();
  157. }
  158. //==============================================================================
  159. bool hasEditor() const override { return true; }
  160. AudioProcessorEditor* createEditor() override
  161. {
  162. return new DspModulePluginDemoAudioProcessorEditor (*this);
  163. }
  164. //==============================================================================
  165. bool acceptsMidi() const override { return false; }
  166. bool producesMidi() const override { return false; }
  167. const String getName() const override { return JucePlugin_Name; }
  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&) override {}
  177. void setStateInformation (const void*, int) override {}
  178. //==============================================================================
  179. void updateParameters()
  180. {
  181. auto newOversampling = oversamplingParam->get();
  182. if (newOversampling != audioCurrentlyOversampled)
  183. {
  184. audioCurrentlyOversampled = newOversampling;
  185. oversampling->reset();
  186. }
  187. //==============================================================================
  188. auto inputdB = Decibels::decibelsToGain (inputVolumeParam->get());
  189. auto outputdB = Decibels::decibelsToGain (outputVolumeParam->get());
  190. if (inputVolume .getGainLinear() != inputdB) inputVolume.setGainLinear (inputdB);
  191. if (outputVolume.getGainLinear() != outputdB) outputVolume.setGainLinear (outputdB);
  192. auto newSlopeType = slopeParam->getIndex();
  193. if (newSlopeType == 0)
  194. {
  195. *lowPassFilter .state = *dsp::IIR::Coefficients<float>::makeFirstOrderLowPass (getSampleRate(), lowPassFilterFreqParam->get());
  196. *highPassFilter.state = *dsp::IIR::Coefficients<float>::makeFirstOrderHighPass (getSampleRate(), highPassFilterFreqParam->get());
  197. }
  198. else
  199. {
  200. *lowPassFilter .state = *dsp::IIR::Coefficients<float>::makeLowPass (getSampleRate(), lowPassFilterFreqParam->get());
  201. *highPassFilter.state = *dsp::IIR::Coefficients<float>::makeHighPass (getSampleRate(), highPassFilterFreqParam->get());
  202. }
  203. //==============================================================================
  204. auto type = cabinetTypeParam->getIndex();
  205. auto currentType = cabinetType.get();
  206. if (type != currentType)
  207. {
  208. cabinetType.set (type);
  209. auto maxSize = static_cast<size_t> (roundToInt (getSampleRate() * (8192.0 / 44100.0)));
  210. auto assetName = (type == 0 ? "Impulse1.wav" : "Impulse2.wav");
  211. std::unique_ptr<InputStream> assetInputStream (createAssetInputStream (assetName));
  212. if (assetInputStream != nullptr)
  213. {
  214. currentCabinetData.reset();
  215. assetInputStream->readIntoMemoryBlock (currentCabinetData);
  216. convolution.loadImpulseResponse (currentCabinetData.getData(), currentCabinetData.getSize(),
  217. false, true, maxSize);
  218. }
  219. }
  220. cabinetIsBypassed = ! cabinetSimParam->get();
  221. }
  222. static inline float clip (float x) { return jmax (-1.0f, jmin (1.0f, x)); }
  223. //==============================================================================
  224. AudioParameterFloat* inputVolumeParam;
  225. AudioParameterFloat* outputVolumeParam;
  226. AudioParameterFloat* lowPassFilterFreqParam;
  227. AudioParameterFloat* highPassFilterFreqParam;
  228. AudioParameterChoice* stereoParam;
  229. AudioParameterChoice* slopeParam;
  230. AudioParameterChoice* waveshaperParam;
  231. AudioParameterChoice* cabinetTypeParam;
  232. AudioParameterBool* cabinetSimParam;
  233. AudioParameterBool* oversamplingParam;
  234. private:
  235. //==============================================================================
  236. /**
  237. This is the editor component that will be displayed.
  238. */
  239. class DspModulePluginDemoAudioProcessorEditor : public AudioProcessorEditor
  240. {
  241. public:
  242. //==============================================================================
  243. DspModulePluginDemoAudioProcessorEditor (DspModulePluginDemoAudioProcessor& p)
  244. : AudioProcessorEditor (&p),
  245. processor (p),
  246. inputVolumeLabel ({}, processor.inputVolumeParam->name),
  247. outputVolumeLabel ({}, processor.outputVolumeParam->name),
  248. lowPassFilterFreqLabel ({}, processor.lowPassFilterFreqParam->name),
  249. highPassFilterFreqLabel ({}, processor.highPassFilterFreqParam->name),
  250. stereoLabel ({}, processor.stereoParam->name),
  251. slopeLabel ({}, processor.slopeParam->name),
  252. waveshaperLabel ({}, processor.waveshaperParam->name),
  253. cabinetTypeLabel ({}, processor.cabinetTypeParam->name)
  254. {
  255. //==============================================================================
  256. inputVolumeSlider .reset (new ParameterSlider (*processor.inputVolumeParam));
  257. outputVolumeSlider .reset (new ParameterSlider (*processor.outputVolumeParam));
  258. lowPassFilterFreqSlider .reset (new ParameterSlider (*processor.lowPassFilterFreqParam));
  259. highPassFilterFreqSlider.reset (new ParameterSlider (*processor.highPassFilterFreqParam));
  260. addAndMakeVisible (inputVolumeSlider .get());
  261. addAndMakeVisible (outputVolumeSlider .get());
  262. addAndMakeVisible (lowPassFilterFreqSlider .get());
  263. addAndMakeVisible (highPassFilterFreqSlider.get());
  264. addAndMakeVisible (inputVolumeLabel);
  265. inputVolumeLabel.setJustificationType (Justification::centredLeft);
  266. inputVolumeLabel.attachToComponent (inputVolumeSlider.get(), true);
  267. addAndMakeVisible (outputVolumeLabel);
  268. outputVolumeLabel.setJustificationType (Justification::centredLeft);
  269. outputVolumeLabel.attachToComponent (outputVolumeSlider.get(), true);
  270. addAndMakeVisible (lowPassFilterFreqLabel);
  271. lowPassFilterFreqLabel.setJustificationType (Justification::centredLeft);
  272. lowPassFilterFreqLabel.attachToComponent (lowPassFilterFreqSlider.get(), true);
  273. addAndMakeVisible (highPassFilterFreqLabel);
  274. highPassFilterFreqLabel.setJustificationType (Justification::centredLeft);
  275. highPassFilterFreqLabel.attachToComponent (highPassFilterFreqSlider.get(), true);
  276. //==============================================================================
  277. addAndMakeVisible (stereoBox);
  278. auto i = 1;
  279. for (auto choice : processor.stereoParam->choices)
  280. stereoBox.addItem (choice, i++);
  281. stereoBox.onChange = [this] { processor.stereoParam->operator= (stereoBox.getSelectedItemIndex()); };
  282. stereoBox.setSelectedId (processor.stereoParam->getIndex() + 1);
  283. addAndMakeVisible (stereoLabel);
  284. stereoLabel.setJustificationType (Justification::centredLeft);
  285. stereoLabel.attachToComponent (&stereoBox, true);
  286. //==============================================================================
  287. addAndMakeVisible(slopeBox);
  288. i = 1;
  289. for (auto choice : processor.slopeParam->choices)
  290. slopeBox.addItem(choice, i++);
  291. slopeBox.onChange = [this] { processor.slopeParam->operator= (slopeBox.getSelectedItemIndex()); };
  292. slopeBox.setSelectedId(processor.slopeParam->getIndex() + 1);
  293. addAndMakeVisible(slopeLabel);
  294. slopeLabel.setJustificationType(Justification::centredLeft);
  295. slopeLabel.attachToComponent(&slopeBox, true);
  296. //==============================================================================
  297. addAndMakeVisible (waveshaperBox);
  298. i = 1;
  299. for (auto choice : processor.waveshaperParam->choices)
  300. waveshaperBox.addItem (choice, i++);
  301. waveshaperBox.onChange = [this] { processor.waveshaperParam->operator= (waveshaperBox.getSelectedItemIndex()); };
  302. waveshaperBox.setSelectedId (processor.waveshaperParam->getIndex() + 1);
  303. addAndMakeVisible (waveshaperLabel);
  304. waveshaperLabel.setJustificationType (Justification::centredLeft);
  305. waveshaperLabel.attachToComponent (&waveshaperBox, true);
  306. //==============================================================================
  307. addAndMakeVisible (cabinetTypeBox);
  308. i = 1;
  309. for (auto choice : processor.cabinetTypeParam->choices)
  310. cabinetTypeBox.addItem (choice, i++);
  311. cabinetTypeBox.onChange = [this] { processor.cabinetTypeParam->operator= (cabinetTypeBox.getSelectedItemIndex()); };
  312. cabinetTypeBox.setSelectedId (processor.cabinetTypeParam->getIndex() + 1);
  313. addAndMakeVisible (cabinetTypeLabel);
  314. cabinetTypeLabel.setJustificationType (Justification::centredLeft);
  315. cabinetTypeLabel.attachToComponent (&cabinetTypeBox, true);
  316. //==============================================================================
  317. addAndMakeVisible (cabinetSimButton);
  318. cabinetSimButton.onClick = [this] { processor.cabinetSimParam->operator= (cabinetSimButton.getToggleState()); };
  319. cabinetSimButton.setButtonText (processor.cabinetSimParam->name);
  320. cabinetSimButton.setToggleState (processor.cabinetSimParam->get(), NotificationType::dontSendNotification);
  321. addAndMakeVisible (oversamplingButton);
  322. oversamplingButton.onClick = [this] { processor.oversamplingParam->operator= (oversamplingButton.getToggleState()); };
  323. oversamplingButton.setButtonText (processor.oversamplingParam->name);
  324. oversamplingButton.setToggleState (processor.oversamplingParam->get(), NotificationType::dontSendNotification);
  325. //==============================================================================
  326. setSize (600, 400);
  327. }
  328. ~DspModulePluginDemoAudioProcessorEditor() {}
  329. //==============================================================================
  330. void paint (Graphics& g) override
  331. {
  332. g.setColour (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
  333. g.fillAll();
  334. }
  335. void resized() override
  336. {
  337. auto bounds = getLocalBounds().reduced (10);
  338. bounds.removeFromTop (10);
  339. bounds.removeFromLeft (125);
  340. //==============================================================================
  341. inputVolumeSlider->setBounds (bounds.removeFromTop (30));
  342. bounds.removeFromTop (5);
  343. outputVolumeSlider->setBounds (bounds.removeFromTop (30));
  344. bounds.removeFromTop (15);
  345. highPassFilterFreqSlider->setBounds (bounds.removeFromTop (30));
  346. bounds.removeFromTop (5);
  347. lowPassFilterFreqSlider->setBounds (bounds.removeFromTop (30));
  348. bounds.removeFromTop (15);
  349. //==============================================================================
  350. stereoBox.setBounds (bounds.removeFromTop(30));
  351. bounds.removeFromTop (5);
  352. slopeBox.setBounds (bounds.removeFromTop (30));
  353. bounds.removeFromTop (5);
  354. waveshaperBox.setBounds (bounds.removeFromTop (30));
  355. bounds.removeFromTop (5);
  356. cabinetTypeBox.setBounds (bounds.removeFromTop (30));
  357. bounds.removeFromTop (15);
  358. //==============================================================================
  359. auto buttonSlice = bounds.removeFromTop (30);
  360. cabinetSimButton.setSize (200, buttonSlice.getHeight());
  361. cabinetSimButton.setCentrePosition (buttonSlice.getCentre());
  362. bounds.removeFromTop(5);
  363. buttonSlice = bounds.removeFromTop (30);
  364. oversamplingButton.setSize(200, buttonSlice.getHeight());
  365. oversamplingButton.setCentrePosition(buttonSlice.getCentre());
  366. }
  367. private:
  368. //==============================================================================
  369. DspModulePluginDemoAudioProcessor& processor;
  370. std::unique_ptr<ParameterSlider> inputVolumeSlider, outputVolumeSlider,
  371. lowPassFilterFreqSlider, highPassFilterFreqSlider;
  372. ComboBox stereoBox, slopeBox, waveshaperBox, cabinetTypeBox;
  373. ToggleButton cabinetSimButton, oversamplingButton;
  374. Label inputVolumeLabel, outputVolumeLabel, lowPassFilterFreqLabel,
  375. highPassFilterFreqLabel, stereoLabel, slopeLabel, waveshaperLabel,
  376. cabinetTypeLabel;
  377. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DspModulePluginDemoAudioProcessorEditor)
  378. };
  379. //==============================================================================
  380. void process (dsp::ProcessContextReplacing<float> context) noexcept
  381. {
  382. ScopedNoDenormals noDenormals;
  383. // Input volume applied with a LinearSmoothedValue
  384. inputVolume.process (context);
  385. // Pre-highpass filtering, very useful for distortion audio effects
  386. // Note : try frequencies around 700 Hz
  387. highPassFilter.process (context);
  388. // Upsampling
  389. dsp::AudioBlock<float> oversampledBlock;
  390. setLatencySamples (audioCurrentlyOversampled ? roundToInt (oversampling->getLatencyInSamples()) : 0);
  391. if (audioCurrentlyOversampled)
  392. oversampledBlock = oversampling->processSamplesUp (context.getInputBlock());
  393. auto waveshaperContext = audioCurrentlyOversampled ? dsp::ProcessContextReplacing<float> (oversampledBlock)
  394. : context;
  395. // Waveshaper processing, for distortion generation, thanks to the input gain
  396. // The fast tanh can be used instead of std::tanh to reduce the CPU load
  397. auto waveshaperIndex = waveshaperParam->getIndex();
  398. if (isPositiveAndBelow (waveshaperIndex, numWaveShapers) )
  399. {
  400. waveShapers[waveshaperIndex].process (waveshaperContext);
  401. if (waveshaperIndex == 1)
  402. clipping.process (waveshaperContext);
  403. waveshaperContext.getOutputBlock() *= 0.7f;
  404. }
  405. // Downsampling
  406. if (audioCurrentlyOversampled)
  407. oversampling->processSamplesDown (context.getOutputBlock());
  408. // Post-lowpass filtering
  409. lowPassFilter.process (context);
  410. // Convolution with the impulse response of a guitar cabinet
  411. auto wasBypassed = context.isBypassed;
  412. context.isBypassed = context.isBypassed || cabinetIsBypassed;
  413. convolution.process (context);
  414. context.isBypassed = wasBypassed;
  415. // Output volume applied with a LinearSmoothedValue
  416. outputVolume.process (context);
  417. }
  418. //==============================================================================
  419. dsp::ProcessorDuplicator<dsp::IIR::Filter<float>, dsp::IIR::Coefficients<float>> lowPassFilter, highPassFilter;
  420. dsp::Convolution convolution;
  421. MemoryBlock currentCabinetData;
  422. static constexpr size_t numWaveShapers = 2;
  423. dsp::WaveShaper<float> waveShapers[numWaveShapers];
  424. dsp::WaveShaper<float> clipping;
  425. dsp::Gain<float> inputVolume, outputVolume;
  426. std::unique_ptr<dsp::Oversampling<float>> oversampling;
  427. bool audioCurrentlyOversampled = false;
  428. Atomic<int> cabinetType;
  429. bool cabinetIsBypassed = false;
  430. //==============================================================================
  431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DspModulePluginDemoAudioProcessor)
  432. };