ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
video_frame.c
Go to the documentation of this file.
1#include <recast/defer.h>
3
9
11#include <ascii-chat/common.h>
12#include <ascii-chat/asciichat_errno.h> // For asciichat_errno system
14#include <ascii-chat/buffer.h>
16#include <string.h>
17#include <stdlib.h>
18
20 if (client_id == 0) {
21 SET_ERRNO(ERROR_INVALID_PARAM, "Client ID is 0");
22 return NULL;
23 }
24
26
27 // Copy client_id string - we own this memory now
28 // (caller's client_id may be a stack variable that goes out of scope)
29 size_t client_id_len = strlen(client_id) + 1;
30 SAFE_MALLOC_DEFER_FREE(client_id_copy, client_id_len, char *);
31 if (!client_id_copy) {
32 SET_ERRNO(ERROR_MEMORY, "Failed to allocate memory for client_id copy");
33 return NULL;
34 }
35 asciichat_error_t strcpy_result = SAFE_STRCPY(client_id_copy, client_id_len, client_id);
36 if (strcpy_result != ASCIICHAT_OK) {
37 log_error("Failed to copy client_id: %s", asciichat_error_format(NULL, strcpy_result));
38 return NULL;
39 }
40 vfb->client_id = client_id_copy;
41 vfb->active = true;
42
43 // Initialize double buffers
44 vfb->front_buffer = &vfb->frames[0];
45 vfb->back_buffer = &vfb->frames[1];
46
47 const size_t frame_size = (size_t)MAX_FRAME_BUFFER_SIZE;
48 vfb->frames[0].data = buffer_alloc(NULL, frame_size);
49 vfb->frames[1].data = buffer_alloc(NULL, frame_size);
50 defer_named(first_frame, buffer_release(vfb->frames[0].data));
51 defer_named(second_frame, buffer_release(vfb->frames[1].data));
52 if (!vfb->frames[0].data || !vfb->frames[1].data) {
53 SET_ERRNO(ERROR_MEMORY, "Video frame buffers exceed memory budget");
54 return NULL;
55 }
56 vfb->allocated_buffer_size = frame_size;
57 memset(vfb->frames[0].data, 0, frame_size);
58 memset(vfb->frames[1].data, 0, frame_size);
59
60 // Initialize synchronization
61 log_info("VFB_MUTEX_INIT_START: About to init mutex for client_id=%s", client_id);
62 if (mutex_init(&vfb->swap_mutex, "video_frame_swap") != 0) {
63 log_error("VFB_MUTEX_INIT_FAILED: mutex_init returned error");
64 SET_ERRNO(ERROR_PLATFORM_INIT, "Failed to initialize mutex for video frame buffer");
65 return NULL;
66 }
67 log_info("VFB_MUTEX_INIT_DONE: mutex initialized successfully");
68 atomic_store_bool(&vfb->new_frame_available, false);
69
70 // Initialize statistics
71 atomic_store_u64(&vfb->total_frames_received, 0);
72 atomic_store_u64(&vfb->total_frames_dropped, 0);
73 atomic_store_u64(&vfb->last_frame_sequence, 0);
74
75 log_debug("Created video frame buffer for client %s with double buffering", client_id);
76
77 // DEBUG: Final state check
78 log_info("VFB_FINAL: vfb=%p, back_buffer=%p (should be %p), frames[0].data=%p, frames[1].data=%p, allocated_size=%zu", (void *)vfb, (void *)vfb->back_buffer, (void *)&vfb->frames[1],
79 (void *)vfb->frames[0].data, (void *)vfb->frames[1].data, vfb->allocated_buffer_size);
80
81 NAMED_REGISTER_VIDEO_FRAME_BUFFER(vfb, "buffer", NULL);
82
83 // Register atomic fields with descriptive names - vfb is their parent
84 NAMED_REGISTER_ATOMIC(&vfb->new_frame_available, "new_frame_available_flag", (uintptr_t)(const void *)(vfb));
85 NAMED_REGISTER_ATOMIC(&vfb->total_frames_received, "total_frames_received_counter", (uintptr_t)(const void *)(vfb));
86 NAMED_REGISTER_ATOMIC(&vfb->total_frames_dropped, "total_frames_dropped_counter", (uintptr_t)(const void *)(vfb));
87 NAMED_REGISTER_ATOMIC(&vfb->last_frame_sequence, "last_frame_sequence_number", (uintptr_t)(const void *)(vfb));
88
89 defer_cancel(second_frame);
90 defer_cancel(first_frame);
91 video_frame_buffer_t *result = vfb;
92 vfb = NULL;
93 client_id_copy = NULL;
94 return result;
95}
96
98 if (!vfb) {
99 SET_ERRNO(ERROR_INVALID_PARAM, "Video frame buffer is NULL");
100 return;
101 }
102
103 NAMED_UNREGISTER(vfb);
104
105 // Unregister atomic fields
110
111 vfb->active = false;
112
113 buffer_release(vfb->frames[0].data);
114 buffer_release(vfb->frames[1].data);
115
116 mutex_destroy(&vfb->swap_mutex);
117
118 // Free the allocated client_id string
119 SAFE_FREE(vfb->client_id);
120
121 SAFE_FREE(vfb);
122}
123
125 if (!vfb) {
126 SET_ERRNO(ERROR_INVALID_PARAM, "Video frame buffer is NULL");
127 return NULL;
128 }
129 if (!vfb->active) {
130 SET_ERRNO(ERROR_INVALID_STATE, "vfb->active is not true");
131 return NULL;
132 }
133
134 // Writer always owns the back buffer
135 return vfb->back_buffer;
136}
137
139 if (!vfb) {
140 SET_ERRNO(ERROR_INVALID_PARAM, "Video frame buffer or active is NULL");
141 return;
142 }
143 if (!vfb->active) {
144 SET_ERRNO(ERROR_INVALID_STATE, "vfb->active is not true");
145 return;
146 }
147
148 // Keep the unread check, pointer swap, and publication atomic with respect
149 // to readers. Checking front_buffer before taking this mutex races with a
150 // reader consuming the previous frame and with another commit swapping it.
151 mutex_lock(&vfb->swap_mutex);
152 if (atomic_load_bool(&vfb->new_frame_available) && vfb->front_buffer->size > 0) {
156 if (drops == 1 || drops % 100 == 0) {
157 log_dev_every(4500 * US_PER_MS_INT, "Dropping frame for client %s (reader too slow, total drops: %llu)", vfb->client_id, (unsigned long long)drops);
158 }
159 }
160 video_frame_t *temp = vfb->front_buffer;
161 vfb->front_buffer = vfb->back_buffer;
162 vfb->back_buffer = temp;
164 mutex_unlock(&vfb->swap_mutex);
165
168}
169
171 if (!vfb) {
172 SET_ERRNO(ERROR_INVALID_PARAM, "Video frame buffer is not active");
173 return NULL;
174 }
175 if (!vfb->active) {
176 SET_ERRNO(ERROR_INVALID_STATE, "vfb->active is not true");
177 return NULL;
178 }
179
180 mutex_lock(&vfb->swap_mutex);
182 mutex_unlock(&vfb->swap_mutex);
183 return NULL;
184 }
186 const video_frame_t *result = vfb->front_buffer;
187 mutex_unlock(&vfb->swap_mutex);
188
189 return result;
190}
191
193 if (!vfb || !vfb->active)
194 return NULL;
195 mutex_lock(&vfb->swap_mutex);
196 const video_frame_t *frame = vfb->front_buffer;
197 const video_frame_t *result = frame && frame->size > 0 ? frame : NULL;
198 mutex_unlock(&vfb->swap_mutex);
199 return result;
200}
201
203 if (!vfb || !stats) {
204 SET_ERRNO(ERROR_INVALID_PARAM, "Video frame buffer or stats is NULL");
205 return;
206 }
207 if (!vfb->active) {
208 SET_ERRNO(ERROR_INVALID_STATE, "vfb->active is not true");
209 return;
210 }
211
214 stats->drop_rate = (stats->total_frames > 0) ? (float)stats->dropped_frames / (float)stats->total_frames : 0.0f;
217}
218
219// Simple frame swap implementation for basic cases
222
223 // Pre-allocate both frames
224 const size_t frame_size = (size_t)MAX_FRAME_BUFFER_SIZE;
225 sfs->frame_a.data = SAFE_MALLOC(frame_size, void *);
226 sfs->frame_b.data = SAFE_MALLOC(frame_size, void *);
227
229 atomic_store_bool(&sfs->use_frame_a, false); // Next write goes to frame_b
230
231 return sfs;
232}
233
235 if (!sfs) {
236 SET_ERRNO(ERROR_INVALID_PARAM, "Simple frame swap is NULL");
237 return;
238 }
239 SAFE_FREE(sfs->frame_a.data);
240 SAFE_FREE(sfs->frame_b.data);
241 SAFE_FREE(sfs);
242}
243
244void simple_frame_swap_update(simple_frame_swap_t *sfs, const void *data, size_t size) {
245 if (!sfs || !data) {
246 SET_ERRNO(ERROR_INVALID_PARAM, "Simple frame swap or data is NULL");
247 return;
248 }
249
250 // Determine which frame to write to
251 bool use_a = atomic_load_bool(&sfs->use_frame_a);
252 video_frame_t *write_frame = use_a ? &sfs->frame_a : &sfs->frame_b;
253
254 // Copy data to write frame
255 if (size <= (size_t)MAX_FRAME_BUFFER_SIZE) {
256 SAFE_MEMCPY(write_frame->data, size, data, size);
257 write_frame->size = size;
258 write_frame->capture_timestamp_ns = time_get_ns();
259
260 // Atomically update current frame pointer
261 atomic_store_u64(&sfs->current_frame, (uintptr_t)write_frame);
262
263 // Toggle for next write
264 atomic_store_bool(&sfs->use_frame_a, !use_a);
265 }
266}
267
269 if (!sfs) {
270 SET_ERRNO(ERROR_INVALID_PARAM, "Simple frame swap is NULL");
271 return NULL;
272 }
273 uintptr_t frame_ptr = atomic_load_u64(&sfs->current_frame);
274 return (const video_frame_t *)(void *)frame_ptr; // NOLINT(bugprone-casting-through-void,performance-no-int-to-ptr)
275}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:272
#define buffer_release(data)
Definition buffer.h:99
Named object registry for debugging — log identifiable resource names.
#define MAX_FRAME_BUFFER_SIZE
Maximum frame buffer size including headers and compression.
#define SAFE_FREE(ptr)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
#define SAFE_STRCPY(dest, dest_size, src)
#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast)
unsigned long long uint64_t
#define SAFE_MEMCPY(dest, dest_size, src, count)
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_REGISTER_VIDEO_FRAME_BUFFER(buf, name, parent_ptr)
Register a video frame buffer with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define US_PER_MS_INT
Definition time.h:176
void video_frame_buffer_destroy(video_frame_buffer_t *vfb)
Destroy frame buffer and free all resources.
Definition video_frame.c:97
const video_frame_t * video_frame_peek_latest(video_frame_buffer_t *vfb)
video_frame_t * video_frame_begin_write(video_frame_buffer_t *vfb)
Writer API: Start writing a new frame.
const video_frame_t * simple_frame_swap_get(simple_frame_swap_t *sfs)
Get current frame from simple frame swap.
simple_frame_swap_t * simple_frame_swap_create(void)
Create a simple atomic frame swap.
video_frame_buffer_t * video_frame_buffer_create(const char *client_id)
Create a double-buffered video frame manager.
Definition video_frame.c:19
void video_frame_commit(video_frame_buffer_t *vfb)
Writer API: Commit the frame and swap buffers.
const video_frame_t * video_frame_get_latest(video_frame_buffer_t *vfb)
Reader API: Get latest frame if available.
void video_frame_get_stats(video_frame_buffer_t *vfb, video_frame_stats_t *stats)
Get frame statistics for quality monitoring.
void simple_frame_swap_update(simple_frame_swap_t *sfs, const void *data, size_t size)
Update frame data in simple frame swap.
void simple_frame_swap_destroy(simple_frame_swap_t *sfs)
Destroy simple frame swap and free resources.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:740
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:78
🔤 String Manipulation and Shell Escaping Utilities
Counters and timing measurements used to monitor frame delivery and quality.
atomic_t use_frame_a
Atomic flag: true = use frame_a next, false = use frame_b.
video_frame_t frame_b
Second pre-allocated frame.
atomic_t current_frame
Atomic pointer to current frame (stored as uint64_t).
video_frame_t frame_a
First pre-allocated frame.
One captured, decoded, or rendered video frame and its timing metadata.
bool active
True if buffer is active (receiving frames).
mutex_t swap_mutex
Brief mutex for pointer swap only.
atomic_t avg_render_time_ns
Average render time in nanoseconds (atomic).
video_frame_t * back_buffer
Currently written frame (writer owns).
atomic_t new_frame_available
Atomic flag: true when new frame available.
atomic_t total_frames_dropped
Total frames dropped (atomic counter).
video_frame_t frames[2]
Pre-allocated frame structures (reused forever).
video_frame_t * front_buffer
Currently displayed frame (reader owns).
atomic_t avg_decode_time_ns
Average decode time in nanoseconds (atomic).
atomic_t total_frames_received
Total frames received (atomic counter).
atomic_t last_frame_sequence
Last frame sequence number (atomic).
const char * client_id
Client ID (name) this buffer belongs to.
Counters and timing measurements used to monitor frame delivery and quality.
uint64_t dropped_frames
Total frames dropped (due to buffer full or errors).
uint64_t total_frames
Total frames received since creation.
uint64_t avg_render_time_ns
Average frame render time in nanoseconds.
float drop_rate
Frame drop rate (dropped_frames / total_frames, 0.0-1.0).
uint64_t avg_decode_time_ns
Average frame decode time in nanoseconds.
When code needs to work with simple frame swap, it keeps current_frame, frame_a, frame_b,...
size_t size
Size of frame data in bytes.
uint64_t capture_timestamp_ns
Timestamp when frame was captured (nanoseconds).
void * data
Frame data pointer (points to pre-allocated buffer).
⏱️ High-precision timing utilities using sokol_time.h and uthash