32#include "freertos/FreeRTOS.h"
33#include "freertos/task.h"
36 #include "esp_heap_caps.h"
37 #include "esp_memory_utils.h"
52int16_t DrumSample::s_decodeTable[256];
55static constexpr int MULAW_BIAS = 0x84;
56static constexpr int MULAW_CLIP = 32635;
61 if (s_decodeTable[0] != 0)
63 for (
int i = 0; i < 256; ++i) {
65 int exponent = (u >> 4) & 7;
66 int mantissa = u & 0x0F;
67 int value = (((mantissa << 3) + MULAW_BIAS) << exponent) - MULAW_BIAS;
68 s_decodeTable[i] = (u & 0x80) ? -value : value;
80 if (value > MULAW_CLIP)
84 for (
int mask = 0x4000; exponent > 0 && (value & mask) == 0; mask >>= 1)
86 int mantissa = (value >> (exponent + 3)) & 0x0F;
87 return ~(sign | (exponent << 4) | mantissa) & 0xFF;
121DrumSample::~DrumSample()
130 free((
void *) m_data);
138static uint8_t * allocSampleBuffer(
int size)
140 #ifndef FABGL_EMULATED
141 auto buf = (uint8_t *) heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
143 buf = (uint8_t *) heap_caps_malloc(size, MALLOC_CAP_8BIT);
146 return (uint8_t *) malloc(size);
153static void safeCopy(uint8_t * dest, uint8_t
const * src,
int count)
155 #ifndef FABGL_EMULATED
156 if (esp_ptr_external_ram(dest)) {
157 for (
int i = 0; i < count; ++i) {
159 __asm__ __volatile__ (
"memw");
164 memcpy(dest, src, count);
187 int count = imin((
int)
sizeof(buf) / frameSize, frames - readFrames);
190 if (fread(buf, frameSize, count, file) != (
size_t) count) {
199 float sampleValue(uint8_t
const * p)
201 switch (bytesPerSample) {
203 return ((
int) p[0] - 128) / 128.0f;
205 return (int16_t) (p[0] | (p[1] << 8)) / 32768.0f;
207 return (int32_t) ((p[0] << 8) | (p[1] << 16) | (p[2] << 24)) / 2147483648.0f;
214 return (int32_t) (p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24)) / 2147483648.0f;
219 bool next(
float * value)
221 if (readFrames >= frames)
223 if (bufPos >= bufFrames && !readChunk())
225 uint8_t
const * frame = buf + bufPos * frameSize;
227 for (
int c = 0; c < channels; ++c)
228 sum += sampleValue(frame + c * bytesPerSample);
229 *value = sum / channels;
235 void rewind(
long dataPos)
237 fseek(file, dataPos, SEEK_SET);
252 void put(uint8_t value)
254 chunk[chunkLen++] = value;
255 if (chunkLen ==
sizeof(chunk))
261 safeCopy(dest + count, chunk, chunkLen);
268uint32_t readLE(uint8_t
const * p,
int bytes)
271 for (
int i = bytes - 1; i >= 0; --i)
283 FILE * file = fopen(filename,
"rb");
288 auto reader =
new WAVReader;
289 auto writer =
new SampleWriter;
292 int wavFormat = 0, channels = 0, srcRate = 0, bits = 0, blockAlign = 0;
297 if (fread(header, 1, 12, file) != 12 || memcmp(header,
"RIFF", 4) || memcmp(header + 8,
"WAVE", 4))
302 if (fread(header, 1, 8, file) != 8)
304 int size = (int) readLE(header + 4, 4);
307 if (memcmp(header,
"fmt ", 4) == 0) {
308 int len = imin(size, (
int)
sizeof(header));
309 if (len < 16 || fread(header, 1, len, file) != (
size_t) len)
311 wavFormat = readLE(header, 2);
312 channels = readLE(header + 2, 2);
313 srcRate = readLE(header + 4, 4);
314 blockAlign = readLE(header + 12, 2);
315 bits = readLE(header + 14, 2);
316 if (wavFormat == 0xFFFE && len >= 26)
317 wavFormat = readLE(header + 24, 2);
318 fseek(file, size - len + (size & 1), SEEK_CUR);
319 }
else if (memcmp(header,
"data", 4) == 0) {
320 dataPos = ftell(file);
324 fseek(file, size + (size & 1), SEEK_CUR);
327 if (channels < 1 || channels > 8 || srcRate < 1000 || srcRate > 200000 || blockAlign < 1) {
331 if (!((wavFormat == 1 && (bits == 8 || bits == 16 || bits == 24 || bits == 32)) || (wavFormat == 3 && bits == 32))) {
335 if (blockAlign != channels * bits / 8) {
342 reader->format = wavFormat;
343 reader->channels = channels;
344 reader->bytesPerSample = bits / 8;
345 reader->frameSize = blockAlign;
346 reader->error =
false;
348 int srcFrames = dataSize / blockAlign;
349 int outLength = (int) ((int64_t) srcFrames *
sampleRate / srcRate);
350 if (outLength > maxLength) {
351 outLength = maxLength;
352 srcFrames = (int) imin(srcFrames, (
int) ((int64_t) maxLength * srcRate /
sampleRate + 2));
358 reader->frames = srcFrames;
362 reader->rewind(dataPos);
363 while (reader->next(&v))
364 peak = fmaxf(peak, fabsf(v));
369 float gain = 32767.0f * (peak > 0.0001f ? 0.98f / peak : 1.0f);
371 auto data = allocSampleBuffer(outLength * (pcm16 ? 2 : 1));
378 constexpr int FADE = 64;
380 auto emit = [&](
float value) {
381 if (out >= outLength)
383 float s = value * gain;
384 if (out >= outLength - FADE)
385 s = s * (outLength - out) / FADE;
386 int x = (int) lroundf(fminf(32767.0f, fmaxf(-32767.0f, s)));
388 writer->put(x & 0xFF);
389 writer->put((x >> 8) & 0xFF);
396 writer->chunkLen = 0;
397 reader->rewind(dataPos);
402 for (int64_t k = 0; reader->next(&v); ++k) {
416 float prev = 0, cur = 0;
417 int64_t curIndex = -1;
418 for (
int j = 0; j < outLength; ++j) {
420 int64_t pos = (int64_t) j * srcRate * 65536 /
sampleRate;
421 int64_t ipos = pos >> 16;
422 while (curIndex < ipos + 1) {
424 if (!reader->next(&cur))
428 float t = (pos & 0xFFFF) / 65536.0f;
429 emit(prev + (cur - prev) * t);
432 while (out < outLength)
443 m_length = outLength;
485 if (step >= 0 && step < MAX_STEPS && instrument >= 0 && instrument <
INSTRUMENTS) {
486 int shift = instrument * 2;
487 steps[step] = (
steps[step] & ~(3u << shift)) | ((uint32_t) (velocity & 3) << shift);
495 set(i, instrument, 0);
505 case '-': velocity = 1;
break;
506 case 'x': velocity = 2;
break;
507 case 'X': velocity = 3;
break;
508 default: velocity = 0;
break;
511 set(i, instrument, velocity);
542DrumMachine::DrumMachine()
543 : m_soundGenerator(nullptr),
544 m_sampleRate(FABGL_SOUNDGEN_DEFAULT_SAMPLE_RATE),
550 m_nextPattern(nullptr),
556 m_startRequest(false),
559 m_timingChanged(true),
574 auto & ins = m_instruments[i];
575 ins.sample =
nullptr;
576 ins.pitchInc = 65536;
577 ins.decayCoef = ENV_ONE;
587 for (
int i = 0; i < VOICES; ++i)
588 m_voices[i].instrument = -1;
589 m_stepLength[0] = 1 << 8;
590 m_stepLength[1] = 1 << 8;
591 setVelocityGains(50, 80, 100);
593 m_channel.setVolume(127);
597DrumMachine::~DrumMachine()
599 if (m_soundGenerator)
600 m_soundGenerator->detach(&m_channel);
607 m_soundGenerator = soundGenerator;
609 soundGenerator->
attach(&m_channel);
610 m_channel.enable(
true);
611 soundGenerator->
play(
true);
624 m_clickLength = m_sampleRate * 12 / 1000;
625 m_click = (int16_t *) malloc(m_clickLength * 2 *
sizeof(int16_t));
626 for (
int k = 0; k < 2; ++k)
627 for (
int i = 0; i < m_clickLength; ++i) {
628 float t = (float) i / m_sampleRate;
629 m_click[k * m_clickLength + i] = (int16_t) (32000.0f * expf(-t * 400.0f) * sinf(2.0f * (
float) M_PI * (k ? 1500.0f : 2000.0f) * t));
635void DrumMachine::waitRender()
637 if (!m_soundGenerator || !m_soundGenerator->
playing())
639 uint32_t start = m_renderCount;
640 for (
int i = 0; i < 50 && m_renderCount - start < 2; ++i)
647 auto & ins = m_instruments[instrument];
649 ins.generation = ins.generation + 1;
656 m_instruments[instrument].level = iclamp(value, 0, 100);
662 auto & ins = m_instruments[instrument];
663 ins.tune = iclamp(cents, -1200, 1200);
664 ins.pitchInc = (uint32_t) lroundf(65536.0f * powf(2.0f, ins.tune / 1200.0f));
670 auto & ins = m_instruments[instrument];
671 ins.decay = iclamp(value, 0, 100);
672 if (ins.decay >= 100)
673 ins.decayCoef = ENV_ONE;
676 float tau = 0.015f * powf(200.0f, ins.decay / 99.0f);
677 ins.decayCoef = imin(ENV_ONE - 1, (
int) (65536.0f * expf(-
BLOCK_SIZE / (tau * m_sampleRate))));
684 m_velocityGain[0] = 0;
685 m_velocityGain[1] = iclamp(soft, 0, 100) * 32767 / 100;
686 m_velocityGain[2] = iclamp(normal, 0, 100) * 32767 / 100;
687 m_velocityGain[3] = iclamp(accent, 0, 100) * 32767 / 100;
693 m_metronomeLevel = iclamp(volume, 0, 100) * 32767 / 100;
703 int next = (w + 1) % HIT_QUEUE_SIZE;
704 if (next == m_hitsRead)
706 m_hits[w].instrument = instrument;
707 m_hits[w].velocity = iclamp(velocity, 1, 3);
708 __sync_synchronize();
715 for (
int i = 0; i <
VOICES; ++i)
716 if (m_voices[i].instrument == instrument && !m_voices[i].fading)
724 m_nextPattern =
nullptr;
727 m_timingChanged =
true;
733 if (m_playing && m_pattern)
745 m_song[len++] = patterns[i];
756 m_startRequest =
true;
763 if (m_songLength == 0)
766 m_songPos = iclamp(position, 0, m_songLength - 1);
767 m_startRequest =
true;
775 m_startRequest =
false;
784 m_timingChanged =
true;
792 m_pattern->swing = iclamp(percent, 50, 75);
793 m_timingChanged =
true;
802 if (!m_playing || m_startRequest || !
pattern ||
step < 0 || instrument < 0 || instrument >=
INSTRUMENTS) {
806 int32_t counter = m_counter;
807 int32_t length = m_stepLength[
step & 1];
809 if (counter < length / 2) {
812 m_skipStep[instrument] = target;
814 pattern->
set(target, instrument, iclamp(velocity, 1, 3));
821void DrumMachine::updateTiming()
823 m_timingChanged =
false;
825 int swing = iclamp(m_pattern->
swing, 50, 75);
826 int32_t
step = m_sampleRate * 15 * 256 / tempo;
827 int32_t even =
step * 2 * swing / 100;
828 m_stepLength[0] = even;
829 m_stepLength[1] =
step * 2 - even;
834void DrumMachine::switchPattern(
DrumPattern * pattern)
838 m_timingChanged =
true;
845void DrumMachine::sequencerAdvance()
847 if (m_startRequest) {
848 m_startRequest =
false;
850 switchPattern(m_song[m_songPos]);
852 m_nextPattern =
nullptr;
853 switchPattern(m_pattern);
859 if (!m_playing || !m_pattern)
863 while (m_playing && m_counter <= 0) {
864 int next = m_step + 1;
865 if (m_step >= 0 && next >= m_pattern->length) {
868 DrumPattern * nextPattern =
nullptr;
870 int pos = m_songPos + 1;
871 if (pos >= m_songLength) {
872 if (!m_songLoop || m_songLength == 0) {
879 nextPattern = m_song[pos];
880 }
else if (m_nextPattern) {
881 nextPattern = m_nextPattern;
882 m_nextPattern =
nullptr;
885 switchPattern(nextPattern);
887 m_loops = m_loops + 1;
889 if (next >= m_pattern->length)
894 m_counter += m_stepLength[next & 1];
901void DrumMachine::playStep()
909 if (m_eraseMask & (1 << i))
910 clear |= 3u << (i * 2);
915 for (
int i = 0; i < INSTRUMENTS; ++i, bits >>= 2) {
916 int velocity = bits & 3;
917 if (velocity && !m_instruments[i].
mute) {
918 if (m_skipStep[i] ==
step)
921 startVoice(i, velocity);
925 if (m_metronome && (
step & 3) == 0) {
927 m_clickOffset =
step == 0 ? 0 : m_clickLength;
933void DrumMachine::startVoice(
int instrument,
int velocity)
935 auto & ins = m_instruments[instrument];
936 m_hitCount[instrument] = m_hitCount[instrument] + 1;
942 int group = ins.chokeGroup;
943 for (
int i = 0; i <
VOICES; ++i) {
944 auto & v = m_voices[i];
945 if (v.instrument == instrument || (group && v.instrument >= 0 && m_instruments[v.instrument].chokeGroup == group))
950 Voice * voice =
nullptr;
951 for (
int i = 0; i <
VOICES && !voice; ++i)
952 if (m_voices[i].instrument < 0)
953 voice = &m_voices[i];
956 for (
int i = 0; i <
VOICES; ++i) {
957 auto & v = m_voices[i];
958 uint32_t age = m_voiceAge - v.age + (v.fading ? 0x80000000 : 0);
959 if (!voice || age > oldest) {
966 uint32_t inc = ins.pitchInc;
976 voice->velocity = m_velocityGain[velocity];
977 voice->env = ENV_ONE;
978 voice->gain = voice->velocity * ins.level / 100;
979 voice->generation = ins.generation;
980 voice->fading =
false;
981 voice->opened =
false;
983 voice->age = ++m_voiceAge;
984 voice->instrument = instrument;
1001static inline int sampleAt(int16_t
const * data, int16_t
const *, uint32_t index) {
return data[index]; }
1002static inline int sampleAt(uint8_t
const * data, int16_t
const * decodeTable, uint32_t index) {
return decodeTable[data[index]]; }
1006template <
typename T>
1007static inline void mixVoice(T
const * data, int16_t
const * decodeTable, VoiceState & st, int32_t * sum)
1009 uint32_t index = st.index, frac = st.frac, inc = st.inc, last = st.last;
1010 int32_t g = st.g, dg = st.dg;
1013 if (index >= last) {
1017 int s0 = sampleAt(data, decodeTable, index);
1018 int s1 = sampleAt(data, decodeTable, index + 1);
1019 int s = s0 + (((s1 - s0) * (int) (frac >> 4)) >> 12);
1021 int out = (s * (g >> 4)) >> 15;
1028 index += frac >> 16;
1038static inline int softClip(
int x)
1040 constexpr int HEADROOM = 24576;
1041 constexpr int R = 32767 - HEADROOM;
1042 int a = x < 0 ? -x : x;
1045 int u = imin(a - HEADROOM, R * 31);
1046 int y = HEADROOM + R * u / (R + u);
1047 return x < 0 ? -y : y;
1052void DrumMachine::renderBlock(int16_t * dest)
1055 while (m_hitsRead != m_hitsWrite) {
1056 auto const & hit = m_hits[m_hitsRead];
1057 startVoice(hit.instrument, hit.velocity);
1058 m_hitsRead = (m_hitsRead + 1) % HIT_QUEUE_SIZE;
1064 auto const decodeTable = DrumSample::s_decodeTable;
1067 int const gate = m_gateLevel ? m_gateLevel * (256 * 128 * 4 / 3) / imax(1, m_channel.volume()) : 0;
1069 for (
int i = 0; i <
VOICES; ++i) {
1070 auto & v = m_voices[i];
1071 if (v.instrument < 0)
1073 auto & ins = m_instruments[v.instrument];
1077 if (ins.generation != v.generation)
1080 int32_t coef = ins.decayCoef;
1081 if (coef < ENV_ONE) {
1082 v.env = (int32_t) (((uint32_t) v.env * (uint32_t) coef) >> 16);
1083 if (v.env < ENV_FLOOR)
1086 g1 = (int32_t) (((int64_t) v.velocity * ins.level / 100 * v.env) >> 16);
1091 int32_t g = v.gain << 4;
1092 int32_t dg = g1 - v.gain;
1093 VoiceState st = { v.index, v.frac, v.inc, v.length - 1, g, dg, 0,
false };
1095 mixVoice((int16_t
const *) v.data,
nullptr, st, sum);
1097 mixVoice((uint8_t
const *) v.data, decodeTable, st, sum);
1111 }
else if (v.opened && ++v.quiet >= GATE_BLOCKS)
1117 if (m_clickPos >= 0) {
1118 auto click = m_click + m_clickOffset;
1119 for (
int n = 0; n < BLOCK_SIZE && m_clickPos >= 0; ++n) {
1120 sum[n] += (click[m_clickPos] * m_metronomeLevel) >> 15;
1121 if (++m_clickPos >= m_clickLength)
1127 int volume = m_channel.volume();
1130 int x = softClip(((sum[n] * volume) >> 7) * 3 / 4);
1131 int a = x < 0 ? -x : x;
1134 dest[n] = iclamp(x, -32767, 32767);
1137 m_outputLevel = imax(peak, m_outputLevel - 32767 *
BLOCK_SIZE * 5 / (m_sampleRate * 2));
1139 m_renderCount = m_renderCount + 1;
void setTempo(int bpm)
Sets the tempo of the playing pattern.
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).
void setVelocityGains(int soft, int normal, int accent)
Sets the gain of the velocities.
bool sounding(int instrument)
Determines whether an instrument is sounding.
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().
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).
void setPattern(DrumPattern *pattern)
Sets the pattern to play (now).
static constexpr int INSTRUMENTS
Number of instruments.
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).
void play()
Starts playing the pattern from the first step.
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.
void trigger(int instrument, int velocity=2)
Plays an instrument now.
static constexpr int MIN_TEMPO
Minimum tempo (BPM).
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.
DrumSampleFormat format() const
Gets the sample format.
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.
void const * data() const
Gets the samples (int16_t or mu-law bytes, see format()).
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.
The sound of a drum instrument: 16 bit linear or 8 bit mu-law samples.
void attach(WaveformGenerator *value)
Attaches a waveform generator.
int sampleRate()
Determines the sample rate.
bool playing()
Determines whether the sound generator is playing.
bool play(bool value)
Starts or stops playing.
int oversampling()
Gets the oversampling factor (see setOversampling()).
SoundGenerator handles audio output.
This file contains the sample based drum machine: DrumSample, DrumPattern and DrumMachine.
DrumSampleFormat
Sample format of a DrumSample.
DrumSampleError
Result of DrumSample::loadWAV().
uint32_t steps[MAX_STEPS]
A drum pattern: up to 32 steps (1/16 notes) for 16 instruments.
void clearSteps()
Removes all hits of all instruments.
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]
A drum pattern: up to 32 steps (1/16 notes) for 16 instruments.