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.

495 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  19. #define __JUCE_SYNTHESISER_JUCEHEADER__
  20. #include "../buffers/juce_AudioSampleBuffer.h"
  21. #include "../midi/juce_MidiBuffer.h"
  22. //==============================================================================
  23. /**
  24. Describes one of the sounds that a Synthesiser can play.
  25. A synthesiser can contain one or more sounds, and a sound can choose which
  26. midi notes and channels can trigger it.
  27. The SynthesiserSound is a passive class that just describes what the sound is -
  28. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  29. more than one SynthesiserVoice to play the same sound at the same time.
  30. @see Synthesiser, SynthesiserVoice
  31. */
  32. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  33. {
  34. protected:
  35. //==============================================================================
  36. SynthesiserSound();
  37. public:
  38. /** Destructor. */
  39. virtual ~SynthesiserSound();
  40. //==============================================================================
  41. /** Returns true if this sound should be played when a given midi note is pressed.
  42. The Synthesiser will use this information when deciding which sounds to trigger
  43. for a given note.
  44. */
  45. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  46. /** Returns true if the sound should be triggered by midi events on a given channel.
  47. The Synthesiser will use this information when deciding which sounds to trigger
  48. for a given note.
  49. */
  50. virtual bool appliesToChannel (const int midiChannel) = 0;
  51. /**
  52. */
  53. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  54. private:
  55. //==============================================================================
  56. JUCE_LEAK_DETECTOR (SynthesiserSound);
  57. };
  58. //==============================================================================
  59. /**
  60. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  61. A voice plays a single sound at a time, and a synthesiser holds an array of
  62. voices so that it can play polyphonically.
  63. @see Synthesiser, SynthesiserSound
  64. */
  65. class JUCE_API SynthesiserVoice
  66. {
  67. public:
  68. //==============================================================================
  69. /** Creates a voice. */
  70. SynthesiserVoice();
  71. /** Destructor. */
  72. virtual ~SynthesiserVoice();
  73. //==============================================================================
  74. /** Returns the midi note that this voice is currently playing.
  75. Returns a value less than 0 if no note is playing.
  76. */
  77. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  78. /** Returns the sound that this voice is currently playing.
  79. Returns 0 if it's not playing.
  80. */
  81. SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  82. /** Must return true if this voice object is capable of playing the given sound.
  83. If there are different classes of sound, and different classes of voice, a voice can
  84. choose which ones it wants to take on.
  85. A typical implementation of this method may just return true if there's only one type
  86. of voice and sound, or it might check the type of the sound object passed-in and
  87. see if it's one that it understands.
  88. */
  89. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  90. /** Called to start a new note.
  91. This will be called during the rendering callback, so must be fast and thread-safe.
  92. */
  93. virtual void startNote (const int midiNoteNumber,
  94. const float velocity,
  95. SynthesiserSound* sound,
  96. const int currentPitchWheelPosition) = 0;
  97. /** Called to stop a note.
  98. This will be called during the rendering callback, so must be fast and thread-safe.
  99. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  100. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  101. and allow the synth to reassign it another sound.
  102. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  103. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  104. finishes playing (during the rendering callback), it must make sure that it calls
  105. clearCurrentNote().
  106. */
  107. virtual void stopNote (const bool allowTailOff) = 0;
  108. /** Called to let the voice know that the pitch wheel has been moved.
  109. This will be called during the rendering callback, so must be fast and thread-safe.
  110. */
  111. virtual void pitchWheelMoved (const int newValue) = 0;
  112. /** Called to let the voice know that a midi controller has been moved.
  113. This will be called during the rendering callback, so must be fast and thread-safe.
  114. */
  115. virtual void controllerMoved (const int controllerNumber,
  116. const int newValue) = 0;
  117. //==============================================================================
  118. /** Renders the next block of data for this voice.
  119. The output audio data must be added to the current contents of the buffer provided.
  120. Only the region of the buffer between startSample and (startSample + numSamples)
  121. should be altered by this method.
  122. If the voice is currently silent, it should just return without doing anything.
  123. If the sound that the voice is playing finishes during the course of this rendered
  124. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  125. The size of the blocks that are rendered can change each time it is called, and may
  126. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  127. the voice's methods will be called to tell it about note and controller events.
  128. */
  129. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  130. int startSample,
  131. int numSamples) = 0;
  132. /** Returns true if the voice is currently playing a sound which is mapped to the given
  133. midi channel.
  134. If it's not currently playing, this will return false.
  135. */
  136. bool isPlayingChannel (int midiChannel) const;
  137. /** Changes the voice's reference sample rate.
  138. The rate is set so that subclasses know the output rate and can set their pitch
  139. accordingly.
  140. This method is called by the synth, and subclasses can access the current rate with
  141. the currentSampleRate member.
  142. */
  143. void setCurrentPlaybackSampleRate (double newRate);
  144. protected:
  145. //==============================================================================
  146. /** Returns the current target sample rate at which rendering is being done.
  147. This is available for subclasses so they can pitch things correctly.
  148. */
  149. double getSampleRate() const { return currentSampleRate; }
  150. /** Resets the state of this voice after a sound has finished playing.
  151. The subclass must call this when it finishes playing a note and becomes available
  152. to play new ones.
  153. It must either call it in the stopNote() method, or if the voice is tailing off,
  154. then it should call it later during the renderNextBlock method, as soon as it
  155. finishes its tail-off.
  156. It can also be called at any time during the render callback if the sound happens
  157. to have finished, e.g. if it's playing a sample and the sample finishes.
  158. */
  159. void clearCurrentNote();
  160. private:
  161. //==============================================================================
  162. friend class Synthesiser;
  163. double currentSampleRate;
  164. int currentlyPlayingNote;
  165. uint32 noteOnTime;
  166. SynthesiserSound::Ptr currentlyPlayingSound;
  167. bool keyIsDown; // the voice may still be playing when the key is not down (i.e. sustain pedal)
  168. bool sostenutoPedalDown;
  169. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  170. };
  171. //==============================================================================
  172. /**
  173. Base class for a musical device that can play sounds.
  174. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  175. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  176. which can play back one of these sounds.
  177. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  178. set of sounds, and a set of voices it can use to play them. If you only give it
  179. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  180. have available.
  181. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  182. events that go in will be scanned for note on/off messages, and these are used to
  183. start and stop the voices playing the appropriate sounds.
  184. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  185. noteOff() and other controller methods.
  186. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  187. what the target playback rate is. This value is passed on to the voices so that
  188. they can pitch their output correctly.
  189. */
  190. class JUCE_API Synthesiser
  191. {
  192. public:
  193. //==============================================================================
  194. /** Creates a new synthesiser.
  195. You'll need to add some sounds and voices before it'll make any sound..
  196. */
  197. Synthesiser();
  198. /** Destructor. */
  199. virtual ~Synthesiser();
  200. //==============================================================================
  201. /** Deletes all voices. */
  202. void clearVoices();
  203. /** Returns the number of voices that have been added. */
  204. int getNumVoices() const { return voices.size(); }
  205. /** Returns one of the voices that have been added. */
  206. SynthesiserVoice* getVoice (int index) const;
  207. /** Adds a new voice to the synth.
  208. All the voices should be the same class of object and are treated equally.
  209. The object passed in will be managed by the synthesiser, which will delete
  210. it later on when no longer needed. The caller should not retain a pointer to the
  211. voice.
  212. */
  213. void addVoice (SynthesiserVoice* newVoice);
  214. /** Deletes one of the voices. */
  215. void removeVoice (int index);
  216. //==============================================================================
  217. /** Deletes all sounds. */
  218. void clearSounds();
  219. /** Returns the number of sounds that have been added to the synth. */
  220. int getNumSounds() const { return sounds.size(); }
  221. /** Returns one of the sounds. */
  222. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  223. /** Adds a new sound to the synthesiser.
  224. The object passed in is reference counted, so will be deleted when it is removed
  225. from the synthesiser, and when no voices are still using it.
  226. */
  227. void addSound (const SynthesiserSound::Ptr& newSound);
  228. /** Removes and deletes one of the sounds. */
  229. void removeSound (int index);
  230. //==============================================================================
  231. /** If set to true, then the synth will try to take over an existing voice if
  232. it runs out and needs to play another note.
  233. The value of this boolean is passed into findFreeVoice(), so the result will
  234. depend on the implementation of this method.
  235. */
  236. void setNoteStealingEnabled (bool shouldStealNotes);
  237. /** Returns true if note-stealing is enabled.
  238. @see setNoteStealingEnabled
  239. */
  240. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  241. //==============================================================================
  242. /** Triggers a note-on event.
  243. The default method here will find all the sounds that want to be triggered by
  244. this note/channel. For each sound, it'll try to find a free voice, and use the
  245. voice to start playing the sound.
  246. Subclasses might want to override this if they need a more complex algorithm.
  247. This method will be called automatically according to the midi data passed into
  248. renderNextBlock(), but may be called explicitly too.
  249. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  250. */
  251. virtual void noteOn (int midiChannel,
  252. int midiNoteNumber,
  253. float velocity);
  254. /** Triggers a note-off event.
  255. This will turn off any voices that are playing a sound for the given note/channel.
  256. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  257. (if they can do). If this is false, the notes will all be cut off immediately.
  258. This method will be called automatically according to the midi data passed into
  259. renderNextBlock(), but may be called explicitly too.
  260. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  261. */
  262. virtual void noteOff (int midiChannel,
  263. int midiNoteNumber,
  264. bool allowTailOff);
  265. /** Turns off all notes.
  266. This will turn off any voices that are playing a sound on the given midi channel.
  267. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  268. which channel they're playing. Otherwise it represents a valid midi channel, from
  269. 1 to 16 inclusive.
  270. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  271. (if they can do). If this is false, the notes will all be cut off immediately.
  272. This method will be called automatically according to the midi data passed into
  273. renderNextBlock(), but may be called explicitly too.
  274. */
  275. virtual void allNotesOff (int midiChannel,
  276. bool allowTailOff);
  277. /** Sends a pitch-wheel message.
  278. This will send a pitch-wheel message to any voices that are playing sounds on
  279. the given midi channel.
  280. This method will be called automatically according to the midi data passed into
  281. renderNextBlock(), but may be called explicitly too.
  282. @param midiChannel the midi channel, from 1 to 16 inclusive
  283. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  284. */
  285. virtual void handlePitchWheel (int midiChannel,
  286. int wheelValue);
  287. /** Sends a midi controller message.
  288. This will send a midi controller message to any voices that are playing sounds on
  289. the given midi channel.
  290. This method will be called automatically according to the midi data passed into
  291. renderNextBlock(), but may be called explicitly too.
  292. @param midiChannel the midi channel, from 1 to 16 inclusive
  293. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  294. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  295. */
  296. virtual void handleController (int midiChannel,
  297. int controllerNumber,
  298. int controllerValue);
  299. virtual void handleSustainPedal (int midiChannel, bool isDown);
  300. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  301. virtual void handleSoftPedal (int midiChannel, bool isDown);
  302. //==============================================================================
  303. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  304. render.
  305. This value is propagated to the voices so that they can use it to render the correct
  306. pitches.
  307. */
  308. void setCurrentPlaybackSampleRate (double sampleRate);
  309. /** Creates the next block of audio output.
  310. This will process the next numSamples of data from all the voices, and add that output
  311. to the audio block supplied, starting from the offset specified. Note that the
  312. data will be added to the current contents of the buffer, so you should clear it
  313. before calling this method if necessary.
  314. The midi events in the inputMidi buffer are parsed for note and controller events,
  315. and these are used to trigger the voices. Note that the startSample offset applies
  316. both to the audio output buffer and the midi input buffer, so any midi events
  317. with timestamps outside the specified region will be ignored.
  318. */
  319. void renderNextBlock (AudioSampleBuffer& outputAudio,
  320. const MidiBuffer& inputMidi,
  321. int startSample,
  322. int numSamples);
  323. protected:
  324. //==============================================================================
  325. /** This is used to control access to the rendering callback and the note trigger methods. */
  326. CriticalSection lock;
  327. OwnedArray <SynthesiserVoice> voices;
  328. ReferenceCountedArray <SynthesiserSound> sounds;
  329. /** The last pitch-wheel values for each midi channel. */
  330. int lastPitchWheelValues [16];
  331. /** Searches through the voices to find one that's not currently playing, and which
  332. can play the given sound.
  333. Returns 0 if all voices are busy and stealing isn't enabled.
  334. This can be overridden to implement custom voice-stealing algorithms.
  335. */
  336. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  337. const bool stealIfNoneAvailable) const;
  338. /** Starts a specified voice playing a particular sound.
  339. You'll probably never need to call this, it's used internally by noteOn(), but
  340. may be needed by subclasses for custom behaviours.
  341. */
  342. void startVoice (SynthesiserVoice* voice,
  343. SynthesiserSound* sound,
  344. int midiChannel,
  345. int midiNoteNumber,
  346. float velocity);
  347. private:
  348. //==============================================================================
  349. double sampleRate;
  350. uint32 lastNoteOnCounter;
  351. bool shouldStealNotes;
  352. BigInteger sustainPedalsDown;
  353. void handleMidiEvent (const MidiMessage& m);
  354. void stopVoice (SynthesiserVoice* voice, bool allowTailOff);
  355. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  356. // Note the new parameters for this method.
  357. virtual int findFreeVoice (const bool) const { return 0; }
  358. #endif
  359. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  360. };
  361. #endif // __JUCE_SYNTHESISER_JUCEHEADER__