ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
video/rgba/image.c
Go to the documentation of this file.
1
6
7#include <stdbool.h>
8#include <stddef.h>
9#include <stdint.h>
10#include <limits.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <math.h>
15#ifndef _WIN32
16#include <unistd.h>
17#endif
18
19#include <ascii-chat/common.h>
26
28#include <options/options.h>
29#include <ascii-chat/buffer.h> // For buffer domain allocation functions
33
34// NOTE: luminance_palette is now passed as parameter to functions instead of using global cache
35
36// ansi_fast functions are declared in ansi_fast.h (already included)
37
38image_t *image_new(size_t width, size_t height) {
40 return NULL;
41 size_t pixels_size;
42 if (checked_size_mul3(width, height, sizeof(rgb_pixel_t), &pixels_size) != ASCIICHAT_OK || pixels_size > IMAGE_MAX_PIXELS_SIZE)
43 return NULL;
44 const size_t offset = (sizeof(image_t) + BUFFER_DEFAULT_ALIGNMENT - 1) & ~(size_t)(BUFFER_DEFAULT_ALIGNMENT - 1);
45 size_t total;
46 if (checked_size_add(offset, pixels_size, &total) != ASCIICHAT_OK)
47 return NULL;
48 image_t *image = buffer_alloc(NULL, total);
49 if (!image)
50 return NULL;
51 image->w = (int)width;
52 image->h = (int)height;
53 image->pixels = (rgb_pixel_t *)((uint8_t *)image + offset);
54 return image;
55}
56
60
62 if (!p || !p->pixels) {
63 SET_ERRNO(ERROR_INVALID_PARAM, "p or p->pixels is NULL");
64 return;
65 }
66 // Check for integer overflow before multiplication.
67 unsigned long w_ul = (unsigned long)p->w;
68 unsigned long h_ul = (unsigned long)p->h;
69 if (w_ul > 0 && h_ul > ULONG_MAX / w_ul) {
70 SET_ERRNO(ERROR_INVALID_PARAM, "dimensions overflow: %d x %d", p->w, p->h);
71 return;
72 }
73 unsigned long pixel_count = w_ul * h_ul;
74 if (pixel_count > ULONG_MAX / sizeof(rgb_pixel_t)) {
75 SET_ERRNO(ERROR_INVALID_PARAM, "buffer size overflow");
76 return;
77 }
78 size_t clear_size = pixel_count * sizeof(rgb_pixel_t);
79 SAFE_MEMSET(p->pixels, clear_size, 0, clear_size);
80}
81
83 if (!source) {
84 SET_ERRNO(ERROR_INVALID_PARAM, "source is NULL");
85 return NULL;
86 }
87
88 // Create new image with same dimensions
89 image_t *copy = image_new((size_t)source->w, (size_t)source->h);
90 if (!copy) {
91 return NULL;
92 }
93
94 // Copy pixel data from source to copy
95 if (source->pixels && copy->pixels) {
96 size_t pixel_count = (size_t)source->w * (size_t)source->h;
97 size_t pixels_size = pixel_count * sizeof(rgb_pixel_t);
98 memcpy(copy->pixels, source->pixels, pixels_size);
99 }
100
101 return copy;
102}
103
104inline rgb_pixel_t *image_pixel(image_t *p, const int x, const int y) {
105 // Add bounds checking to prevent buffer overflow on invalid coordinates
106 if (!p || !p->pixels || x < 0 || x >= p->w || y < 0 || y >= p->h) {
107 return NULL;
108 }
109 return &p->pixels[x + y * p->w];
110}
111
112void image_resize(const image_t *s, image_t *d) {
113 if (!s || !d) {
114 SET_ERRNO(ERROR_INVALID_PARAM, "s or d is NULL");
115 return;
116 }
117
119}
120
121// Optimized interpolation function with better integer arithmetic and memory
122// access
124 if (!source || !dest || !source->pixels || !dest->pixels) {
125 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
126 return;
127 }
128
129 const int src_w = source->w;
130 const int src_h = source->h;
131 const int dst_w = dest->w;
132 const int dst_h = dest->h;
133
134 // Handle edge cases
135 if (src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0) {
136 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid image dimensions for resize: src=%dx%d dst=%dx%d", src_w, src_h, dst_w, dst_h);
137 return;
138 }
139
140 // Defensive checks to prevent invalid shift (UBSan protection)
141 if (src_w < 1 || src_h < 1 || dst_w < 1 || dst_h < 1) {
142 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid dimensions detected after first check");
143 return;
144 }
145
146 // Use fixed-point arithmetic for better performance
147 // Use uint64_t intermediate to prevent overflow when shifting large dimensions
148 const uint32_t x_ratio = (uint32_t)((((uint64_t)src_w << 16) / (uint64_t)dst_w) + 1);
149 const uint32_t y_ratio = (uint32_t)((((uint64_t)src_h << 16) / (uint64_t)dst_h) + 1);
150
151 const rgb_pixel_t *src_pixels = source->pixels;
152 rgb_pixel_t *dst_pixels = dest->pixels;
153
154 for (int y = 0; y < dst_h; y++) {
155 const uint32_t src_y = ((uint32_t)(unsigned int)y * y_ratio) >> 16;
156 // Explicitly clamp to valid range [0, src_h-1]
157 const uint32_t safe_src_y = src_y >= (uint32_t)(unsigned int)src_h ? (uint32_t)(src_h - 1) : src_y;
158
159 // Bounds check: ensure safe_src_y is valid
160 if (safe_src_y >= (uint32_t)(unsigned int)src_h) {
161 SET_ERRNO(ERROR_INVALID_PARAM, "safe_src_y out of bounds: %u >= %d", safe_src_y, src_h);
162 return;
163 }
164
165 const rgb_pixel_t *src_row = src_pixels + (safe_src_y * (size_t)src_w);
166
167 rgb_pixel_t *dst_row = dst_pixels + ((size_t)y * (size_t)dst_w);
168
169 for (int x = 0; x < dst_w; x++) {
170 const uint32_t src_x = ((uint32_t)(unsigned int)x * x_ratio) >> 16;
171 // Explicitly clamp to valid range [0, src_w-1]
172 const uint32_t safe_src_x = src_x >= (uint32_t)(unsigned int)src_w ? (uint32_t)(src_w - 1) : src_x;
173
174 // Bounds check: ensure safe_src_x is valid
175 if (safe_src_x >= (uint32_t)(unsigned int)src_w) {
176 SET_ERRNO(ERROR_INVALID_PARAM, "safe_src_x out of bounds: %u >= %d", safe_src_x, src_w);
177 return;
178 }
179
180 dst_row[x] = src_row[safe_src_x];
181 }
182 }
183}
184
185// Note: luminance_palette is now handled by ascii_simd.c via g_ascii_cache.luminance_palette
186
187void precalc_rgb_palettes(const float red, const float green, const float blue) {
188 // Validate input parameters to prevent overflow
189 // Luminance weights should typically be in range 0.0-1.0
190 // But allow slightly larger values for brightness adjustment
191 const float max_weight = 255.0f; // Maximum value that won't overflow when multiplied by 255
192 const float min_weight = -255.0f; // Allow negative for color correction
193
194 // Note: isfinite() checks are skipped in Release builds due to -ffinite-math-only flag
195 // which disables NaN/infinity support for performance. Range checks below are sufficient.
196#if !defined(NDEBUG) && !defined(__FAST_MATH__)
197 if (!isfinite(red) || !isfinite(green) || !isfinite(blue)) {
198 log_error("Invalid weight values (non-finite): red=%f, green=%f, blue=%f", red, green, blue);
199 SET_ERRNO(ERROR_INVALID_PARAM, "non-finite weight values");
200 return;
201 }
202#endif
203
204 if (red < min_weight || red > max_weight || green < min_weight || green > max_weight || blue < min_weight || blue > max_weight) {
205 log_warn("Weight values out of expected range: red=%f, green=%f, blue=%f (clamping to safe range)", red, green, blue);
206 }
207
208 // A corrupted startup value must not turn into a black/invalid palette.
209 // Restore the canonical luminance weights instead of clamping it to +/-255.
210 const bool invalid_weight = red < min_weight || red > max_weight || green < min_weight || green > max_weight || blue < min_weight || blue > max_weight;
211 const float effective_red = invalid_weight ? 0.2989f : red;
212 const float effective_green = invalid_weight ? 0.5866f : green;
213 const float effective_blue = invalid_weight ? 0.1145f : blue;
214
215 // Clamp weights to safe range to prevent overflow
216 const float safe_red = (effective_red < min_weight) ? min_weight : ((effective_red > max_weight) ? max_weight : effective_red);
217 const float safe_green = (effective_green < min_weight) ? min_weight : ((effective_green > max_weight) ? max_weight : effective_green);
218 const float safe_blue = (effective_blue < min_weight) ? min_weight : ((effective_blue > max_weight) ? max_weight : effective_blue);
219
220 const unsigned short max_ushort = 65535;
221 const unsigned short min_ushort = 0;
222
223 for (int n = 0; n < ASCII_LUMINANCE_LEVELS; ++n) {
224 // Compute with float, then clamp to unsigned short range
225 float red_val = (float)n * safe_red;
226 float green_val = (float)n * safe_green;
227 float blue_val = (float)n * safe_blue;
228
229 // Clamp to unsigned short range before assignment
230 if (red_val < (float)min_ushort) {
231 red_val = (float)min_ushort;
232 } else if (red_val > (float)max_ushort) {
233 red_val = (float)max_ushort;
234 }
235
236 if (green_val < (float)min_ushort) {
237 green_val = (float)min_ushort;
238 } else if (green_val > (float)max_ushort) {
239 green_val = (float)max_ushort;
240 }
241
242 if (blue_val < (float)min_ushort) {
243 blue_val = (float)min_ushort;
244 } else if (blue_val > (float)max_ushort) {
245 blue_val = (float)max_ushort;
246 }
247
248 RED[n] = (unsigned short)red_val;
249 GREEN[n] = (unsigned short)green_val;
250 BLUE[n] = (unsigned short)blue_val;
251 GRAY[n] = (unsigned short)n;
252 }
253}
ANSI escape sequence utilities and fast color code generation.
#define SET_ERRNO(code,...)
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:294
#define BUFFER_DEFAULT_ALIGNMENT
Definition buffer.h:30
#define buffer_release(data)
Definition buffer.h:108
audio_visualization_source_t source
Definition fft.c:25
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned int uint32_t
#define SAFE_MEMSET(dest, dest_size, ch, count)
unsigned long long uint64_t
unsigned char uint8_t
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
unsigned short int GRAY[256]
Grayscale lookup table.
unsigned short int BLUE[256]
Blue channel lookup table.
unsigned short int GREEN[256]
Green channel lookup table.
unsigned short int RED[256]
Red channel lookup table.
image_t * image_new_copy(const image_t *source)
Create a copy of an existing image.
void precalc_rgb_palettes(const float red, const float green, const float blue)
Precalculate RGB palettes with color adjustment.
void image_resize_interpolation(const image_t *source, image_t *dest)
Resize image using bilinear interpolation.
#define ASCII_LUMINANCE_LEVELS
Number of luminance levels supported (256).
Definition ascii.h:438
#define IMAGE_MAX_PIXELS_SIZE
Maximum pixel data size in bytes.
void image_clear(image_t *p)
Clear image (set all pixels to black).
void image_resize(const image_t *s, image_t *d)
Resize image using nearest-neighbor interpolation.
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
SIMD-optimized ASCII conversion interface.
🔢 Mathematical Utility Functions
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
✅ Safe Integer Arithmetic and Overflow Detection
🔤 String Manipulation and Shell Escaping Utilities
SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the la...
int h
Image height in pixels (must be > 0).
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
int w
Image width in pixels (must be > 0).
asciichat_error_t image_validate_dimensions(size_t width, size_t height)
Validate image dimensions (non-zero, within limits).
Definition util/image.c:116
🖼️ Safe overflow-checked buffer size calculations for images and video frames
rgb_pixel_t * image_pixel(image_t *p, const int x, const int y)