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.

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