| 1 | #define STB_IMAGE_IMPLEMENTATION |
| 2 | #include "../include/vendor/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 / (float)original_width; |
| 41 | float scale_y = (float)max_output_height / (float)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)((float)original_width * scale); |
| 49 | *optimal_height = (int)((float)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, int src_channels, |
| 62 | unsigned char *dst_data, int dst_width, |
| 63 | int dst_height, int dst_channels) { |
| 64 | if (!src_data || !dst_data) { |
| 65 | return -1; |
| 66 | } |
| 67 | |
| 68 | float x_ratio = (float)src_width / (float)dst_width; |
| 69 | float y_ratio = (float)src_height / (float)dst_height; |
| 70 | |
| 71 | for (int y = 0; y < dst_height; y++) { |
| 72 | for (int x = 0; x < dst_width; x++) { |
| 73 | // Calculate corresponding source pixel |
| 74 | int src_x = (int)((float)x * x_ratio); |
| 75 | int src_y = (int)((float)y * y_ratio); |
| 76 | |
| 77 | // Ensure we're within bounds |
| 78 | src_x = (src_x >= src_width) ? src_width - 1 : src_x; |
| 79 | src_y = (src_y >= src_height) ? src_height - 1 : src_y; |
| 80 | |
| 81 | // Copy pixel data |
| 82 | int src_idx = (src_y * src_width + src_x) * src_channels; |
| 83 | int dst_idx = (y * dst_width + x) * dst_channels; |
| 84 | |
| 85 | dst_data[dst_idx + 0] = src_data[src_idx + 0]; // R |
| 86 | dst_data[dst_idx + 1] = src_data[src_idx + 1]; // G |
| 87 | dst_data[dst_idx + 2] = src_data[src_idx + 2]; // B |
| 88 | if (dst_channels == 4 && src_channels == 4) { |
| 89 | dst_data[dst_idx + 3] = src_data[src_idx + 3]; // A |
| 90 | } else if (dst_channels == 4) { |
| 91 | dst_data[dst_idx + 3] = 255; // Full alpha for RGB source |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | return 0; |
| 97 | } |
| 98 | |
| 99 | // Load image from file with configurable downsampling |
| 100 | // output_width/output_height: actual output dimensions for intelligent |
| 101 | // downsampling |
| 102 | int chroma_image_load(chroma_image_t *image, const char *path, |
| 103 | const chroma_config_t *config, int output_width, |
| 104 | int output_height) { |
| 105 | if (!image || !path) { |
| 106 | chroma_log("ERROR", "Invalid parameters for image loading"); |
| 107 | return CHROMA_ERROR_INIT; |
| 108 | } |
| 109 | |
| 110 | // Initialize image structure |
| 111 | memset(image, 0, sizeof(chroma_image_t)); |
| 112 | strncpy(image->path, path, MAX_PATH_LEN - 1); |
| 113 | image->path[MAX_PATH_LEN - 1] = '\0'; |
| 114 | |
| 115 | // Check if file exists |
| 116 | if (!file_exists(path)) { |
| 117 | chroma_log("ERROR", "Image file does not exist: %s", path); |
| 118 | return CHROMA_ERROR_IMAGE; |
| 119 | } |
| 120 | |
| 121 | // Get file size for logging |
| 122 | long file_size = get_file_size(path); |
| 123 | if (file_size > 0) { |
| 124 | chroma_log("DEBUG", "Loading image: %s (%.2f MB)", path, |
| 125 | (double)file_size / (1024.0 * 1024.0)); |
| 126 | } |
| 127 | |
| 128 | // Load image data using stb_image |
| 129 | // First, check actual channels to decide if we need alpha |
| 130 | stbi_set_flip_vertically_on_load(0); // keep images right-side up |
| 131 | |
| 132 | int actual_channels = 0; |
| 133 | if (!stbi_info(path, &image->width, &image->height, &actual_channels)) { |
| 134 | chroma_log("ERROR", "Failed to get image info for %s: %s", path, |
| 135 | stbi_failure_reason()); |
| 136 | return CHROMA_ERROR_IMAGE; |
| 137 | } |
| 138 | |
| 139 | // Load with actual channels or force RGBA if image has alpha |
| 140 | // For wallpapers, we typically don't need alpha unless the image has it |
| 141 | int desired_channels = (actual_channels == 4 || actual_channels == 2) ? 4 : 3; |
| 142 | |
| 143 | image->data = stbi_load(path, &image->width, &image->height, &image->channels, |
| 144 | desired_channels); |
| 145 | image->channels = desired_channels; |
| 146 | image->data_from_stbi = true; |
| 147 | if (!image->data) { |
| 148 | chroma_log("ERROR", "Failed to load image %s: %s", path, |
| 149 | stbi_failure_reason()); |
| 150 | return CHROMA_ERROR_IMAGE; |
| 151 | } |
| 152 | |
| 153 | // Validate image dimensions |
| 154 | if (image->width <= 0 || image->height <= 0) { |
| 155 | chroma_log("ERROR", "Invalid image dimensions: %dx%d", image->width, |
| 156 | image->height); |
| 157 | chroma_image_free(image); |
| 158 | return CHROMA_ERROR_IMAGE; |
| 159 | } |
| 160 | |
| 161 | chroma_log("DEBUG", "Loaded image %s with %d channels (original had %d)", |
| 162 | path, image->channels, actual_channels); |
| 163 | |
| 164 | // Store original dimensions before potential downsampling |
| 165 | int original_width = image->width; |
| 166 | int original_height = image->height; |
| 167 | |
| 168 | // Apply intelligent downsampling if enabled |
| 169 | bool should_downsample = false; |
| 170 | int optimal_width = original_width; |
| 171 | int optimal_height = original_height; |
| 172 | |
| 173 | if (config && config->enable_downsampling) { |
| 174 | // Use output dimensions if provided, otherwise fall back to config defaults |
| 175 | int max_width = |
| 176 | (output_width > 0) ? output_width : config->max_output_width; |
| 177 | int max_height = |
| 178 | (output_height > 0) ? output_height : config->max_output_height; |
| 179 | |
| 180 | calculate_optimal_size(original_width, original_height, max_width, |
| 181 | max_height, &optimal_width, &optimal_height); |
| 182 | |
| 183 | // Apply minimum scale factor constraint |
| 184 | float scale_x = (float)optimal_width / (float)original_width; |
| 185 | float scale_y = (float)optimal_height / (float)original_height; |
| 186 | float scale = (scale_x < scale_y) ? scale_x : scale_y; |
| 187 | |
| 188 | if (scale < config->min_scale_factor) { |
| 189 | scale = config->min_scale_factor; |
| 190 | optimal_width = (int)((float)original_width * scale); |
| 191 | optimal_height = (int)((float)original_height * scale); |
| 192 | |
| 193 | // Ensure even dimensions |
| 194 | optimal_width = (optimal_width / 2) * 2; |
| 195 | optimal_height = (optimal_height / 2) * 2; |
| 196 | } |
| 197 | |
| 198 | should_downsample = |
| 199 | (optimal_width < original_width || optimal_height < original_height); |
| 200 | } |
| 201 | |
| 202 | // Downsample if needed and enabled |
| 203 | if (should_downsample) { |
| 204 | double reduction_ratio = (double)(optimal_width * optimal_height) / |
| 205 | (double)(original_width * original_height) * 100.0; |
| 206 | chroma_log("INFO", |
| 207 | "Downsampling image from %dx%d to %dx%d (%.1f%% of original)", |
| 208 | original_width, original_height, optimal_width, optimal_height, |
| 209 | reduction_ratio); |
| 210 | |
| 211 | size_t optimal_size = |
| 212 | (size_t)optimal_width * (size_t)optimal_height * image->channels; |
| 213 | unsigned char *downsampled_data = malloc(optimal_size); |
| 214 | if (!downsampled_data) { |
| 215 | chroma_log("ERROR", "Failed to allocate memory for downsampled image"); |
| 216 | chroma_image_free(image); |
| 217 | return CHROMA_ERROR_MEMORY; |
| 218 | } |
| 219 | |
| 220 | if (downsample_image(image->data, original_width, original_height, |
| 221 | image->channels, downsampled_data, optimal_width, |
| 222 | optimal_height, image->channels) != 0) { |
| 223 | chroma_log("ERROR", "Failed to downsample image"); |
| 224 | free(downsampled_data); |
| 225 | chroma_image_free(image); |
| 226 | return CHROMA_ERROR_IMAGE; |
| 227 | } |
| 228 | |
| 229 | stbi_image_free(image->data); |
| 230 | image->data = downsampled_data; |
| 231 | image->data_from_stbi = false; |
| 232 | image->width = optimal_width; |
| 233 | image->height = optimal_height; |
| 234 | |
| 235 | chroma_log("DEBUG", "Successfully downsampled image to %dx%d", |
| 236 | optimal_width, optimal_height); |
| 237 | } else if (config && !config->enable_downsampling) { |
| 238 | chroma_log("DEBUG", |
| 239 | "Downsampling disabled, keeping original resolution %dx%d", |
| 240 | original_width, original_height); |
| 241 | } |
| 242 | |
| 243 | image->loaded = true; |
| 244 | image->ref_count = 1; // Initial reference from the first output |
| 245 | |
| 246 | // Calculate and log memory allocation |
| 247 | size_t image_size = |
| 248 | (size_t)image->width * (size_t)image->height * (size_t)image->channels; |
| 249 | chroma_log_resource_allocation("image_data", image_size, path); |
| 250 | |
| 251 | chroma_log("INFO", "Loaded image: %s (%dx%d, %d channels, %.2f MB)%s", path, |
| 252 | image->width, image->height, image->channels, |
| 253 | (double)image_size / (1024.0 * 1024.0), |
| 254 | should_downsample ? " (downsampled)" : ""); |
| 255 | |
| 256 | return CHROMA_OK; |
| 257 | } |
| 258 | |
| 259 | // Free image data |
| 260 | void chroma_image_free(chroma_image_t *image) { |
| 261 | if (!image) { |
| 262 | return; |
| 263 | } |
| 264 | |
| 265 | if (image->data) { |
| 266 | // Log memory deallocation before freeing |
| 267 | size_t image_size = |
| 268 | (size_t)image->width * (size_t)image->height * (size_t)image->channels; |
| 269 | |
| 270 | if (strlen(image->path) > 0) { |
| 271 | chroma_log("DEBUG", "Freed image: %s", image->path); |
| 272 | } |
| 273 | |
| 274 | chroma_log_resource_deallocation("image_data", image_size, image->path); |
| 275 | |
| 276 | if (image->data_from_stbi) { |
| 277 | stbi_image_free(image->data); |
| 278 | } else { |
| 279 | free(image->data); |
| 280 | } |
| 281 | image->data = NULL; |
| 282 | } |
| 283 | |
| 284 | image->width = 0; |
| 285 | image->height = 0; |
| 286 | image->channels = 0; |
| 287 | image->loaded = false; |
| 288 | image->ref_count = 0; |
| 289 | |
| 290 | if (strlen(image->path) > 0) { |
| 291 | chroma_log("DEBUG", "Freed image: %s", image->path); |
| 292 | } |
| 293 | |
| 294 | memset(image->path, 0, sizeof(image->path)); |
| 295 | } |
| 296 | |
| 297 | // Release a reference to an image; free when ref_count reaches zero |
| 298 | void chroma_image_release(chroma_image_t *image) { |
| 299 | if (!image || !image->loaded) { |
| 300 | return; |
| 301 | } |
| 302 | |
| 303 | image->ref_count--; |
| 304 | if (image->ref_count <= 0) { |
| 305 | chroma_image_free(image); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // Find image by path in state |
| 310 | chroma_image_t *chroma_image_find_by_path(chroma_state_t *state, |
| 311 | const char *path) { |
| 312 | if (!state || !path) { |
| 313 | return NULL; |
| 314 | } |
| 315 | |
| 316 | for (int i = 0; i < state->image_count; i++) { |
| 317 | if (strcmp(state->images[i].path, path) == 0) { |
| 318 | return &state->images[i]; |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | return NULL; |
| 323 | } |
| 324 | |
| 325 | // Load image if not already loaded |
| 326 | // output_width/output_height: actual output dimensions for intelligent |
| 327 | // downsampling |
| 328 | chroma_image_t *chroma_image_get_or_load(chroma_state_t *state, |
| 329 | const char *path, int output_width, |
| 330 | int output_height) { |
| 331 | if (!state || !path) { |
| 332 | return NULL; |
| 333 | } |
| 334 | |
| 335 | // Check if already loaded |
| 336 | chroma_image_t *existing = chroma_image_find_by_path(state, path); |
| 337 | if (existing && existing->loaded) { |
| 338 | chroma_log("DEBUG", "Using cached image: %s (ref_count: %d)", path, |
| 339 | existing->ref_count); |
| 340 | existing->ref_count++; |
| 341 | return existing; |
| 342 | } |
| 343 | |
| 344 | // Find empty slot or reuse existing |
| 345 | chroma_image_t *image = existing; |
| 346 | if (!image) { |
| 347 | if (state->image_count >= MAX_OUTPUTS) { |
| 348 | chroma_log("ERROR", "Maximum number of images reached"); |
| 349 | return NULL; |
| 350 | } |
| 351 | image = &state->images[state->image_count]; |
| 352 | state->image_count++; |
| 353 | } |
| 354 | |
| 355 | // Load the image with configuration and output dimensions |
| 356 | if (chroma_image_load(image, path, &state->config, output_width, |
| 357 | output_height) != CHROMA_OK) { |
| 358 | // If this was a new slot, decrement count |
| 359 | if (!existing) { |
| 360 | state->image_count--; |
| 361 | } |
| 362 | return NULL; |
| 363 | } |
| 364 | |
| 365 | return image; |
| 366 | } |
| 367 | |
| 368 | // Validate image file format |
| 369 | int chroma_image_validate(const char *path) { |
| 370 | if (!path || !file_exists(path)) { |
| 371 | return CHROMA_ERROR_IMAGE; |
| 372 | } |
| 373 | |
| 374 | // Check file extension (basic validation) |
| 375 | const char *ext = strrchr(path, '.'); |
| 376 | if (!ext) { |
| 377 | return CHROMA_ERROR_IMAGE; |
| 378 | } |
| 379 | |
| 380 | ext++; // Skip the dot |
| 381 | |
| 382 | // Check supported extensions |
| 383 | if (strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0 || |
| 384 | strcasecmp(ext, "png") == 0 || strcasecmp(ext, "bmp") == 0 || |
| 385 | strcasecmp(ext, "tga") == 0 || strcasecmp(ext, "psd") == 0 || |
| 386 | strcasecmp(ext, "gif") == 0 || strcasecmp(ext, "hdr") == 0 || |
| 387 | strcasecmp(ext, "pic") == 0 || strcasecmp(ext, "ppm") == 0 || |
| 388 | strcasecmp(ext, "pgm") == 0) { |
| 389 | return CHROMA_OK; |
| 390 | } |
| 391 | |
| 392 | chroma_log("WARN", "Potentially unsupported image format: %s", ext); |
| 393 | return CHROMA_ERROR_IMAGE; |
| 394 | } |
| 395 | |
| 396 | // Get image info without loading full data |
| 397 | int chroma_image_get_info(const char *path, int *width, int *height, |
| 398 | int *channels) { |
| 399 | if (!path || !width || !height || !channels) { |
| 400 | return CHROMA_ERROR_INIT; |
| 401 | } |
| 402 | |
| 403 | if (!file_exists(path)) { |
| 404 | return CHROMA_ERROR_IMAGE; |
| 405 | } |
| 406 | |
| 407 | if (!stbi_info(path, width, height, channels)) { |
| 408 | chroma_log("ERROR", "Failed to get image info for %s: %s", path, |
| 409 | stbi_failure_reason()); |
| 410 | return CHROMA_ERROR_IMAGE; |
| 411 | } |
| 412 | |
| 413 | return CHROMA_OK; |
| 414 | } |
| 415 | |
| 416 | // Cleanup all images in state |
| 417 | void chroma_images_cleanup(chroma_state_t *state) { |
| 418 | if (!state) { |
| 419 | return; |
| 420 | } |
| 421 | |
| 422 | chroma_log("DEBUG", "Cleaning up %d images", state->image_count); |
| 423 | |
| 424 | for (int i = 0; i < state->image_count; i++) { |
| 425 | chroma_image_release(&state->images[i]); |
| 426 | } |
| 427 | |
| 428 | state->image_count = 0; |
| 429 | chroma_log("INFO", "Cleaned up all images"); |
| 430 | chroma_log_memory_stats("post-image-cleanup"); |
| 431 | } |
| 432 | |
| 433 | // Preload common image formats for validation |
| 434 | void chroma_image_init_stb(void) { |
| 435 | // Set stb_image options |
| 436 | stbi_set_flip_vertically_on_load(0); |
| 437 | |
| 438 | // FIXME: these could be made configurable |
| 439 | stbi_ldr_to_hdr_gamma(2.2f); |
| 440 | stbi_ldr_to_hdr_scale(1.0f); |
| 441 | |
| 442 | chroma_log("DEBUG", "Initialized stb_image library"); |
| 443 | } |