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 3A 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 8Learn it first
- Buffers and data structures · Ring buffers, pools, lists and bitmaps on static memory.
More Buffers and data structures problems
- Ring buffer · Implement put and get for a fixed-size FIFO.
- Fill level from two indices · Compute how many items a FIFO holds from its head and tail.
- Overwriting log buffer · Keep only the most recent entries, replacing the oldest when full.
- Fixed-size stack · Push and pop on an array-backed stack with overflow and underflow checks.
- Sorted insert into a linked list · Insert a caller-provided node into an ascending singly linked list.
- Reverse a linked list · Reverse a singly linked list in place.
- Fixed-block memory pool · Allocate and free fixed-size blocks from a static pool.
- Small priority queue · Keep pending jobs ordered by priority in a fixed array.
- Bitmap operations · Set, clear and test individual bits in a byte array.
- First free slot · Find the first zero bit in a bitmap of a given length.
- Sample history by age · Store the last few samples and read them back by how old they are.
- Bump allocator · Hand out aligned chunks from a static buffer.
- Fix: the console drops characters · A serial console echoes the wrong characters once its receive buffer wraps.
- An opaque FIFO module: fifo.h and fifo.c · Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions.