Simvik

Bluetooth speaker: never overwrite unplayed audio

A sample ring buffer that refuses new samples when full instead of overwriting the ones not yet played. A medium embedded C problem (Buffers and data…

medium · Buffers and data structures · ring-buffer · overflow · audio · product

Product: Bluetooth speaker (Consumer electronics)

Requirement. Radio packets arrive in bursts; the audio DAC takes one sample at a time. A burst that arrives while the buffer is full must be dropped (the codec conceals one lost packet), never written over audio that has not played yet: that is heard as a loud click.

rb_put stores a sample and returns true, or returns false and changes nothing when all 8 slots are full. rb_get takes the oldest sample into *s and returns true, or returns false when empty.

Starter code

bool rb_put(ring_t *r, int16_t s) {
  r->buf[r->head] = s;
  r->head = (uint8_t)((r->head + 1) % 8);
  r->count++;
  return true;
}

bool rb_get(ring_t *r, int16_t *s) {
  if (r->count == 0) return false;
  *s = r->buf[r->tail];
  r->tail = (uint8_t)((r->tail + 1) % 8);
  r->count--;
  return true;
}

Example tests

In and out in order

ring_t r;
memset(&r, 0, sizeof r);
for (int i = 1; i <= 3; i++) rb_put(&r, i);
int16_t s;
while (rb_get(&r, &s)) printf("%d ", s);
printf("\n");

Expected output:

1 2 3

A burst bigger than the buffer

ring_t r;
memset(&r, 0, sizeof r);
for (int i = 1; i <= 10; i++) printf("%d ", rb_put(&r, i));
printf("\n");
int16_t s;
while (rb_get(&r, &s)) printf("%d ", s);
printf("\n");

Expected output:

1 1 1 1 1 1 1 1 0 0
1 2 3 4 5 6 7 8

Learn it first

More Buffers and data structures problems