FabGL2 2.0.0
Graphics, audio, GUI and retro-computing library for the ESP32 (ESP-IDF)
Loading...
Searching...
No Matches
drummachine.cpp
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#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <math.h>
31
32#include "freertos/FreeRTOS.h"
33#include "freertos/task.h"
34
35#ifndef FABGL_EMULATED
36 #include "esp_heap_caps.h"
37 #include "esp_memory_utils.h"
38#endif
39
40#include "drummachine.h"
41
42
43
44namespace fabgl {
45
46
47
49// DrumSample
50
51
52int16_t DrumSample::s_decodeTable[256];
53
54
55static constexpr int MULAW_BIAS = 0x84;
56static constexpr int MULAW_CLIP = 32635;
57
58
60{
61 if (s_decodeTable[0] != 0)
62 return; // already built
63 for (int i = 0; i < 256; ++i) {
64 int u = ~i & 0xFF;
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;
69 }
70}
71
72
73uint8_t DrumSample::encode(int value)
74{
75 int sign = 0;
76 if (value < 0) {
77 sign = 0x80;
78 value = -value;
79 }
80 if (value > MULAW_CLIP)
81 value = MULAW_CLIP;
82 value += MULAW_BIAS;
83 int exponent = 7;
84 for (int mask = 0x4000; exponent > 0 && (value & mask) == 0; mask >>= 1)
85 --exponent;
86 int mantissa = (value >> (exponent + 3)) & 0x0F;
87 return ~(sign | (exponent << 4) | mantissa) & 0xFF;
88}
89
90
92 : m_data(nullptr),
93 m_length(0),
94 m_sampleRate(0),
95 m_format(DrumSampleFormat::PCM16),
96 m_owned(false)
97{
98}
99
100
101DrumSample::DrumSample(uint8_t const * muLawData, int length, int sampleRate)
102 : m_data(muLawData),
103 m_length(length),
104 m_sampleRate(sampleRate),
105 m_format(DrumSampleFormat::MuLaw),
106 m_owned(false)
107{
108}
109
110
111DrumSample::DrumSample(int16_t const * pcmData, int length, int sampleRate)
112 : m_data(pcmData),
113 m_length(length),
114 m_sampleRate(sampleRate),
115 m_format(DrumSampleFormat::PCM16),
116 m_owned(false)
117{
118}
119
120
121DrumSample::~DrumSample()
122{
123 clear();
124}
125
126
128{
129 if (m_owned)
130 free((void *) m_data);
131 m_data = nullptr;
132 m_length = 0;
133 m_owned = false;
134}
135
136
137// a buffer for the converted samples, in PSRAM when available
138static uint8_t * allocSampleBuffer(int size)
139{
140 #ifndef FABGL_EMULATED
141 auto buf = (uint8_t *) heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
142 if (!buf)
143 buf = (uint8_t *) heap_caps_malloc(size, MALLOC_CAP_8BIT);
144 return buf;
145 #else
146 return (uint8_t *) malloc(size);
147 #endif
148}
149
150
151// copies to PSRAM with a MEMW after every store: on ESP32 before rev3 a PSRAM store followed by a load may be lost
152// (the library is not compiled with the PSRAM cache workaround)
153static void safeCopy(uint8_t * dest, uint8_t const * src, int count)
154{
155 #ifndef FABGL_EMULATED
156 if (esp_ptr_external_ram(dest)) {
157 for (int i = 0; i < count; ++i) {
158 dest[i] = src[i];
159 __asm__ __volatile__ ("memw");
160 }
161 return;
162 }
163 #endif
164 memcpy(dest, src, count);
165}
166
167
168namespace {
169
170// reads the frames of a WAV data chunk as mono float values (-1..1)
171struct WAVReader {
172
173 FILE * file;
174 int format; // 1 = PCM, 3 = float
175 int channels;
176 int bytesPerSample;
177 int frameSize;
178 int frames; // frames to read
179 int readFrames;
180 uint8_t buf[1024];
181 int bufFrames;
182 int bufPos;
183 bool error;
184
185 bool readChunk()
186 {
187 int count = imin((int) sizeof(buf) / frameSize, frames - readFrames);
188 if (count <= 0)
189 return false;
190 if (fread(buf, frameSize, count, file) != (size_t) count) {
191 error = true;
192 return false;
193 }
194 bufFrames = count;
195 bufPos = 0;
196 return true;
197 }
198
199 float sampleValue(uint8_t const * p)
200 {
201 switch (bytesPerSample) {
202 case 1:
203 return ((int) p[0] - 128) / 128.0f;
204 case 2:
205 return (int16_t) (p[0] | (p[1] << 8)) / 32768.0f;
206 case 3:
207 return (int32_t) ((p[0] << 8) | (p[1] << 16) | (p[2] << 24)) / 2147483648.0f;
208 default:
209 if (format == 3) {
210 float f;
211 memcpy(&f, p, 4);
212 return f;
213 }
214 return (int32_t) (p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24)) / 2147483648.0f;
215 }
216 }
217
218 // false at the end of the data
219 bool next(float * value)
220 {
221 if (readFrames >= frames)
222 return false;
223 if (bufPos >= bufFrames && !readChunk())
224 return false;
225 uint8_t const * frame = buf + bufPos * frameSize;
226 float sum = 0;
227 for (int c = 0; c < channels; ++c)
228 sum += sampleValue(frame + c * bytesPerSample);
229 *value = sum / channels;
230 ++bufPos;
231 ++readFrames;
232 return true;
233 }
234
235 void rewind(long dataPos)
236 {
237 fseek(file, dataPos, SEEK_SET);
238 readFrames = 0;
239 bufFrames = 0;
240 bufPos = 0;
241 }
242};
243
244
245// collects the encoded samples and copies them to the destination buffer in chunks
246struct SampleWriter {
247 uint8_t * dest;
248 int count;
249 uint8_t chunk[256];
250 int chunkLen;
251
252 void put(uint8_t value)
253 {
254 chunk[chunkLen++] = value;
255 if (chunkLen == sizeof(chunk))
256 flush();
257 }
258
259 void flush()
260 {
261 safeCopy(dest + count, chunk, chunkLen);
262 count += chunkLen;
263 chunkLen = 0;
264 }
265};
266
267
268uint32_t readLE(uint8_t const * p, int bytes)
269{
270 uint32_t r = 0;
271 for (int i = bytes - 1; i >= 0; --i)
272 r = (r << 8) | p[i];
273 return r;
274}
275
276} // anonymous namespace
277
278
279DrumSampleError DrumSample::loadWAV(char const * filename, int sampleRate, int maxLength, DrumSampleFormat format)
280{
281 clear();
282
283 FILE * file = fopen(filename, "rb");
284 if (!file)
286
287 auto result = DrumSampleError::InvalidFormat;
288 auto reader = new WAVReader;
289 auto writer = new SampleWriter;
290
291 uint8_t header[40];
292 int wavFormat = 0, channels = 0, srcRate = 0, bits = 0, blockAlign = 0;
293 bool pcm16 = format == DrumSampleFormat::PCM16;
294 long dataPos = 0;
295 int dataSize = 0;
296
297 if (fread(header, 1, 12, file) != 12 || memcmp(header, "RIFF", 4) || memcmp(header + 8, "WAVE", 4))
298 goto done;
299
300 // chunks
301 while (true) {
302 if (fread(header, 1, 8, file) != 8)
303 goto done;
304 int size = (int) readLE(header + 4, 4);
305 if (size < 0)
306 goto done;
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)
310 goto done;
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); // WAVE_FORMAT_EXTENSIBLE: subformat
318 fseek(file, size - len + (size & 1), SEEK_CUR);
319 } else if (memcmp(header, "data", 4) == 0) {
320 dataPos = ftell(file);
321 dataSize = size;
322 break;
323 } else
324 fseek(file, size + (size & 1), SEEK_CUR);
325 }
326
327 if (channels < 1 || channels > 8 || srcRate < 1000 || srcRate > 200000 || blockAlign < 1) {
329 goto done;
330 }
331 if (!((wavFormat == 1 && (bits == 8 || bits == 16 || bits == 24 || bits == 32)) || (wavFormat == 3 && bits == 32))) {
333 goto done;
334 }
335 if (blockAlign != channels * bits / 8) {
337 goto done;
338 }
339
340 {
341 reader->file = file;
342 reader->format = wavFormat;
343 reader->channels = channels;
344 reader->bytesPerSample = bits / 8;
345 reader->frameSize = blockAlign;
346 reader->error = false;
347
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));
353 }
354 if (outLength < 2) {
356 goto done;
357 }
358 reader->frames = srcFrames;
359
360 // first pass: peak level, to normalize
361 float peak = 0, v;
362 reader->rewind(dataPos);
363 while (reader->next(&v))
364 peak = fmaxf(peak, fabsf(v));
365 if (reader->error) {
367 goto done;
368 }
369 float gain = 32767.0f * (peak > 0.0001f ? 0.98f / peak : 1.0f);
370
371 auto data = allocSampleBuffer(outLength * (pcm16 ? 2 : 1));
372 if (!data) {
374 goto done;
375 }
376
377 // second pass: sample rate conversion (box average when reducing, linear interpolation when increasing)
378 constexpr int FADE = 64; // fade out of the last samples
379 int out = 0;
380 auto emit = [&](float value) {
381 if (out >= outLength)
382 return;
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)));
387 if (pcm16) {
388 writer->put(x & 0xFF); // little endian
389 writer->put((x >> 8) & 0xFF);
390 } else
391 writer->put(encode(x));
392 ++out;
393 };
394 writer->dest = data;
395 writer->count = 0;
396 writer->chunkLen = 0;
397 reader->rewind(dataPos);
398 if (srcRate > sampleRate) {
399 float sum = 0;
400 int count = 0;
401 int64_t bin = 0;
402 for (int64_t k = 0; reader->next(&v); ++k) {
403 int64_t b = k * sampleRate / srcRate;
404 if (b != bin) {
405 emit(sum / count);
406 sum = 0;
407 count = 0;
408 bin = b;
409 }
410 sum += v;
411 ++count;
412 }
413 if (count)
414 emit(sum / count);
415 } else {
416 float prev = 0, cur = 0;
417 int64_t curIndex = -1; // index of "cur" in the source
418 for (int j = 0; j < outLength; ++j) {
419 // source position of the output sample j
420 int64_t pos = (int64_t) j * srcRate * 65536 / sampleRate;
421 int64_t ipos = pos >> 16;
422 while (curIndex < ipos + 1) {
423 prev = cur;
424 if (!reader->next(&cur))
425 cur = 0;
426 ++curIndex;
427 }
428 float t = (pos & 0xFFFF) / 65536.0f;
429 emit(prev + (cur - prev) * t);
430 }
431 }
432 while (out < outLength)
433 emit(0);
434 writer->flush();
435
436 if (reader->error) {
437 free(data);
439 goto done;
440 }
441
442 m_data = data;
443 m_length = outLength;
444 m_sampleRate = sampleRate;
445 m_format = format;
446 m_owned = true;
447 result = DrumSampleError::None;
448 }
449
450done:
451 delete writer;
452 delete reader;
453 fclose(file);
454 return result;
455}
456
457
458// DrumSample
460
461
462
464// DrumPattern
465
466
468{
469 clearSteps();
470 length = 16;
471 swing = 50;
472 tempo = 120;
473 memset(name, 0, sizeof(name));
474}
475
476
478{
479 memset(steps, 0, sizeof(steps));
480}
481
482
483void DrumPattern::set(int step, int instrument, int velocity)
484{
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);
488 }
489}
490
491
493{
494 for (int i = 0; i < MAX_STEPS; ++i)
495 set(i, instrument, 0);
496}
497
498
499void DrumPattern::setRow(int instrument, char const * text)
500{
501 for (int i = 0; i < MAX_STEPS; ++i) {
502 int velocity = 0;
503 if (text && *text) {
504 switch (*text++) {
505 case '-': velocity = 1; break;
506 case 'x': velocity = 2; break;
507 case 'X': velocity = 3; break;
508 default: velocity = 0; break;
509 }
510 }
511 set(i, instrument, velocity);
512 }
513}
514
515
517{
518 for (int i = 0; i < MAX_STEPS; ++i)
519 if (steps[i])
520 return false;
521 return true;
522}
523
524
525void DrumPattern::setName(char const * value)
526{
527 memset(name, 0, sizeof(name));
528 if (value)
529 strncpy(name, value, NAME_LENGTH);
530}
531
532
533// DrumPattern
535
536
537
539// DrumMachine
540
541
542DrumMachine::DrumMachine()
543 : m_soundGenerator(nullptr),
544 m_sampleRate(FABGL_SOUNDGEN_DEFAULT_SAMPLE_RATE),
545 m_channel(this),
546 m_voiceAge(0),
547 m_hitsWrite(0),
548 m_hitsRead(0),
549 m_pattern(nullptr),
550 m_nextPattern(nullptr),
551 m_songLength(0),
552 m_songLoop(true),
553 m_songMode(false),
554 m_songPos(0),
555 m_playing(false),
556 m_startRequest(false),
557 m_step(-1),
558 m_counter(0),
559 m_timingChanged(true),
560 m_loops(0),
561 m_eraseMask(0),
562 m_metronome(false),
563 m_metronomeLevel(0),
564 m_gateLevel(3),
565 m_click(nullptr),
566 m_clickLength(0),
567 m_clickPos(-1),
568 m_clickOffset(0),
569 m_renderCount(0),
570 m_outputLevel(0)
571{
573 for (int i = 0; i < INSTRUMENTS; ++i) {
574 auto & ins = m_instruments[i];
575 ins.sample = nullptr;
576 ins.pitchInc = 65536;
577 ins.decayCoef = ENV_ONE;
578 ins.level = 80;
579 ins.tune = 0;
580 ins.decay = 100;
581 ins.mute = false;
582 ins.chokeGroup = 0;
583 ins.generation = 0;
584 m_hitCount[i] = 0;
585 m_skipStep[i] = -1;
586 }
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);
592 setMetronome(false);
593 m_channel.setVolume(127);
594}
595
596
597DrumMachine::~DrumMachine()
598{
599 if (m_soundGenerator)
600 m_soundGenerator->detach(&m_channel);
601 free(m_click);
602}
603
604
605void DrumMachine::begin(SoundGenerator * soundGenerator)
606{
607 m_soundGenerator = soundGenerator;
608
609 soundGenerator->attach(&m_channel);
610 m_channel.enable(true);
611 soundGenerator->play(true);
612
613 // the actual sample rate is known after the sound generator starts
614 m_sampleRate = soundGenerator->sampleRate();
615
616 // the oversampled output keeps the resolution of the quiet tails: no noise gate
617 if (soundGenerator->oversampling() > 1)
618 m_gateLevel = 0;
619
620 for (int i = 0; i < INSTRUMENTS; ++i)
621 setDecay(i, m_instruments[i].decay);
622
623 // metronome clicks: 12 ms, accent at 2 kHz, normal at 1.5 kHz
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));
630 }
631}
632
633
634// waits until the sound generator has rendered a whole block after the caller changes
635void DrumMachine::waitRender()
636{
637 if (!m_soundGenerator || !m_soundGenerator->playing())
638 return;
639 uint32_t start = m_renderCount;
640 for (int i = 0; i < 50 && m_renderCount - start < 2; ++i)
641 vTaskDelay(1);
642}
643
644
645void DrumMachine::setSample(int instrument, DrumSample const * sample)
646{
647 auto & ins = m_instruments[instrument];
648 ins.sample = sample;
649 ins.generation = ins.generation + 1; // stops the voices of the previous sample
650 waitRender();
651}
652
653
654void DrumMachine::setLevel(int instrument, int value)
655{
656 m_instruments[instrument].level = iclamp(value, 0, 100);
657}
658
659
660void DrumMachine::setTune(int instrument, int cents)
661{
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));
665}
666
667
668void DrumMachine::setDecay(int instrument, int value)
669{
670 auto & ins = m_instruments[instrument];
671 ins.decay = iclamp(value, 0, 100);
672 if (ins.decay >= 100)
673 ins.decayCoef = ENV_ONE;
674 else {
675 // time constant from 15 ms (0) to 3 s (99)
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))));
678 }
679}
680
681
682void DrumMachine::setVelocityGains(int soft, int normal, int accent)
683{
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;
688}
689
690
691void DrumMachine::setMetronome(bool value, int volume)
692{
693 m_metronomeLevel = iclamp(volume, 0, 100) * 32767 / 100;
694 m_metronome = value;
695}
696
697
698void DrumMachine::trigger(int instrument, int velocity)
699{
700 if (instrument < 0 || instrument >= INSTRUMENTS)
701 return;
702 int w = m_hitsWrite;
703 int next = (w + 1) % HIT_QUEUE_SIZE;
704 if (next == m_hitsRead)
705 return; // queue full
706 m_hits[w].instrument = instrument;
707 m_hits[w].velocity = iclamp(velocity, 1, 3);
708 __sync_synchronize();
709 m_hitsWrite = next;
710}
711
712
713bool DrumMachine::sounding(int instrument)
714{
715 for (int i = 0; i < VOICES; ++i)
716 if (m_voices[i].instrument == instrument && !m_voices[i].fading)
717 return true;
718 return false;
719}
720
721
723{
724 m_nextPattern = nullptr;
725 m_pattern = pattern;
726 m_loops = 0;
727 m_timingChanged = true;
728}
729
730
732{
733 if (m_playing && m_pattern)
734 m_nextPattern = pattern;
735 else
737}
738
739
740void DrumMachine::setSong(DrumPattern * const * patterns, int count, bool loop)
741{
742 int len = 0;
743 for (int i = 0; i < count && len < MAX_SONG_STEPS; ++i)
744 if (patterns[i])
745 m_song[len++] = patterns[i];
746 m_songLoop = loop;
747 m_songLength = len;
748}
749
750
752{
753 if (!m_pattern)
754 return;
755 m_songMode = false;
756 m_startRequest = true;
757 m_playing = true;
758}
759
760
761void DrumMachine::playSong(int position)
762{
763 if (m_songLength == 0)
764 return;
765 m_songMode = true;
766 m_songPos = iclamp(position, 0, m_songLength - 1);
767 m_startRequest = true;
768 m_playing = true;
769}
770
771
773{
774 m_playing = false;
775 m_startRequest = false;
776 m_eraseMask = 0;
777}
778
779
781{
782 if (m_pattern) {
783 m_pattern->tempo = iclamp(bpm, MIN_TEMPO, MAX_TEMPO);
784 m_timingChanged = true;
785 }
786}
787
788
789void DrumMachine::setSwing(int percent)
790{
791 if (m_pattern) {
792 m_pattern->swing = iclamp(percent, 50, 75);
793 m_timingChanged = true;
794 }
795}
796
797
798int DrumMachine::recordHit(int instrument, int velocity)
799{
800 auto pattern = m_pattern;
801 int step = m_step;
802 if (!m_playing || m_startRequest || !pattern || step < 0 || instrument < 0 || instrument >= INSTRUMENTS) {
803 trigger(instrument, velocity);
804 return -1;
805 }
806 int32_t counter = m_counter; // samples (Q8) to the next step
807 int32_t length = m_stepLength[step & 1];
808 int target = step;
809 if (counter < length / 2) {
810 // nearer to the next step: it is played now, the sequencer must not play it again
811 target = (step + 1) % imax(1, pattern->length);
812 m_skipStep[instrument] = target;
813 }
814 pattern->set(target, instrument, iclamp(velocity, 1, 3));
815 trigger(instrument, velocity);
816 return target;
817}
818
819
820// runs inside the sound generator interrupt
821void DrumMachine::updateTiming()
822{
823 m_timingChanged = false;
824 int tempo = iclamp(m_pattern->tempo, MIN_TEMPO, MAX_TEMPO);
825 int swing = iclamp(m_pattern->swing, 50, 75);
826 int32_t step = m_sampleRate * 15 * 256 / tempo; // 1/16 note, Q8
827 int32_t even = step * 2 * swing / 100;
828 m_stepLength[0] = even;
829 m_stepLength[1] = step * 2 - even;
830}
831
832
833// runs inside the sound generator interrupt
834void DrumMachine::switchPattern(DrumPattern * pattern)
835{
836 m_pattern = pattern;
837 m_loops = 0;
838 m_timingChanged = true;
839 for (int i = 0; i < INSTRUMENTS; ++i)
840 m_skipStep[i] = -1;
841}
842
843
844// runs inside the sound generator interrupt: advances the sequencer by one block
845void DrumMachine::sequencerAdvance()
846{
847 if (m_startRequest) {
848 m_startRequest = false;
849 if (m_songMode)
850 switchPattern(m_song[m_songPos]);
851 else {
852 m_nextPattern = nullptr;
853 switchPattern(m_pattern);
854 }
855 m_step = -1;
856 m_counter = BLOCK_SIZE << 8; // the first step plays in this block
857 }
858
859 if (!m_playing || !m_pattern)
860 return;
861
862 m_counter -= BLOCK_SIZE << 8;
863 while (m_playing && m_counter <= 0) {
864 int next = m_step + 1;
865 if (m_step >= 0 && next >= m_pattern->length) {
866 // end of the pattern
867 next = 0;
868 DrumPattern * nextPattern = nullptr;
869 if (m_songMode) {
870 int pos = m_songPos + 1;
871 if (pos >= m_songLength) {
872 if (!m_songLoop || m_songLength == 0) {
873 m_playing = false;
874 break;
875 }
876 pos = 0;
877 }
878 m_songPos = pos;
879 nextPattern = m_song[pos];
880 } else if (m_nextPattern) {
881 nextPattern = m_nextPattern;
882 m_nextPattern = nullptr;
883 }
884 if (nextPattern)
885 switchPattern(nextPattern);
886 else
887 m_loops = m_loops + 1;
888 }
889 if (next >= m_pattern->length)
890 next = 0; // the pattern has been shortened
891 m_step = next;
892 if (m_timingChanged)
893 updateTiming();
894 m_counter += m_stepLength[next & 1];
895 playStep();
896 }
897}
898
899
900// runs inside the sound generator interrupt
901void DrumMachine::playStep()
902{
903 auto pattern = m_pattern;
904 int step = m_step;
905
906 if (m_eraseMask) {
907 uint32_t clear = 0;
908 for (int i = 0; i < INSTRUMENTS; ++i)
909 if (m_eraseMask & (1 << i))
910 clear |= 3u << (i * 2);
911 pattern->steps[step] &= ~clear;
912 }
913
914 uint32_t bits = pattern->steps[step];
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)
919 m_skipStep[i] = -1;
920 else
921 startVoice(i, velocity);
922 }
923 }
924
925 if (m_metronome && (step & 3) == 0) {
926 m_clickPos = 0;
927 m_clickOffset = step == 0 ? 0 : m_clickLength;
928 }
929}
930
931
932// runs inside the sound generator interrupt
933void DrumMachine::startVoice(int instrument, int velocity)
934{
935 auto & ins = m_instruments[instrument];
936 m_hitCount[instrument] = m_hitCount[instrument] + 1;
937 auto sample = ins.sample;
938 if (!sample || sample->length() < 2)
939 return;
940
941 // the previous sound of the instrument and the sounds of its choke group fade out (no clicks)
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))
946 v.fading = true;
947 }
948
949 // a free voice, else the oldest one (preferring the fading ones)
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];
954 if (!voice) {
955 uint32_t oldest = 0;
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) {
960 voice = &v;
961 oldest = age;
962 }
963 }
964 }
965
966 uint32_t inc = ins.pitchInc;
967 if (sample->sampleRate() != m_sampleRate)
968 inc = ((inc >> 4) * sample->sampleRate() / m_sampleRate) << 4;
969
970 voice->data = sample->data();
971 voice->pcm16 = sample->format() == DrumSampleFormat::PCM16;
972 voice->length = sample->length();
973 voice->index = 0;
974 voice->frac = 0;
975 voice->inc = inc;
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;
982 voice->quiet = 0;
983 voice->age = ++m_voiceAge;
984 voice->instrument = instrument;
985}
986
987
988// state of a voice while it is mixed into a block
989struct VoiceState {
990 uint32_t index; // integer part of the position
991 uint32_t frac; // fractional part (Q16)
992 uint32_t inc; // Q16
993 uint32_t last; // last index
994 int32_t g; // gain (Q15 << 4), ramps by dg every sample
995 int32_t dg;
996 int peak; // peak of the output (noise gate)
997 bool ended;
998};
999
1000
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]]; }
1003
1004
1005// mixes a block of a voice (linear interpolation), runs inside the sound generator interrupt
1006template <typename T>
1007static inline void mixVoice(T const * data, int16_t const * decodeTable, VoiceState & st, int32_t * sum)
1008{
1009 uint32_t index = st.index, frac = st.frac, inc = st.inc, last = st.last;
1010 int32_t g = st.g, dg = st.dg;
1011 int peak = 0;
1012 for (int n = 0; n < DrumMachine::BLOCK_SIZE; ++n) {
1013 if (index >= last) {
1014 st.ended = true;
1015 break;
1016 }
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);
1020 g += dg;
1021 int out = (s * (g >> 4)) >> 15;
1022 sum[n] += out;
1023 if (out < 0)
1024 out = -out;
1025 if (out > peak)
1026 peak = out;
1027 frac += inc;
1028 index += frac >> 16;
1029 frac &= 0xFFFF;
1030 }
1031 st.index = index;
1032 st.frac = frac;
1033 st.peak = peak;
1034}
1035
1036
1037// soft limiter: linear up to HEADROOM, then smoothly bent towards the full scale
1038static inline int softClip(int x)
1039{
1040 constexpr int HEADROOM = 24576;
1041 constexpr int R = 32767 - HEADROOM;
1042 int a = x < 0 ? -x : x;
1043 if (a <= HEADROOM)
1044 return x;
1045 int u = imin(a - HEADROOM, R * 31);
1046 int y = HEADROOM + R * u / (R + u);
1047 return x < 0 ? -y : y;
1048}
1049
1050
1051// runs inside the sound generator interrupt: fixed point only. Renders BLOCK_SIZE samples (-32767..32767)
1052void DrumMachine::renderBlock(int16_t * dest)
1053{
1054 // live hits
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;
1059 }
1060
1061 sequencerAdvance();
1062
1063 int32_t sum[BLOCK_SIZE] = { };
1064 auto const decodeTable = DrumSample::s_decodeTable;
1065
1066 // noise gate level in mix units: one step of the 8 bit output is 256 * 128 / volume * 4 / 3 (see the mix below)
1067 int const gate = m_gateLevel ? m_gateLevel * (256 * 128 * 4 / 3) / imax(1, m_channel.volume()) : 0;
1068
1069 for (int i = 0; i < VOICES; ++i) {
1070 auto & v = m_voices[i];
1071 if (v.instrument < 0)
1072 continue;
1073 auto & ins = m_instruments[v.instrument];
1074
1075 // gain at the end of this block (Q15): the gain ramps from the previous one, no zipper noise
1076 int32_t g1 = 0;
1077 if (ins.generation != v.generation)
1078 v.fading = true;
1079 if (!v.fading) {
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)
1084 v.fading = true;
1085 }
1086 g1 = (int32_t) (((int64_t) v.velocity * ins.level / 100 * v.env) >> 16);
1087 }
1088 if (v.fading)
1089 g1 = 0;
1090
1091 int32_t g = v.gain << 4;
1092 int32_t dg = g1 - v.gain; // per sample (Q15 << 4) / 16
1093 VoiceState st = { v.index, v.frac, v.inc, v.length - 1, g, dg, 0, false };
1094 if (v.pcm16)
1095 mixVoice((int16_t const *) v.data, nullptr, st, sum);
1096 else
1097 mixVoice((uint8_t const *) v.data, decodeTable, st, sum);
1098 if (st.ended)
1099 v.instrument = -1; // end of the sound
1100 int peak = st.peak;
1101 v.index = st.index;
1102 v.frac = st.frac;
1103 v.gain = g1;
1104 if (v.fading)
1105 v.instrument = -1;
1106 else if (gate) {
1107 // noise gate: the tail below the gate level fades out in the next block
1108 if (peak >= gate) {
1109 v.opened = true;
1110 v.quiet = 0;
1111 } else if (v.opened && ++v.quiet >= GATE_BLOCKS)
1112 v.fading = true;
1113 }
1114 }
1115
1116 // metronome
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)
1122 m_clickPos = -1;
1123 }
1124 }
1125
1126 // mix: master volume, headroom 0.75, soft limiter, 8 bit
1127 int volume = m_channel.volume();
1128 int peak = 0;
1129 for (int n = 0; n < BLOCK_SIZE; ++n) {
1130 int x = softClip(((sum[n] * volume) >> 7) * 3 / 4);
1131 int a = x < 0 ? -x : x;
1132 if (a > peak)
1133 peak = a;
1134 dest[n] = iclamp(x, -32767, 32767);
1135 }
1136 // meter: peak hold with a decay of about 0.4 s
1137 m_outputLevel = imax(peak, m_outputLevel - 32767 * BLOCK_SIZE * 5 / (m_sampleRate * 2));
1138
1139 m_renderCount = m_renderCount + 1;
1140}
1141
1142
1143// DrumMachine
1145
1146
1147
1148} // end of namespace
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.
Definition drummachine.h:91
void attach(WaveformGenerator *value)
Attaches a waveform generator.
Definition soundgen.cpp:706
int sampleRate()
Determines the sample rate.
Definition soundgen.h:534
bool playing()
Determines whether the sound generator is playing.
Definition soundgen.h:490
bool play(bool value)
Starts or stops playing.
Definition soundgen.cpp:666
int oversampling()
Gets the oversampling factor (see setOversampling()).
Definition soundgen.h:555
SoundGenerator handles audio output.
Definition soundgen.h:393
This file contains the sample based drum machine: DrumSample, DrumPattern and DrumMachine.
DrumSampleFormat
Sample format of a DrumSample.
Definition drummachine.h:65
DrumSampleError
Result of DrumSample::loadWAV().
Definition drummachine.h:52
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]
char name[NAME_LENGTH+1]
A drum pattern: up to 32 steps (1/16 notes) for 16 instruments.