FabGL2 2.0.0
Graphics, audio, GUI and retro-computing library for the ESP32 (ESP-IDF)
Loading...
Searching...
No Matches
drummachine.h
Go to the documentation of this file.
1/*
2 Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
3 Copyright (c) 2019-2026 Fabrizio Di Vittorio.
4 All rights reserved.
5
6
7* Please contact fdivitto2013@gmail.com if you need a commercial license.
8
9
10* This library and related software is available under GPL v3.
11
12 FabGL is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 FabGL is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with FabGL. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26
27#pragma once
28
29
35
36
37#include <stdint.h>
38#include <stddef.h>
39
40#include "fabglconf.h"
41#include "soundgen.h"
42
43
44
45namespace fabgl {
46
47
48
60
61
69
70
92
93public:
94
96 DrumSample();
97
105 DrumSample(uint8_t const * muLawData, int length, int sampleRate);
106
114 DrumSample(int16_t const * pcmData, int length, int sampleRate);
115
116 ~DrumSample();
117
118 DrumSample(DrumSample const &) = delete;
119 DrumSample & operator=(DrumSample const &) = delete;
120
135 DrumSampleError loadWAV(char const * filename, int sampleRate, int maxLength = 22050 * 4, DrumSampleFormat format = DrumSampleFormat::PCM16);
136
138 void clear();
139
141 void const * data() const { return m_data; }
142
144 DrumSampleFormat format() const { return m_format; }
145
147 int length() const { return m_length; }
148
150 int sampleRate() const { return m_sampleRate; }
151
153 bool empty() const { return m_length == 0; }
154
156 bool owned() const { return m_owned; }
157
159 int durationMS() const { return m_sampleRate ? (int) ((int64_t) m_length * 1000 / m_sampleRate) : 0; }
160
168 static uint8_t encode(int value);
169
177 static int16_t decode(uint8_t value) { return s_decodeTable[value]; }
178
180 static void initDecodeTable();
181
182 // mu-law -> 16 bit linear
183 static int16_t s_decodeTable[256];
184
185private:
186
187 void const * m_data;
188 int m_length;
189 int m_sampleRate;
190 DrumSampleFormat m_format;
191 bool m_owned;
192};
193
194
195
209struct DrumPattern {
210
212 static constexpr int MAX_STEPS = 32;
213
215 static constexpr int INSTRUMENTS = 16;
216
218 static constexpr int NAME_LENGTH = 15;
219
220 uint32_t steps[MAX_STEPS];
221 uint8_t length;
222 uint8_t swing;
223 uint16_t tempo;
224 char name[NAME_LENGTH + 1];
225
226 DrumPattern() { clear(); }
227
229 void clear();
230
232 void clearSteps();
233
242 int get(int step, int instrument) const { return (steps[step] >> (instrument * 2)) & 3; }
243
251 void set(int step, int instrument, int velocity);
252
258 void clearInstrument(int instrument);
259
269 void setRow(int instrument, char const * text);
270
272 bool empty() const;
273
275 void setName(char const * value);
276};
277
278
279
315class DrumMachine {
316
317public:
318
320 static constexpr int INSTRUMENTS = DrumPattern::INSTRUMENTS;
321
323 static constexpr int VOICES = 24;
324
326 static constexpr int BLOCK_SIZE = 16;
327
329 static constexpr int MIN_TEMPO = 30;
330
332 static constexpr int MAX_TEMPO = 300;
333
335 static constexpr int MAX_SONG_STEPS = 64;
336
337 DrumMachine();
338
339 ~DrumMachine();
340
349 void begin(SoundGenerator * soundGenerator);
350
352 int sampleRate() { return m_sampleRate; }
353
354
356
365 void setSample(int instrument, DrumSample const * sample);
366
368 DrumSample const * sample(int instrument) { return m_instruments[instrument].sample; }
369
376 void setLevel(int instrument, int value);
377
379 int level(int instrument) { return m_instruments[instrument].level; }
380
387 void setTune(int instrument, int cents);
388
390 int tune(int instrument) { return m_instruments[instrument].tune; }
391
398 void setDecay(int instrument, int value);
399
401 int decay(int instrument) { return m_instruments[instrument].decay; }
402
409 void setMute(int instrument, bool value) { m_instruments[instrument].mute = value; }
410
412 bool mute(int instrument) { return m_instruments[instrument].mute; }
413
422 void setChokeGroup(int instrument, int group) { m_instruments[instrument].chokeGroup = group; }
423
425 int chokeGroup(int instrument) { return m_instruments[instrument].chokeGroup; }
426
433 void trigger(int instrument, int velocity = 2);
434
442 uint8_t hitCount(int instrument) { return m_hitCount[instrument]; }
443
445 bool sounding(int instrument);
446
456 void setVelocityGains(int soft, int normal, int accent);
457
471 void setNoiseGate(int level) { m_gateLevel = level < 0 ? 0 : level; }
472
473
475
481 WaveformGenerator & channel() { return m_channel; }
482
488 int outputLevel() { return m_outputLevel * 100 / 32767; }
489
490
492
499
506
508 DrumPattern * pattern() { return m_pattern; }
509
511 DrumPattern * queuedPattern() { return m_nextPattern; }
512
520 void setSong(DrumPattern * const * patterns, int count, bool loop = true);
521
523 void play();
524
530 void playSong(int position = 0);
531
533 void stop();
534
536 bool playing() { return m_playing; }
537
539 bool playingSong() { return m_playing && m_songMode; }
540
542 int songPosition() { return m_playing && m_songMode ? m_songPos : -1; }
543
545 int step() { return m_playing ? m_step : -1; }
546
548 int loops() { return m_loops; }
549
555 void setTempo(int bpm);
556
562 void setSwing(int percent);
563
574 int recordHit(int instrument, int velocity = 2);
575
581 void setErase(uint32_t mask) { m_eraseMask = mask; }
582
589 void setMetronome(bool value, int volume = 60);
590
592 bool metronome() { return m_metronome; }
593
601 static int stepDurationMS(int tempo) { return 15000 / tempo; }
602
603
604private:
605
606 static constexpr int ENV_ONE = 1 << 16; // envelope full level
607 static constexpr int ENV_FLOOR = 64; // below this level the voice stops
608 static constexpr int GATE_BLOCKS = 24; // noise gate hold time (blocks)
609
610 struct Instrument {
611 DrumSample const * volatile sample;
612 volatile uint32_t pitchInc; // Q16 (65536 = sample rate of the sound generator)
613 volatile int32_t decayCoef; // Q16 per block, ENV_ONE = no decay
614 volatile int16_t level; // 0..100
615 int16_t tune; // cents
616 int8_t decay; // 0..100
617 volatile bool mute;
618 volatile uint8_t chokeGroup;
619 volatile uint8_t generation; // incremented when the sample changes: stops its voices
620 };
621
622 struct Voice {
623 void const * data;
624 bool pcm16; // int16_t samples, else mu-law
625 uint32_t length;
626 uint32_t index; // integer part of the position
627 uint32_t frac; // fractional part of the position (Q16)
628 uint32_t inc; // Q16
629 int32_t velocity; // Q15
630 int32_t env; // Q16
631 int32_t gain; // Q15, gain at the end of the previous block (ramps)
632 int8_t instrument; // -1 = idle
633 uint8_t generation;
634 bool fading; // fades to 0 in the next block, then stops
635 bool opened; // the output went above the gate level
636 uint8_t quiet; // consecutive blocks below the gate level
637 uint32_t age;
638 };
639
640 class Channel : public WaveformGenerator {
641 public:
642 Channel(DrumMachine * dm) : m_dm(dm), m_pos(BLOCK_SIZE) { }
643 int getSample16()
644 {
645 if (m_pos >= BLOCK_SIZE) {
646 m_dm->renderBlock(m_block);
647 m_pos = 0;
648 }
649 return m_block[m_pos++];
650 }
651 int getSample()
652 {
653 int x = (getSample16() + 128) >> 8;
654 return x > 127 ? 127 : (x < -127 ? -127 : x);
655 }
656 void setFrequency(int value) { }
657 private:
658 DrumMachine * m_dm;
659 int16_t m_block[BLOCK_SIZE];
660 int m_pos;
661 };
662
663 // pending live hits (written by the application, consumed by the sound generator)
664 static constexpr int HIT_QUEUE_SIZE = 32;
665 struct Hit {
666 int8_t instrument;
667 int8_t velocity;
668 };
669
670 void renderBlock(int16_t * dest);
671 void sequencerAdvance();
672 void playStep();
673 void startVoice(int instrument, int velocity);
674 void updateTiming();
675 void switchPattern(DrumPattern * pattern);
676 void waitRender();
677
678 SoundGenerator * m_soundGenerator;
679 int m_sampleRate;
680 Channel m_channel;
681 Instrument m_instruments[INSTRUMENTS];
682 Voice m_voices[VOICES];
683 uint32_t m_voiceAge;
684 volatile uint8_t m_hitCount[INSTRUMENTS];
685 int32_t m_velocityGain[4]; // Q15
686
687 Hit m_hits[HIT_QUEUE_SIZE];
688 volatile int m_hitsWrite;
689 volatile int m_hitsRead;
690
691 DrumPattern * volatile m_pattern;
692 DrumPattern * volatile m_nextPattern;
693 DrumPattern * m_song[MAX_SONG_STEPS];
694 volatile int m_songLength;
695 volatile bool m_songLoop;
696 volatile bool m_songMode;
697 volatile int m_songPos;
698 volatile bool m_playing;
699 volatile bool m_startRequest;
700 volatile int m_step;
701 volatile int32_t m_counter; // samples to the next step (Q8)
702 volatile int32_t m_stepLength[2]; // Q8: even and odd steps (swing)
703 volatile bool m_timingChanged;
704 volatile int m_loops;
705 volatile uint32_t m_eraseMask;
706 volatile int8_t m_skipStep[INSTRUMENTS]; // recorded hits already played live
707
708 volatile bool m_metronome;
709 int m_metronomeLevel; // Q15
710 int m_gateLevel; // noise gate, steps of the 8 bit output
711 int16_t * m_click; // click sound (two pitches)
712 int m_clickLength;
713 int m_clickPos; // -1 = idle
714 int m_clickOffset; // 0 = accent, m_clickLength = normal
715
716 volatile uint32_t m_renderCount;
717 int32_t m_outputLevel;
718};
719
720
721
722} // end of namespace
DrumSampleFormat format() const
Gets the sample format.
DrumSample()
Creates an empty sample.
int length() const
Gets the number of samples.
DrumSampleError loadWAV(char const *filename, int sampleRate, int maxLength=22050 *4, DrumSampleFormat format=DrumSampleFormat::PCM16)
Loads a WAV file.
void clear()
Releases the samples (the sample becomes empty).
int sampleRate() const
Gets the sample rate in Hertz.
void setTempo(int bpm)
Sets the tempo of the playing pattern.
int chokeGroup(int instrument)
Gets the choke group of an instrument.
void setDecay(int instrument, int value)
Sets the decay of an instrument.
void setTune(int instrument, int cents)
Sets the tuning of an instrument.
int decay(int instrument)
Gets the decay of an instrument (0..100).
uint8_t hitCount(int instrument)
Counts the hits of an instrument (live and sequencer), to show the activity.
void setVelocityGains(int soft, int normal, int accent)
Sets the gain of the velocities.
bool sounding(int instrument)
Determines whether an instrument is sounding.
int sampleRate()
Gets the sample rate of the sound generator.
void setSwing(int percent)
Sets the swing of the playing pattern.
void setSong(DrumPattern *const *patterns, int count, bool loop=true)
Sets the song: a list of patterns played in sequence by playSong().
WaveformGenerator & channel()
Gets the sound generator channel that plays the drum machine.
void setSample(int instrument, DrumSample const *sample)
Sets the sound of an instrument.
static constexpr int VOICES
Number of voices (sounds playing at the same time).
static constexpr int MAX_TEMPO
Maximum tempo (BPM).
bool playingSong()
Determines whether the sequencer is playing the song.
void setPattern(DrumPattern *pattern)
Sets the pattern to play (now).
static constexpr int INSTRUMENTS
Number of instruments.
int loops()
Counts the completed repetitions of the playing pattern.
void playSong(int position=0)
Starts playing the song.
bool mute(int instrument)
Determines whether an instrument is muted.
int step()
Gets the step that is playing (-1 = stopped).
static int stepDurationMS(int tempo)
Calculates the duration of a step.
int tune(int instrument)
Gets the tuning of an instrument in cents.
void play()
Starts playing the pattern from the first step.
bool metronome()
Determines whether the metronome is enabled.
void setNoiseGate(int level)
Sets the noise gate of the voices.
bool playing()
Determines whether the sequencer is playing.
void stop()
Stops the sequencer (the sounds play until they end).
int recordHit(int instrument, int velocity=2)
Records a hit in the playing pattern, quantized to the nearest step, and plays it.
DrumPattern * pattern()
Gets the playing pattern.
int level(int instrument)
Gets the level of an instrument (0..100).
void setErase(uint32_t mask)
Erases the hits of instruments while the playhead passes them.
int outputLevel()
Gets the output level (peak, with a short decay), to show a meter.
DrumPattern * queuedPattern()
Gets the queued pattern, nullptr if none.
void trigger(int instrument, int velocity=2)
Plays an instrument now.
static constexpr int MIN_TEMPO
Minimum tempo (BPM).
int songPosition()
Gets the song entry that is playing (-1 = not playing the song).
void setMute(int instrument, bool value)
Mutes an instrument: the sequencer doesn't play it (trigger() still does).
void setChokeGroup(int instrument, int group)
Sets the choke group of an instrument.
void setMetronome(bool value, int volume=60)
Enables the metronome: a click on every quarter note, accented on the first beat.
static constexpr int BLOCK_SIZE
Samples rendered at once: the timing resolution of the sequencer.
void queuePattern(DrumPattern *pattern)
Sets the pattern to play at the end of the current one (immediately when stopped).
static constexpr int MAX_SONG_STEPS
Maximum number of entries of a song.
DrumSample const * sample(int instrument)
Gets the sound of an instrument.
void begin(SoundGenerator *soundGenerator)
Attaches the drum machine to the sound generator and starts the sound generator.
void setLevel(int instrument, int value)
Sets the level of an instrument.
bool owned() const
Determines whether the samples are owned (loaded from a file).
DrumSampleFormat format() const
Gets the sample format.
int durationMS() const
Gets the duration in milliseconds.
DrumSample()
Creates an empty sample.
static void initDecodeTable()
Builds the decoding table (called by DrumMachine).
static uint8_t encode(int value)
Encodes a 16 bit linear value to mu-law.
bool empty() const
Determines whether the sample is empty.
static int16_t decode(uint8_t value)
Decodes a mu-law value.
void const * data() const
Gets the samples (int16_t or mu-law bytes, see format()).
int length() const
Gets the number of samples.
int sampleRate() const
Gets the sample rate in Hertz.
The sound of a drum instrument: 16 bit linear or 8 bit mu-law samples.
Definition drummachine.h:91
SoundGenerator handles audio output.
Definition soundgen.h:393
Abstract base class for waveform generators. A waveform generator is an audio channel that SoundGener...
Definition soundgen.h:74
This file contains the FabGL configuration settings, such as queue sizes, task stack sizes and priori...
DrumSampleFormat
Sample format of a DrumSample.
Definition drummachine.h:65
DrumSampleError
Result of DrumSample::loadWAV().
Definition drummachine.h:52
This file contains all the classes of the FabGL sound system.
void clearSteps()
Removes all hits of all instruments.
int get(int step, int instrument) const
Gets the velocity of an instrument at a step.
void setRow(int instrument, char const *text)
Sets the hits of an instrument from a text, one character per step.
void setName(char const *value)
Sets the name (truncated to NAME_LENGTH characters).
static constexpr int INSTRUMENTS
Number of instruments.
bool empty() const
Determines whether the pattern has no hits.
static constexpr int NAME_LENGTH
Maximum name length (terminator not included).
void clearInstrument(int instrument)
Removes all hits of an instrument.
void set(int step, int instrument, int velocity)
Sets the velocity of an instrument at a step.
void clear()
Removes all hits and sets the defaults: 16 steps, 120 BPM, no swing, no name.
static constexpr int MAX_STEPS
Maximum number of steps.
uint32_t steps[MAX_STEPS]
char name[NAME_LENGTH+1]
A drum pattern: up to 32 steps (1/16 notes) for 16 instruments.