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.

774 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 final : 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()
  218. {
  219. auto options = MessageBoxOptions::makeOptionsOk (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. messageBox = AlertWindow::showScopedAsync (options, nullptr);
  225. }
  226. Range<int> getLegacyModeChannelRange() const
  227. {
  228. return { legacyStartChannel.getText().getIntValue(),
  229. legacyEndChannel.getText().getIntValue() + 1 };
  230. }
  231. int getLegacyModePitchbendRange() const
  232. {
  233. return legacyPitchbendRange.getText().getIntValue();
  234. }
  235. //==============================================================================
  236. void voiceStealingEnabledToggleClicked()
  237. {
  238. jassert (onSynthParametersChange != nullptr);
  239. onSynthParametersChange();
  240. }
  241. void numberOfVoicesChanged()
  242. {
  243. jassert (onSynthParametersChange != nullptr);
  244. onSynthParametersChange();
  245. }
  246. //==============================================================================
  247. MPEInstrument& instrument;
  248. ComboBox memberChannels, masterPitchbendRange, notePitchbendRange;
  249. ToggleButton isLowerZoneButton { "Lower zone" };
  250. Label memberChannelsLabel { {}, "Nr. of member channels:" };
  251. Label masterPitchbendRangeLabel { {}, "Master pitchbend range (semitones):" };
  252. Label notePitchbendRangeLabel { {}, "Note pitchbend range (semitones):" };
  253. TextButton setZoneButton { "Set zone" };
  254. TextButton clearAllZonesButton { "Clear all zones" };
  255. ComboBox legacyStartChannel, legacyEndChannel, legacyPitchbendRange;
  256. Label legacyStartChannelLabel { {}, "First channel:" };
  257. Label legacyEndChannelLabel { {}, "Last channel:" };
  258. Label legacyPitchbendRangeLabel { {}, "Pitchbend range (semitones):"};
  259. ToggleButton legacyModeEnabledToggle { "Enable Legacy Mode" };
  260. ToggleButton voiceStealingEnabledToggle { "Enable synth voice stealing" };
  261. ComboBox numberOfVoices;
  262. Label numberOfVoicesLabel { {}, "Number of synth voices"};
  263. ScopedMessageBox messageBox;
  264. static constexpr int defaultMemberChannels = 15,
  265. defaultMasterPitchbendRange = 2,
  266. defaultNotePitchbendRange = 48;
  267. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPESetupComponent)
  268. };
  269. //==============================================================================
  270. class ZoneLayoutComponent final : public Component,
  271. private MPEInstrument::Listener
  272. {
  273. public:
  274. //==============================================================================
  275. ZoneLayoutComponent (MPEInstrument& instr, ZoneColourPicker& zoneColourPicker)
  276. : instrument (instr),
  277. colourPicker (zoneColourPicker)
  278. {
  279. instrument.addListener (this);
  280. }
  281. ~ZoneLayoutComponent() override
  282. {
  283. instrument.removeListener (this);
  284. }
  285. //==============================================================================
  286. void paint (Graphics& g) override
  287. {
  288. paintBackground (g);
  289. if (instrument.isLegacyModeEnabled())
  290. paintLegacyMode (g);
  291. else
  292. paintZones (g);
  293. }
  294. private:
  295. //==============================================================================
  296. void zoneLayoutChanged() override
  297. {
  298. repaint();
  299. }
  300. //==============================================================================
  301. void paintBackground (Graphics& g)
  302. {
  303. g.setColour (Colours::black);
  304. auto channelWidth = getChannelRectangleWidth();
  305. for (auto i = 0; i < numMidiChannels; ++i)
  306. {
  307. auto x = float (i) * channelWidth;
  308. Rectangle<int> channelArea ((int) x, 0, (int) channelWidth, getHeight());
  309. g.drawLine ({ x, 0.0f, x, float (getHeight()) });
  310. g.drawText (String (i + 1), channelArea.reduced (4, 4), Justification::topLeft, false);
  311. }
  312. }
  313. //==============================================================================
  314. void paintZones (Graphics& g)
  315. {
  316. auto channelWidth = getChannelRectangleWidth();
  317. auto zoneLayout = instrument.getZoneLayout();
  318. Array<MPEZoneLayout::Zone> activeZones;
  319. if (zoneLayout.getLowerZone().isActive()) activeZones.add (zoneLayout.getLowerZone());
  320. if (zoneLayout.getUpperZone().isActive()) activeZones.add (zoneLayout.getUpperZone());
  321. for (auto zone : activeZones)
  322. {
  323. auto zoneColour = colourPicker.getColourForZone (zone.isLowerZone());
  324. auto xPos = zone.isLowerZone() ? 0 : zone.getLastMemberChannel() - 1;
  325. Rectangle<int> zoneRect { int (channelWidth * (float) xPos), 20,
  326. int (channelWidth * (float) (zone.numMemberChannels + 1)), getHeight() - 20 };
  327. g.setColour (zoneColour);
  328. g.drawRect (zoneRect, 3);
  329. auto masterRect = zone.isLowerZone() ? zoneRect.removeFromLeft ((int) channelWidth) : zoneRect.removeFromRight ((int) channelWidth);
  330. g.setColour (zoneColour.withAlpha (0.3f));
  331. g.fillRect (masterRect);
  332. g.setColour (zoneColour.contrasting());
  333. g.drawText ("<>" + String (zone.masterPitchbendRange), masterRect.reduced (4), Justification::top, false);
  334. g.drawText ("<>" + String (zone.perNotePitchbendRange), masterRect.reduced (4), Justification::bottom, false);
  335. }
  336. }
  337. //==============================================================================
  338. void paintLegacyMode (Graphics& g)
  339. {
  340. auto channelRange = instrument.getLegacyModeChannelRange();
  341. auto startChannel = channelRange.getStart() - 1;
  342. auto numChannels = channelRange.getEnd() - startChannel - 1;
  343. Rectangle<int> zoneRect (int (getChannelRectangleWidth() * (float) startChannel), 0,
  344. int (getChannelRectangleWidth() * (float) numChannels), getHeight());
  345. zoneRect.removeFromTop (20);
  346. g.setColour (Colours::white);
  347. g.drawRect (zoneRect, 3);
  348. g.drawText ("LGCY", zoneRect.reduced (4, 4), Justification::topLeft, false);
  349. g.drawText ("<>" + String (instrument.getLegacyModePitchbendRange()), zoneRect.reduced (4, 4), Justification::bottomLeft, false);
  350. }
  351. //==============================================================================
  352. float getChannelRectangleWidth() const noexcept
  353. {
  354. return (float) getWidth() / (float) numMidiChannels;
  355. }
  356. //==============================================================================
  357. static constexpr int numMidiChannels = 16;
  358. MPEInstrument& instrument;
  359. ZoneColourPicker& colourPicker;
  360. };
  361. //==============================================================================
  362. class MPEDemoSynthVoice final : public MPESynthesiserVoice
  363. {
  364. public:
  365. //==============================================================================
  366. MPEDemoSynthVoice() {}
  367. //==============================================================================
  368. void noteStarted() override
  369. {
  370. jassert (currentlyPlayingNote.isValid());
  371. jassert (currentlyPlayingNote.keyState == MPENote::keyDown
  372. || currentlyPlayingNote.keyState == MPENote::keyDownAndSustained);
  373. level .setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  374. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  375. timbre .setTargetValue (currentlyPlayingNote.timbre.asUnsignedFloat());
  376. phase = 0.0;
  377. auto cyclesPerSample = frequency.getNextValue() / currentSampleRate;
  378. phaseDelta = MathConstants<double>::twoPi * cyclesPerSample;
  379. tailOff = 0.0;
  380. }
  381. void noteStopped (bool allowTailOff) override
  382. {
  383. jassert (currentlyPlayingNote.keyState == MPENote::off);
  384. if (allowTailOff)
  385. {
  386. // start a tail-off by setting this flag. The render callback will pick up on
  387. // this and do a fade out, calling clearCurrentNote() when it's finished.
  388. if (approximatelyEqual (tailOff, 0.0)) // we only need to begin a tail-off if it's not already doing so - the
  389. // stopNote method could be called more than once.
  390. tailOff = 1.0;
  391. }
  392. else
  393. {
  394. // we're being told to stop playing immediately, so reset everything..
  395. clearCurrentNote();
  396. phaseDelta = 0.0;
  397. }
  398. }
  399. void notePressureChanged() override
  400. {
  401. level.setTargetValue (currentlyPlayingNote.pressure.asUnsignedFloat());
  402. }
  403. void notePitchbendChanged() override
  404. {
  405. frequency.setTargetValue (currentlyPlayingNote.getFrequencyInHertz());
  406. }
  407. void noteTimbreChanged() override
  408. {
  409. timbre.setTargetValue (currentlyPlayingNote.timbre.asUnsignedFloat());
  410. }
  411. void noteKeyStateChanged() override {}
  412. void setCurrentSampleRate (double newRate) override
  413. {
  414. if (! approximatelyEqual (currentSampleRate, newRate))
  415. {
  416. noteStopped (false);
  417. currentSampleRate = newRate;
  418. level .reset (currentSampleRate, smoothingLengthInSeconds);
  419. timbre .reset (currentSampleRate, smoothingLengthInSeconds);
  420. frequency.reset (currentSampleRate, smoothingLengthInSeconds);
  421. }
  422. }
  423. //==============================================================================
  424. virtual void renderNextBlock (AudioBuffer<float>& outputBuffer,
  425. int startSample,
  426. int numSamples) override
  427. {
  428. if (! approximatelyEqual (phaseDelta, 0.0))
  429. {
  430. if (tailOff > 0.0)
  431. {
  432. while (--numSamples >= 0)
  433. {
  434. auto currentSample = getNextSample() * (float) tailOff;
  435. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  436. outputBuffer.addSample (i, startSample, currentSample);
  437. ++startSample;
  438. tailOff *= 0.99;
  439. if (tailOff <= 0.005)
  440. {
  441. clearCurrentNote();
  442. phaseDelta = 0.0;
  443. break;
  444. }
  445. }
  446. }
  447. else
  448. {
  449. while (--numSamples >= 0)
  450. {
  451. auto currentSample = getNextSample();
  452. for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
  453. outputBuffer.addSample (i, startSample, currentSample);
  454. ++startSample;
  455. }
  456. }
  457. }
  458. }
  459. using MPESynthesiserVoice::renderNextBlock;
  460. private:
  461. //==============================================================================
  462. float getNextSample() noexcept
  463. {
  464. auto levelDb = (level.getNextValue() - 1.0) * maxLevelDb;
  465. auto amplitude = pow (10.0f, 0.05f * levelDb) * maxLevel;
  466. // timbre is used to blend between a sine and a square.
  467. auto f1 = std::sin (phase);
  468. auto f2 = copysign (1.0, f1);
  469. auto a2 = timbre.getNextValue();
  470. auto a1 = 1.0 - a2;
  471. auto nextSample = float (amplitude * ((a1 * f1) + (a2 * f2)));
  472. auto cyclesPerSample = frequency.getNextValue() / currentSampleRate;
  473. phaseDelta = MathConstants<double>::twoPi * cyclesPerSample;
  474. phase = std::fmod (phase + phaseDelta, MathConstants<double>::twoPi);
  475. return nextSample;
  476. }
  477. //==============================================================================
  478. SmoothedValue<double> level, timbre, frequency;
  479. double phase = 0.0;
  480. double phaseDelta = 0.0;
  481. double tailOff = 0.0;
  482. const double maxLevel = 0.05;
  483. const double maxLevelDb = 31.0;
  484. const double smoothingLengthInSeconds = 0.01;
  485. };
  486. //==============================================================================
  487. class MPEDemo final : public Component,
  488. private AudioIODeviceCallback,
  489. private MidiInputCallback,
  490. private MPEInstrument::Listener
  491. {
  492. public:
  493. //==============================================================================
  494. MPEDemo()
  495. {
  496. #ifndef JUCE_DEMO_RUNNER
  497. audioDeviceManager.initialise (0, 2, nullptr, true, {}, nullptr);
  498. #endif
  499. audioDeviceManager.addMidiInputDeviceCallback ({}, this);
  500. audioDeviceManager.addAudioCallback (this);
  501. addAndMakeVisible (audioSetupComp);
  502. addAndMakeVisible (mpeSetupComp);
  503. addAndMakeVisible (zoneLayoutComp);
  504. addAndMakeVisible (keyboardComponent);
  505. synth.setVoiceStealingEnabled (false);
  506. for (auto i = 0; i < 15; ++i)
  507. synth.addVoice (new MPEDemoSynthVoice());
  508. mpeSetupComp.onSynthParametersChange = [this]
  509. {
  510. synth.setVoiceStealingEnabled (mpeSetupComp.isVoiceStealingEnabled());
  511. auto numVoices = mpeSetupComp.getNumVoices();
  512. if (numVoices < synth.getNumVoices())
  513. {
  514. synth.reduceNumVoices (numVoices);
  515. }
  516. else
  517. {
  518. while (synth.getNumVoices() < numVoices)
  519. synth.addVoice (new MPEDemoSynthVoice());
  520. }
  521. };
  522. instrument.addListener (this);
  523. setSize (880, 720);
  524. }
  525. ~MPEDemo() override
  526. {
  527. audioDeviceManager.removeMidiInputDeviceCallback ({}, this);
  528. audioDeviceManager.removeAudioCallback (this);
  529. }
  530. //==============================================================================
  531. void resized() override
  532. {
  533. auto zoneLayoutCompHeight = 60;
  534. auto audioSetupCompRelativeWidth = 0.55f;
  535. auto r = getLocalBounds();
  536. keyboardComponent.setBounds (r.removeFromBottom (150));
  537. r.reduce (10, 10);
  538. zoneLayoutComp.setBounds (r.removeFromBottom (zoneLayoutCompHeight));
  539. audioSetupComp.setBounds (r.removeFromLeft (proportionOfWidth (audioSetupCompRelativeWidth)));
  540. mpeSetupComp .setBounds (r);
  541. }
  542. //==============================================================================
  543. void audioDeviceIOCallbackWithContext (const float* const* inputChannelData, int numInputChannels,
  544. float* const* outputChannelData, int numOutputChannels,
  545. int numSamples, const AudioIODeviceCallbackContext& context) override
  546. {
  547. ignoreUnused (inputChannelData, numInputChannels, context);
  548. AudioBuffer<float> buffer (outputChannelData, numOutputChannels, numSamples);
  549. buffer.clear();
  550. MidiBuffer incomingMidi;
  551. midiCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  552. synth.renderNextBlock (buffer, incomingMidi, 0, numSamples);
  553. }
  554. void audioDeviceAboutToStart (AudioIODevice* device) override
  555. {
  556. auto sampleRate = device->getCurrentSampleRate();
  557. midiCollector.reset (sampleRate);
  558. synth.setCurrentPlaybackSampleRate (sampleRate);
  559. }
  560. void audioDeviceStopped() override {}
  561. private:
  562. //==============================================================================
  563. void handleIncomingMidiMessage (MidiInput* /*source*/,
  564. const MidiMessage& message) override
  565. {
  566. instrument.processNextMidiEvent (message);
  567. midiCollector.addMessageToQueue (message);
  568. }
  569. //==============================================================================
  570. void zoneLayoutChanged() override
  571. {
  572. if (instrument.isLegacyModeEnabled())
  573. {
  574. colourPicker.setLegacyModeEnabled (true);
  575. synth.enableLegacyMode (instrument.getLegacyModePitchbendRange(),
  576. instrument.getLegacyModeChannelRange());
  577. }
  578. else
  579. {
  580. colourPicker.setLegacyModeEnabled (false);
  581. auto zoneLayout = instrument.getZoneLayout();
  582. if (auto* midiOutput = audioDeviceManager.getDefaultMidiOutput())
  583. midiOutput->sendBlockOfMessagesNow (MPEMessages::setZoneLayout (zoneLayout));
  584. synth.setZoneLayout (zoneLayout);
  585. colourPicker.setZoneLayout (zoneLayout);
  586. }
  587. }
  588. //==============================================================================
  589. // if this PIP is running inside the demo runner, we'll use the shared device manager instead
  590. #ifndef JUCE_DEMO_RUNNER
  591. AudioDeviceManager audioDeviceManager;
  592. #else
  593. AudioDeviceManager& audioDeviceManager { getSharedAudioDeviceManager (0, 2) };
  594. #endif
  595. AudioDeviceSelectorComponent audioSetupComp { audioDeviceManager, 0, 0, 0, 256, true, true, true, false };
  596. MidiMessageCollector midiCollector;
  597. MPEInstrument instrument { MPEZone (MPEZone::Type::lower, 15) };
  598. ZoneColourPicker colourPicker;
  599. MPESetupComponent mpeSetupComp { instrument };
  600. ZoneLayoutComponent zoneLayoutComp { instrument, colourPicker};
  601. MPESynthesiser synth { instrument };
  602. MPEKeyboardComponent keyboardComponent { instrument, MPEKeyboardComponent::horizontalKeyboard };
  603. //==============================================================================
  604. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPEDemo)
  605. };