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.

666 lines
25KB

  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: AudioPluginDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: 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, vs2017, vs2022, linux_make, xcode_iphone, androidstudio
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: AudioProcessor
  31. mainClass: JuceDemoPluginAudioProcessor
  32. useLocalCopy: 1
  33. pluginCharacteristics: pluginIsSynth, pluginWantsMidiIn, pluginProducesMidiOut,
  34. pluginEditorRequiresKeys
  35. extraPluginFormats: AUv3
  36. END_JUCE_PIP_METADATA
  37. *******************************************************************************/
  38. #pragma once
  39. //==============================================================================
  40. /** A demo synth sound that's just a basic sine wave.. */
  41. class SineWaveSound : public SynthesiserSound
  42. {
  43. public:
  44. SineWaveSound() {}
  45. bool appliesToNote (int /*midiNoteNumber*/) override { return true; }
  46. bool appliesToChannel (int /*midiChannel*/) override { return true; }
  47. };
  48. //==============================================================================
  49. /** A simple demo synth voice that just plays a sine wave.. */
  50. class SineWaveVoice : public SynthesiserVoice
  51. {
  52. public:
  53. SineWaveVoice() {}
  54. bool canPlaySound (SynthesiserSound* sound) override
  55. {
  56. return dynamic_cast<SineWaveSound*> (sound) != nullptr;
  57. }
  58. void startNote (int midiNoteNumber, float velocity,
  59. SynthesiserSound* /*sound*/,
  60. int /*currentPitchWheelPosition*/) override
  61. {
  62. currentAngle = 0.0;
  63. level = velocity * 0.15;
  64. tailOff = 0.0;
  65. auto cyclesPerSecond = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  66. auto cyclesPerSample = cyclesPerSecond / getSampleRate();
  67. angleDelta = cyclesPerSample * MathConstants<double>::twoPi;
  68. }
  69. void stopNote (float /*velocity*/, bool allowTailOff) override
  70. {
  71. if (allowTailOff)
  72. {
  73. // start a tail-off by setting this flag. The render callback will pick up on
  74. // this and do a fade out, calling clearCurrentNote() when it's finished.
  75. if (tailOff == 0.0) // we only need to begin a tail-off if it's not already doing so - the
  76. // stopNote method could be called more than once.
  77. tailOff = 1.0;
  78. }
  79. else
  80. {
  81. // we're being told to stop playing immediately, so reset everything..
  82. clearCurrentNote();
  83. angleDelta = 0.0;
  84. }
  85. }
  86. void pitchWheelMoved (int /*newValue*/) override
  87. {
  88. // not implemented for the purposes of this demo!
  89. }
  90. void controllerMoved (int /*controllerNumber*/, int /*newValue*/) override
  91. {
  92. // not implemented for the purposes of this demo!
  93. }
  94. void renderNextBlock (AudioBuffer<float>& outputBuffer, int startSample, int numSamples) override
  95. {
  96. if (angleDelta != 0.0)
  97. {
  98. if (tailOff > 0.0)
  99. {
  100. while (--numSamples >= 0)
  101. {
  102. auto currentSample = (float) (sin (currentAngle) * level * tailOff);
  103. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  104. outputBuffer.addSample (i, startSample, currentSample);
  105. currentAngle += angleDelta;
  106. ++startSample;
  107. tailOff *= 0.99;
  108. if (tailOff <= 0.005)
  109. {
  110. // tells the synth that this voice has stopped
  111. clearCurrentNote();
  112. angleDelta = 0.0;
  113. break;
  114. }
  115. }
  116. }
  117. else
  118. {
  119. while (--numSamples >= 0)
  120. {
  121. auto currentSample = (float) (sin (currentAngle) * level);
  122. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  123. outputBuffer.addSample (i, startSample, currentSample);
  124. currentAngle += angleDelta;
  125. ++startSample;
  126. }
  127. }
  128. }
  129. }
  130. using SynthesiserVoice::renderNextBlock;
  131. private:
  132. double currentAngle = 0.0;
  133. double angleDelta = 0.0;
  134. double level = 0.0;
  135. double tailOff = 0.0;
  136. };
  137. //==============================================================================
  138. /** As the name suggest, this class does the actual audio processing. */
  139. class JuceDemoPluginAudioProcessor : public AudioProcessor
  140. {
  141. public:
  142. //==============================================================================
  143. JuceDemoPluginAudioProcessor()
  144. : AudioProcessor (getBusesProperties()),
  145. state (*this, nullptr, "state",
  146. { std::make_unique<AudioParameterFloat> (ParameterID { "gain", 1 }, "Gain", NormalisableRange<float> (0.0f, 1.0f), 0.9f),
  147. std::make_unique<AudioParameterFloat> (ParameterID { "delay", 1 }, "Delay Feedback", NormalisableRange<float> (0.0f, 1.0f), 0.5f) })
  148. {
  149. // Add a sub-tree to store the state of our UI
  150. state.state.addChild ({ "uiState", { { "width", 400 }, { "height", 200 } }, {} }, -1, nullptr);
  151. initialiseSynth();
  152. }
  153. ~JuceDemoPluginAudioProcessor() override = default;
  154. //==============================================================================
  155. bool isBusesLayoutSupported (const BusesLayout& layouts) const override
  156. {
  157. // Only mono/stereo and input/output must have same layout
  158. const auto& mainOutput = layouts.getMainOutputChannelSet();
  159. const auto& mainInput = layouts.getMainInputChannelSet();
  160. // input and output layout must either be the same or the input must be disabled altogether
  161. if (! mainInput.isDisabled() && mainInput != mainOutput)
  162. return false;
  163. // only allow stereo and mono
  164. if (mainOutput.size() > 2)
  165. return false;
  166. return true;
  167. }
  168. void prepareToPlay (double newSampleRate, int /*samplesPerBlock*/) override
  169. {
  170. // Use this method as the place to do any pre-playback
  171. // initialisation that you need..
  172. synth.setCurrentPlaybackSampleRate (newSampleRate);
  173. keyboardState.reset();
  174. if (isUsingDoublePrecision())
  175. {
  176. delayBufferDouble.setSize (2, 12000);
  177. delayBufferFloat .setSize (1, 1);
  178. }
  179. else
  180. {
  181. delayBufferFloat .setSize (2, 12000);
  182. delayBufferDouble.setSize (1, 1);
  183. }
  184. reset();
  185. }
  186. void releaseResources() override
  187. {
  188. // When playback stops, you can use this as an opportunity to free up any
  189. // spare memory, etc.
  190. keyboardState.reset();
  191. }
  192. void reset() override
  193. {
  194. // Use this method as the place to clear any delay lines, buffers, etc, as it
  195. // means there's been a break in the audio's continuity.
  196. delayBufferFloat .clear();
  197. delayBufferDouble.clear();
  198. }
  199. //==============================================================================
  200. void processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiMessages) override
  201. {
  202. jassert (! isUsingDoublePrecision());
  203. process (buffer, midiMessages, delayBufferFloat);
  204. }
  205. void processBlock (AudioBuffer<double>& buffer, MidiBuffer& midiMessages) override
  206. {
  207. jassert (isUsingDoublePrecision());
  208. process (buffer, midiMessages, delayBufferDouble);
  209. }
  210. //==============================================================================
  211. bool hasEditor() const override { return true; }
  212. AudioProcessorEditor* createEditor() override
  213. {
  214. return new JuceDemoPluginAudioProcessorEditor (*this);
  215. }
  216. //==============================================================================
  217. const String getName() const override { return "AudioPluginDemo"; }
  218. bool acceptsMidi() const override { return true; }
  219. bool producesMidi() const override { return true; }
  220. double getTailLengthSeconds() const override { return 0.0; }
  221. //==============================================================================
  222. int getNumPrograms() override { return 0; }
  223. int getCurrentProgram() override { return 0; }
  224. void setCurrentProgram (int) override {}
  225. const String getProgramName (int) override { return "None"; }
  226. void changeProgramName (int, const String&) override {}
  227. //==============================================================================
  228. void getStateInformation (MemoryBlock& destData) override
  229. {
  230. // Store an xml representation of our state.
  231. if (auto xmlState = state.copyState().createXml())
  232. copyXmlToBinary (*xmlState, destData);
  233. }
  234. void setStateInformation (const void* data, int sizeInBytes) override
  235. {
  236. // Restore our plug-in's state from the xml representation stored in the above
  237. // method.
  238. if (auto xmlState = getXmlFromBinary (data, sizeInBytes))
  239. state.replaceState (ValueTree::fromXml (*xmlState));
  240. }
  241. //==============================================================================
  242. void updateTrackProperties (const TrackProperties& properties) override
  243. {
  244. {
  245. const ScopedLock sl (trackPropertiesLock);
  246. trackProperties = properties;
  247. }
  248. MessageManager::callAsync ([this]
  249. {
  250. if (auto* editor = dynamic_cast<JuceDemoPluginAudioProcessorEditor*> (getActiveEditor()))
  251. editor->updateTrackProperties();
  252. });
  253. }
  254. TrackProperties getTrackProperties() const
  255. {
  256. const ScopedLock sl (trackPropertiesLock);
  257. return trackProperties;
  258. }
  259. class SpinLockedPosInfo
  260. {
  261. public:
  262. // Wait-free, but setting new info may fail if the main thread is currently
  263. // calling `get`. This is unlikely to matter in practice because
  264. // we'll be calling `set` much more frequently than `get`.
  265. void set (const AudioPlayHead::PositionInfo& newInfo)
  266. {
  267. const juce::SpinLock::ScopedTryLockType lock (mutex);
  268. if (lock.isLocked())
  269. info = newInfo;
  270. }
  271. AudioPlayHead::PositionInfo get() const noexcept
  272. {
  273. const juce::SpinLock::ScopedLockType lock (mutex);
  274. return info;
  275. }
  276. private:
  277. juce::SpinLock mutex;
  278. AudioPlayHead::PositionInfo info;
  279. };
  280. //==============================================================================
  281. // These properties are public so that our editor component can access them
  282. // A bit of a hacky way to do it, but it's only a demo! Obviously in your own
  283. // code you'll do this much more neatly..
  284. // this is kept up to date with the midi messages that arrive, and the UI component
  285. // registers with it so it can represent the incoming messages
  286. MidiKeyboardState keyboardState;
  287. // this keeps a copy of the last set of time info that was acquired during an audio
  288. // callback - the UI component will read this and display it.
  289. SpinLockedPosInfo lastPosInfo;
  290. // Our plug-in's current state
  291. AudioProcessorValueTreeState state;
  292. private:
  293. //==============================================================================
  294. /** This is the editor component that our filter will display. */
  295. class JuceDemoPluginAudioProcessorEditor : public AudioProcessorEditor,
  296. private Timer,
  297. private Value::Listener
  298. {
  299. public:
  300. JuceDemoPluginAudioProcessorEditor (JuceDemoPluginAudioProcessor& owner)
  301. : AudioProcessorEditor (owner),
  302. midiKeyboard (owner.keyboardState, MidiKeyboardComponent::horizontalKeyboard),
  303. gainAttachment (owner.state, "gain", gainSlider),
  304. delayAttachment (owner.state, "delay", delaySlider)
  305. {
  306. // add some sliders..
  307. addAndMakeVisible (gainSlider);
  308. gainSlider.setSliderStyle (Slider::Rotary);
  309. addAndMakeVisible (delaySlider);
  310. delaySlider.setSliderStyle (Slider::Rotary);
  311. // add some labels for the sliders..
  312. gainLabel.attachToComponent (&gainSlider, false);
  313. gainLabel.setFont (Font (11.0f));
  314. delayLabel.attachToComponent (&delaySlider, false);
  315. delayLabel.setFont (Font (11.0f));
  316. // add the midi keyboard component..
  317. addAndMakeVisible (midiKeyboard);
  318. // add a label that will display the current timecode and status..
  319. addAndMakeVisible (timecodeDisplayLabel);
  320. timecodeDisplayLabel.setFont (Font (Font::getDefaultMonospacedFontName(), 15.0f, Font::plain));
  321. // set resize limits for this plug-in
  322. setResizeLimits (400, 200, 1024, 700);
  323. setResizable (true, owner.wrapperType != wrapperType_AudioUnitv3);
  324. lastUIWidth .referTo (owner.state.state.getChildWithName ("uiState").getPropertyAsValue ("width", nullptr));
  325. lastUIHeight.referTo (owner.state.state.getChildWithName ("uiState").getPropertyAsValue ("height", nullptr));
  326. // set our component's initial size to be the last one that was stored in the filter's settings
  327. setSize (lastUIWidth.getValue(), lastUIHeight.getValue());
  328. lastUIWidth. addListener (this);
  329. lastUIHeight.addListener (this);
  330. updateTrackProperties();
  331. // start a timer which will keep our timecode display updated
  332. startTimerHz (30);
  333. }
  334. ~JuceDemoPluginAudioProcessorEditor() override {}
  335. //==============================================================================
  336. void paint (Graphics& g) override
  337. {
  338. g.setColour (backgroundColour);
  339. g.fillAll();
  340. }
  341. void resized() override
  342. {
  343. // This lays out our child components...
  344. auto r = getLocalBounds().reduced (8);
  345. timecodeDisplayLabel.setBounds (r.removeFromTop (26));
  346. midiKeyboard .setBounds (r.removeFromBottom (70));
  347. r.removeFromTop (20);
  348. auto sliderArea = r.removeFromTop (60);
  349. gainSlider.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth() / 2)));
  350. delaySlider.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth())));
  351. lastUIWidth = getWidth();
  352. lastUIHeight = getHeight();
  353. }
  354. void timerCallback() override
  355. {
  356. updateTimecodeDisplay (getProcessor().lastPosInfo.get());
  357. }
  358. void hostMIDIControllerIsAvailable (bool controllerIsAvailable) override
  359. {
  360. midiKeyboard.setVisible (! controllerIsAvailable);
  361. }
  362. int getControlParameterIndex (Component& control) override
  363. {
  364. if (&control == &gainSlider)
  365. return 0;
  366. if (&control == &delaySlider)
  367. return 1;
  368. return -1;
  369. }
  370. void updateTrackProperties()
  371. {
  372. auto trackColour = getProcessor().getTrackProperties().colour;
  373. auto& lf = getLookAndFeel();
  374. backgroundColour = (trackColour == Colour() ? lf.findColour (ResizableWindow::backgroundColourId)
  375. : trackColour.withAlpha (1.0f).withBrightness (0.266f));
  376. repaint();
  377. }
  378. private:
  379. MidiKeyboardComponent midiKeyboard;
  380. Label timecodeDisplayLabel,
  381. gainLabel { {}, "Throughput level:" },
  382. delayLabel { {}, "Delay:" };
  383. Slider gainSlider, delaySlider;
  384. AudioProcessorValueTreeState::SliderAttachment gainAttachment, delayAttachment;
  385. Colour backgroundColour;
  386. // these are used to persist the UI's size - the values are stored along with the
  387. // filter's other parameters, and the UI component will update them when it gets
  388. // resized.
  389. Value lastUIWidth, lastUIHeight;
  390. //==============================================================================
  391. JuceDemoPluginAudioProcessor& getProcessor() const
  392. {
  393. return static_cast<JuceDemoPluginAudioProcessor&> (processor);
  394. }
  395. //==============================================================================
  396. // quick-and-dirty function to format a timecode string
  397. static String timeToTimecodeString (double seconds)
  398. {
  399. auto millisecs = roundToInt (seconds * 1000.0);
  400. auto absMillisecs = std::abs (millisecs);
  401. return String::formatted ("%02d:%02d:%02d.%03d",
  402. millisecs / 3600000,
  403. (absMillisecs / 60000) % 60,
  404. (absMillisecs / 1000) % 60,
  405. absMillisecs % 1000);
  406. }
  407. // quick-and-dirty function to format a bars/beats string
  408. static String quarterNotePositionToBarsBeatsString (double quarterNotes, AudioPlayHead::TimeSignature sig)
  409. {
  410. if (sig.numerator == 0 || sig.denominator == 0)
  411. return "1|1|000";
  412. auto quarterNotesPerBar = (sig.numerator * 4 / sig.denominator);
  413. auto beats = (fmod (quarterNotes, quarterNotesPerBar) / quarterNotesPerBar) * sig.numerator;
  414. auto bar = ((int) quarterNotes) / quarterNotesPerBar + 1;
  415. auto beat = ((int) beats) + 1;
  416. auto ticks = ((int) (fmod (beats, 1.0) * 960.0 + 0.5));
  417. return String::formatted ("%d|%d|%03d", bar, beat, ticks);
  418. }
  419. // Updates the text in our position label.
  420. void updateTimecodeDisplay (const AudioPlayHead::PositionInfo& pos)
  421. {
  422. MemoryOutputStream displayText;
  423. const auto sig = pos.getTimeSignature().orFallback (AudioPlayHead::TimeSignature{});
  424. displayText << "[" << SystemStats::getJUCEVersion() << "] "
  425. << String (pos.getBpm().orFallback (120.0), 2) << " bpm, "
  426. << sig.numerator << '/' << sig.denominator
  427. << " - " << timeToTimecodeString (pos.getTimeInSeconds().orFallback (0.0))
  428. << " - " << quarterNotePositionToBarsBeatsString (pos.getPpqPosition().orFallback (0.0), sig);
  429. if (pos.getIsRecording())
  430. displayText << " (recording)";
  431. else if (pos.getIsPlaying())
  432. displayText << " (playing)";
  433. timecodeDisplayLabel.setText (displayText.toString(), dontSendNotification);
  434. }
  435. // called when the stored window size changes
  436. void valueChanged (Value&) override
  437. {
  438. setSize (lastUIWidth.getValue(), lastUIHeight.getValue());
  439. }
  440. };
  441. //==============================================================================
  442. template <typename FloatType>
  443. void process (AudioBuffer<FloatType>& buffer, MidiBuffer& midiMessages, AudioBuffer<FloatType>& delayBuffer)
  444. {
  445. auto gainParamValue = state.getParameter ("gain") ->getValue();
  446. auto delayParamValue = state.getParameter ("delay")->getValue();
  447. auto numSamples = buffer.getNumSamples();
  448. // In case we have more outputs than inputs, we'll clear any output
  449. // channels that didn't contain input data, (because these aren't
  450. // guaranteed to be empty - they may contain garbage).
  451. for (auto i = getTotalNumInputChannels(); i < getTotalNumOutputChannels(); ++i)
  452. buffer.clear (i, 0, numSamples);
  453. // Now pass any incoming midi messages to our keyboard state object, and let it
  454. // add messages to the buffer if the user is clicking on the on-screen keys
  455. keyboardState.processNextMidiBuffer (midiMessages, 0, numSamples, true);
  456. // and now get our synth to process these midi events and generate its output.
  457. synth.renderNextBlock (buffer, midiMessages, 0, numSamples);
  458. // Apply our delay effect to the new output..
  459. applyDelay (buffer, delayBuffer, delayParamValue);
  460. // Apply our gain change to the outgoing data..
  461. applyGain (buffer, delayBuffer, gainParamValue);
  462. // Now ask the host for the current time so we can store it to be displayed later...
  463. updateCurrentTimeInfoFromHost();
  464. }
  465. template <typename FloatType>
  466. void applyGain (AudioBuffer<FloatType>& buffer, AudioBuffer<FloatType>& delayBuffer, float gainLevel)
  467. {
  468. ignoreUnused (delayBuffer);
  469. for (auto channel = 0; channel < getTotalNumOutputChannels(); ++channel)
  470. buffer.applyGain (channel, 0, buffer.getNumSamples(), gainLevel);
  471. }
  472. template <typename FloatType>
  473. void applyDelay (AudioBuffer<FloatType>& buffer, AudioBuffer<FloatType>& delayBuffer, float delayLevel)
  474. {
  475. auto numSamples = buffer.getNumSamples();
  476. auto delayPos = 0;
  477. for (auto channel = 0; channel < getTotalNumOutputChannels(); ++channel)
  478. {
  479. auto channelData = buffer.getWritePointer (channel);
  480. auto delayData = delayBuffer.getWritePointer (jmin (channel, delayBuffer.getNumChannels() - 1));
  481. delayPos = delayPosition;
  482. for (auto i = 0; i < numSamples; ++i)
  483. {
  484. auto in = channelData[i];
  485. channelData[i] += delayData[delayPos];
  486. delayData[delayPos] = (delayData[delayPos] + in) * delayLevel;
  487. if (++delayPos >= delayBuffer.getNumSamples())
  488. delayPos = 0;
  489. }
  490. }
  491. delayPosition = delayPos;
  492. }
  493. AudioBuffer<float> delayBufferFloat;
  494. AudioBuffer<double> delayBufferDouble;
  495. int delayPosition = 0;
  496. Synthesiser synth;
  497. CriticalSection trackPropertiesLock;
  498. TrackProperties trackProperties;
  499. void initialiseSynth()
  500. {
  501. auto numVoices = 8;
  502. // Add some voices...
  503. for (auto i = 0; i < numVoices; ++i)
  504. synth.addVoice (new SineWaveVoice());
  505. // ..and give the synth a sound to play
  506. synth.addSound (new SineWaveSound());
  507. }
  508. void updateCurrentTimeInfoFromHost()
  509. {
  510. const auto newInfo = [&]
  511. {
  512. if (auto* ph = getPlayHead())
  513. if (auto result = ph->getPosition())
  514. return *result;
  515. // If the host fails to provide the current time, we'll just use default values
  516. return AudioPlayHead::PositionInfo{};
  517. }();
  518. lastPosInfo.set (newInfo);
  519. }
  520. static BusesProperties getBusesProperties()
  521. {
  522. return BusesProperties().withInput ("Input", AudioChannelSet::stereo(), true)
  523. .withOutput ("Output", AudioChannelSet::stereo(), true);
  524. }
  525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceDemoPluginAudioProcessor)
  526. };