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 23KB

10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 (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 (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. The velocity indicates how quickly the note was released - 0 is slowly, 1 is quickly.
  96. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  97. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  98. and allow the synth to reassign it another sound.
  99. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  100. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  101. finishes playing (during the rendering callback), it must make sure that it calls
  102. clearCurrentNote().
  103. */
  104. virtual void stopNote (float velocity, bool allowTailOff) = 0;
  105. /** Called to let the voice know that the pitch wheel has been moved.
  106. This will be called during the rendering callback, so must be fast and thread-safe.
  107. */
  108. virtual void pitchWheelMoved (int newPitchWheelValue) = 0;
  109. /** Called to let the voice know that a midi controller has been moved.
  110. This will be called during the rendering callback, so must be fast and thread-safe.
  111. */
  112. virtual void controllerMoved (int controllerNumber, int newControllerValue) = 0;
  113. /** Called to let the voice know that the aftertouch has changed.
  114. This will be called during the rendering callback, so must be fast and thread-safe.
  115. */
  116. virtual void aftertouchChanged (int newAftertouchValue);
  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. /** 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. virtual void setCurrentPlaybackSampleRate (double newRate);
  139. /** Returns the current target sample rate at which rendering is being done.
  140. Subclasses may need to know this so that they can pitch things correctly.
  141. */
  142. double getSampleRate() const noexcept { return currentSampleRate; }
  143. /** Returns true if the voice is currently playing a sound which is mapped to the given
  144. midi channel.
  145. If it's not currently playing, this will return false.
  146. */
  147. bool isPlayingChannel (int midiChannel) const;
  148. /** Returns true if the key that triggered this voice is still held down.
  149. Note that the voice may still be playing after the key was released (e.g because the
  150. sostenuto pedal is down).
  151. */
  152. bool isKeyDown() const noexcept { return keyIsDown; }
  153. /** Returns true if the sostenuto pedal is currently active for this voice. */
  154. bool isSostenutoPedalDown() const noexcept { return sostenutoPedalDown; }
  155. /** Returns true if this voice started playing its current note before the other voice did. */
  156. bool wasStartedBefore (const SynthesiserVoice& other) const noexcept;
  157. protected:
  158. /** Resets the state of this voice after a sound has finished playing.
  159. The subclass must call this when it finishes playing a note and becomes available
  160. to play new ones.
  161. It must either call it in the stopNote() method, or if the voice is tailing off,
  162. then it should call it later during the renderNextBlock method, as soon as it
  163. finishes its tail-off.
  164. It can also be called at any time during the render callback if the sound happens
  165. to have finished, e.g. if it's playing a sample and the sample finishes.
  166. */
  167. void clearCurrentNote();
  168. private:
  169. //==============================================================================
  170. friend class Synthesiser;
  171. double currentSampleRate;
  172. int currentlyPlayingNote;
  173. uint32 noteOnTime;
  174. SynthesiserSound::Ptr currentlyPlayingSound;
  175. bool keyIsDown, sostenutoPedalDown;
  176. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  177. // Note the new parameters for this method.
  178. virtual int stopNote (bool) { return 0; }
  179. #endif
  180. JUCE_LEAK_DETECTOR (SynthesiserVoice)
  181. };
  182. //==============================================================================
  183. /**
  184. Base class for a musical device that can play sounds.
  185. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  186. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  187. which can play back one of these sounds.
  188. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  189. set of sounds, and a set of voices it can use to play them. If you only give it
  190. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  191. have available.
  192. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  193. events that go in will be scanned for note on/off messages, and these are used to
  194. start and stop the voices playing the appropriate sounds.
  195. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  196. noteOff() and other controller methods.
  197. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  198. what the target playback rate is. This value is passed on to the voices so that
  199. they can pitch their output correctly.
  200. */
  201. class JUCE_API Synthesiser
  202. {
  203. public:
  204. //==============================================================================
  205. /** Creates a new synthesiser.
  206. You'll need to add some sounds and voices before it'll make any sound.
  207. */
  208. Synthesiser();
  209. /** Destructor. */
  210. virtual ~Synthesiser();
  211. //==============================================================================
  212. /** Deletes all voices. */
  213. void clearVoices();
  214. /** Returns the number of voices that have been added. */
  215. int getNumVoices() const noexcept { return voices.size(); }
  216. /** Returns one of the voices that have been added. */
  217. SynthesiserVoice* getVoice (int index) const;
  218. /** Adds a new voice to the synth.
  219. All the voices should be the same class of object and are treated equally.
  220. The object passed in will be managed by the synthesiser, which will delete
  221. it later on when no longer needed. The caller should not retain a pointer to the
  222. voice.
  223. */
  224. SynthesiserVoice* addVoice (SynthesiserVoice* newVoice);
  225. /** Deletes one of the voices. */
  226. void removeVoice (int index);
  227. //==============================================================================
  228. /** Deletes all sounds. */
  229. void clearSounds();
  230. /** Returns the number of sounds that have been added to the synth. */
  231. int getNumSounds() const noexcept { return sounds.size(); }
  232. /** Returns one of the sounds. */
  233. SynthesiserSound* getSound (int index) const noexcept { return sounds [index]; }
  234. /** Adds a new sound to the synthesiser.
  235. The object passed in is reference counted, so will be deleted when the
  236. synthesiser and all voices are no longer using it.
  237. */
  238. SynthesiserSound* addSound (const SynthesiserSound::Ptr& newSound);
  239. /** Removes and deletes one of the sounds. */
  240. void removeSound (int index);
  241. //==============================================================================
  242. /** If set to true, then the synth will try to take over an existing voice if
  243. it runs out and needs to play another note.
  244. The value of this boolean is passed into findFreeVoice(), so the result will
  245. depend on the implementation of this method.
  246. */
  247. void setNoteStealingEnabled (bool shouldStealNotes);
  248. /** Returns true if note-stealing is enabled.
  249. @see setNoteStealingEnabled
  250. */
  251. bool isNoteStealingEnabled() const noexcept { return shouldStealNotes; }
  252. //==============================================================================
  253. /** Triggers a note-on event.
  254. The default method here will find all the sounds that want to be triggered by
  255. this note/channel. For each sound, it'll try to find a free voice, and use the
  256. voice to start playing the sound.
  257. Subclasses might want to override this if they need a more complex algorithm.
  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 noteOn (int midiChannel,
  263. int midiNoteNumber,
  264. float velocity);
  265. /** Triggers a note-off event.
  266. This will turn off any voices that are playing a sound for the given note/channel.
  267. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  268. (if they can do). If this is false, the notes will all be cut off immediately.
  269. This method will be called automatically according to the midi data passed into
  270. renderNextBlock(), but may be called explicitly too.
  271. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  272. */
  273. virtual void noteOff (int midiChannel,
  274. int midiNoteNumber,
  275. float velocity,
  276. bool allowTailOff);
  277. /** Turns off all notes.
  278. This will turn off any voices that are playing a sound on the given midi channel.
  279. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  280. which channel they're playing. Otherwise it represents a valid midi channel, from
  281. 1 to 16 inclusive.
  282. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  283. (if they can do). If this is false, the notes will all be cut off immediately.
  284. This method will be called automatically according to the midi data passed into
  285. renderNextBlock(), but may be called explicitly too.
  286. */
  287. virtual void allNotesOff (int midiChannel,
  288. bool allowTailOff);
  289. /** Sends a pitch-wheel message to any active voices.
  290. This will send a pitch-wheel message to any voices that are playing sounds on
  291. the given midi channel.
  292. This method will be called automatically according to the midi data passed into
  293. renderNextBlock(), but may be called explicitly too.
  294. @param midiChannel the midi channel, from 1 to 16 inclusive
  295. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  296. */
  297. virtual void handlePitchWheel (int midiChannel,
  298. int wheelValue);
  299. /** Sends a midi controller message to any active voices.
  300. This will send a midi controller message to any voices that are playing sounds on
  301. the given midi channel.
  302. This method will be called automatically according to the midi data passed into
  303. renderNextBlock(), but may be called explicitly too.
  304. @param midiChannel the midi channel, from 1 to 16 inclusive
  305. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  306. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  307. */
  308. virtual void handleController (int midiChannel,
  309. int controllerNumber,
  310. int controllerValue);
  311. /** Sends an aftertouch message.
  312. This will send an aftertouch message to any voices that are playing sounds on
  313. the given midi channel and note number.
  314. This method will be called automatically according to the midi data passed into
  315. renderNextBlock(), but may be called explicitly too.
  316. @param midiChannel the midi channel, from 1 to 16 inclusive
  317. @param midiNoteNumber the midi note number, 0 to 127
  318. @param aftertouchValue the aftertouch value, between 0 and 127,
  319. as returned by MidiMessage::getAftertouchValue()
  320. */
  321. virtual void handleAftertouch (int midiChannel, int midiNoteNumber, int aftertouchValue);
  322. /** Handles a sustain pedal event. */
  323. virtual void handleSustainPedal (int midiChannel, bool isDown);
  324. /** Handles a sostenuto pedal event. */
  325. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  326. /** Can be overridden to handle soft pedal events. */
  327. virtual void handleSoftPedal (int midiChannel, bool isDown);
  328. //==============================================================================
  329. /** Tells the synthesiser what the sample rate is for the audio it's being used to render.
  330. This value is propagated to the voices so that they can use it to render the correct
  331. pitches.
  332. */
  333. virtual void setCurrentPlaybackSampleRate (double sampleRate);
  334. /** Creates the next block of audio output.
  335. This will process the next numSamples of data from all the voices, and add that output
  336. to the audio block supplied, starting from the offset specified. Note that the
  337. data will be added to the current contents of the buffer, so you should clear it
  338. before calling this method if necessary.
  339. The midi events in the inputMidi buffer are parsed for note and controller events,
  340. and these are used to trigger the voices. Note that the startSample offset applies
  341. both to the audio output buffer and the midi input buffer, so any midi events
  342. with timestamps outside the specified region will be ignored.
  343. */
  344. void renderNextBlock (AudioSampleBuffer& outputAudio,
  345. const MidiBuffer& inputMidi,
  346. int startSample,
  347. int numSamples);
  348. /** Returns the current target sample rate at which rendering is being done.
  349. Subclasses may need to know this so that they can pitch things correctly.
  350. */
  351. double getSampleRate() const noexcept { return sampleRate; }
  352. protected:
  353. //==============================================================================
  354. /** This is used to control access to the rendering callback and the note trigger methods. */
  355. CriticalSection lock;
  356. OwnedArray<SynthesiserVoice> voices;
  357. ReferenceCountedArray<SynthesiserSound> sounds;
  358. /** The last pitch-wheel values for each midi channel. */
  359. int lastPitchWheelValues [16];
  360. /** Renders the voices for the given range.
  361. By default this just calls renderNextBlock() on each voice, but you may need
  362. to override it to handle custom cases.
  363. */
  364. virtual void renderVoices (AudioSampleBuffer& outputAudio,
  365. int startSample, int numSamples);
  366. /** Searches through the voices to find one that's not currently playing, and
  367. which can play the given sound.
  368. Returns nullptr if all voices are busy and stealing isn't enabled.
  369. To implement a custom note-stealing algorithm, you can either override this
  370. method, or (preferably) override findVoiceToSteal().
  371. */
  372. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  373. int midiChannel,
  374. int midiNoteNumber,
  375. bool stealIfNoneAvailable) const;
  376. /** Chooses a voice that is most suitable for being re-used.
  377. The default method will attempt to find the oldest voice that isn't the
  378. bottom or top note being played. If that's not suitable for your synth,
  379. you can override this method and do something more cunning instead.
  380. */
  381. virtual SynthesiserVoice* findVoiceToSteal (SynthesiserSound* soundToPlay,
  382. int midiChannel,
  383. int midiNoteNumber) const;
  384. /** Starts a specified voice playing a particular sound.
  385. You'll probably never need to call this, it's used internally by noteOn(), but
  386. may be needed by subclasses for custom behaviours.
  387. */
  388. void startVoice (SynthesiserVoice* voice,
  389. SynthesiserSound* sound,
  390. int midiChannel,
  391. int midiNoteNumber,
  392. float velocity);
  393. /** Can be overridden to do custom handling of incoming midi events. */
  394. virtual void handleMidiEvent (const MidiMessage&);
  395. private:
  396. //==============================================================================
  397. double sampleRate;
  398. uint32 lastNoteOnCounter;
  399. bool shouldStealNotes;
  400. BigInteger sustainPedalsDown;
  401. void stopVoice (SynthesiserVoice*, float velocity, bool allowTailOff);
  402. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  403. // Note the new parameters for these methods.
  404. virtual int findFreeVoice (const bool) const { return 0; }
  405. virtual int noteOff (int, int, int) { return 0; }
  406. virtual int findFreeVoice (SynthesiserSound*, const bool) { return 0; }
  407. virtual int findVoiceToSteal (SynthesiserSound*) const { return 0; }
  408. #endif
  409. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser)
  410. };
  411. #endif // JUCE_SYNTHESISER_H_INCLUDED