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.

771 lines
29KB

  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: MPEDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Simple MPE synthesiser application.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_processors, juce_audio_utils, juce_core,
  26. juce_data_structures, juce_events, juce_graphics,
  27. juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2022, linux_make, androidstudio, xcode_iphone
  29. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  30. type: Component
  31. mainClass: MPEDemo
  32. useLocalCopy: 1
  33. END_JUCE_PIP_METADATA
  34. *******************************************************************************/
  35. #pragma once
  36. //==============================================================================
  37. class ZoneColourPicker
  38. {
  39. public:
  40. ZoneColourPicker() {}
  41. //==============================================================================
  42. Colour getColourForMidiChannel (int midiChannel) noexcept
  43. {
  44. if (legacyModeEnabled)
  45. return Colours::white;
  46. if (zoneLayout.getLowerZone().isUsingChannelAsMemberChannel (midiChannel))
  47. return getColourForZone (true);
  48. if (zoneLayout.getUpperZone().isUsingChannelAsMemberChannel (midiChannel))
  49. return getColourForZone (false);
  50. return Colours::transparentBlack;
  51. }
  52. //==============================================================================
  53. Colour getColourForZone (bool isLowerZone) const noexcept
  54. {
  55. if (legacyModeEnabled)
  56. return Colours::white;
  57. if (isLowerZone)
  58. return Colours::blue;
  59. return Colours::red;
  60. }
  61. //==============================================================================
  62. void setZoneLayout (MPEZoneLayout layout) noexcept { zoneLayout = layout; }
  63. void setLegacyModeEnabled (bool shouldBeEnabled) noexcept { legacyModeEnabled = shouldBeEnabled; }
  64. private:
  65. //==============================================================================
  66. MPEZoneLayout zoneLayout;
  67. bool legacyModeEnabled = false;
  68. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZoneColourPicker)
  69. };
  70. //==============================================================================
  71. class MPESetupComponent : public Component
  72. {
  73. public:
  74. //==============================================================================
  75. MPESetupComponent (MPEInstrument& instr)
  76. : instrument (instr)
  77. {
  78. addAndMakeVisible (isLowerZoneButton);
  79. isLowerZoneButton.setToggleState (true, NotificationType::dontSendNotification);
  80. initialiseComboBoxWithConsecutiveIntegers (memberChannels, memberChannelsLabel, 0, 16, defaultMemberChannels);
  81. initialiseComboBoxWithConsecutiveIntegers (masterPitchbendRange, masterPitchbendRangeLabel, 0, 96, defaultMasterPitchbendRange);
  82. initialiseComboBoxWithConsecutiveIntegers (notePitchbendRange, notePitchbendRangeLabel, 0, 96, defaultNotePitchbendRange);
  83. initialiseComboBoxWithConsecutiveIntegers (legacyStartChannel, legacyStartChannelLabel, 1, 16, 1, false);
  84. initialiseComboBoxWithConsecutiveIntegers (legacyEndChannel, legacyEndChannelLabel, 1, 16, 16, false);
  85. initialiseComboBoxWithConsecutiveIntegers (legacyPitchbendRange, legacyPitchbendRangeLabel, 0, 96, 2, false);
  86. addAndMakeVisible (setZoneButton);
  87. setZoneButton.onClick = [this] { setZoneButtonClicked(); };
  88. addAndMakeVisible (clearAllZonesButton);
  89. clearAllZonesButton.onClick = [this] { clearAllZonesButtonClicked(); };
  90. addAndMakeVisible (legacyModeEnabledToggle);
  91. legacyModeEnabledToggle.onClick = [this] { legacyModeEnabledToggleClicked(); };
  92. addAndMakeVisible (voiceStealingEnabledToggle);
  93. voiceStealingEnabledToggle.onClick = [this] { voiceStealingEnabledToggleClicked(); };
  94. initialiseComboBoxWithConsecutiveIntegers (numberOfVoices, numberOfVoicesLabel, 1, 20, 15);
  95. }
  96. //==============================================================================
  97. void resized() override
  98. {
  99. Rectangle<int> r (proportionOfWidth (0.65f), 15, proportionOfWidth (0.25f), 3000);
  100. auto h = 24;
  101. auto hspace = 6;
  102. auto hbigspace = 18;
  103. isLowerZoneButton.setBounds (r.removeFromTop (h));
  104. r.removeFromTop (hspace);
  105. memberChannels.setBounds (r.removeFromTop (h));
  106. r.removeFromTop (hspace);
  107. notePitchbendRange.setBounds (r.removeFromTop (h));
  108. r.removeFromTop (hspace);
  109. masterPitchbendRange.setBounds (r.removeFromTop (h));
  110. legacyStartChannel .setBounds (isLowerZoneButton .getBounds());
  111. legacyEndChannel .setBounds (memberChannels .getBounds());
  112. legacyPitchbendRange.setBounds (notePitchbendRange.getBounds());
  113. r.removeFromTop (hbigspace);
  114. auto buttonLeft = proportionOfWidth (0.5f);
  115. setZoneButton.setBounds (r.removeFromTop (h).withLeft (buttonLeft));
  116. r.removeFromTop (hspace);
  117. clearAllZonesButton.setBounds (r.removeFromTop (h).withLeft (buttonLeft));
  118. r.removeFromTop (hbigspace);
  119. auto toggleLeft = proportionOfWidth (0.25f);
  120. legacyModeEnabledToggle.setBounds (r.removeFromTop (h).withLeft (toggleLeft));
  121. r.removeFromTop (hspace);
  122. voiceStealingEnabledToggle.setBounds (r.removeFromTop (h).withLeft (toggleLeft));
  123. r.removeFromTop (hspace);
  124. numberOfVoices.setBounds (r.removeFromTop (h));
  125. }
  126. //==============================================================================
  127. bool isVoiceStealingEnabled() const { return voiceStealingEnabledToggle.getToggleState(); }
  128. int getNumVoices() const { return numberOfVoices.getText().getIntValue(); }
  129. std::function<void()> onSynthParametersChange;
  130. private:
  131. //==============================================================================
  132. void initialiseComboBoxWithConsecutiveIntegers (ComboBox& comboBox, Label& labelToAttach,
  133. int firstValue, int numValues, int valueToSelect,
  134. bool makeVisible = true)
  135. {
  136. for (auto i = 0; i < numValues; ++i)
  137. comboBox.addItem (String (i + firstValue), i + 1);
  138. comboBox.setSelectedId (valueToSelect - firstValue + 1);
  139. labelToAttach.attachToComponent (&comboBox, true);
  140. if (makeVisible)
  141. addAndMakeVisible (comboBox);
  142. else
  143. addChildComponent (comboBox);
  144. if (&comboBox == &numberOfVoices)
  145. comboBox.onChange = [this] { numberOfVoicesChanged(); };
  146. else if (&comboBox == &legacyPitchbendRange)
  147. comboBox.onChange = [this] { if (legacyModeEnabledToggle.getToggleState()) legacyModePitchbendRangeChanged(); };
  148. else if (&comboBox == &legacyStartChannel || &comboBox == &legacyEndChannel)
  149. comboBox.onChange = [this] { if (legacyModeEnabledToggle.getToggleState()) legacyModeChannelRangeChanged(); };
  150. }
  151. //==============================================================================
  152. void setZoneButtonClicked()
  153. {
  154. auto isLowerZone = isLowerZoneButton.getToggleState();
  155. auto numMemberChannels = memberChannels.getText().getIntValue();
  156. auto perNotePb = notePitchbendRange.getText().getIntValue();
  157. auto masterPb = masterPitchbendRange.getText().getIntValue();
  158. auto zoneLayout = instrument.getZoneLayout();
  159. if (isLowerZone)
  160. zoneLayout.setLowerZone (numMemberChannels, perNotePb, masterPb);
  161. else
  162. zoneLayout.setUpperZone (numMemberChannels, perNotePb, masterPb);
  163. instrument.setZoneLayout (zoneLayout);
  164. }
  165. void clearAllZonesButtonClicked()
  166. {
  167. instrument.setZoneLayout ({});
  168. }
  169. void legacyModeEnabledToggleClicked()
  170. {
  171. auto legacyModeEnabled = legacyModeEnabledToggle.getToggleState();
  172. isLowerZoneButton .setVisible (! legacyModeEnabled);
  173. memberChannels .setVisible (! legacyModeEnabled);
  174. notePitchbendRange .setVisible (! legacyModeEnabled);
  175. masterPitchbendRange.setVisible (! legacyModeEnabled);
  176. setZoneButton .setVisible (! legacyModeEnabled);
  177. clearAllZonesButton .setVisible (! legacyModeEnabled);
  178. legacyStartChannel .setVisible (legacyModeEnabled);
  179. legacyEndChannel .setVisible (legacyModeEnabled);
  180. legacyPitchbendRange.setVisible (legacyModeEnabled);
  181. if (legacyModeEnabled)
  182. {
  183. if (areLegacyModeParametersValid())
  184. {
  185. instrument.enableLegacyMode();
  186. instrument.setLegacyModeChannelRange (getLegacyModeChannelRange());
  187. instrument.setLegacyModePitchbendRange (getLegacyModePitchbendRange());
  188. }
  189. else
  190. {
  191. handleInvalidLegacyModeParameters();
  192. }
  193. }
  194. else
  195. {
  196. instrument.setZoneLayout ({ MPEZone (MPEZone::Type::lower, 15) });
  197. }
  198. }
  199. //==============================================================================
  200. void legacyModePitchbendRangeChanged()
  201. {
  202. jassert (legacyModeEnabledToggle.getToggleState() == true);
  203. instrument.setLegacyModePitchbendRange (getLegacyModePitchbendRange());
  204. }
  205. void legacyModeChannelRangeChanged()
  206. {
  207. jassert (legacyModeEnabledToggle.getToggleState() == true);
  208. if (areLegacyModeParametersValid())
  209. instrument.setLegacyModeChannelRange (getLegacyModeChannelRange());
  210. else
  211. handleInvalidLegacyModeParameters();
  212. }
  213. bool areLegacyModeParametersValid() const
  214. {
  215. return legacyStartChannel.getText().getIntValue() <= legacyEndChannel.getText().getIntValue();
  216. }
  217. void handleInvalidLegacyModeParameters() const
  218. {
  219. AlertWindow::showMessageBoxAsync (MessageBoxIconType::WarningIcon,
  220. "Invalid legacy mode channel layout",
  221. "Cannot set legacy mode start/end channel:\n"
  222. "The end channel must not be less than the start channel!",
  223. "Got it");
  224. }
  225. Range<int> getLegacyModeChannelRange() const
  226. {
  227. return { legacyStartChannel.getText().getIntValue(),
  228. legacyEndChannel.getText().getIntValue() + 1 };
  229. }
  230. int getLegacyModePitchbendRange() const
  231. {
  232. return legacyPitchbendRange.getText().getIntValue();
  233. }
  234. //==============================================================================
  235. void voiceStealingEnabledToggleClicked()
  236. {
  237. jassert (onSynthParametersChange != nullptr);
  238. onSynthParametersChange();
  239. }
  240. void numberOfVoicesChanged()
  241. {
  242. jassert (onSynthParametersChange != nullptr);
  243. onSynthParametersChange();
  244. }
  245. //==============================================================================
  246. MPEInstrument& instrument;
  247. ComboBox memberChannels, masterPitchbendRange, notePitchbendRange;
  248. ToggleButton isLowerZoneButton { "Lower zone" };
  249. Label memberChannelsLabel { {}, "Nr. of member channels:" };
  250. Label masterPitchbendRangeLabel { {}, "Master pitchbend range (semitones):" };
  251. Label notePitchbendRangeLabel { {}, "Note pitchbend range (semitones):" };
  252. TextButton setZoneButton { "Set zone" };
  253. TextButton clearAllZonesButton { "Clear all zones" };
  254. ComboBox legacyStartChannel, legacyEndChannel, legacyPitchbendRange;
  255. Label legacyStartChannelLabel { {}, "First channel:" };
  256. Label legacyEndChannelLabel { {}, "Last channel:" };
  257. Label legacyPitchbendRangeLabel { {}, "Pitchbend range (semitones):"};
  258. ToggleButton legacyModeEnabledToggle { "Enable Legacy Mode" };
  259. ToggleButton voiceStealingEnabledToggle { "Enable synth voice stealing" };
  260. ComboBox numberOfVoices;
  261. Label numberOfVoicesLabel { {}, "Number of synth voices"};
  262. static constexpr int defaultMemberChannels = 15,
  263. defaultMasterPitchbendRange = 2,
  264. defaultNotePitchbendRange = 48;
  265. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPESetupComponent)
  266. };
  267. //==============================================================================
  268. class ZoneLayoutComponent : public Component,
  269. private MPEInstrument::Listener
  270. {
  271. public:
  272. //==============================================================================
  273. ZoneLayoutComponent (MPEInstrument& instr, ZoneColourPicker& zoneColourPicker)
  274. : instrument (instr),
  275. colourPicker (zoneColourPicker)
  276. {
  277. instrument.addListener (this);
  278. }
  279. ~ZoneLayoutComponent() override
  280. {
  281. instrument.removeListener (this);
  282. }
  283. //==============================================================================
  284. void paint (Graphics& g) override
  285. {
  286. paintBackground (g);
  287. if (instrument.isLegacyModeEnabled())
  288. paintLegacyMode (g);
  289. else
  290. paintZones (g);
  291. }
  292. private:
  293. //==============================================================================
  294. void zoneLayoutChanged() override
  295. {
  296. repaint();
  297. }
  298. //==============================================================================
  299. void paintBackground (Graphics& g)
  300. {
  301. g.setColour (Colours::black);
  302. auto channelWidth = getChannelRectangleWidth();
  303. for (auto i = 0; i < numMidiChannels; ++i)
  304. {
  305. auto x = float (i) * channelWidth;
  306. Rectangle<int> channelArea ((int) x, 0, (int) channelWidth, getHeight());
  307. g.drawLine ({ x, 0.0f, x, float (getHeight()) });
  308. g.drawText (String (i + 1), channelArea.reduced (4, 4), Justification::topLeft, false);
  309. }
  310. }
  311. //==============================================================================
  312. void paintZones (Graphics& g)
  313. {
  314. auto channelWidth = getChannelRectangleWidth();
  315. auto zoneLayout = instrument.getZoneLayout();
  316. Array<MPEZoneLayout::Zone> activeZones;
  317. if (zoneLayout.getLowerZone().isActive()) activeZones.add (zoneLayout.getLowerZone());
  318. if (zoneLayout.getUpperZone().isActive()) activeZones.add (zoneLayout.getUpperZone());
  319. for (auto zone : activeZones)
  320. {
  321. auto zoneColour = colourPicker.getColourForZone (zone.isLowerZone());
  322. auto xPos = zone.isLowerZone() ? 0 : zone.getLastMemberChannel() - 1;
  323. Rectangle<int> zoneRect { int (channelWidth * (float) xPos), 20,
  324. int (channelWidth * (float) (zone.numMemberChannels + 1)), getHeight() - 20 };
  325. g.setColour (zoneColour);
  326. g.drawRect (zoneRect, 3);
  327. auto masterRect = zone.isLowerZone() ? zoneRect.removeFromLeft ((int) channelWidth) : zoneRect.removeFromRight ((int) channelWidth);
  328. g.setColour (zoneColour.withAlpha (0.3f));
  329. g.fillRect (masterRect);
  330. g.setColour (zoneColour.contrasting());
  331. g.drawText ("<>" + String (zone.masterPitchbendRange), masterRect.reduced (4), Justification::top, false);
  332. g.drawText ("<>" + String (zone.perNotePitchbendRange), masterRect.reduced (4), Justification::bottom, false);
  333. }
  334. }
  335. //==============================================================================
  336. void paintLegacyMode (Graphics& g)
  337. {
  338. auto channelRange = instrument.getLegacyModeChannelRange();
  339. auto startChannel = channelRange.getStart() - 1;
  340. auto numChannels = channelRange.getEnd() - startChannel - 1;
  341. Rectangle<int> zoneRect (int (getChannelRectangleWidth() * (float) startChannel), 0,
  342. int (getChannelRectangleWidth() * (float) numChannels), getHeight());
  343. zoneRect.removeFromTop (20);
  344. g.setColour (Colours::white);
  345. g.drawRect (zoneRect, 3);
  346. g.drawText ("LGCY", zoneRect.reduced (4, 4), Justification::topLeft, false);
  347. g.drawText ("<>" + String (instrument.getLegacyModePitchbendRange()), zoneRect.reduced (4, 4), Justification::bottomLeft, false);
  348. }
  349. //==============================================================================
  350. float getChannelRectangleWidth() const noexcept
  351. {
  352. return (float) getWidth() / (float) numMidiChannels;
  353. }
  354. //==============================================================================
  355. static constexpr int numMidiChannels = 16;
  356. MPEInstrument& instrument;
  357. ZoneColourPicker& colourPicker;
  358. };
  359. //==============================================================================
  360. class MPEDemoSynthVoice : public MPESynthesiserVoice
  361. {
  362. public:
  363. //==============================================================================
  364. MPEDemoSynthVoice() {}
  365. //==============================================================================
  366. void noteStarted() override
  367. {
  368. jassert (currentlyPlayingNote.isValid());
  369. jassert (currentlyPlayingNote.keyState == MPENote::keyDown
  370. || currentlyPlayingNote.keyState == MPENote::keyDownAndSustained);
  371. level .setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  372. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  373. timbre .setTargetValue (currentlyPlayingNote.timbre.asUnsignedFloat());
  374. phase = 0.0;
  375. auto cyclesPerSample = frequency.getNextValue() / currentSampleRate;
  376. phaseDelta = MathConstants<double>::twoPi * cyclesPerSample;
  377. tailOff = 0.0;
  378. }
  379. void noteStopped (bool allowTailOff) override
  380. {
  381. jassert (currentlyPlayingNote.keyState == MPENote::off);
  382. if (allowTailOff)
  383. {
  384. // start a tail-off by setting this flag. The render callback will pick up on
  385. // this and do a fade out, calling clearCurrentNote() when it's finished.
  386. if (tailOff == 0.0) // we only need to begin a tail-off if it's not already doing so - the
  387. // stopNote method could be called more than once.
  388. tailOff = 1.0;
  389. }
  390. else
  391. {
  392. // we're being told to stop playing immediately, so reset everything..
  393. clearCurrentNote();
  394. phaseDelta = 0.0;
  395. }
  396. }
  397. void notePressureChanged() override
  398. {
  399. level.setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  400. }
  401. void notePitchbendChanged() override
  402. {
  403. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  404. }
  405. void noteTimbreChanged() override
  406. {
  407. timbre.setTargetValue (currentlyPlayingNote.timbre.asUnsignedFloat());
  408. }
  409. void noteKeyStateChanged() override {}
  410. void setCurrentSampleRate (double newRate) override
  411. {
  412. if (currentSampleRate != newRate)
  413. {
  414. noteStopped (false);
  415. currentSampleRate = newRate;
  416. level .reset (currentSampleRate, smoothingLengthInSeconds);
  417. timbre .reset (currentSampleRate, smoothingLengthInSeconds);
  418. frequency.reset (currentSampleRate, smoothingLengthInSeconds);
  419. }
  420. }
  421. //==============================================================================
  422. virtual void renderNextBlock (AudioBuffer<float>& outputBuffer,
  423. int startSample,
  424. int numSamples) override
  425. {
  426. if (phaseDelta != 0.0)
  427. {
  428. if (tailOff > 0.0)
  429. {
  430. while (--numSamples >= 0)
  431. {
  432. auto currentSample = getNextSample() * (float) tailOff;
  433. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  434. outputBuffer.addSample (i, startSample, currentSample);
  435. ++startSample;
  436. tailOff *= 0.99;
  437. if (tailOff <= 0.005)
  438. {
  439. clearCurrentNote();
  440. phaseDelta = 0.0;
  441. break;
  442. }
  443. }
  444. }
  445. else
  446. {
  447. while (--numSamples >= 0)
  448. {
  449. auto currentSample = getNextSample();
  450. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  451. outputBuffer.addSample (i, startSample, currentSample);
  452. ++startSample;
  453. }
  454. }
  455. }
  456. }
  457. using MPESynthesiserVoice::renderNextBlock;
  458. private:
  459. //==============================================================================
  460. float getNextSample() noexcept
  461. {
  462. auto levelDb = (level.getNextValue() - 1.0) * maxLevelDb;
  463. auto amplitude = pow (10.0f, 0.05f * levelDb) * maxLevel;
  464. // timbre is used to blend between a sine and a square.
  465. auto f1 = std::sin (phase);
  466. auto f2 = copysign (1.0, f1);
  467. auto a2 = timbre.getNextValue();
  468. auto a1 = 1.0 - a2;
  469. auto nextSample = float (amplitude * ((a1 * f1) + (a2 * f2)));
  470. auto cyclesPerSample = frequency.getNextValue() / currentSampleRate;
  471. phaseDelta = MathConstants<double>::twoPi * cyclesPerSample;
  472. phase = std::fmod (phase + phaseDelta, MathConstants<double>::twoPi);
  473. return nextSample;
  474. }
  475. //==============================================================================
  476. SmoothedValue<double> level, timbre, frequency;
  477. double phase = 0.0;
  478. double phaseDelta = 0.0;
  479. double tailOff = 0.0;
  480. const double maxLevel = 0.05;
  481. const double maxLevelDb = 31.0;
  482. const double smoothingLengthInSeconds = 0.01;
  483. };
  484. //==============================================================================
  485. class MPEDemo : public Component,
  486. private AudioIODeviceCallback,
  487. private MidiInputCallback,
  488. private MPEInstrument::Listener
  489. {
  490. public:
  491. //==============================================================================
  492. MPEDemo()
  493. {
  494. #ifndef JUCE_DEMO_RUNNER
  495. audioDeviceManager.initialise (0, 2, nullptr, true, {}, nullptr);
  496. #endif
  497. audioDeviceManager.addMidiInputDeviceCallback ({}, this);
  498. audioDeviceManager.addAudioCallback (this);
  499. addAndMakeVisible (audioSetupComp);
  500. addAndMakeVisible (mpeSetupComp);
  501. addAndMakeVisible (zoneLayoutComp);
  502. addAndMakeVisible (keyboardComponent);
  503. synth.setVoiceStealingEnabled (false);
  504. for (auto i = 0; i < 15; ++i)
  505. synth.addVoice (new MPEDemoSynthVoice());
  506. mpeSetupComp.onSynthParametersChange = [this]
  507. {
  508. synth.setVoiceStealingEnabled (mpeSetupComp.isVoiceStealingEnabled());
  509. auto numVoices = mpeSetupComp.getNumVoices();
  510. if (numVoices < synth.getNumVoices())
  511. {
  512. synth.reduceNumVoices (numVoices);
  513. }
  514. else
  515. {
  516. while (synth.getNumVoices() < numVoices)
  517. synth.addVoice (new MPEDemoSynthVoice());
  518. }
  519. };
  520. instrument.addListener (this);
  521. setSize (880, 720);
  522. }
  523. ~MPEDemo() override
  524. {
  525. audioDeviceManager.removeMidiInputDeviceCallback ({}, this);
  526. audioDeviceManager.removeAudioCallback (this);
  527. }
  528. //==============================================================================
  529. void resized() override
  530. {
  531. auto zoneLayoutCompHeight = 60;
  532. auto audioSetupCompRelativeWidth = 0.55f;
  533. auto r = getLocalBounds();
  534. keyboardComponent.setBounds (r.removeFromBottom (150));
  535. r.reduce (10, 10);
  536. zoneLayoutComp.setBounds (r.removeFromBottom (zoneLayoutCompHeight));
  537. audioSetupComp.setBounds (r.removeFromLeft (proportionOfWidth (audioSetupCompRelativeWidth)));
  538. mpeSetupComp .setBounds (r);
  539. }
  540. //==============================================================================
  541. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData, int numInputChannels,
  542. float* const* outputChannelData, int numOutputChannels,
  543. int numSamples, const AudioIODeviceCallbackContext& context) override
  544. {
  545. ignoreUnused (inputChannelData, numInputChannels, context);
  546. AudioBuffer<float> buffer (outputChannelData, numOutputChannels, numSamples);
  547. buffer.clear();
  548. MidiBuffer incomingMidi;
  549. midiCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  550. synth.renderNextBlock (buffer, incomingMidi, 0, numSamples);
  551. }
  552. void audioDeviceAboutToStart (AudioIODevice* device) override
  553. {
  554. auto sampleRate = device->getCurrentSampleRate();
  555. midiCollector.reset (sampleRate);
  556. synth.setCurrentPlaybackSampleRate (sampleRate);
  557. }
  558. void audioDeviceStopped() override {}
  559. private:
  560. //==============================================================================
  561. void handleIncomingMidiMessage (MidiInput* /*source*/,
  562. const MidiMessage& message) override
  563. {
  564. instrument.processNextMidiEvent (message);
  565. midiCollector.addMessageToQueue (message);
  566. }
  567. //==============================================================================
  568. void zoneLayoutChanged() override
  569. {
  570. if (instrument.isLegacyModeEnabled())
  571. {
  572. colourPicker.setLegacyModeEnabled (true);
  573. synth.enableLegacyMode (instrument.getLegacyModePitchbendRange(),
  574. instrument.getLegacyModeChannelRange());
  575. }
  576. else
  577. {
  578. colourPicker.setLegacyModeEnabled (false);
  579. auto zoneLayout = instrument.getZoneLayout();
  580. if (auto* midiOutput = audioDeviceManager.getDefaultMidiOutput())
  581. midiOutput->sendBlockOfMessagesNow (MPEMessages::setZoneLayout (zoneLayout));
  582. synth.setZoneLayout (zoneLayout);
  583. colourPicker.setZoneLayout (zoneLayout);
  584. }
  585. }
  586. //==============================================================================
  587. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  588. #ifndef JUCE_DEMO_RUNNER
  589. AudioDeviceManager audioDeviceManager;
  590. #else
  591. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (0, 2) };
  592. #endif
  593. AudioDeviceSelectorComponent audioSetupComp { audioDeviceManager, 0, 0, 0, 256, true, true, true, false };
  594. MidiMessageCollector midiCollector;
  595. MPEInstrument instrument { MPEZone (MPEZone::Type::lower, 15) };
  596. ZoneColourPicker colourPicker;
  597. MPESetupComponent mpeSetupComp { instrument };
  598. ZoneLayoutComponent zoneLayoutComp { instrument, colourPicker};
  599. MPESynthesiser synth { instrument };
  600. MPEKeyboardComponent keyboardComponent { instrument, MPEKeyboardComponent::horizontalKeyboard };
  601. //==============================================================================
  602. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPEDemo)
  603. };