Audio plugin host https://kx.studio/carla
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.

383 lines
17KB

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