ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Ring Buffer

🔁 Lock-free circular buffers for audio/video More...

Files

file  ringbuffer.c
 đŸŽŻ Lock-free circular buffer for audio streaming with atomic operations
file  ringbuffer.h
 Lock-Free Ring Buffer and Frame Buffer Management.

Data Structures

struct  ringbuffer_t
 Audio ring buffer for real-time audio streaming. More...
struct  audio_ring_buffer
 Audio ring buffer for real-time audio streaming. More...
struct  frame_t
 One variable-length payload in the video ring buffer. More...
struct  multi_source_frame_t
 One variable-length payload in the video ring buffer. More...
struct  framebuffer_t
 Mutex-protected ring buffer used to exchange video frames. More...

Typedefs

typedef struct audio_ring_buffer audio_ring_buffer_t
 Audio ring buffer for real-time audio streaming.

Functions

ringbuffer_t * ringbuffer_create (size_t element_size, size_t capacity)
 Create a new ring buffer.
void ringbuffer_destroy (ringbuffer_t *rb)
 Destroy a ring buffer and free its memory.
bool ringbuffer_write (ringbuffer_t *rb, const void *data)
 Try to write an element to the ring buffer (non-blocking).
bool ringbuffer_read (ringbuffer_t *rb, void *data)
 Try to read an element from the ring buffer (non-blocking).
bool ringbuffer_peek (ringbuffer_t *rb, void *data)
 Peek at the next element without removing it.
size_t ringbuffer_size (const ringbuffer_t *rb)
 Get current number of elements in the buffer.
bool ringbuffer_is_empty (const ringbuffer_t *rb)
 Check if buffer is empty.
bool ringbuffer_is_full (const ringbuffer_t *rb)
 Check if buffer is full.
void ringbuffer_clear (ringbuffer_t *rb)
 Clear all elements from the buffer.
framebuffer_t * framebuffer_create (size_t capacity)
 Mutex-protected ring buffer used to exchange video frames.
framebuffer_t * framebuffer_create_multi (size_t capacity)
 Create a multi-source frame buffer for multi-user support.
void framebuffer_destroy (framebuffer_t *fb)
 Destroy a frame buffer.
bool framebuffer_write_frame (framebuffer_t *fb, const char *frame_data, size_t frame_size)
 Write a frame to the buffer.
bool framebuffer_read_frame (framebuffer_t *fb, frame_t *frame)
 Read a frame from the buffer.
void framebuffer_clear (framebuffer_t *fb)
 Clear all frames from the buffer, freeing their data.
bool framebuffer_write_multi_frame (framebuffer_t *fb, const char *frame_data, size_t frame_size, uint32_t source_client_id, uint32_t frame_sequence, uint32_t timestamp)
 Write a multi-source frame to the buffer (for multi-user support).
bool framebuffer_read_multi_frame (framebuffer_t *fb, multi_source_frame_t *frame)
 Read a multi-source frame from the buffer.
bool framebuffer_peek_latest_multi_frame (framebuffer_t *fb, multi_source_frame_t *frame)
 Peek at the latest multi-source frame without removing it.

Audio Ring Buffer Constants

Owns the temporary storage used by ringbuffer. The data pointers and size or cursor fields describe the live portion of the allocation; callers must use the type's cleanup path when the buffer or queue is no longer needed.

#define AUDIO_RING_BUFFER_SIZE   192000
 Audio ring buffer size in samples (192000 samples = 4 seconds @ 48kHz).
#define AUDIO_JITTER_BUFFER_THRESHOLD   4800
 Jitter buffer threshold - samples needed before starting playback.
#define AUDIO_JITTER_LOW_WATER_MARK   2400
 Low water mark - warn when available drops below this.
#define AUDIO_JITTER_HIGH_WATER_MARK   (AUDIO_JITTER_BUFFER_THRESHOLD * 2)
 High water mark - drop OLD samples when buffer exceeds this.
#define AUDIO_JITTER_TARGET_LEVEL   (AUDIO_JITTER_BUFFER_THRESHOLD + 480)
 Target buffer level after dropping old samples.
#define AUDIO_CROSSFADE_SAMPLES   256
 Crossfade duration in samples for smooth underrun recovery.

Frame Magic Numbers

#define FRAME_MAGIC   MAGIC_FRAME_VALID
 Magic number indicating a valid frame (0xDEADBEEF) - Alias for backward compatibility.
#define FRAME_FREED   MAGIC_FRAME_FREED
 Magic number indicating a freed frame (0xFEEDFACE) - Alias for backward compatibility.

Detailed Description

🔁 Lock-free circular buffers for audio/video

This header provides lock-free ring buffer implementations for high-performance producer-consumer scenarios in ascii-chat. The system includes both generic lock-free ring buffers and specialized audio and frame buffers for media streaming.

CORE FEATURES:

  • Lock-free ring buffers using atomic operations
  • Thread-safe producer-consumer data transfer
  • Power-of-2 capacity optimization for fast modulo
  • Specialized audio ring buffers with jitter buffering
  • Frame buffer management for video frames
  • Multi-source frame support for multi-client scenarios

RING BUFFER ARCHITECTURE:

The lock-free ring buffer uses atomic operations for:

  • Lock-free writes (producer never blocks consumer)
  • Lock-free reads (consumer never blocks producer)
  • Atomic size tracking for fast emptiness checks
  • Power-of-2 capacity enables bit masking instead of modulo

AUDIO RING BUFFER:

Specialized audio ring buffer with:

  • Fixed-size circular buffer for audio samples
  • Jitter buffer threshold for network latency compensation
  • Mutex-protected operations for audio thread safety
  • Optimized for real-time audio streaming

FRAME BUFFER:

Frame buffer system for ASCII video frames:

  • Generic frame buffers for single-source scenarios
  • Multi-source frame buffers for multi-client support
  • Magic number validation for corruption detection
  • Automatic frame data management

PERFORMANCE BENEFITS:

  • Lock-free operations minimize latency
  • Power-of-2 capacity enables fast bit masking
  • Zero-allocation pattern after initialization
  • Efficient producer-consumer data transfer

THREAD SAFETY:

  • Generic ring buffers: Lock-free using atomic operations
  • Audio ring buffers: Mutex-protected for thread safety
  • Frame buffers: Mutex-protected for concurrent access
Note
Ring buffers are ideal for producer-consumer scenarios where one thread produces data and another consumes it.
The lock-free ring buffer requires power-of-2 capacity for optimal performance (uses bit masking instead of modulo).
Audio ring buffers use jitter buffering to compensate for network latency and packet timing variations.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
August 2025

Ring Buffer

Overview

Welcome! Let's talk about the ring buffer—one of the coolest data structures in ascii-chat. If you've ever wondered how to pass data between threads really fast without all the overhead of mutexes and locks, you're in the right place.

Picture this: you have one thread capturing video frames (the producer) and another thread encoding them (the consumer). How do you hand frames from one to the other? You could use a mutex-protected queue, but that means locking and unlocking for every single frame. Not ideal when you're doing this 30 times per second!

That's where the ring buffer shines. It's a circular buffer that uses atomic operations instead of locks, making it blazingly fast for the single-producer, single-consumer pattern. Think of it like a race track where the producer and consumer chase each other around—one writing, one reading, never quite catching up to each other.

You can find the implementation in lib/ringbuffer.c and lib/ringbuffer.h.

What makes ring buffers special?

Ring buffers are designed from the ground up for speed. They use C11 atomics instead of mutexes, which means way less overhead when passing data between threads. The design is intentionally simple—no complex algorithms here, just a circular buffer done right.

The implementation takes advantage of a clever trick: power-of-2 capacities allow us to use bitwise masking instead of slow modulo operations. This might sound like a small detail, but it makes index calculations 15-30 times faster!

We also have specialized versions for different use cases. Frame buffers handle ASCII art frames with metadata like magic numbers for corruption detection. Audio ring buffers include jitter buffering to smooth out network hiccups. Each one is tailored to its specific job.

Architecture

Let's dive into how ring buffers actually work under the hood. The design is elegant in its simplicity—just a few atomic variables and a chunk of memory, but combined in a way that achieves lock-free thread safety.

Ring Buffer Structure

The core structure is pretty straightforward:

