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.

juce_Synthesiser.h 20KB

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