Skip to content

Commit f7ae557

Browse files
committed
R2RConfig: add buffer_size and buffer_count
1 parent cfd7f68 commit f7ae557

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/AudioLibs/R2ROutput.h

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
namespace audio_tools {
1111

12+
1213
/**
1314
* @brief R2R configuration
1415
* @author Phil Schatzmann
@@ -19,6 +20,8 @@ class R2RConfig : public AudioInfo {
1920
public:
2021
std::vector<int> channel1_pins;
2122
std::vector<int> channel2_pins;
23+
uint16_t buffer_size = DEFAULT_BUFFER_SIZE; // automatic determination from write size
24+
uint16_t buffer_count = 2; // double buffer
2225
};
2326

2427
/**
@@ -57,16 +60,26 @@ class R2ROutput : public AudioOutput {
5760
LOGE("channel2_pins not defined");
5861
return false;
5962
}
63+
if (rcfg.buffer_size * rcfg.buffer_count == 0){
64+
LOGE("buffer_size or buffer_count is 0");
65+
return false;
66+
}
67+
buffer.resize(rcfg.buffer_size, rcfg.buffer_count);
6068
setupPins();
6169
timer.setCallbackParameter(this);
6270
timer.setIsSave(true);
6371
return timer.begin(r2r_timer_callback, cfg.sample_rate, HZ);
6472
}
6573

6674
size_t write(const uint8_t *data, size_t len) override {
75+
// if buffer has not been allocated (buffer_size==0)
76+
if (len > rcfg.buffer_size) {
77+
LOGE("buffer_size %d too small for write size: %d", rcfg.buffer_size, len);
78+
return len;
79+
}
6780
size_t result = buffer.writeArray(data, len);
68-
// activate output when buffer is full
69-
if (!is_active && buffer.isFull()) {
81+
// activate output when buffer is half full
82+
if (!is_active && buffer.bufferCountFilled() >= rcfg.buffer_count / 2) {
7083
LOGI("is_active = true");
7184
is_active = true;
7285
}
@@ -76,10 +89,10 @@ class R2ROutput : public AudioOutput {
7689
protected:
7790
TimerAlarmRepeating timer;
7891
// Double buffer
79-
NBuffer<uint8_t> buffer{DEFAULT_BUFFER_SIZE, 2};
92+
NBuffer<uint8_t> buffer{DEFAULT_BUFFER_SIZE, 0};
8093
R2RConfig rcfg;
8194

82-
void setupPins() {
95+
virtual void setupPins() {
8396
TRACED();
8497
for (auto pin : rcfg.channel1_pins) {
8598
LOGI("Setup channel1 pin %d", pin);
@@ -116,9 +129,13 @@ class R2ROutput : public AudioOutput {
116129
unsigned uvalue = (int)value + NumberConverter::maxValueT<T>() + 1;
117130
// scale value
118131
uvalue = uvalue >> ((sizeof(T) * 8) - rcfg.channel1_pins.size());
119-
//Serial.println(uvalue);
132+
// Serial.println(uvalue);
120133

121134
// output pins
135+
writePins(channel, uvalue);
136+
}
137+
138+
virtual void writePins(int channel, unsigned uvalue){
122139
switch (channel) {
123140
case 0:
124141
for (int j = 0; j < rcfg.channel1_pins.size(); j++) {

0 commit comments

Comments
 (0)