typedef struct {
char *buffer; // Actual memory
size_t element_size; // Size per element
size_t capacity; // Max elements (power of 2)
_Atomic size_t head; // Write position (producer)
_Atomic size_t tail; // Read position (consumer)
_Atomic size_t size; // Current element count
bool is_power_of_two; // Optimization flag
size_t capacity_mask; // Fast modulo mask
Audio ring buffer for real-time audio streaming.
Definition ringbuffer.h:94

The key insight here is that head and tail are atomic variables. The producer writes at head and advances it, while the consumer reads from tail and advances it. Since each position is only accessed by one thread, we don't need locks—just atomic operations to make sure reads and writes are visible across threads.

The capacity_mask is the secret sauce for performance. When capacity is a power of 2, we can use head & capacity_mask instead of head % capacity. Bitwise AND is a single CPU instruction, while modulo takes 15-30 cycles. That adds up fast when you're doing it thousands of times per second!

Lock-Free Algorithm

The ring buffer uses atomic operations for thread-safe access without locks. Here's how the producer and consumer interact:

Write operation (producer):

When the producer wants to write data, it first checks if there's room in the buffer. If the buffer is full, we return false—simple as that. Otherwise, we calculate the write index using our fast bitwise mask trick, copy the data into place, and atomically advance the head.

bool ringbuffer_write(ringbuffer_t *rb, const void *data) {
size_t current_size = atomic_load(&rb->size);
if (current_size >= rb->capacity) {
return false; // Buffer full
}
size_t head = atomic_load(&rb->head);
size_t index = head & rb->capacity_mask; // Fast modulo
// Write data
memcpy(rb->buffer + (index * rb->element_size), data, rb->element_size);
// Advance head atomically
atomic_store(&rb->head, head + 1);
atomic_fetch_add(&rb->size, 1);
return true;
}
bool ringbuffer_write(ringbuffer_t *rb, const void *data)
Try to write an element to the ring buffer (non-blocking).
Definition ringbuffer.c:70
static bool size_t index
Definition queries.h:8
size_t capacity
Number of elements that can be stored.
Definition ringbuffer.h:100
atomic_t head
Write position (producer) - atomic for lock-free operations.
Definition ringbuffer.h:102
atomic_t size
Current number of elements - atomic for fast size checks.
Definition ringbuffer.h:106
size_t capacity_mask
Mask for fast modulo when capacity is power of 2.
Definition ringbuffer.h:110
size_t element_size
Size of each element in bytes.
Definition ringbuffer.h:98
char * buffer
The actual buffer memory.
Definition ringbuffer.h:96

Read operation (consumer):

The consumer side is the mirror image. We check if there's data available, calculate the read index the same way, copy data out, and atomically advance the tail.

bool ringbuffer_read(ringbuffer_t *rb, void *data) {
size_t current_size = atomic_load(&rb->size);
if (current_size == 0) {
return false; // Buffer empty
}
size_t tail = atomic_load(&rb->tail);
size_t index = tail & rb->capacity_mask; // Fast modulo
// Read data
memcpy(data, rb->buffer + (index * rb->element_size), rb->element_size);
// Advance tail atomically
atomic_store(&rb->tail, tail + 1);
atomic_fetch_sub(&rb->size, 1);
return true;
}
bool ringbuffer_read(ringbuffer_t *rb, void *data)
Try to read an element from the ring buffer (non-blocking).
Definition ringbuffer.c:92
atomic_t tail
Read position (consumer) - atomic for lock-free operations.
Definition ringbuffer.h:104

The beauty of this design is that the producer and consumer can run completely independently. They never block each other—the worst case is one returns false if the buffer is full or empty, but that's a check we'd need anyway.

Buffer Types

We have several flavors of ring buffer, each optimized for a specific use case. The generic ring buffer handles arbitrary element types, while frame and audio buffers are specialized for their domains.

Generic Ring Buffer

The generic ring buffer is your go-to choice when you need to pass arbitrary data types between threads. It's simple, fast, and gets the job done.

Here's a quick example of using it:

// Create ring buffer for 256 integers
ringbuffer_t *rb = ringbuffer_create(sizeof(int), 256);
// Producer thread
int value = 42;
if (!ringbuffer_write(rb, &value)) {
log_warn("Ring buffer full, dropping data");
}
// Consumer thread
int received;
if (ringbuffer_read(rb, &received)) {
printf("Received: %d\n", received);
}
// Cleanup
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
ringbuffer_t * ringbuffer_create(size_t element_size, size_t capacity)
Create a new ring buffer.
Definition ringbuffer.c:34
void ringbuffer_destroy(ringbuffer_t *rb)
Destroy a ring buffer and free its memory.
Definition ringbuffer.c:60

Notice how the capacity gets rounded up to the next power of 2 automatically (256 is already a power of 2, so it stays as-is). If you ask for 100 elements, you'll get 128 instead—a small price to pay for the performance benefits.

Frame Buffer

Frame buffers are specialized for ASCII art frames. They handle variable-sized frames and include metadata like magic numbers for corruption detection. This is crucial when frames are being passed between threads—we need to make sure we're not reading garbage if something goes wrong.

The frame structure looks like this:

typedef struct {
uint32_t magic; // FRAME_MAGIC (0xDEADBEEF) for corruption detection
size_t size; // Actual frame size
char *data; // Frame data (owned by consumer after read)
typedef struct {
mutex_t mutex; // Protects frame data allocation/free
unsigned int uint32_t
One variable-length payload in the video ring buffer.
Definition ringbuffer.h:398
Mutex-protected ring buffer used to exchange video frames.
Definition ringbuffer.h:456
Note
Reading transfers ownership to the consumer, which must buffer_release(frame.data).

The magic number serves as a sanity check. When you read a frame, you can verify that frame.magic == FRAME_MAGIC to make sure you got a valid frame and not corrupted memory. It's a simple check, but it can catch a lot of subtle bugs!

Here's how you'd use it in practice:

// Create frame buffer (capacity = 60 frames)
// Producer: Write ASCII frame
char *ascii_frame = generate_ascii_art(...);
if (!framebuffer_write_frame(fb, ascii_frame, strlen(ascii_frame))) {
log_warn("Frame buffer full, dropping frame");
}
// Consumer: Read ASCII frame
frame_t frame;
if (framebuffer_read_frame(fb, &frame)) {
if (frame.magic == FRAME_MAGIC) {
render_frame(frame.data, frame.size);
}
}
// Cleanup (automatically frees all frame data via buffer domain)
#define buffer_release(data)
Definition buffer.h:99
void framebuffer_destroy(framebuffer_t *fb)
Destroy a frame buffer.
Definition ringbuffer.c:214
framebuffer_t * framebuffer_create(size_t capacity)
Mutex-protected ring buffer used to exchange video frames.
Definition ringbuffer.c:156
bool framebuffer_read_frame(framebuffer_t *fb, frame_t *frame)
Read a frame from the buffer.
Definition ringbuffer.c:287
#define FRAME_MAGIC
Magic number indicating a valid frame (0xDEADBEEF) - Alias for backward compatibility.
Definition ringbuffer.h:441
bool framebuffer_write_frame(framebuffer_t *fb, const char *frame_data, size_t frame_size)
Write a frame to the buffer.
Definition ringbuffer.c:233
char * data
Owning frame payload; release with buffer_release() after reading.
Definition ringbuffer.h:404
uint64_t magic
Magic number to detect corruption (FRAME_MAGIC when valid).
Definition ringbuffer.h:400
size_t size
Actual size of frame data in bytes.
Definition ringbuffer.h:402
Note
Clearing or destroying a framebuffer releases only frames still queued.

Multi-Source Frame Buffer

When you have multiple clients sending frames, you need to track which client sent what. That's where the multi-source frame buffer comes in. It's essentially the same as a regular frame buffer, but each frame includes metadata about its source.

The multi-source frame structure tracks the client ID, frame sequence number, and timestamp:

typedef struct {
uint32_t magic;
uint32_t source_client_id; // Which client sent this
uint32_t frame_sequence; // Frame number
uint32_t timestamp; // Capture time
size_t size;
char *data;
One variable-length payload in the video ring buffer.
Definition ringbuffer.h:419

Using it is straightforward:

// Create multi-source frame buffer
// Producer: Write frame from client 3
framebuffer_write_multi_frame(fb, frame_data, frame_size,
3, // client_id
frame_seq,
timestamp);
// Consumer: Read frame
if (framebuffer_read_multi_frame(fb, &frame)) {
log_debug("Frame from client %u: seq=%u size=%zu",
frame.source_client_id, frame.frame_sequence, frame.size);
render_client_frame(frame.source_client_id, frame.data, frame.size);
SAFE_FREE(frame.data);
}
#define SAFE_FREE(ptr)
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
bool framebuffer_read_multi_frame(framebuffer_t *fb, multi_source_frame_t *frame)
Read a multi-source frame from the buffer.
Definition ringbuffer.c:433
framebuffer_t * framebuffer_create_multi(size_t capacity)
Create a multi-source frame buffer for multi-user support.
Definition ringbuffer.c:185
bool framebuffer_write_multi_frame(framebuffer_t *fb, const char *frame_data, size_t frame_size, uint32_t source_client_id, uint32_t frame_sequence, uint32_t timestamp)
Write a multi-source frame to the buffer (for multi-user support).
Definition ringbuffer.c:388
char * data
Owning frame payload; release with buffer_release() after reading.
Definition ringbuffer.h:431
uint32_t frame_sequence
Frame sequence number for ordering.
Definition ringbuffer.h:425
size_t size
Actual size of frame data in bytes.
Definition ringbuffer.h:429
char source_client_id[MAX_CLIENT_ID_LEN]
Client ID that sent this frame.
Definition ringbuffer.h:423

Audio Ring Buffer

Audio ring buffers are a bit different from the others. They're designed for real-time audio playback, which means they need to handle network jitter gracefully. The buffer accumulates samples before starting playback, creating a "jitter buffer" that smooths out irregularities in network timing.

The audio buffer uses a fixed size tuned for audio needs:

#define AUDIO_RING_BUFFER_SIZE (256 * 32) // 8192 samples = ~186ms @ 44.1kHz
#define AUDIO_JITTER_BUFFER_THRESHOLD (256 * 8) // Wait 46ms before playback
typedef struct audio_ring_buffer {
volatile int write_index;
volatile int read_index;
volatile bool jitter_buffer_filled; // True after initial fill
mutex_t mutex;
struct audio_ring_buffer audio_ring_buffer_t
#define AUDIO_RING_BUFFER_SIZE
Audio ring buffer size in samples (192000 samples = 4 seconds @ 48kHz).
Definition ringbuffer.h:136
Audio ring buffer for real-time audio streaming.
Definition ringbuffer.h:213
atomic_t jitter_buffer_filled
True after initial jitter buffer fill.
Definition ringbuffer.h:226
atomic_t read_index
Read index (consumer position) - LOCK-FREE with atomic operations.
Definition ringbuffer.h:220
mutex_t mutex
Mutex for SLOW PATH only (clear/destroy operations, not regular read/write).
Definition ringbuffer.h:243
atomic_t write_index
Write index (producer position) - LOCK-FREE with atomic operations.
Definition ringbuffer.h:218
float data[192000]
Audio sample data buffer.
Definition ringbuffer.h:216

Why the jitter buffer?

Network audio packets don't arrive at perfectly regular intervals. Sometimes packets come early, sometimes they're delayed. Without buffering, you'd get audio crackling whenever a packet was late. The jitter buffer waits until it has enough samples to smooth out these timing variations before starting playback.

The threshold is set to about 46 milliseconds of audio. This is usually enough to handle typical network jitter without introducing noticeable latency. Once the buffer has reached this threshold, playback begins and the buffer continues to absorb timing variations.

Here's how it works in practice:

audio_ring_buffer_t *arb = audio_ringbuffer_create();
// Network receive thread: Write samples
void receive_audio(audio_ring_buffer_t *arb, float *samples, int count) {
mutex_lock(&arb->mutex);
for (int i = 0; i < count; i++) {
arb->data[arb->write_index] = samples[i];
}
// Check if jitter buffer filled
int available = (arb->write_index - arb->read_index + AUDIO_RING_BUFFER_SIZE)
arb->jitter_buffer_filled = true;
log_info("Jitter buffer filled, starting playback");
}
mutex_unlock(&arb->mutex);
}
// Audio callback: Read samples for playback
void audio_callback(audio_ring_buffer_t *arb, float *output, int count) {
mutex_lock(&arb->mutex);
if (!arb->jitter_buffer_filled) {
// Not ready yet, output silence
memset(output, 0, count * sizeof(float));
mutex_unlock(&arb->mutex);
return;
}
for (int i = 0; i < count; i++) {
output[i] = arb->data[arb->read_index];
}
mutex_unlock(&arb->mutex);
}
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define AUDIO_JITTER_BUFFER_THRESHOLD
Jitter buffer threshold - samples needed before starting playback.
Definition ringbuffer.h:151

Note that the audio buffer uses a mutex. Unlike the generic ring buffer, this one can benefit from mutual exclusion since audio callbacks have strict timing requirements and we need to coordinate the jitter buffer logic.

API Reference

Now let's look at the actual API you'll be working with. The functions are straightforward and follow a consistent pattern.

Creation/Destruction

Creating a ring buffer is simple—just specify the element size and desired capacity:

// Create generic ring buffer (capacity rounded up to power of 2)
ringbuffer_t *ringbuffer_create(size_t element_size, size_t capacity);
// Create frame buffer
// Create multi-source frame buffer
// Destroy buffers (frees all memory)

Remember that the capacity gets rounded up to the next power of 2 for performance reasons. If you request 100 elements, you'll get 128. This usually isn't a problem, but it's good to be aware of.

Operations

The core operations are write, read, and peek. The query functions let you check the buffer state without modifying it.

// Generic ring buffer
bool ringbuffer_write(ringbuffer_t *rb, const void *data);
bool ringbuffer_read(ringbuffer_t *rb, void *data);
bool ringbuffer_peek(ringbuffer_t *rb, void *data); // Read without removing
// Query state
size_t ringbuffer_size(const ringbuffer_t *rb);
// Frame buffer
bool framebuffer_write_frame(framebuffer_t *fb, const char *data, size_t size);
// Multi-source frame buffer
bool framebuffer_write_multi_frame(framebuffer_t *fb, const char *data, size_t size,
uint32_t client_id, uint32_t seq, uint32_t ts);
void ringbuffer_clear(ringbuffer_t *rb)
Clear all elements from the buffer.
Definition ringbuffer.c:143
size_t ringbuffer_size(const ringbuffer_t *rb)
Get current number of elements in the buffer.
Definition ringbuffer.c:131
bool ringbuffer_is_full(const ringbuffer_t *rb)
Check if buffer is full.
Definition ringbuffer.c:139
bool ringbuffer_is_empty(const ringbuffer_t *rb)
Check if buffer is empty.
Definition ringbuffer.c:135
bool framebuffer_peek_latest_multi_frame(framebuffer_t *fb, multi_source_frame_t *frame)
Peek at the latest multi-source frame without removing it.
Definition ringbuffer.c:466
bool ringbuffer_peek(ringbuffer_t *rb, void *data)
Peek at the next element without removing it.
Definition ringbuffer.c:114

All the write and read functions return false if the operation couldn't complete (buffer full or empty). This lets you decide what to do—maybe drop the data, maybe wait and retry, maybe signal an error. It's up to you!

Performance

Let's talk numbers. The ring buffer isn't just fast—it's dramatically faster than traditional mutex-protected queues. Here's what the benchmarks show.

Benchmarks

We compared the lock-free ring buffer against a mutex-protected queue in a contention-free scenario (producer and consumer on the same CPU core):

Operation Ring Buffer Mutex Queue Speedup
Write 18 ns 95 ns 5.3x faster
Read 20 ns 102 ns 5.1x faster
Write+Read pair 38 ns 197 ns 5.2x faster

These numbers are from an AMD Ryzen 9 5950X in a contention-free scenario. The ring buffer operations are so fast they're barely more expensive than a simple memory copy!

Contention Behavior

What happens when things get more intense? We also tested with high contention, where the producer and consumer are running on different CPU cores. This stresses the cache coherency protocol, but the ring buffer still comes out way ahead:

Under high contention:

  • Ring buffer: ~45 ns per operation (2.4x slowdown from cache coherency)
  • Mutex queue: ~280 ns per operation (2.8x slowdown from lock contention)
  • Ring buffer still 6.2x faster under contention

Even when the CPU cores are fighting over cache lines, the ring buffer's lock-free design means it doesn't have to wait for mutexes to be released. The atomic operations are still much faster than lock acquisition.

Capacity Management

Getting the capacity right is important for performance. Too small and you'll drop data. Too large and you're wasting memory. The ring buffer helps by optimizing capacity calculations automatically.

Power-of-2 Optimization

The ring buffer always rounds capacity up to the next power of 2. This lets us use bitwise AND instead of modulo for index calculations, which is dramatically faster.

Here's how it works:

// Request 100 elements → gets rounded to 128 (next power of 2)
ringbuffer_t *rb = ringbuffer_create(sizeof(int), 100);
assert(rb->capacity == 128);
// Fast modulo using bitwise AND
size_t index = head & rb->capacity_mask; // Instead of head % capacity
// Where capacity_mask = capacity - 1 (e.g., 128 - 1 = 127 = 0b01111111)

The performance impact is significant:

  • Bitwise AND: 1 CPU cycle
  • Integer modulo: 15-30 CPU cycles
  • Speedup: 15-30x for index calculation

Since we're calculating the index on every read and write, this optimization really adds up. It's one of those small details that makes a big difference when you're doing thousands of operations per second.

Sizing Guidelines

Choosing the right buffer size depends on what you're buffering. Let's look at some common scenarios:

Video frames (30 FPS):

For video, you want enough frames to survive brief CPU spikes and scheduling delays. We recommend at least 2 seconds worth (60 frames) as a minimum. That gives you enough cushion that a momentary slowdown won't cause frame drops. For more robust operation, 4 seconds (120 frames) is better. Going beyond 10 seconds (300 frames) doesn't usually help much—by then you're just increasing latency.

Audio samples (48 kHz):

Audio buffering is a balancing act. You need enough buffer to absorb network jitter, but not so much that latency becomes noticeable. Our audio ring buffer uses:

  • Jitter buffer threshold: 46ms (2208 samples) - waits this long before starting playback
  • Total buffer: 186ms (8928 samples) - prevents underruns during playback

These numbers are tuned for typical network conditions. If you're on a very jittery network, you might want to increase the jitter buffer threshold. If latency is more important than smoothness, you can decrease it.

Thread Safety

This is important: ring buffers are only safe for the Single Producer, Single Consumer (SPSC) pattern. That means exactly one thread writing and exactly one thread reading. If you need multiple producers or consumers, you'll want to use packet_queue instead, which is mutex-protected.

SPSC Guarantee

The lock-free design relies on the fact that each position in the buffer is only accessed by one thread. The producer writes at head, the consumer reads from tail, and they never touch each other's positions. This is what makes the atomic operations sufficient—we don't need locks because there's no contention.

Here's the correct pattern:

// ✅ CORRECT: One producer, one consumer
void* producer_thread(void *arg) {
while (running) {
int data = generate_data();
ringbuffer_write(rb, &data);
}
}
void* consumer_thread(void *arg) {
while (running) {
int data;
if (ringbuffer_read(rb, &data)) {
process_data(data);
}
}
}

And here's what not to do:

// ❌ WRONG: Multiple producers (not thread-safe!)
void* producer_thread_1(void *arg) {
ringbuffer_write(rb, &data); // Race condition!
}
void* producer_thread_2(void *arg) {
ringbuffer_write(rb, &data); // Race condition!
}

If you try to have multiple producers writing at the same time, you'll get race conditions on the head pointer. Same problem with multiple consumers. The lock-free design only works when there's exactly one of each.

For multiple producers or consumers, use packet_queue instead—it uses mutexes and can handle multiple writers and readers safely, though it won't be as fast.

Best Practices

Here are some tips we've learned from using ring buffers in ascii-chat:

Use power-of-2 capacities when possible

While the ring buffer will round up for you, if you know your requirements in advance, it's cleaner to request a power of 2 directly. That way there's no surprise about the actual capacity you get.

ringbuffer_create(sizeof(int), 128); // Good (power of 2)
ringbuffer_create(sizeof(int), 100); // Still works, but rounded to 128

Handle full/empty cases gracefully

When ringbuffer_write() returns false, the buffer is full. When ringbuffer_read() returns false, it's empty. You need to decide what to do in each case:

if (!ringbuffer_write(rb, &data)) {
// Buffer full - decide policy:
// - Drop data (real-time video - newest frame is most important)
// - Wait and retry (critical data - can't afford to lose)
// - Overwrite oldest (circular log - keep latest N items)
}

For real-time video, dropping frames is usually fine—better to show the latest frame than to delay everything. For critical data, you might want to block until there's room. It depends on your use case.

Reading transfers frame ownership

After a successful read or peek, release the returned owning payload after use.

frame_t frame;
if (framebuffer_read_frame(fb, &frame)) {
process_frame(frame.data, frame.size);
}

Clearing the queue does not release payloads already handed to consumers. Owning buffers use buffer_release(), never SAFE_FREE().

Validate magic numbers

Frame buffers include magic numbers for a reason—they help catch corruption. Always check that you got a valid frame:

if (frame.magic != FRAME_MAGIC) {
log_error("Corrupted frame detected (magic=0x%08X)", frame.magic);
return;
}
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628

This is a cheap sanity check that can save you from chasing weird bugs later. If you read garbage memory (maybe from a use-after-free or buffer overflow), the magic number won't match and you'll know immediately that something's wrong.

Size jitter buffers appropriately

For audio buffers, the jitter buffer size is a trade-off. Too small and you'll get audio crackling from underruns. Too large and you'll have noticeable latency. The sweet spot is usually about 2-3 times your typical network jitter.

Our default is 46 milliseconds, which works well for most network conditions. If you're on a very stable network (like a local connection), you could go smaller. If network jitter is severe, you might need to increase it, though you'll pay for it with latency.

See also
ringbuffer.h
ringbuffer.c

Macro Definition Documentation

◆ AUDIO_CROSSFADE_SAMPLES

#define AUDIO_CROSSFADE_SAMPLES   256

#include <include/ascii-chat/ringbuffer.h>

Crossfade duration in samples for smooth underrun recovery.

When recovering from an underrun, we fade in the audio over this many samples to prevent clicks and pops. 256 samples @ 48kHz = ~5.3ms

Definition at line 194 of file ringbuffer.h.

Referenced by audio_ring_buffer_read().

◆ AUDIO_JITTER_BUFFER_THRESHOLD

#define AUDIO_JITTER_BUFFER_THRESHOLD   4800

#include <include/ascii-chat/ringbuffer.h>

Jitter buffer threshold - samples needed before starting playback.

This threshold determines how much audio must be buffered before playback starts. Too small = underruns and audio gaps when network packets arrive late Too large = excessive latency + AEC3 gets silence during fill period

INCREASED from 960 (20ms) to 4800 (100ms) to eliminate stuttering caused by:

  • Network jitter (packets arriving in bursts)
  • Packet processing overhead
  • Thread scheduling delays

4800 samples @ 48kHz = 100ms = 5 Opus frames

Definition at line 151 of file ringbuffer.h.

◆ AUDIO_JITTER_HIGH_WATER_MARK

#define AUDIO_JITTER_HIGH_WATER_MARK   (AUDIO_JITTER_BUFFER_THRESHOLD * 2)

#include <include/ascii-chat/ringbuffer.h>

High water mark - drop OLD samples when buffer exceeds this.

When the playback buffer grows beyond this level, we have accumulated too much latency. We drop OLD samples to keep latency bounded. This prevents the "latency grows over time" problem where network bursts fill the buffer faster than playback can drain it.

Set to 2x jitter threshold = 40ms for LAN. This gives enough headroom for network jitter while preventing unbounded latency accumulation. 1920 samples @ 48kHz = 40ms = 2 Opus frames

Definition at line 177 of file ringbuffer.h.

Referenced by audio_ring_buffer_write().

◆ AUDIO_JITTER_LOW_WATER_MARK

#define AUDIO_JITTER_LOW_WATER_MARK   2400

#include <include/ascii-chat/ringbuffer.h>

Low water mark - warn when available drops below this.

When playback buffer drops below this threshold, we log a warning but keep playing to avoid choppy audio. The jitter buffer should absorb network jitter without constantly pausing/resuming.

INCREASED from 480 (10ms) to 2400 (50ms) to provide adequate headroom and prevent thousands of micro-underruns that cause audio stuttering.

2400 samples @ 48kHz = 50ms = 2.5 Opus frames

Definition at line 164 of file ringbuffer.h.

◆ AUDIO_JITTER_TARGET_LEVEL

#define AUDIO_JITTER_TARGET_LEVEL   (AUDIO_JITTER_BUFFER_THRESHOLD + 480)

#include <include/ascii-chat/ringbuffer.h>

Target buffer level after dropping old samples.

When we drop old samples due to exceeding HIGH_WATER_MARK, we bring the buffer back down to this level. Set slightly above jitter threshold to avoid immediately triggering underrun detection.

1440 samples @ 48kHz = 30ms = 1.5 Opus frames

Definition at line 187 of file ringbuffer.h.

Referenced by audio_ring_buffer_write().

◆ AUDIO_RING_BUFFER_SIZE

#define AUDIO_RING_BUFFER_SIZE   192000

#include <include/ascii-chat/ringbuffer.h>

Audio ring buffer size in samples (192000 samples = 4 seconds @ 48kHz).

Sized to handle:

  1. Single-client period where audio accumulates before a second client joins
  2. Mixer processing overhead (can take 3-15ms, exceeding 10ms target)
  3. System scheduling delays under load

4 seconds provides headroom for mixer slowdowns and prevents overflow during processing spikes. The mixer reads adaptively to catch up.

Definition at line 136 of file ringbuffer.h.

Referenced by audio_ring_buffer_available_read(), audio_ring_buffer_available_write(), audio_ring_buffer_peek(), audio_ring_buffer_read(), audio_ring_buffer_write(), and session_display_write_audio().

◆ FRAME_FREED

#define FRAME_FREED   MAGIC_FRAME_FREED

#include <include/ascii-chat/ringbuffer.h>

Magic number indicating a freed frame (0xFEEDFACE) - Alias for backward compatibility.

Definition at line 443 of file ringbuffer.h.

◆ FRAME_MAGIC

#define FRAME_MAGIC   MAGIC_FRAME_VALID

#include <include/ascii-chat/ringbuffer.h>

Magic number indicating a valid frame (0xDEADBEEF) - Alias for backward compatibility.

Definition at line 441 of file ringbuffer.h.

Referenced by framebuffer_clear(), framebuffer_peek_latest_multi_frame(), framebuffer_read_frame(), framebuffer_read_multi_frame(), and framebuffer_write_frame().

Typedef Documentation

◆ audio_ring_buffer_t

#include <include/ascii-chat/ringbuffer.h>

Audio ring buffer for real-time audio streaming.

Specialized ring buffer for audio samples with jitter buffering to compensate for network latency and packet timing variations. Uses mutex-protected operations for thread-safe audio access.

Features:

  • Jitter buffering: waits for threshold fill before starting playback
  • Low water mark: resets jitter state when buffer runs low
  • Crossfade: smoothly fades audio in/out during underrun recovery
  • Underrun tracking: counts underruns for diagnostics

Function Documentation

◆ framebuffer_clear()

void framebuffer_clear ( framebuffer_t * fb)

#include <include/ascii-chat/ringbuffer.h>

Clear all frames from the buffer, freeing their data.

Parameters
fbFrame buffer (must not be NULL)

Removes all frames from the buffer and frees their associated data. This operation is thread-safe but should be used with caution if other threads may be reading frames.

Note
Thread-safe: Protected by mutex for concurrent access.

Definition at line 334 of file ringbuffer.c.

334 {
335 if (!fb || !fb->rb)
336 return;
337
338 // Thread-safe access to framebuffer (was missing, causing race conditions)
339 mutex_lock(&fb->mutex);
340
341 // Check the element size to determine frame type
342 if (fb->rb->element_size == sizeof(multi_source_frame_t)) {
343 // Multi-source frame buffer - read and free multi_source_frame_t
344 multi_source_frame_t multi_frame;
345 while (ringbuffer_read(fb->rb, &multi_frame)) {
346 if (IS_FRAME_VALID((frame_t *)&multi_frame)) {
347 MARK_FRAME_FREED((frame_t *)&multi_frame); // Mark as freed to detect use-after-free
348 buffer_release(multi_frame.data);
349 } else if (!IS_MAGIC_VALID(multi_frame.magic, FRAME_MAGIC) && multi_frame.magic != 0) {
350 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid multi-source frame magic 0x%x during clear", multi_frame.magic);
351 }
352 }
353 } else if (fb->rb->element_size == sizeof(frame_t)) {
354 // Single-source frame buffer - read and free frame_t
355 frame_t frame;
356 while (ringbuffer_read(fb->rb, &frame)) {
357 if (IS_FRAME_VALID(&frame)) {
358 MARK_FRAME_FREED(&frame); // Mark as freed to detect use-after-free
359 buffer_release(frame.data);
360 } else if (!IS_MAGIC_VALID(frame.magic, FRAME_MAGIC) && frame.magic != 0) {
361 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid frame magic 0x%x during clear", frame.magic);
362 }
363 }
364 } else {
365 SET_ERRNO(ERROR_INVALID_STATE, "Unknown frame buffer type with element size %zu", fb->rb->element_size);
366 }
367
368 // Clear the ringbuffer indices
369 ringbuffer_clear(fb->rb);
370
371 // Zero out the entire buffer to prevent any dangling pointers
372 if (fb->rb->buffer) {
373 // Check for integer overflow before multiplication
374 if (fb->rb->capacity > SIZE_MAX / fb->rb->element_size) {
375 SET_ERRNO(ERROR_INVALID_PARAM, "Buffer size would overflow: capacity=%zu, element_size=%zu", fb->rb->capacity, fb->rb->element_size);
376 mutex_unlock(&fb->mutex);
377 return;
378 }
379 size_t buffer_size = fb->rb->capacity * fb->rb->element_size;
381 }
382
383 mutex_unlock(&fb->mutex);
384}
#define SET_ERRNO(code,...)
int buffer_size
Size of circular buffer.
Definition grep.c:68
#define SAFE_MEMSET(dest, dest_size, ch, count)
@ ERROR_INVALID_STATE
@ ERROR_INVALID_PARAM
#define IS_MAGIC_VALID(magic, expected)
Check if magic number is valid (true if matches expected).
Definition magic.h:34
#define IS_FRAME_VALID(frame)
Check if frame is valid and not freed.
Definition magic.h:37
#define MARK_FRAME_FREED(frame)
Mark a frame as freed.
Definition magic.h:43
mutex_t mutex
Mutex for thread-safe access to framebuffer operations.
Definition ringbuffer.h:460
ringbuffer_t * rb
Underlying ring buffer for frame storage.
Definition ringbuffer.h:458

References ringbuffer_t::buffer, buffer_release, buffer_size, ringbuffer_t::capacity, frame_t::data, ringbuffer_t::element_size, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, FRAME_MAGIC, IS_FRAME_VALID, IS_MAGIC_VALID, frame_t::magic, MARK_FRAME_FREED, framebuffer_t::mutex, framebuffer_t::rb, ringbuffer_clear(), ringbuffer_read(), SAFE_MEMSET, and SET_ERRNO.

Referenced by framebuffer_destroy().

◆ framebuffer_create()

framebuffer_t * framebuffer_create ( size_t capacity)

#include <include/ascii-chat/ringbuffer.h>

Mutex-protected ring buffer used to exchange video frames.

Create a frame buffer for ASCII frames

Parameters
capacityNumber of frames to buffer
Returns
Frame buffer or NULL on failure

Creates a new frame buffer for single-source frame scenarios. The capacity is automatically rounded up to the next power of 2 for optimal performance.

Definition at line 156 of file ringbuffer.c.

156 {
157 if (capacity == 0) {
158 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid frame buffer parameters");
159 return NULL;
160 }
161
163
164 // Initialize mutex for thread-safe access
165 if (mutex_init(&fb->mutex, "framebuffer") != 0) {
166 SET_ERRNO(ERROR_THREAD, "Failed to initialize framebuffer mutex");
167 return NULL;
168 }
169
170 defer_named(framebuffer_mutex, mutex_destroy(&fb->mutex));
171
172 // Create ringbuffer to store frame_t structs
173 fb->rb = ringbuffer_create(sizeof(frame_t), capacity);
174 if (!fb->rb) {
175 SET_ERRNO(ERROR_MEMORY, "Failed to allocate frame buffer");
176 return NULL;
177 }
178
179 defer_cancel(framebuffer_mutex);
180 framebuffer_t *result = fb;
181 fb = NULL;
182 return result;
183}
#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast)
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_THREAD

References ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_THREAD, ringbuffer_create(), SAFE_CALLOC_DEFER_FREE, and SET_ERRNO.

◆ framebuffer_create_multi()

framebuffer_t * framebuffer_create_multi ( size_t capacity)

#include <include/ascii-chat/ringbuffer.h>

Create a multi-source frame buffer for multi-user support.

Parameters
capacityNumber of frames to buffer
Returns
Frame buffer or NULL on failure

Creates a new frame buffer for multi-client frame scenarios. Supports tracking frame sources, sequence numbers, and timestamps for proper multi-user frame display.

Definition at line 185 of file ringbuffer.c.

185 {
186 if (capacity == 0) {
187 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid capacity: %zu", capacity);
188 return NULL;
189 }
190
192
193 // Initialize mutex for thread-safe access
194 if (mutex_init(&fb->mutex, "framebuffer_multi") != 0) {
195 SET_ERRNO(ERROR_THREAD, "Failed to initialize framebuffer mutex");
196 return NULL;
197 }
198
199 defer_named(framebuffer_mutex, mutex_destroy(&fb->mutex));
200
201 // Create ringbuffer to store multi_source_frame_t structs
202 fb->rb = ringbuffer_create(sizeof(multi_source_frame_t), capacity);
203
204 if (!fb->rb) {
205 return NULL;
206 }
207
208 defer_cancel(framebuffer_mutex);
209 framebuffer_t *result = fb;
210 fb = NULL;
211 return result;
212}

References ERROR_INVALID_PARAM, ERROR_THREAD, ringbuffer_create(), SAFE_CALLOC_DEFER_FREE, and SET_ERRNO.

◆ framebuffer_destroy()

void framebuffer_destroy ( framebuffer_t * fb)

#include <include/ascii-chat/ringbuffer.h>

Destroy a frame buffer.

Parameters
fbFrame buffer to destroy (must not be NULL)

Frees all memory associated with the frame buffer, including any frames still in the buffer. The buffer must not be in use by any threads when this function is called.

Definition at line 214 of file ringbuffer.c.

214 {
215 if (!fb)
216 return;
217
218 // Add magic number check to detect double-free using rb pointer
219 if (fb->rb == (ringbuffer_t *)0xDEADBEEF) {
220 SET_ERRNO(ERROR_INVALID_STATE, "DOUBLE-FREE DETECTED: framebuffer %p already destroyed!", fb);
221 return;
222 }
223
226 mutex_destroy(&fb->mutex);
227
228 // Mark as destroyed before freeing
229 fb->rb = (ringbuffer_t *)0xDEADBEEF;
230 SAFE_FREE(fb);
231}
void framebuffer_clear(framebuffer_t *fb)
Clear all frames from the buffer, freeing their data.
Definition ringbuffer.c:334

References ERROR_INVALID_STATE, framebuffer_clear(), framebuffer_t::mutex, framebuffer_t::rb, ringbuffer_destroy(), SAFE_FREE, and SET_ERRNO.

◆ framebuffer_peek_latest_multi_frame()

bool framebuffer_peek_latest_multi_frame ( framebuffer_t * fb,
multi_source_frame_t * frame )

#include <include/ascii-chat/ringbuffer.h>

Peek at the latest multi-source frame without removing it.

Parameters
fbFrame buffer (must not be NULL)
framePointer to multi_source_frame_t struct to be filled (must not be NULL)
Returns
true if successful, false if buffer is empty

Examines the latest multi-source frame without removing it from the buffer. Useful for previewing frames or checking frame metadata before reading.

Note
Thread-safe: Protected by mutex for concurrent access.
Returns an independent owning copy. The caller must buffer_release(frame->data).

Definition at line 466 of file ringbuffer.c.

466 {
467 if (!fb || !fb->rb || !frame) {
468 return false;
469 }
470
471 // Thread-safe access to framebuffer
472 mutex_lock(&fb->mutex);
473
474 // Use ringbuffer_peek to get the frame without consuming it
475 bool result = ringbuffer_peek(fb->rb, frame);
476
477 if (result) {
478 // Validate frame magic
479 if (!IS_MAGIC_VALID(frame->magic, FRAME_MAGIC)) {
480 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid multi-source frame magic 0x%x (expected 0x%x) in peek", frame->magic, FRAME_MAGIC);
481 frame->data = NULL;
482 frame->size = 0;
483 memset(frame->source_client_id, 0, sizeof(frame->source_client_id));
484 mutex_unlock(&fb->mutex);
485 return false;
486 }
487
488 // Additional validation
489 if (frame->size == 0 || !frame->data) {
490 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid multi-source frame data (size=%zu, data=%p) in peek", frame->size, frame->data);
491 mutex_unlock(&fb->mutex);
492 return false;
493 }
494
495 // IMPORTANT: We need to make a copy of the data since we're not consuming the frame
496 // The original data pointer will remain valid in the ring buffer
497 // Caller is responsible for freeing this copy with buffer_release()
498 char *data_copy;
499 data_copy = (char *)buffer_alloc(NULL, frame->size);
500 if (!data_copy) {
501 SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for frame data copy in peek");
502 mutex_unlock(&fb->mutex);
503 return false;
504 }
505 SAFE_MEMCPY(data_copy, frame->size, frame->data, frame->size);
506 frame->data = data_copy;
507 }
508
509 mutex_unlock(&fb->mutex);
510 return result;
511}
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:272
#define SAFE_MEMCPY(dest, dest_size, src, count)
uint64_t magic
Magic number to detect corruption (FRAME_MAGIC when valid).
Definition ringbuffer.h:421

References buffer_alloc(), multi_source_frame_t::data, ERROR_INVALID_STATE, ERROR_MEMORY, FRAME_MAGIC, IS_MAGIC_VALID, multi_source_frame_t::magic, framebuffer_t::mutex, framebuffer_t::rb, ringbuffer_peek(), SAFE_MEMCPY, SET_ERRNO, multi_source_frame_t::size, and multi_source_frame_t::source_client_id.

◆ framebuffer_read_frame()

bool framebuffer_read_frame ( framebuffer_t * fb,
frame_t * frame )

#include <include/ascii-chat/ringbuffer.h>

Read a frame from the buffer.

Parameters
fbFrame buffer (must not be NULL)
framePointer to frame_t struct to be filled (must not be NULL)
Returns
true if successful, false if buffer is empty

Reads a single-source frame and transfers its payload ownership to the caller.

Note
Thread-safe: Protected by mutex for concurrent access.
The caller must buffer_release(frame->data) after use.

Definition at line 287 of file ringbuffer.c.

287 {
288 if (!fb || !frame) {
289 return false;
290 }
291
292 // Initialize frame to safe values
293 frame->magic = 0;
294 frame->data = NULL;
295 frame->size = 0;
296
297 // Thread-safe access to framebuffer (fixes TOCTOU race condition)
298 mutex_lock(&fb->mutex);
299
300 bool result = ringbuffer_read(fb->rb, frame);
301
302 // Validate the frame we just read
303 if (result) {
304 if (!IS_MAGIC_VALID(frame->magic, FRAME_MAGIC)) {
305 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid frame magic 0x%x (expected 0x%x)", frame->magic, FRAME_MAGIC);
306 frame->data = NULL;
307 frame->size = 0;
308 mutex_unlock(&fb->mutex);
309 return false;
310 }
311
312 if (IS_FRAME_FREED(frame)) {
313 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Reading already-freed frame!");
314 frame->data = NULL;
315 frame->size = 0;
316 mutex_unlock(&fb->mutex);
317 return false;
318 }
319
320 if (frame->size > 10 * 1024 * 1024) {
321 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Frame size too large: %zu", frame->size);
322 buffer_release(frame->data);
323 frame->data = NULL;
324 frame->size = 0;
325 mutex_unlock(&fb->mutex);
326 return false;
327 }
328 }
329
330 mutex_unlock(&fb->mutex);
331 return result;
332}
#define IS_FRAME_FREED(frame)
Check if frame has been freed (corruption detection).
Definition magic.h:40

References buffer_release, frame_t::data, ERROR_INVALID_STATE, FRAME_MAGIC, IS_FRAME_FREED, IS_MAGIC_VALID, frame_t::magic, framebuffer_t::mutex, framebuffer_t::rb, ringbuffer_read(), SET_ERRNO, and frame_t::size.

◆ framebuffer_read_multi_frame()

bool framebuffer_read_multi_frame ( framebuffer_t * fb,
multi_source_frame_t * frame )

#include <include/ascii-chat/ringbuffer.h>

Read a multi-source frame from the buffer.

Parameters
fbFrame buffer (must not be NULL)
framePointer to multi_source_frame_t struct to be filled (must not be NULL)
Returns
true if successful, false if buffer is empty

Reads a multi-source frame and transfers its payload ownership to the caller.

Note
Thread-safe: Protected by mutex for concurrent access.
The caller must buffer_release(frame->data) after use.

Definition at line 433 of file ringbuffer.c.

433 {
434 if (!fb || !fb->rb || !frame) {
435 return false;
436 }
437
438 // Thread-safe access to framebuffer
439 mutex_lock(&fb->mutex);
440
441 bool result = ringbuffer_read(fb->rb, frame);
442
443 if (result) {
444 // Validate frame magic
445 if (!IS_MAGIC_VALID(frame->magic, FRAME_MAGIC)) {
446 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid multi-source frame magic 0x%x (expected 0x%x)", frame->magic, FRAME_MAGIC);
447 frame->data = NULL;
448 frame->size = 0;
449 memset(frame->source_client_id, 0, sizeof(frame->source_client_id));
450 mutex_unlock(&fb->mutex);
451 return false;
452 }
453
454 // Additional validation
455 if (frame->size == 0 || !frame->data) {
456 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid multi-source frame data (size=%zu, data=%p)", frame->size, frame->data);
457 mutex_unlock(&fb->mutex);
458 return false;
459 }
460 }
461
462 mutex_unlock(&fb->mutex);
463 return result;
464}

References multi_source_frame_t::data, ERROR_INVALID_STATE, FRAME_MAGIC, IS_MAGIC_VALID, multi_source_frame_t::magic, framebuffer_t::mutex, framebuffer_t::rb, ringbuffer_read(), SET_ERRNO, multi_source_frame_t::size, and multi_source_frame_t::source_client_id.

◆ framebuffer_write_frame()

bool framebuffer_write_frame ( framebuffer_t * fb,
const char * frame_data,
size_t frame_size )

#include <include/ascii-chat/ringbuffer.h>

Write a frame to the buffer.

Parameters
fbFrame buffer (must not be NULL)
frame_dataFrame data (must not be NULL)
frame_sizeActual size of frame data in bytes
Returns
true if successful, false if buffer is full

Writes a single-source frame to the buffer. The frame data is copied into the buffer, so the caller retains ownership of the original data.

Note
Thread-safe: Protected by mutex for concurrent access.

Definition at line 233 of file ringbuffer.c.

233 {
234 if (!fb || !frame_data || frame_size == 0)
235 return false;
236
237 // Validate frame size to prevent overflow
238 if (frame_size > 10 * 1024 * 1024) { // 10MB max for ASCII frames
239 SET_ERRNO(ERROR_INVALID_PARAM, "Rejecting oversized frame: %zu bytes", frame_size);
240 return false;
241 }
242
243 // Thread-safe access to framebuffer (was missing, causing race conditions)
244 mutex_lock(&fb->mutex);
245
246 // Check if buffer is full - if so, we need to drop the oldest frame
247 if (ringbuffer_size(fb->rb) >= fb->rb->capacity) {
248 // Buffer is full, read and free the oldest frame before writing new one
249 frame_t old_frame;
250 if (ringbuffer_read(fb->rb, &old_frame)) {
251 if (IS_FRAME_VALID(&old_frame)) {
252 MARK_FRAME_FREED(&old_frame);
253 // Use buffer_release since data was allocated with buffer_alloc
254 buffer_release(old_frame.data);
255 } else if (!IS_MAGIC_VALID(old_frame.magic, FRAME_MAGIC)) {
256 SET_ERRNO(ERROR_INVALID_STATE, "CORRUPTION: Invalid old frame magic 0x%x when dropping", old_frame.magic);
257 }
258 }
259 }
260
261 // Allocate a copy of the frame data using buffer domain for better performance
262 char *frame_copy = (char *)buffer_alloc(NULL, frame_size + 1);
263 if (!frame_copy) {
264 mutex_unlock(&fb->mutex);
265 SET_ERRNO(ERROR_MEMORY, "Failed to allocate %zu bytes from buffer domain for frame", frame_size + 1);
266 return false;
267 }
268
269 SAFE_MEMCPY(frame_copy, frame_size, frame_data, frame_size);
270 frame_copy[frame_size] = '\0'; // Ensure null termination
271
272 // Create a frame_t struct with the copy (store allocated size for proper cleanup)
273 frame_t frame = {.magic = MAGIC_FRAME_VALID, .size = frame_size + 1, .data = frame_copy};
274
275 bool result = ringbuffer_write(fb->rb, &frame);
276
277 if (!result) {
278 // If we still couldn't write to ringbuffer, return the buffer to pool
279 buffer_release(frame_copy);
280 SET_ERRNO(ERROR_INVALID_STATE, "Failed to write frame to ringbuffer even after dropping oldest");
281 }
282
283 mutex_unlock(&fb->mutex);
284 return result;
285}
#define MAGIC_FRAME_VALID
Magic number for valid ring buffer frames (0xA5C11C4A1 = "ASCIICHAT" in hex).
Definition magic.h:21

References buffer_alloc(), buffer_release, ringbuffer_t::capacity, frame_t::data, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, FRAME_MAGIC, IS_FRAME_VALID, IS_MAGIC_VALID, frame_t::magic, MAGIC_FRAME_VALID, MARK_FRAME_FREED, framebuffer_t::mutex, framebuffer_t::rb, ringbuffer_read(), ringbuffer_size(), ringbuffer_write(), SAFE_MEMCPY, and SET_ERRNO.

◆ framebuffer_write_multi_frame()

bool framebuffer_write_multi_frame ( framebuffer_t * fb,
const char * frame_data,
size_t frame_size,
uint32_t source_client_id,
uint32_t frame_sequence,
uint32_t timestamp )

#include <include/ascii-chat/ringbuffer.h>

Write a multi-source frame to the buffer (for multi-user support).

Parameters
fbFrame buffer (must not be NULL)
frame_dataFrame data (must not be NULL)
frame_sizeActual size of frame data in bytes
source_client_idClient ID that sent this frame
frame_sequenceFrame sequence number for ordering
timestampTimestamp when frame was captured
Returns
true if successful, false if buffer is full

Writes a multi-source frame to the buffer with associated metadata. The frame data is copied into the buffer, so the caller retains ownership of the original data.

Note
Thread-safe: Protected by mutex for concurrent access.
The frame buffer must have been created with framebuffer_create_multi() for multi-source support.

Definition at line 388 of file ringbuffer.c.

388 {
389 if (!fb || !fb->rb || !frame_data || frame_size == 0) {
390 return false;
391 }
392
393 // Allocate memory for frame data using buffer domain for better performance
394 char *data_copy = (char *)buffer_alloc(NULL, frame_size);
395 if (!data_copy) {
396 SET_ERRNO(ERROR_MEMORY, "Failed to allocate %zu bytes from buffer domain for multi-source frame", frame_size);
397 return false;
398 }
399
400 // Copy frame data
401 SAFE_MEMCPY(data_copy, frame_size, frame_data, frame_size);
402
403 // Convert client ID number to string for storage in frame metadata
404 char client_id_str[RINGBUFFER_CLIENT_ID_BUFFER_SIZE];
405 snprintf(client_id_str, sizeof(client_id_str), "%u", source_client_id);
406
407 // Create multi-source frame
408 multi_source_frame_t multi_frame = {
409 .magic = MAGIC_FRAME_VALID,
410 .source_client_id = {0},
411 .frame_sequence = frame_sequence,
412 .timestamp = timestamp,
413 .size = frame_size,
414 .data = data_copy,
415 };
416 SAFE_MEMCPY(multi_frame.source_client_id, sizeof(multi_frame.source_client_id), client_id_str, strlen(client_id_str) + 1);
417
418 // Thread-safe access to framebuffer
419 mutex_lock(&fb->mutex);
420
421 // Try to write to ring buffer
422 bool success = ringbuffer_write(fb->rb, &multi_frame);
423 if (!success) {
424 // Buffer full, return the buffer to pool
425 buffer_release(data_copy);
426 log_debug("Frame buffer full, dropping multi-source frame from client %u", source_client_id);
427 }
428
429 mutex_unlock(&fb->mutex);
430 return success;
431}
#define RINGBUFFER_CLIENT_ID_BUFFER_SIZE
Definition ringbuffer.c:8

References buffer_alloc(), buffer_release, ERROR_MEMORY, log_debug, MAGIC_FRAME_VALID, framebuffer_t::mutex, framebuffer_t::rb, RINGBUFFER_CLIENT_ID_BUFFER_SIZE, ringbuffer_write(), SAFE_MEMCPY, SET_ERRNO, and multi_source_frame_t::source_client_id.

◆ ringbuffer_clear()

void ringbuffer_clear ( ringbuffer_t * rb)

#include <include/ascii-chat/ringbuffer.h>

Clear all elements from the buffer.

Parameters
rbRing buffer (must not be NULL)

Removes all elements from the buffer and resets it to empty state. This operation is not atomic with respect to concurrent read/write operations - use with caution in multi-threaded scenarios.

Note
Thread-safe: Uses atomic operations, but concurrent operations may still occur during clearing.

Definition at line 143 of file ringbuffer.c.

143 {
144 if (rb) {
145 atomic_store_u64(&rb->head, 0);
146 atomic_store_u64(&rb->tail, 0);
147 atomic_store_u64(&rb->size, 0);
148 }
149}
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.

References atomic_store_u64(), ringbuffer_t::head, ringbuffer_t::size, and ringbuffer_t::tail.

Referenced by framebuffer_clear().

◆ ringbuffer_create()

ringbuffer_t * ringbuffer_create ( size_t element_size,
size_t capacity )

#include <include/ascii-chat/ringbuffer.h>

Create a new ring buffer.

Parameters
element_sizeSize of each element in bytes
capacityNumber of elements (will be rounded up to power of 2)
Returns
Pointer to ring buffer or NULL on failure

Creates a new lock-free ring buffer with the specified element size and capacity. The capacity is automatically rounded up to the next power of 2 to enable fast bit masking optimizations.

Definition at line 34 of file ringbuffer.c.

34 {
35 if (element_size == 0 || capacity == 0) {
36 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ring buffer parameters: element_size=%zu, capacity=%zu", element_size, capacity);
37 return NULL;
38 }
39
40 ringbuffer_t *rb;
41 rb = SAFE_CALLOC(1, sizeof(ringbuffer_t), ringbuffer_t *);
42
43 /* Round capacity up to power of 2 for optimization */
44 size_t actual_capacity = math_next_power_of_two(capacity);
45
46 rb->buffer = SAFE_CALLOC(actual_capacity, element_size, char *);
47
48 rb->element_size = element_size;
49 rb->capacity = actual_capacity;
50 rb->is_power_of_two = true;
51 rb->capacity_mask = actual_capacity - 1;
52 /* Atomic fields are zero-initialized by SAFE_CALLOC */
53 NAMED_REGISTER_ATOMIC(&rb->head, "ringbuffer.head", NULL);
54 NAMED_REGISTER_ATOMIC(&rb->tail, "ringbuffer.tail", NULL);
55 NAMED_REGISTER_ATOMIC(&rb->size, "ringbuffer.size", NULL);
56
57 return rb;
58}
#define SAFE_CALLOC(count, size, cast)
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
bool is_power_of_two
Whether capacity is power of 2 (enables bit masking optimization).
Definition ringbuffer.h:108

References ringbuffer_t::buffer, ringbuffer_t::capacity, ringbuffer_t::capacity_mask, ringbuffer_t::element_size, ERROR_INVALID_PARAM, ringbuffer_t::head, ringbuffer_t::is_power_of_two, NAMED_REGISTER_ATOMIC, SAFE_CALLOC, SET_ERRNO, ringbuffer_t::size, and ringbuffer_t::tail.

Referenced by acip_async_tcp_client_create(), acip_async_tcp_transport_create(), framebuffer_create(), framebuffer_create_multi(), session_host_add_client(), and session_host_add_memory_participant().

◆ ringbuffer_destroy()

void ringbuffer_destroy ( ringbuffer_t * rb)

#include <include/ascii-chat/ringbuffer.h>

Destroy a ring buffer and free its memory.

Parameters
rbRing buffer to destroy (must not be NULL)

Frees all memory associated with the ring buffer. The buffer must not be in use by any threads when this function is called.

Definition at line 60 of file ringbuffer.c.

60 {
61 if (rb) {
65 SAFE_FREE(rb->buffer);
66 SAFE_FREE(rb);
67 }
68}
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.

References ringbuffer_t::buffer, ringbuffer_t::head, NAMED_UNREGISTER, SAFE_FREE, ringbuffer_t::size, and ringbuffer_t::tail.

Referenced by acip_async_tcp_transport_create(), acip_websocket_client_transport_create(), framebuffer_destroy(), session_host_add_client(), session_host_add_memory_participant(), session_host_destroy(), and session_host_remove_client().

◆ ringbuffer_is_empty()

bool ringbuffer_is_empty ( const ringbuffer_t * rb)

#include <include/ascii-chat/ringbuffer.h>

Check if buffer is empty.

Parameters
rbRing buffer (must not be NULL)
Returns
true if buffer is empty, false otherwise

Performs a fast check to determine if the buffer contains any elements. More efficient than checking if size() == 0.

Note
Thread-safe: Uses atomic operations for lock-free check.

Definition at line 135 of file ringbuffer.c.

135 {
136 return ringbuffer_size(rb) == 0;
137}

References ringbuffer_size().

Referenced by acip_websocket_transport_flush().

◆ ringbuffer_is_full()

bool ringbuffer_is_full ( const ringbuffer_t * rb)

#include <include/ascii-chat/ringbuffer.h>

Check if buffer is full.

Parameters
rbRing buffer (must not be NULL)
Returns
true if buffer is full, false otherwise

Performs a fast check to determine if the buffer has reached capacity. More efficient than checking if size() == capacity.

Note
Thread-safe: Uses atomic operations for lock-free check.

Definition at line 139 of file ringbuffer.c.

139 {
140 return rb ? ringbuffer_size(rb) >= rb->capacity : true;
141}

References ringbuffer_t::capacity, and ringbuffer_size().

◆ ringbuffer_peek()

bool ringbuffer_peek ( ringbuffer_t * rb,
void * data )

#include <include/ascii-chat/ringbuffer.h>

Peek at the next element without removing it.

Parameters
rbRing buffer (must not be NULL)
dataBuffer to peek into (must not be NULL, must be element_size bytes)
Returns
true if successful, false if buffer is empty

Examines the next element without removing it from the buffer. This is useful for previewing data before committing to reading it.

Note
SPSC only: Single Producer, Single Consumer. NOT thread-safe for multiple concurrent peek operations.

Definition at line 114 of file ringbuffer.c.

114 {
115 if (!rb || !data)
116 return false;
117
118 size_t current_size = atomic_load_u64(&rb->size);
119 if (current_size == 0) {
120 return false; /* Buffer empty */
121 }
122
123 size_t tail = atomic_load_u64(&rb->tail);
124
125 /* Copy data without updating tail */
126 SAFE_MEMCPY(data, rb->element_size, rb->buffer + (tail * rb->element_size), rb->element_size);
127
128 return true;
129}
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.

References atomic_load_u64(), ringbuffer_t::buffer, ringbuffer_t::element_size, SAFE_MEMCPY, ringbuffer_t::size, and ringbuffer_t::tail.

Referenced by framebuffer_peek_latest_multi_frame().

◆ ringbuffer_read()

bool ringbuffer_read ( ringbuffer_t * rb,
void * data )

#include <include/ascii-chat/ringbuffer.h>

Try to read an element from the ring buffer (non-blocking).

Parameters
rbRing buffer (must not be NULL)
dataBuffer to read into (must not be NULL, must be element_size bytes)
Returns
true if successful, false if buffer is empty

Attempts to read an element from the ring buffer. This is a non-blocking operation that uses lock-free atomic operations. Returns false immediately if the buffer is empty.

Note
SPSC only: Single Producer, Single Consumer. NOT thread-safe for multiple consumers - use external synchronization if needed.

Definition at line 92 of file ringbuffer.c.

92 {
93 if (!rb || !data)
94 return false;
95
96 size_t current_size = atomic_load_u64(&rb->size);
97 if (current_size == 0) {
98 return false; /* Buffer empty */
99 }
100
101 size_t tail = atomic_load_u64(&rb->tail);
102 size_t next_tail = (tail + 1) & rb->capacity_mask;
103
104 /* Copy data */
105 SAFE_MEMCPY(data, rb->element_size, rb->buffer + (tail * rb->element_size), rb->element_size);
106
107 /* Update tail and size atomically */
108 atomic_store_u64(&rb->tail, next_tail);
109 atomic_fetch_sub_u64(&rb->size, 1);
110
111 return true;
112}
uint64_t atomic_fetch_sub_u64(atomic_t *a, uint64_t delta)
Atomically subtract from a uint64_t and return the previous value.

References atomic_fetch_sub_u64(), atomic_load_u64(), atomic_store_u64(), ringbuffer_t::buffer, ringbuffer_t::capacity_mask, ringbuffer_t::element_size, SAFE_MEMCPY, ringbuffer_t::size, and ringbuffer_t::tail.

Referenced by framebuffer_clear(), framebuffer_read_frame(), framebuffer_read_multi_frame(), framebuffer_write_frame(), session_host_render_audio(), and websocket_transport_write_pending().

◆ ringbuffer_size()

size_t ringbuffer_size ( const ringbuffer_t * rb)

#include <include/ascii-chat/ringbuffer.h>

Get current number of elements in the buffer.

Parameters
rbRing buffer (must not be NULL)
Returns
Number of elements currently in the buffer

Returns the current size of the buffer. This is a snapshot value that may change immediately after return due to concurrent operations.

Note
Thread-safe: Uses atomic operations for lock-free size check.

Definition at line 131 of file ringbuffer.c.

131 {
132 return rb ? atomic_load_u64(&rb->size) : 0;
133}

References atomic_load_u64(), and ringbuffer_t::size.

Referenced by framebuffer_write_frame(), ringbuffer_is_empty(), and ringbuffer_is_full().

◆ ringbuffer_write()

bool ringbuffer_write ( ringbuffer_t * rb,
const void * data )

#include <include/ascii-chat/ringbuffer.h>

Try to write an element to the ring buffer (non-blocking).

Parameters
rbRing buffer (must not be NULL)
dataData to write (must not be NULL, must be element_size bytes)
Returns
true if successful, false if buffer is full

Attempts to write an element to the ring buffer. This is a non-blocking operation that uses lock-free atomic operations. Returns false immediately if the buffer is full.

Note
SPSC only: Single Producer, Single Consumer. NOT thread-safe for multiple producers - use external synchronization if needed.

Definition at line 70 of file ringbuffer.c.

70 {
71 if (!rb || !data)
72 return false;
73
74 size_t current_size = atomic_load_u64(&rb->size);
75 if (current_size >= rb->capacity) {
76 return false; /* Buffer full */
77 }
78
79 size_t head = atomic_load_u64(&rb->head);
80 size_t next_head = (head + 1) & rb->capacity_mask;
81
82 /* Copy data */
83 SAFE_MEMCPY(rb->buffer + (head * rb->element_size), rb->element_size, data, rb->element_size);
84
85 /* Update head and size atomically */
86 atomic_store_u64(&rb->head, next_head);
88
89 return true;
90}
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.

References atomic_fetch_add_u64(), atomic_load_u64(), atomic_store_u64(), ringbuffer_t::buffer, ringbuffer_t::capacity, ringbuffer_t::capacity_mask, ringbuffer_t::element_size, ringbuffer_t::head, SAFE_MEMCPY, and ringbuffer_t::size.

Referenced by acip_async_tcp_client_create(), framebuffer_write_frame(), framebuffer_write_multi_frame(), session_host_inject_audio(), and session_host_receive_packet().