-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioEngine.cpp
More file actions
431 lines (364 loc) · 14 KB
/
AudioEngine.cpp
File metadata and controls
431 lines (364 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#include "AudioEngine.h"
#include "NetAudio.h"
#include <M5Unified.h>
#include <esp_heap_caps.h>
#include <cstring>
#include <cstdint>
#include <cstdlib>
AudioEngine Engine;
// ---------------------------------------------------------------------------
// Setup
// ---------------------------------------------------------------------------
bool AudioEngine::begin() {
const size_t bytes = MAX_SAMPLES * sizeof(int16_t);
for (uint8_t i = 0; i < NUM_TRACKS; ++i) {
_tracks[i].buf =
(int16_t*)heap_caps_malloc(bytes, MALLOC_CAP_SPIRAM);
if (!_tracks[i].buf) return false;
memset(_tracks[i].buf, 0, bytes);
}
_master = (int16_t*)heap_caps_malloc(bytes, MALLOC_CAP_SPIRAM);
if (!_master) return false;
// Start clean: neither mic nor speaker active.
M5.Speaker.end();
M5.Mic.end();
return true;
}
// ---------------------------------------------------------------------------
// Recording (mic active, speaker off)
// ---------------------------------------------------------------------------
void AudioEngine::resetMasterIfTrack(uint8_t track) {
// Re-recording the master track redefines the tempo grid.
if ((int8_t)track == _masterTrack) {
_masterLoopLen = 0;
_masterTrack = -1;
}
}
void AudioEngine::startRecording(uint8_t track) {
if (track >= NUM_TRACKS) return;
if (_state == STATE_PLAYING) stopPlayback();
resetMasterIfTrack(track);
M5.Speaker.end(); // free the shared I2S bus
auto cfg = M5.Mic.config();
cfg.sample_rate = SAMPLE_RATE;
cfg.noise_filter_level = 8; // gentle high-pass, kills DC rumble
M5.Mic.config(cfg);
M5.Mic.begin();
// Discard the mic/PDM + DC-filter settling transient, otherwise every
// take starts with an audible click/pop at the loop seam.
static int16_t scratch[REC_CHUNK];
uint32_t toDiscard = MIC_WARMUP_SAMPLES;
while (toDiscard) {
size_t n = (toDiscard < REC_CHUNK) ? toDiscard : REC_CHUNK;
M5.Mic.record(scratch, n, SAMPLE_RATE, false);
while (M5.Mic.isRecording()) { M5.delay(1); }
toDiscard -= n;
}
_micSource = MIC_INTERNAL;
_recTrack = track;
_recPos = 0;
_recStartMs = millis(); // beat 0 of the visual metronome
_tracks[track].length = 0; // overwrite from scratch
_state = STATE_RECORDING;
}
void AudioEngine::serviceRecording() {
if (_state != STATE_RECORDING) return;
Track& t = _tracks[_recTrack];
// Queue another chunk while there is room in the mic DMA and buffer space.
if (_recPos < MAX_SAMPLES && M5.Mic.isRecording() != 2) {
size_t chunk = MAX_SAMPLES - _recPos;
if (chunk > REC_CHUNK) chunk = REC_CHUNK;
if (M5.Mic.record(t.buf + _recPos, chunk, SAMPLE_RATE, false)) {
_recPos += chunk;
}
}
// Track buffer is full -> auto-stop.
if (_recPos >= MAX_SAMPLES) stopRecording();
}
void AudioEngine::stopRecording() {
if (_state != STATE_RECORDING) return;
while (M5.Mic.isRecording()) { M5.delay(1); } // flush last chunk
M5.Mic.end();
finalizeTake();
_state = STATE_IDLE;
}
// ---------------------------------------------------------------------------
// Remote recording (StickS3 over ESP-NOW) - true overdub: playback keeps
// running, the internal mic is never touched.
// ---------------------------------------------------------------------------
void AudioEngine::startRemoteRecording(uint8_t track) {
if (track >= NUM_TRACKS) return;
resetMasterIfTrack(track);
_micSource = MIC_REMOTE;
_recTrack = track;
_recPos = 0;
_recStartMs = millis();
_tracks[track].length = 0;
_state = STATE_RECORDING; // playback (if any) is left running
}
void AudioEngine::serviceRemoteRecording(NetAudio& net) {
if (_state != STATE_RECORDING || _micSource != MIC_REMOTE) return;
Track& tr = _tracks[_recTrack];
if (_recPos >= MAX_SAMPLES) { stopRemoteRecording(); return; }
size_t got = net.pull(tr.buf + _recPos, MAX_SAMPLES - _recPos);
_recPos += got;
}
void AudioEngine::stopRemoteRecording() {
if (_state != STATE_RECORDING || _micSource != MIC_REMOTE) return;
// Drop the tail (KEY1-release transient picked up by the mic).
if (_recPos > REMOTE_TAIL_TRIM) _recPos -= REMOTE_TAIL_TRIM;
else _recPos = 0;
finalizeTake();
_state = STATE_IDLE;
startPlayback(); // play the new mix incl. the fresh take
}
// ---------------------------------------------------------------------------
// Shared take finalisation: onset trim, master quantisation, auto-align, fade.
// ---------------------------------------------------------------------------
void AudioEngine::finalizeTake() {
Track& tr = _tracks[_recTrack];
int16_t* buf = tr.buf;
uint32_t rawLen = _recPos;
const bool hadMaster = hasMaster(); // captured before we maybe set one
// (2) Onset trim: shift content so the first hit sits on sample 0.
uint32_t onset = findOnset(buf, rawLen);
if (onset > 0) {
memmove(buf, buf + onset, (rawLen - onset) * sizeof(int16_t));
}
uint32_t lenT = rawLen - onset;
// (1) Master loop length: first take defines the grid, the rest snap to it.
uint32_t finalLen;
if (!hadMaster) {
finalLen = lenT;
_masterLoopLen = lenT;
_masterTrack = _recTrack;
} else {
uint32_t k = (lenT + _masterLoopLen / 2) / _masterLoopLen; // round
if (k < 1) k = 1;
finalLen = k * _masterLoopLen;
while (finalLen > MAX_SAMPLES && k > 1) finalLen = (--k) * _masterLoopLen;
if (finalLen > lenT) { // pad the tail with silence up to the grid length
memset(buf + lenT, 0, (finalLen - lenT) * sizeof(int16_t));
}
}
tr.length = finalLen;
// (5) Auto-align a follower's groove to the master via cross-correlation.
if (hadMaster && finalLen > 0) {
int32_t shift = bestAlignShift(buf, finalLen);
if (shift > 0) rotateLeft(buf, finalLen, (uint32_t)shift);
}
// (4) Smooth the loop seam.
applyFades(buf, finalLen);
}
// ---------------------------------------------------------------------------
// Loop-matching helpers
// ---------------------------------------------------------------------------
uint32_t AudioEngine::findOnset(const int16_t* buf, uint32_t len) const {
if (len == 0) return 0;
int32_t peak = 1;
for (uint32_t i = 0; i < len; ++i) {
int32_t a = abs((int32_t)buf[i]);
if (a > peak) peak = a;
}
int32_t thr = peak / 8;
if (thr < ONSET_FLOOR) thr = ONSET_FLOOR;
uint32_t o = 0;
while (o < len && abs((int32_t)buf[o]) <= thr) ++o;
if (o >= len) return 0; // silent take -> don't trim
return (o > ONSET_PREROLL) ? o - ONSET_PREROLL : 0;
}
void AudioEngine::applyFades(int16_t* buf, uint32_t len) const {
if (len < 2 * FADE_SAMPLES) return;
for (uint32_t i = 0; i < FADE_SAMPLES; ++i) {
int32_t g = (int32_t)i; // 0..FADE_SAMPLES
buf[i] = (int16_t)((int32_t)buf[i] * g / (int32_t)FADE_SAMPLES);
buf[len - 1 - i] = (int16_t)((int32_t)buf[len - 1 - i] * g / (int32_t)FADE_SAMPLES);
}
}
// Find the circular left-shift (0..len) that best lines the new loop up with
// the master mix. Down-sampled and windowed so it stays cheap on the ESP32.
int32_t AudioEngine::bestAlignShift(const int16_t* buf, uint32_t len) const {
if (_masterTrack < 0 || _masterLoopLen == 0 || len == 0) return 0;
const int16_t* m = _tracks[_masterTrack].buf;
const uint32_t mLen = _masterLoopLen;
uint32_t cmp = mLen < len ? mLen : len;
if (cmp > ALIGN_CMP_LEN) cmp = ALIGN_CMP_LEN;
int64_t best = INT64_MIN;
int32_t bestShift = 0;
for (int32_t d = -(int32_t)ALIGN_WINDOW; d <= (int32_t)ALIGN_WINDOW;
d += (int32_t)ALIGN_DECIM) {
int64_t acc = 0;
for (uint32_t i = 0; i < cmp; i += ALIGN_DECIM) {
uint32_t fi = ((int32_t)i + d + (int32_t)len) % (int32_t)len;
acc += (int32_t)buf[fi] * (int32_t)m[i % mLen];
}
if (acc > best) { best = acc; bestShift = d; }
}
return ((bestShift % (int32_t)len) + (int32_t)len) % (int32_t)len;
}
// In-place circular left rotation via the three-reversal trick (no scratch).
void AudioEngine::rotateLeft(int16_t* buf, uint32_t len, uint32_t shift) const {
shift %= len;
if (shift == 0) return;
auto rev = [&](uint32_t a, uint32_t b) {
while (a < b) { int16_t t = buf[a]; buf[a] = buf[b]; buf[b] = t; ++a; --b; }
};
rev(0, shift - 1);
rev(shift, len - 1);
rev(0, len - 1);
}
// ---------------------------------------------------------------------------
// Mixing
// ---------------------------------------------------------------------------
// i-outer / track-inner so per-track effect state (LOFI hold) is trivial and
// no big int32 accumulator buffer is needed. ~4 * masterLen ops -> a few ms.
void AudioEngine::render() {
_masterLen = 0;
for (uint8_t t = 0; t < NUM_TRACKS; ++t) {
if (_tracks[t].hasContent() && !_tracks[t].muted) {
if (_tracks[t].length > _masterLen) _masterLen = _tracks[t].length;
}
}
if (_masterLen == 0) return;
int16_t hold[NUM_TRACKS] = {0}; // sample-and-hold state for LOFI
for (uint32_t i = 0; i < _masterLen; ++i) {
int32_t sum = 0;
for (uint8_t t = 0; t < NUM_TRACKS; ++t) {
if (_tracks[t].hasContent() && !_tracks[t].muted) {
sum += effectedSample(_tracks[t], i, hold[t]);
}
}
_master[i] = clip16(sum);
}
}
// One track's effect-processed sample at global index i, looped over its own
// length. `hold` carries the LOFI sample-and-hold state across calls.
int32_t AudioEngine::effectedSample(const Track& tr, uint32_t i,
int16_t& hold) const {
if (!tr.hasContent()) return 0;
const uint32_t L = tr.length;
uint32_t idx = i % L;
if (tr.fx == FX_REVERSE) idx = (L - 1) - idx;
int32_t s = tr.buf[idx];
switch (tr.fx) {
case FX_BITCRUSH:
s &= CRUSH_MASK;
break;
case FX_LOFI:
if ((i % LOFI_DECIM) == 0) hold = (int16_t)s;
s = hold;
break;
case FX_DRIVE:
s = clip16(s * DRIVE_GAIN);
break;
case FX_ECHO: {
uint32_t d = (idx >= ECHO_DELAY) ? idx - ECHO_DELAY : idx + L - ECHO_DELAY;
s = clip16(s + (tr.buf[d] >> 1));
break;
}
default: // FX_NONE / FX_REVERSE handled above
break;
}
return s;
}
// ---------------------------------------------------------------------------
// Merge: bake src (with its effect) into dst, then free src. The combined
// audio replaces dst and its effect is reset (already baked in).
// ---------------------------------------------------------------------------
void AudioEngine::mergeTracks(uint8_t dst, uint8_t src) {
if (dst >= NUM_TRACKS || src >= NUM_TRACKS || dst == src) return;
Track& a = _tracks[dst];
Track& b = _tracks[src];
if (!a.hasContent() && !b.hasContent()) return;
const uint32_t L = a.hasContent() ? a.length : b.length;
if (L == 0 || L > MAX_SAMPLES) return;
const bool wasPlaying = (_state == STATE_PLAYING);
if (wasPlaying) stopPlayback(); // frees _master to use as scratch
int16_t holdA = 0, holdB = 0;
for (uint32_t i = 0; i < L; ++i) {
int32_t s = effectedSample(a, i, holdA) + effectedSample(b, i, holdB);
_master[i] = clip16(s);
}
memcpy(a.buf, _master, L * sizeof(int16_t));
a.length = L;
a.fx = FX_NONE; // effects are now baked into the audio
// Free the source; keep a tempo grid if the source defined it.
const bool srcWasMaster = ((int8_t)src == _masterTrack);
b.length = 0; b.muted = false; b.fx = FX_NONE;
if (srcWasMaster) { _masterTrack = (int8_t)dst; _masterLoopLen = L; }
if (wasPlaying) startPlayback();
}
// ---------------------------------------------------------------------------
// Playback (speaker active, mic off)
// ---------------------------------------------------------------------------
void AudioEngine::startPlayback() {
if (_state == STATE_RECORDING) return;
render();
if (_masterLen == 0) return; // nothing recorded yet
M5.Mic.end(); // free the shared I2S bus
M5.Speaker.begin();
M5.Speaker.setVolume(_volume);
// repeat = 0xFFFFFFFF -> effectively endless loop, handled by the
// speaker's own background task.
M5.Speaker.playRaw(_master, _masterLen, SAMPLE_RATE,
false /*mono*/, 0xFFFFFFFFu, 0, true);
_playStartMs = millis();
_state = STATE_PLAYING;
}
void AudioEngine::stopPlayback() {
if (_state != STATE_PLAYING) return;
M5.Speaker.stop();
M5.Speaker.end();
_state = STATE_IDLE;
}
void AudioEngine::refreshPlayback() {
if (_state != STATE_PLAYING) return;
render();
if (_masterLen == 0) { stopPlayback(); return; }
M5.Speaker.playRaw(_master, _masterLen, SAMPLE_RATE,
false, 0xFFFFFFFFu, 0, true);
_playStartMs = millis();
}
// ---------------------------------------------------------------------------
// Editing
// ---------------------------------------------------------------------------
void AudioEngine::cycleFx(uint8_t track) {
if (track >= NUM_TRACKS) return;
_tracks[track].fx = (Fx)((_tracks[track].fx + 1) % FX_COUNT);
refreshPlayback();
}
void AudioEngine::toggleMute(uint8_t track) {
if (track >= NUM_TRACKS) return;
_tracks[track].muted = !_tracks[track].muted;
refreshPlayback();
}
void AudioEngine::setVolume(uint8_t v) {
_volume = v;
M5.Speaker.setVolume(_volume); // master volume, safe to set any time
}
void AudioEngine::clearTrack(uint8_t track) {
if (track >= NUM_TRACKS) return;
_tracks[track].length = 0;
_tracks[track].muted = false;
_tracks[track].fx = FX_NONE;
// Clearing the master track drops the tempo grid; the next take redefines it.
if (track == _masterTrack) {
_masterLoopLen = 0;
_masterTrack = -1;
}
refreshPlayback();
}
// ---------------------------------------------------------------------------
// Progress reporting for the UI
// ---------------------------------------------------------------------------
float AudioEngine::progress() const {
if (_state == STATE_RECORDING) {
return (float)_recPos / (float)MAX_SAMPLES;
}
if (_state == STATE_PLAYING && _masterLen) {
float loopMs = 1000.0f * _masterLen / SAMPLE_RATE;
float pos = fmodf((float)(millis() - _playStartMs), loopMs);
return pos / loopMs;
}
return 0.0f;
}