-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio_output_chain.cpp
More file actions
284 lines (235 loc) · 8.98 KB
/
Copy pathaudio_output_chain.cpp
File metadata and controls
284 lines (235 loc) · 8.98 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
#include "audio_internal.h"
#include <math.h>
#include <string.h>
namespace AudioInternal {
bool AudioFileSourceRamWav::open(const uint8_t *pcmData,
uint32_t pcmBytes,
uint16_t channelCount,
uint32_t sampleRate,
uint16_t bitsPerSample) {
if (!pcmData || pcmBytes == 0 || channelCount == 0 || sampleRate == 0 || bitsPerSample == 0) {
return false;
}
const uint16_t blockAlign = static_cast<uint16_t>(channelCount * (bitsPerSample / 8U));
if (blockAlign == 0) return false;
const uint32_t byteRate = sampleRate * static_cast<uint32_t>(blockAlign);
const uint32_t riffSize = 36U + pcmBytes;
memset(header_, 0, sizeof(header_));
memcpy(&header_[0], "RIFF", 4);
writeLe32(&header_[4], riffSize);
memcpy(&header_[8], "WAVE", 4);
memcpy(&header_[12], "fmt ", 4);
writeLe32(&header_[16], 16U);
writeLe16(&header_[20], 1U);
writeLe16(&header_[22], channelCount);
writeLe32(&header_[24], sampleRate);
writeLe32(&header_[28], byteRate);
writeLe16(&header_[32], blockAlign);
writeLe16(&header_[34], bitsPerSample);
memcpy(&header_[36], "data", 4);
writeLe32(&header_[40], pcmBytes);
data_ = pcmData;
dataBytes_ = pcmBytes;
pos_ = 0;
open_ = true;
return true;
}
uint32_t AudioFileSourceRamWav::read(void *data, uint32_t len) {
if (!open_ || !data || len == 0) return 0;
const uint32_t total = getSize();
if (pos_ >= total) return 0;
uint8_t *out = static_cast<uint8_t *>(data);
uint32_t remaining = len;
uint32_t copied = 0;
while (remaining > 0 && pos_ < total) {
if (pos_ < kHeaderBytes) {
const uint32_t headerOffset = pos_;
const uint32_t available = kHeaderBytes - headerOffset;
const uint32_t chunk = (remaining < available) ? remaining : available;
memcpy(out + copied, header_ + headerOffset, chunk);
pos_ += chunk;
copied += chunk;
remaining -= chunk;
} else {
const uint32_t dataOffset = pos_ - kHeaderBytes;
const uint32_t available = dataBytes_ - dataOffset;
const uint32_t chunk = (remaining < available) ? remaining : available;
memcpy(out + copied, data_ + dataOffset, chunk);
pos_ += chunk;
copied += chunk;
remaining -= chunk;
}
}
return copied;
}
bool AudioFileSourceRamWav::seek(int32_t pos, int dir) {
if (!open_) return false;
int64_t target = 0;
if (dir == SEEK_SET) {
target = pos;
} else if (dir == SEEK_CUR) {
target = static_cast<int64_t>(pos_) + pos;
} else if (dir == SEEK_END) {
target = static_cast<int64_t>(getSize()) + pos;
} else {
return false;
}
if (target < 0 || static_cast<uint64_t>(target) > static_cast<uint64_t>(getSize())) {
return false;
}
pos_ = static_cast<uint32_t>(target);
return true;
}
bool AudioFileSourceRamWav::close() {
data_ = nullptr;
dataBytes_ = 0;
pos_ = 0;
open_ = false;
return true;
}
bool AudioFileSourceRamWav::isOpen() { return open_; }
uint32_t AudioFileSourceRamWav::getSize() { return kHeaderBytes + dataBytes_; }
uint32_t AudioFileSourceRamWav::getPos() { return pos_; }
void AudioFileSourceRamWav::writeLe16(uint8_t *dst, uint16_t value) {
dst[0] = static_cast<uint8_t>(value & 0xFFU);
dst[1] = static_cast<uint8_t>((value >> 8) & 0xFFU);
}
void AudioFileSourceRamWav::writeLe32(uint8_t *dst, uint32_t value) {
dst[0] = static_cast<uint8_t>(value & 0xFFU);
dst[1] = static_cast<uint8_t>((value >> 8) & 0xFFU);
dst[2] = static_cast<uint8_t>((value >> 16) & 0xFFU);
dst[3] = static_cast<uint8_t>((value >> 24) & 0xFFU);
}
bool FreshStartAudioGeneratorWAV::begin(AudioFileSource *source, AudioOutput *output) {
// AudioGenerator keeps lastSample between runs; clear it to avoid start transient on retrigger.
lastSample[0] = 0;
lastSample[1] = 0;
return AudioGeneratorWAV::begin(source, output);
}
bool FreshStartAudioGeneratorWAV::stop() {
const bool ok = AudioGeneratorWAV::stop();
lastSample[0] = 0;
lastSample[1] = 0;
return ok;
}
StableAudioOutputI2S::StableAudioOutputI2S(int port, int outputMode, int dmaCount, int useApll)
: AudioOutputI2S(port, outputMode, dmaCount, useApll) {}
bool StableAudioOutputI2S::begin() {
if (!AudioOutputI2S::begin()) return false;
#ifdef ESP32
// Callbacks can be registered only while the channel is disabled. The codec
// is still muted when the mixer first starts this sink.
i2s_event_callbacks_t callbacks = {};
callbacks.on_send_q_ovf = onSendQueueOverflow;
if (i2s_channel_disable(_tx_handle) == ESP_OK) {
i2s_channel_register_event_callback(_tx_handle, &callbacks, this);
i2sOn = (i2s_channel_enable(_tx_handle) == ESP_OK);
}
return i2sOn;
#else
return true;
#endif
}
bool StableAudioOutputI2S::SetRate(int hz) {
rateSetCalls_++;
if (lastRateHz_ == hz) {
skippedRateSetCalls_++;
return true;
}
lastRateHz_ = hz;
appliedRateSetCalls_++;
return AudioOutputI2S::SetRate(hz);
}
#ifdef ESP32
size_t StableAudioOutputI2S::writeBlock(void *context, const uint8_t *data, size_t bytes) {
auto *self = static_cast<StableAudioOutputI2S *>(context);
size_t written = 0;
// Nonblocking: a full DMA queue must not prevent servicing other voices.
// Preserve partial writes even when the API reports a timeout.
i2s_channel_write(self->_tx_handle, data, bytes, &written, 0);
return written;
}
bool IRAM_ATTR StableAudioOutputI2S::onSendQueueOverflow(i2s_chan_handle_t,
i2s_event_data_t *,
void *context) {
// The DMA finished every queued block before the next write arrived, so it
// replays stale data: audible as stutter and apparent time stretching.
auto *self = static_cast<StableAudioOutputI2S *>(context);
self->underrunCount_ = self->underrunCount_ + 1;
return false;
}
#endif
bool StableAudioOutputI2S::ConsumeSample(int16_t sample[2]) {
#ifdef ESP32
if (!i2sOn) return false;
int16_t output[2] = {sample[0], sample[1]};
MakeSampleStereo16(output);
if (mono) output[0] = output[1] = (int32_t(output[0]) + output[1]) / 2;
output[0] = Amplify(output[0]);
output[1] = Amplify(output[1]);
// Audio continuously feeds silence after EOF, so partial blocks complete
// without stopping I2S or dropping queued tails. Adds at most 128 frames.
return block_.consume(output, writeBlock, this);
#else
return AudioOutputI2S::ConsumeSample(sample);
#endif
}
uint32_t StableAudioOutputI2S::rateSetCalls() const { return rateSetCalls_; }
uint32_t StableAudioOutputI2S::skippedRateSetCalls() const { return skippedRateSetCalls_; }
uint32_t StableAudioOutputI2S::appliedRateSetCalls() const { return appliedRateSetCalls_; }
uint32_t StableAudioOutputI2S::underrunCount() const { return underrunCount_; }
WaveformAudioOutput::WaveformAudioOutput(AudioOutput *sink,
WaveformCaptureState *waveformCapture)
: sink_(sink), waveformCapture_(waveformCapture) {}
bool WaveformAudioOutput::SetRate(int hz) {
return sink_ && sink_->SetRate(hz);
}
bool WaveformAudioOutput::SetChannels(int channels) {
return sink_ && sink_->SetChannels(channels);
}
bool WaveformAudioOutput::begin() { return sink_ && sink_->begin(); }
bool WaveformAudioOutput::stop() {
return sink_ && sink_->stop();
}
bool WaveformAudioOutput::loop() { return sink_ && sink_->loop(); }
bool WaveformAudioOutput::ConsumeSample(int16_t sample[2]) {
if (!sink_) return false;
int16_t output[2] = {sample[0], sample[1]};
if (!sink_->ConsumeSample(output)) return false;
captureWaveformSample(sample);
return true;
}
void WaveformAudioOutput::captureWaveformSample(const int16_t sample[2]) {
if (!waveformCapture_) return;
waveformCapture_->decimationCounter++;
if (waveformCapture_->decimationCounter < kWaveformDecimation) {
return;
}
waveformCapture_->decimationCounter = 0;
const int32_t mono = (static_cast<int32_t>(sample[0]) + static_cast<int32_t>(sample[1])) / 2;
int32_t quantized = mono / 256;
if (quantized > 127) quantized = 127;
if (quantized < -128) quantized = -128;
portENTER_CRITICAL(&waveformCapture_->lock);
waveformCapture_->ring[waveformCapture_->head] = static_cast<int8_t>(quantized);
waveformCapture_->head = (waveformCapture_->head + 1U) % Audio::kWaveformPointCount;
if (waveformCapture_->count < Audio::kWaveformPointCount) {
waveformCapture_->count++;
}
portEXIT_CRITICAL(&waveformCapture_->lock);
}
bool copyWaveformSnapshot(const WaveformCaptureState &capture, Audio::WaveformSnapshot &snapshot) {
snapshot.validPoints = 0;
portENTER_CRITICAL(&capture.lock);
const uint16_t count = capture.count;
const uint16_t head = capture.head;
const uint16_t start = (count == Audio::kWaveformPointCount) ? head : 0;
for (uint16_t i = 0; i < count; i++) {
const uint16_t index = (start + i) % Audio::kWaveformPointCount;
snapshot.points[i] = capture.ring[index];
}
portEXIT_CRITICAL(&capture.lock);
snapshot.validPoints = count;
return count > 0;
}
} // namespace AudioInternal