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.

377 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. #pragma once
  18. //==============================================================================
  19. /*
  20. This class represents an instrument handling MPE.
  21. It has an MPE zone layout and maintans a state of currently
  22. active (playing) notes and the values of their dimensions of expression.
  23. You can trigger and modulate notes:
  24. - by passing MIDI messages with the method processNextMidiEvent;
  25. - by directly calling the methods noteOn, noteOff etc.
  26. The class implements the channel and note management logic specified in
  27. MPE. If you pass it a message, it will know what notes on what
  28. channels (if any) should be affected by that message.
  29. The class has a Listener class with the three callbacks MPENoteAdded,
  30. MPENoteChanged, and MPENoteFinished. Implement such a
  31. Listener class to react to note changes and trigger some functionality for
  32. your application that depends on the MPE note state.
  33. For example, you can use this class to write an MPE visualiser.
  34. If you want to write a real-time audio synth with MPE functionality,
  35. you should instead use the classes MPESynthesiserBase, which adds
  36. the ability to render audio and to manage voices.
  37. @see MPENote, MPEZoneLayout, MPESynthesiser
  38. */
  39. class JUCE_API MPEInstrument
  40. {
  41. public:
  42. /** Constructor.
  43. This will construct an MPE instrument with initially no MPE zones.
  44. In order to process incoming MIDI, call setZoneLayout, define the layout
  45. via MIDI RPN messages, or set the instrument to legacy mode.
  46. */
  47. MPEInstrument() noexcept;
  48. /** Destructor. */
  49. virtual ~MPEInstrument();
  50. //==============================================================================
  51. /** Returns the current zone layout of the instrument.
  52. This happens by value, to enforce thread-safety and class invariants.
  53. Note: If the instrument is in legacy mode, the return value of this
  54. method is unspecified.
  55. */
  56. MPEZoneLayout getZoneLayout() const noexcept;
  57. /** Re-sets the zone layout of the instrument to the one passed in.
  58. As a side effect, this will discard all currently playing notes,
  59. and call noteReleased for all of them.
  60. This will also disable legacy mode in case it was enabled previously.
  61. */
  62. void setZoneLayout (MPEZoneLayout newLayout);
  63. /** Returns true if the given MIDI channel (1-16) is a note channel in any
  64. of the MPEInstrument's MPE zones; false otherwise.
  65. When in legacy mode, this will return true if the given channel is
  66. contained in the current legacy mode channel range; false otherwise.
  67. */
  68. bool isNoteChannel (int midiChannel) const noexcept;
  69. /** Returns true if the given MIDI channel (1-16) is a master channel in any
  70. of the MPEInstrument's MPE zones; false otherwise.
  71. When in legacy mode, this will always return false.
  72. */
  73. bool isMasterChannel (int midiChannel) const noexcept;
  74. //==============================================================================
  75. /** The MPE note tracking mode. In case there is more than one note playing
  76. simultaneously on the same MIDI channel, this determines which of these
  77. notes will be modulated by an incoming MPE message on that channel
  78. (pressure, pitchbend, or timbre).
  79. The default is lastNotePlayedOnChannel.
  80. */
  81. enum TrackingMode
  82. {
  83. lastNotePlayedOnChannel, //! The most recent note on the channel that is still played (key down and/or sustained)
  84. lowestNoteOnChannel, //! The lowest note (by initialNote) on the channel with the note key still down
  85. highestNoteOnChannel, //! The highest note (by initialNote) on the channel with the note key still down
  86. allNotesOnChannel //! All notes on the channel (key down and/or sustained)
  87. };
  88. /** Set the MPE tracking mode for the pressure dimension. */
  89. void setPressureTrackingMode (TrackingMode modeToUse);
  90. /** Set the MPE tracking mode for the pitchbend dimension. */
  91. void setPitchbendTrackingMode (TrackingMode modeToUse);
  92. /** Set the MPE tracking mode for the timbre dimension. */
  93. void setTimbreTrackingMode (TrackingMode modeToUse);
  94. //==============================================================================
  95. /** Process a MIDI message and trigger the appropriate method calls
  96. (noteOn, noteOff etc.)
  97. You can override this method if you need some special MIDI message
  98. treatment on top of the standard MPE logic implemented here.
  99. */
  100. virtual void processNextMidiEvent (const MidiMessage& message);
  101. //==============================================================================
  102. /** Request a note-on on the given channel, with the given initial note
  103. number and velocity.
  104. If the message arrives on a valid note channel, this will create a
  105. new MPENote and call the noteAdded callback.
  106. */
  107. virtual void noteOn (int midiChannel, int midiNoteNumber, MPEValue midiNoteOnVelocity);
  108. /** Request a note-off. If there is a matching playing note, this will
  109. release the note (except if it is sustained by a sustain or sostenuto
  110. pedal) and call the noteReleased callback.
  111. */
  112. virtual void noteOff (int midiChannel, int midiNoteNumber, MPEValue midiNoteOffVelocity);
  113. /** Request a pitchbend on the given channel with the given value (in units
  114. of MIDI pitchwheel position).
  115. Internally, this will determine whether the pitchwheel move is a
  116. per-note pitchbend or a master pitchbend (depending on midiChannel),
  117. take the correct per-note or master pitchbend range of the affected MPE
  118. zone, and apply the resulting pitchbend to the affected note(s) (if any).
  119. */
  120. virtual void pitchbend (int midiChannel, MPEValue pitchbend);
  121. /** Request a pressure change on the given channel with the given value.
  122. This will modify the pressure dimension of the note currently held down
  123. on this channel (if any). If the channel is a zone master channel,
  124. the pressure change will be broadcast to all notes in this zone.
  125. */
  126. virtual void pressure (int midiChannel, MPEValue value);
  127. /** Request a third dimension (timbre) change on the given channel with the
  128. given value.
  129. This will modify the timbre dimension of the note currently held down
  130. on this channel (if any). If the channel is a zone master channel,
  131. the timbre change will be broadcast to all notes in this zone.
  132. */
  133. virtual void timbre (int midiChannel, MPEValue value);
  134. /** Request a sustain pedal press or release. If midiChannel is a zone's
  135. master channel, this will act on all notes in that zone; otherwise,
  136. nothing will happen.
  137. */
  138. virtual void sustainPedal (int midiChannel, bool isDown);
  139. /** Request a sostenuto pedal press or release. If midiChannel is a zone's
  140. master channel, this will act on all notes in that zone; otherwise,
  141. nothing will happen.
  142. */
  143. virtual void sostenutoPedal (int midiChannel, bool isDown);
  144. /** Discard all currently playing notes.
  145. This will also call the noteReleased listener callback for all of them.
  146. */
  147. void releaseAllNotes();
  148. //==============================================================================
  149. /** Returns the number of MPE notes currently played by the
  150. instrument.
  151. */
  152. int getNumPlayingNotes() const noexcept;
  153. /** Returns the note at the given index. If there is no such note, returns
  154. an invalid MPENote. The notes are sorted such that the most recently
  155. added note is the last element.
  156. */
  157. MPENote getNote (int index) const noexcept;
  158. /** Returns the note currently playing on the given midiChannel with the
  159. specified initial MIDI note number, if there is such a note.
  160. Otherwise, this returns an invalid MPENote
  161. (check with note.isValid() before use!)
  162. */
  163. MPENote getNote (int midiChannel, int midiNoteNumber) const noexcept;
  164. /** Returns the most recent note that is playing on the given midiChannel
  165. (this will be the note which has received the most recent note-on without
  166. a corresponding note-off), if there is such a note.
  167. Otherwise, this returns an invalid MPENote
  168. (check with note.isValid() before use!)
  169. */
  170. MPENote getMostRecentNote (int midiChannel) const noexcept;
  171. /** Returns the most recent note that is not the note passed in.
  172. If there is no such note, this returns an invalid MPENote
  173. (check with note.isValid() before use!)
  174. This helper method might be useful for some custom voice handling algorithms.
  175. */
  176. MPENote getMostRecentNoteOtherThan (MPENote otherThanThisNote) const noexcept;
  177. //==============================================================================
  178. /** Derive from this class to be informed about any changes in the expressive
  179. MIDI notes played by this instrument.
  180. Note: This listener type receives its callbacks immediately, and not
  181. via the message thread (so you might be for example in the MIDI thread).
  182. Therefore you should never do heavy work such as graphics rendering etc.
  183. inside those callbacks.
  184. */
  185. class JUCE_API Listener
  186. {
  187. public:
  188. /** Destructor. */
  189. virtual ~Listener() {}
  190. /** Implement this callback to be informed whenever a new expressive
  191. MIDI note is triggered.
  192. */
  193. virtual void noteAdded (MPENote newNote) = 0;
  194. /** Implement this callback to be informed whenever a currently
  195. playing MPE note's pressure value changes.
  196. */
  197. virtual void notePressureChanged (MPENote changedNote) = 0;
  198. /** Implement this callback to be informed whenever a currently
  199. playing MPE note's pitchbend value changes.
  200. Note: This can happen if the note itself is bent, if there is a
  201. master channel pitchbend event, or if both occur simultaneously.
  202. Call MPENote::getFrequencyInHertz to get the effective note frequency.
  203. */
  204. virtual void notePitchbendChanged (MPENote changedNote) = 0;
  205. /** Implement this callback to be informed whenever a currently
  206. playing MPE note's timbre value changes.
  207. */
  208. virtual void noteTimbreChanged (MPENote changedNote) = 0;
  209. /** Implement this callback to be informed whether a currently playing
  210. MPE note's key state (whether the key is down and/or the note is
  211. sustained) has changed.
  212. Note: if the key state changes to MPENote::off, noteReleased is
  213. called instead.
  214. */
  215. virtual void noteKeyStateChanged (MPENote changedNote) = 0;
  216. /** Implement this callback to be informed whenever an MPE note
  217. is released (either by a note-off message, or by a sustain/sostenuto
  218. pedal release for a note that already received a note-off),
  219. and should therefore stop playing.
  220. */
  221. virtual void noteReleased (MPENote finishedNote) = 0;
  222. };
  223. //==============================================================================
  224. /** Adds a listener. */
  225. void addListener (Listener* listenerToAdd) noexcept;
  226. /** Removes a listener. */
  227. void removeListener (Listener* listenerToRemove) noexcept;
  228. //==============================================================================
  229. /** Puts the instrument into legacy mode.
  230. As a side effect, this will discard all currently playing notes,
  231. and call noteReleased for all of them.
  232. This special zone layout mode is for backwards compatibility with
  233. non-MPE MIDI devices. In this mode, the instrument will ignore the
  234. current MPE zone layout. It will instead take a range of MIDI channels
  235. (default: all channels 1-16) and treat them as note channels, with no
  236. master channel. MIDI channels outside of this range will be ignored.
  237. @param pitchbendRange The note pitchbend range in semitones to use when in legacy mode.
  238. Must be between 0 and 96, otherwise behaviour is undefined.
  239. The default pitchbend range in legacy mode is +/- 2 semitones.
  240. @param channelRange The range of MIDI channels to use for notes when in legacy mode.
  241. The default is to use all MIDI channels (1-16).
  242. To get out of legacy mode, set a new MPE zone layout using setZoneLayout.
  243. */
  244. void enableLegacyMode (int pitchbendRange = 2,
  245. Range<int> channelRange = Range<int> (1, 17));
  246. /** Returns true if the instrument is in legacy mode, false otherwise. */
  247. bool isLegacyModeEnabled() const noexcept;
  248. /** Returns the range of MIDI channels (1-16) to be used for notes when in legacy mode. */
  249. Range<int> getLegacyModeChannelRange() const noexcept;
  250. /** Re-sets the range of MIDI channels (1-16) to be used for notes when in legacy mode. */
  251. void setLegacyModeChannelRange (Range<int> channelRange);
  252. /** Returns the pitchbend range in semitones (0-96) to be used for notes when in legacy mode. */
  253. int getLegacyModePitchbendRange() const noexcept;
  254. /** Re-sets the pitchbend range in semitones (0-96) to be used for notes when in legacy mode. */
  255. void setLegacyModePitchbendRange (int pitchbendRange);
  256. private:
  257. //==============================================================================
  258. CriticalSection lock;
  259. Array<MPENote> notes;
  260. MPEZoneLayout zoneLayout;
  261. ListenerList<Listener> listeners;
  262. uint8 lastPressureLowerBitReceivedOnChannel[16];
  263. uint8 lastTimbreLowerBitReceivedOnChannel[16];
  264. bool isNoteChannelSustained[16];
  265. struct LegacyMode
  266. {
  267. bool isEnabled;
  268. Range<int> channelRange;
  269. int pitchbendRange;
  270. };
  271. struct MPEDimension
  272. {
  273. MPEDimension() noexcept : trackingMode (lastNotePlayedOnChannel) {}
  274. TrackingMode trackingMode;
  275. MPEValue lastValueReceivedOnChannel[16];
  276. MPEValue MPENote::* value;
  277. MPEValue& getValue (MPENote& note) noexcept { return note.*(value); }
  278. };
  279. LegacyMode legacyMode;
  280. MPEDimension pitchbendDimension, pressureDimension, timbreDimension;
  281. void updateDimension (int midiChannel, MPEDimension&, MPEValue);
  282. void updateDimensionMaster (MPEZone&, MPEDimension&, MPEValue);
  283. void updateDimensionForNote (MPENote&, MPEDimension&, MPEValue);
  284. void callListenersDimensionChanged (MPENote&, MPEDimension&);
  285. MPEValue getInitialValueForNewNote (int midiChannel, MPEDimension&) const;
  286. void processMidiNoteOnMessage (const MidiMessage&);
  287. void processMidiNoteOffMessage (const MidiMessage&);
  288. void processMidiPitchWheelMessage (const MidiMessage&);
  289. void processMidiChannelPressureMessage (const MidiMessage&);
  290. void processMidiControllerMessage (const MidiMessage&);
  291. void processMidiAllNotesOffMessage (const MidiMessage&);
  292. void handlePressureMSB (int midiChannel, int value) noexcept;
  293. void handlePressureLSB (int midiChannel, int value) noexcept;
  294. void handleTimbreMSB (int midiChannel, int value) noexcept;
  295. void handleTimbreLSB (int midiChannel, int value) noexcept;
  296. void handleSustainOrSostenuto (int midiChannel, bool isDown, bool isSostenuto);
  297. MPENote* getNotePtr (int midiChannel, int midiNoteNumber) const noexcept;
  298. MPENote* getNotePtr (int midiChannel, TrackingMode) const noexcept;
  299. MPENote* getLastNotePlayedPtr (int midiChannel) const noexcept;
  300. MPENote* getHighestNotePtr (int midiChannel) const noexcept;
  301. MPENote* getLowestNotePtr (int midiChannel) const noexcept;
  302. void updateNoteTotalPitchbend (MPENote&);
  303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MPEInstrument)
  304. };