Skip to content

Commit 35a4d57

Browse files
Fix I2s::available/availableForWrite() (#1496)
Return the actual number of samples that can be read/written, not the number of 32-bit values there is space for.
1 parent 579e366 commit 35a4d57

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

libraries/I2S/src/I2S.cpp

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ I2S::I2S(PinMode direction) {
4848
_freq = 48000;
4949
_arb = nullptr;
5050
_cb = nullptr;
51-
_buffers = 8;
51+
_buffers = 6;
5252
_bufferWords = 0;
5353
_silenceSample = 0;
5454
_isLSBJ = false;
@@ -163,7 +163,7 @@ bool I2S::begin() {
163163
_silenceSample = (a << 16) | a;
164164
}
165165
if (!_bufferWords) {
166-
_bufferWords = 16 * (_bps == 32 ? 2 : 1);
166+
_bufferWords = 64 * (_bps == 32 ? 2 : 1);
167167
}
168168
_arb = new AudioBufferManager(_buffers, _bufferWords, _silenceSample, _isOutput ? OUTPUT : INPUT);
169169
_arb->begin(pio_get_dreq(_pio, _sm, _isOutput), _isOutput ? &_pio->txf[_sm] : (volatile void*)&_pio->rxf[_sm]);
@@ -187,10 +187,32 @@ void I2S::end() {
187187
int I2S::available() {
188188
if (!_running) {
189189
return 0;
190-
} else if (_isOutput) {
191-
return availableForWrite(); // Do what I mean, not what I say
192190
} else {
193-
return _arb->available();
191+
auto avail = _arb->available();
192+
switch (_bps) {
193+
case 8:
194+
avail *= 4; // 4 samples per 32-bits
195+
if (_isOutput) {
196+
avail += (32 - _isHolding) / 8;
197+
} else {
198+
avail += _isHolding / 8;
199+
}
200+
break;
201+
case 16:
202+
avail *= 2; // 2 samples per 32-bits
203+
if (_isOutput) {
204+
avail += (32 - _isHolding) / 16;
205+
} else {
206+
avail += _isHolding / 16;
207+
}
208+
break;
209+
case 24:
210+
case 32:
211+
default:
212+
// All stored in 32-bit words and no holding required
213+
break;
214+
}
215+
return avail;
194216
}
195217
}
196218

@@ -219,7 +241,7 @@ int I2S::read() {
219241
case 16:
220242
ret = _holdWord >> 16;
221243
_holdWord <<= 16;
222-
_isHolding -= 32;
244+
_isHolding -= 16;
223245
return ret;
224246
case 24:
225247
case 32:
@@ -399,5 +421,5 @@ int I2S::availableForWrite() {
399421
if (!_running || !_isOutput) {
400422
return 0;
401423
}
402-
return _arb->available();
424+
return available();
403425
}

0 commit comments

Comments
 (0)