| 1 | #define STB_IMAGE_IMPLEMENTATION |
| 2 | #include "../include/stb_image.h" |
| 3 | |
| 4 | #include <stdio.h> |
| 5 | #include <stdlib.h> |
| 6 | #include <string.h> |
| 7 | #include <strings.h> |
| 8 | #include <sys/stat.h> |
| 9 | |
| 10 | #include "../include/chroma.h" |
| 11 | |
| 12 | // Check if file exists and is readable |
| 13 | static int file_exists(const char *path) { |
| 14 | struct stat st; |
| 15 | return (stat(path, &st) == 0 && S_ISREG(st.st_mode)); |
| 16 | } |
| 17 | |
| 18 | // Get file size |
| 19 | static long get_file_size(const char *path) { |
| 20 | struct stat st; |
| 21 | if (stat(path, &st) != 0) { |
| 22 | return -1; |
| 23 | } |
| 24 | return st.st_size; |
| 25 | } |
| 26 | |
| 27 | // Calculate optimal image size based on output dimensions |
| 28 | static void calculate_optimal_size(int original_width, int original_height, |
| 29 | int max_output_width, int max_output_height, |
| 30 | int *optimal_width, int *optimal_height) { |
| 31 | // If image is smaller than outputs, keep original size |
| 32 | if (original_width <= max_output_width && |
| 33 | original_height <= max_output_height) { |
| 34 | *optimal_width = original_width; |
| 35 | *optimal_height = original_height; |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | // Calculate scale factor to fit within max output dimensions |
| 40 | float scale_x = (float)max_output_width / original_width; |
| 41 | float scale_y = (float)max_output_height / original_height; |
| 42 | float scale = (scale_x < scale_y) ? scale_x : scale_y; |
| 43 | |
| 44 | // Apply scale factor with minimum size to avoid too small images |
| 45 | scale = (scale > 1.0f) ? 1.0f : scale; |
| 46 | scale = (scale < 0.25f) ? 0.25f : scale; // XXX: don't scale below 25% |
| 47 | |
| 48 | *optimal_width = (int)(original_width * scale); |
| 49 | *optimal_height = (int)(original_height * scale); |
| 50 | |
| 51 | // Ensure even dimensions for better GPU alignment |
| 52 | *optimal_width = (*optimal_width / 2) * 2; |
| 53 | *optimal_height = (*optimal_height / 2) * 2; |
| 54 | } |
| 55 | |
| 56 | // FIXME: this is a very simple way of implementing box filter downsampling for |
| 57 | // memory efficiency Could be better, but this is good enough *for the time |
| 58 | // being*. Must be revisited in the future to see how it stands as the program |
| 59 | // evolves. |
| 60 | static int downsample_image(unsigned char *src_data, int src_width, |
| 61 | int src_height, unsigned char *dst_data, |
| 62 | int dst_width, int dst_height) { |
| 63 | if (!src_data || !dst_data) { |
| 64 | return -1; |
| 65 | } |
| 66 | |
| 67 | float x_ratio = (float)src_width / dst_width; |
| 68 | float y_ratio = (float)src_height / dst_height; |
| 69 | |
| 70 | for (int y = 0; y < dst_height; y++) { |
| 71 | for (int x = 0; x < dst_width; x++) { |
| 72 | // Calculate corresponding source pixel |
| 73 | int src_x = (int)(x * x_ratio); |
| 74 | int src_y = (int)(y * y_ratio); |
| 75 | |
| 76 | // Ensure we're within bounds |
| 77 | src_x = (src_x >= src_width) ? src_width - 1 : src_x; |
| 78 | src_y = (src_y >= src_height) ? src_height - 1 : src_y; |
| 79 | |
| 80 | // Copy pixel (RGBA) |
| 81 | int src_idx = (src_y * src_width + src_x) * 4; |
| 82 | int dst_idx = (y * dst_width + x) * 4; |
| 83 | |
| 84 | dst_data[dst_idx + 0] = src_data[src_idx + 0]; // R |
| 85 | dst_data[dst_idx + 1] = src_data[src_idx + 1]; // G |
| 86 | dst_data[dst_idx + 2] = src_data[src_idx + 2]; // B |
| 87 | dst_data[dst_idx + 3] = src_data[src_idx + 3]; // A |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | return 0; |
| 92 | } |
| 93 | |
| 94 | // Load image from file with configurable downsampling |
| 95 | int chroma_image_load(chroma_image_t *image, const char *path, |
| 96 | const chroma_config_t *config) { |
| 97 | if (!image || !path) { |
| 98 | chroma_log("ERROR", "Invalid parameters for image loading"); |
| 99 | return CHROMA_ERROR_INIT; |
| 100 | } |
| 101 | |
| 102 | // Initialize image structure |
| 103 | memset(image, 0, sizeof(chroma_image_t)); |
| 104 | strncpy(image->path, path, MAX_PATH_LEN - 1); |
| 105 | image->path[MAX_PATH_LEN - 1] = '\0'; |
| 106 | |
| 107 | // Check if file exists |
| 108 | if (!file_exists(path)) { |
| 109 | chroma_log("ERROR", "Image file does not exist: %s", path); |
| 110 | return CHROMA_ERROR_IMAGE; |
| 111 | } |
| 112 | |
| 113 | // Get file size for logging |
| 114 | long file_size = get_file_size(path); |
| 115 | if (file_size > 0) { |
| 116 | chroma_log("DEBUG", "Loading image: %s (%.2f MB)", path, |
| 117 | (double)file_size / (1024.0 * 1024.0)); |
| 118 | } |
| 119 | |
| 120 | // Load image data using stb_image, force RGBA format to avoid conversion |
| 121 | stbi_set_flip_vertically_on_load(0); // keep images right-side up |
| 122 | |
| 123 | image->data = |
| 124 | stbi_load(path, &image->width, &image->height, &image->channels, 4); |
| 125 | image->channels = 4; // always RGBA after forced conversion |
| 126 | if (!image->data) { |
| 127 | chroma_log("ERROR", "Failed to load image %s: %s", path, |
| 128 | stbi_failure_reason()); |
| 129 | return CHROMA_ERROR_IMAGE; |
| 130 | } |
| 131 | |
| 132 | // Validate image dimensions |
| 133 | if (image->width <= 0 || image->height <= 0) { |
| 134 | chroma_log("ERROR", "Invalid image dimensions: %dx%d", image->width, |
| 135 | image->height); |
| 136 | chroma_image_free(image); |
| 137 | return CHROMA_ERROR_IMAGE; |
| 138 | } |
| 139 | |
| 140 | // Validate we have RGBA data (should always be true with forced conversion) |
| 141 | if (image->channels != 4) { |
| 142 | chroma_log("ERROR", "Failed to load image as RGBA: got %d channels", |
| 143 | image->channels); |
| 144 | chroma_image_free(image); |
| 145 | return CHROMA_ERROR_IMAGE; |
| 146 | } |
| 147 | |
| 148 | // Store original dimensions before potential downsampling |
| 149 | int original_width = image->width; |
| 150 | int original_height = image->height; |
| 151 | |
| 152 | // Apply intelligent downsampling if enabled |
| 153 | bool should_downsample = false; |
| 154 | int optimal_width = original_width; |
| 155 | int optimal_height = original_height; |
| 156 | |
| 157 | if (config && config->enable_downsampling) { |
| 158 | calculate_optimal_size(original_width, original_height, |
| 159 | config->max_output_width, config->max_output_height, |
| 160 | &optimal_width, &optimal_height); |
| 161 | |
| 162 | // Apply minimum scale factor constraint |
| 163 | float scale_x = (float)optimal_width / original_width; |
| 164 | float scale_y = (float)optimal_height / original_height; |
| 165 | float scale = (scale_x < scale_y) ? scale_x : scale_y; |
| 166 | |
| 167 | if (scale < config->min_scale_factor) { |
| 168 | scale = config->min_scale_factor; |
| 169 | optimal_width = (int)(original_width * scale); |
| 170 | optimal_height = (int)(original_height * scale); |
| 171 | |
| 172 | // Ensure even dimensions |
| 173 | optimal_width = (optimal_width / 2) * 2; |
| 174 | optimal_height = (optimal_height / 2) * 2; |
| 175 | } |
| 176 | |
| 177 | should_downsample = |
| 178 | (optimal_width < original_width || optimal_height < original_height); |
| 179 | } |
| 180 | |
| 181 | // Downsamp if needed and enabled |
| 182 | if (should_downsample) { |
| 183 | chroma_log("INFO", |
| 184 | "Downsampling image from %dx%d to %dx%d (%.1f%% of original)", |
| 185 | original_width, original_height, optimal_width, optimal_height, |
| 186 | (float)(optimal_width * optimal_height) / |
| 187 | (original_width * original_height) * 100.0f); |
| 188 | |
| 189 | size_t optimal_size = (size_t)optimal_width * optimal_height * 4; |
| 190 | unsigned char *downsampled_data = malloc(optimal_size); |
| 191 | if (!downsampled_data) { |
| 192 | chroma_log("ERROR", "Failed to allocate memory for downsampled image"); |
| 193 | chroma_image_free(image); |
| 194 | return CHROMA_ERROR_MEMORY; |
| 195 | } |
| 196 | |
| 197 | if (downsample_image(image->data, original_width, original_height, |
| 198 | downsampled_data, optimal_width, |
| 199 | optimal_height) != 0) { |
| 200 | chroma_log("ERROR", "Failed to downsample image"); |
| 201 | free(downsampled_data); |
| 202 | chroma_image_free(image); |
| 203 | return CHROMA_ERROR_IMAGE; |
| 204 | } |
| 205 | |
| 206 | stbi_image_free(image->data); |
| 207 | image->data = downsampled_data; |
| 208 | image->width = optimal_width; |
| 209 | image->height = optimal_height; |
| 210 | |
| 211 | chroma_log("DEBUG", "Successfully downsampled image to %dx%d", |
| 212 | optimal_width, optimal_height); |
| 213 | } else if (config && !config->enable_downsampling) { |
| 214 | chroma_log("DEBUG", |
| 215 | "Downsampling disabled, keeping original resolution %dx%d", |
| 216 | original_width, original_height); |
| 217 | } |
| 218 | |
| 219 | image->loaded = true; |
| 220 | |
| 221 | // Calculate and log memory allocation |
| 222 | size_t image_size = (size_t)image->width * image->height * image->channels; |
| 223 | chroma_log_resource_allocation("image_data", image_size, path); |
| 224 | |
| 225 | chroma_log("INFO", "Loaded image: %s (%dx%d, %d channels, %.2f MB)%s", path, |
| 226 | image->width, image->height, image->channels, |
| 227 | (double)image_size / (1024.0 * 1024.0), |
| 228 | should_downsample ? " (downsampled)" : ""); |
| 229 | |
| 230 | return CHROMA_OK; |
| 231 | } |
| 232 | |
| 233 | // Free image data |
| 234 | void chroma_image_free(chroma_image_t *image) { |
| 235 | if (!image) { |
| 236 | return; |
| 237 | } |
| 238 | |
| 239 | if (image->data) { |
| 240 | // Log memory deallocation before freeing |
| 241 | size_t image_size = (size_t)image->width * image->height * image->channels; |
| 242 | chroma_log_resource_deallocation("image_data", image_size, image->path); |
| 243 | |
| 244 | // Always use stbi_image_free since we load directly with stbi_load |
| 245 | stbi_image_free(image->data); |
| 246 | image->data = NULL; |
| 247 | } |
| 248 | |
| 249 | image->width = 0; |
| 250 | image->height = 0; |
| 251 | image->channels = 0; |
| 252 | image->loaded = false; |
| 253 | |
| 254 | if (strlen(image->path) > 0) { |
| 255 | chroma_log("DEBUG", "Freed image: %s", image->path); |
| 256 | } |
| 257 | |
| 258 | memset(image->path, 0, sizeof(image->path)); |
| 259 | } |
| 260 | |
| 261 | // Find image by path in state |
| 262 | chroma_image_t *chroma_image_find_by_path(chroma_state_t *state, |
| 263 | const char *path) { |
| 264 | if (!state || !path) { |
| 265 | return NULL; |
| 266 | } |
| 267 | |
| 268 | for (int i = 0; i < state->image_count; i++) { |
| 269 | if (strcmp(state->images[i].path, path) == 0) { |
| 270 | return &state->images[i]; |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | return NULL; |
| 275 | } |
| 276 | |
| 277 | // Load image if not already loaded |
| 278 | chroma_image_t *chroma_image_get_or_load(chroma_state_t *state, |
| 279 | const char *path) { |
| 280 | if (!state || !path) { |
| 281 | return NULL; |
| 282 | } |
| 283 | |
| 284 | // Check if already loaded |
| 285 | chroma_image_t *existing = chroma_image_find_by_path(state, path); |
| 286 | if (existing && existing->loaded) { |
| 287 | chroma_log("DEBUG", "Using cached image: %s", path); |
| 288 | return existing; |
| 289 | } |
| 290 | |
| 291 | // Find empty slot or reuse existing |
| 292 | chroma_image_t *image = existing; |
| 293 | if (!image) { |
| 294 | if (state->image_count >= MAX_OUTPUTS) { |
| 295 | chroma_log("ERROR", "Maximum number of images reached"); |
| 296 | return NULL; |
| 297 | } |
| 298 | image = &state->images[state->image_count]; |
| 299 | state->image_count++; |
| 300 | } |
| 301 | |
| 302 | // Load the image with configuration |
| 303 | if (chroma_image_load(image, path, &state->config) != CHROMA_OK) { |
| 304 | // If this was a new slot, decrement count |
| 305 | if (!existing) { |
| 306 | state->image_count--; |
| 307 | } |
| 308 | return NULL; |
| 309 | } |
| 310 | |
| 311 | return image; |
| 312 | } |
| 313 | |
| 314 | // Validate image file format |
| 315 | int chroma_image_validate(const char *path) { |
| 316 | if (!path || !file_exists(path)) { |
| 317 | return CHROMA_ERROR_IMAGE; |
| 318 | } |
| 319 | |
| 320 | // Check file extension (basic validation) |
| 321 | const char *ext = strrchr(path, '.'); |
| 322 | if (!ext) { |
| 323 | return CHROMA_ERROR_IMAGE; |
| 324 | } |
| 325 | |
| 326 | ext++; // Skip the dot |
| 327 | |
| 328 | // Check supported extensions |
| 329 | if (strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0 || |
| 330 | strcasecmp(ext, "png") == 0 || strcasecmp(ext, "bmp") == 0 || |
| 331 | strcasecmp(ext, "tga") == 0 || strcasecmp(ext, "psd") == 0 || |
| 332 | strcasecmp(ext, "gif") == 0 || strcasecmp(ext, "hdr") == 0 || |
| 333 | strcasecmp(ext, "pic") == 0 || strcasecmp(ext, "ppm") == 0 || |
| 334 | strcasecmp(ext, "pgm") == 0) { |
| 335 | return CHROMA_OK; |
| 336 | } |
| 337 | |
| 338 | chroma_log("WARN", "Potentially unsupported image format: %s", ext); |
| 339 | return CHROMA_ERROR_IMAGE; |
| 340 | } |
| 341 | |
| 342 | // Get image info without loading full data |
| 343 | int chroma_image_get_info(const char *path, int *width, int *height, |
| 344 | int *channels) { |
| 345 | if (!path || !width || !height || !channels) { |
| 346 | return CHROMA_ERROR_INIT; |
| 347 | } |
| 348 | |
| 349 | if (!file_exists(path)) { |
| 350 | return CHROMA_ERROR_IMAGE; |
| 351 | } |
| 352 | |
| 353 | if (!stbi_info(path, width, height, channels)) { |
| 354 | chroma_log("ERROR", "Failed to get image info for %s: %s", path, |
| 355 | stbi_failure_reason()); |
| 356 | return CHROMA_ERROR_IMAGE; |
| 357 | } |
| 358 | |
| 359 | return CHROMA_OK; |
| 360 | } |
| 361 | |
| 362 | // Cleanup all images in state |
| 363 | void chroma_images_cleanup(chroma_state_t *state) { |
| 364 | if (!state) { |
| 365 | return; |
| 366 | } |
| 367 | |
| 368 | chroma_log("DEBUG", "Cleaning up %d images", state->image_count); |
| 369 | |
| 370 | for (int i = 0; i < state->image_count; i++) { |
| 371 | chroma_image_free(&state->images[i]); |
| 372 | } |
| 373 | |
| 374 | state->image_count = 0; |
| 375 | chroma_log("INFO", "Cleaned up all images"); |
| 376 | chroma_log_memory_stats("post-image-cleanup"); |
| 377 | } |
| 378 | |
| 379 | // Preload common image formats for validation |
| 380 | void chroma_image_init_stb(void) { |
| 381 | // Set stb_image options |
| 382 | stbi_set_flip_vertically_on_load(0); |
| 383 | |
| 384 | // FIXME: these could be made configurable |
| 385 | stbi_ldr_to_hdr_gamma(2.2f); |
| 386 | stbi_ldr_to_hdr_scale(1.0f); |
| 387 | |
| 388 | chroma_log("DEBUG", "Initialized stb_image library"); |
| 389 | } |