brewery
notashelf /
172c36ba42b26c85d310f1e55773d63642061ada

chroma

public

Lightweight wallpaper daemon for Wayland

Star0tarball
clone
ssh://git@git.notashelf.dev:33/notashelf/chroma.git
src/image.cC553 lines17.7 KB
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 a solid color image
100
int chroma_image_load_color(chroma_image_t *image, uint32_t color_rgba,
101
                            int width, int height) {
102
  if (!image || width <= 0 || height <= 0) {
103
    return CHROMA_ERROR_INIT;
104
  }
105
106
  memset(image, 0, sizeof(chroma_image_t));
107
  snprintf(image->path, sizeof(image->path), "color:#%08X", color_rgba);
108
109
  size_t size = (size_t)width * (size_t)height * 4;
110
  image->data = malloc(size);
111
  if (!image->data) {
112
    return CHROMA_ERROR_MEMORY;
113
  }
114
  image->data_from_stbi = false;
115
116
  unsigned char r = (unsigned char)((color_rgba >> 16) & 0xFF);
117
  unsigned char g = (unsigned char)((color_rgba >> 8) & 0xFF);
118
  unsigned char b = (unsigned char)(color_rgba & 0xFF);
119
  unsigned char a = (unsigned char)((color_rgba >> 24) & 0xFF);
120
121
  for (size_t i = 0; i < size; i += 4) {
122
    image->data[i + 0] = r;
123
    image->data[i + 1] = g;
124
    image->data[i + 2] = b;
125
    image->data[i + 3] = a;
126
  }
127
128
  image->width = width;
129
  image->height = height;
130
  image->channels = 4;
131
  image->loaded = true;
132
  image->ref_count = 1;
133
  image->is_solid_color = true;
134
  image->solid_color_rgba = color_rgba;
135
136
  chroma_log("DEBUG", "Generated solid color image: %dx%d #%06X", width, height,
137
             color_rgba & 0xFFFFFF);
138
  return CHROMA_OK;
139
}
140
141
// Try loading with a different format loader based on file extension
142
static int load_with_alternate_loader(chroma_image_t *image, const char *path,
143
                                      int output_width, int output_height) {
144
  const char *ext = strrchr(path, '.');
145
  if (!ext) {
146
    return -1;
147
  }
148
  ext++; // skip dot
149
150
  if (strcasecmp(ext, "ff") == 0 || strcasecmp(ext, "farbfeld") == 0) {
151
    return chroma_image_load_farbfeld(image, path);
152
  }
153
  if (strcasecmp(ext, "svg") == 0) {
154
    return chroma_image_load_svg(image, path, output_width, output_height);
155
  }
156
  if (strcasecmp(ext, "webp") == 0) {
157
    return chroma_image_load_webp(image, path);
158
  }
159
  if (strcasecmp(ext, "tif") == 0 || strcasecmp(ext, "tiff") == 0) {
160
    return chroma_image_load_tiff(image, path);
161
  }
162
  if (strcasecmp(ext, "avif") == 0) {
163
    return chroma_image_load_avif(image, path);
164
  }
165
  if (strcasecmp(ext, "jxl") == 0 || strcasecmp(ext, "jpegxl") == 0) {
166
    return chroma_image_load_jpegxl(image, path);
167
  }
168
169
  return -1; // no alternate loader matched
170
}
171
172
// Load image from file with configurable downsampling
173
// output_width/output_height: actual output dimensions for intelligent
174
// downsampling
175
int chroma_image_load(chroma_image_t *image, const char *path,
176
                      const chroma_config_t *config, int output_width,
177
                      int output_height) {
178
  if (!image || !path) {
179
    chroma_log("ERROR", "Invalid parameters for image loading");
180
    return CHROMA_ERROR_INIT;
181
  }
182
183
  // Initialize image structure
184
  memset(image, 0, sizeof(chroma_image_t));
185
  strncpy(image->path, path, MAX_PATH_LEN - 1);
186
  image->path[MAX_PATH_LEN - 1] = '\0';
187
188
  // Check if file exists
189
  if (!file_exists(path)) {
190
    chroma_log("ERROR", "Image file does not exist: %s", path);
191
    return CHROMA_ERROR_IMAGE;
192
  }
193
194
  // Get file size for logging
195
  long file_size = get_file_size(path);
196
  if (file_size > 0) {
197
    chroma_log("DEBUG", "Loading image: %s (%.2f MB)", path,
198
               (double)file_size / (1024.0 * 1024.0));
199
  }
200
201
  // Load image data using stb_image
202
  // First, check actual channels to decide if we need alpha
203
  stbi_set_flip_vertically_on_load(0); // keep images right-side up
204
205
  int actual_channels = 0;
206
  if (!stbi_info(path, &image->width, &image->height, &actual_channels)) {
207
    // stb_image doesn't support this format; try alternate loaders
208
    int alt_ret =
209
        load_with_alternate_loader(image, path, output_width, output_height);
210
    if (alt_ret == CHROMA_OK) {
211
      image->loaded = true;
212
      image->ref_count = 1;
213
      chroma_log("INFO", "Loaded image via alternate loader: %s", path);
214
      return CHROMA_OK;
215
    }
216
    chroma_log("ERROR", "Failed to get image info for %s: %s", path,
217
               stbi_failure_reason());
218
    return CHROMA_ERROR_IMAGE;
219
  }
220
221
  // Try animated GIF first for .gif files
222
  const char *ext_check = strrchr(path, '.');
223
  if (ext_check && strcasecmp(ext_check + 1, "gif") == 0) {
224
    int gif_ret = chroma_anim_load_gif(image, path);
225
    if (gif_ret == CHROMA_OK) {
226
      // Animated GIF loaded successfully
227
      image->loaded = true;
228
      chroma_log("INFO", "Loaded animated GIF: %s", path);
229
      return CHROMA_OK;
230
    }
231
    if (gif_ret == CHROMA_ERROR_MEMORY) {
232
      return CHROMA_ERROR_MEMORY;
233
    }
234
    // gif_ret == 1 means single-frame, fall through to stb_image loading
235
    // gif_ret == CHROMA_ERROR_IMAGE means parsing failed, also fall through
236
  }
237
238
  // Load with actual channels or force RGBA if image has alpha
239
  // For wallpapers, we typically don't need alpha unless the image has it
240
  int desired_channels = (actual_channels == 4 || actual_channels == 2) ? 4 : 3;
241
242
  image->data = stbi_load(path, &image->width, &image->height, &image->channels,
243
                          desired_channels);
244
  image->channels = desired_channels;
245
  image->data_from_stbi = true;
246
  if (!image->data) {
247
    chroma_log("ERROR", "Failed to load image %s: %s", path,
248
               stbi_failure_reason());
249
    return CHROMA_ERROR_IMAGE;
250
  }
251
252
  // Validate image dimensions
253
  if (image->width <= 0 || image->height <= 0) {
254
    chroma_log("ERROR", "Invalid image dimensions: %dx%d", image->width,
255
               image->height);
256
    chroma_image_free(image);
257
    return CHROMA_ERROR_IMAGE;
258
  }
259
260
  chroma_log("DEBUG", "Loaded image %s with %d channels (original had %d)",
261
             path, image->channels, actual_channels);
262
263
  // Store original dimensions before potential downsampling
264
  int original_width = image->width;
265
  int original_height = image->height;
266
267
  // Apply intelligent downsampling if enabled
268
  bool should_downsample = false;
269
  int optimal_width = original_width;
270
  int optimal_height = original_height;
271
272
  if (config && config->enable_downsampling) {
273
    // Use output dimensions if provided, otherwise fall back to config defaults
274
    int max_width =
275
        (output_width > 0) ? output_width : config->max_output_width;
276
    int max_height =
277
        (output_height > 0) ? output_height : config->max_output_height;
278
279
    calculate_optimal_size(original_width, original_height, max_width,
280
                           max_height, &optimal_width, &optimal_height);
281
282
    // Apply minimum scale factor constraint
283
    float scale_x = (float)optimal_width / (float)original_width;
284
    float scale_y = (float)optimal_height / (float)original_height;
285
    float scale = (scale_x < scale_y) ? scale_x : scale_y;
286
287
    if (scale < config->min_scale_factor) {
288
      scale = config->min_scale_factor;
289
      optimal_width = (int)((float)original_width * scale);
290
      optimal_height = (int)((float)original_height * scale);
291
292
      // Ensure even dimensions
293
      optimal_width = (optimal_width / 2) * 2;
294
      optimal_height = (optimal_height / 2) * 2;
295
    }
296
297
    should_downsample =
298
        (optimal_width < original_width || optimal_height < original_height);
299
  }
300
301
  // Downsample if needed and enabled
302
  if (should_downsample) {
303
    double reduction_ratio = (double)(optimal_width * optimal_height) /
304
                             (double)(original_width * original_height) * 100.0;
305
    chroma_log("INFO",
306
               "Downsampling image from %dx%d to %dx%d (%.1f%% of original)",
307
               original_width, original_height, optimal_width, optimal_height,
308
               reduction_ratio);
309
310
    size_t optimal_size =
311
        (size_t)optimal_width * (size_t)optimal_height * image->channels;
312
    unsigned char *downsampled_data = malloc(optimal_size);
313
    if (!downsampled_data) {
314
      chroma_log("ERROR", "Failed to allocate memory for downsampled image");
315
      chroma_image_free(image);
316
      return CHROMA_ERROR_MEMORY;
317
    }
318
319
    if (downsample_image(image->data, original_width, original_height,
320
                         image->channels, downsampled_data, optimal_width,
321
                         optimal_height, image->channels) != 0) {
322
      chroma_log("ERROR", "Failed to downsample image");
323
      free(downsampled_data);
324
      chroma_image_free(image);
325
      return CHROMA_ERROR_IMAGE;
326
    }
327
328
    stbi_image_free(image->data);
329
    image->data = downsampled_data;
330
    image->data_from_stbi = false;
331
    image->width = optimal_width;
332
    image->height = optimal_height;
333
334
    chroma_log("DEBUG", "Successfully downsampled image to %dx%d",
335
               optimal_width, optimal_height);
336
  } else if (config && !config->enable_downsampling) {
337
    chroma_log("DEBUG",
338
               "Downsampling disabled, keeping original resolution %dx%d",
339
               original_width, original_height);
340
  }
341
342
  image->loaded = true;
343
  image->ref_count = 1; // Initial reference from the first output
344
345
  // Calculate and log memory allocation
346
  size_t image_size =
347
      (size_t)image->width * (size_t)image->height * (size_t)image->channels;
348
  chroma_log_resource_allocation("image_data", image_size, path);
349
350
  chroma_log("INFO", "Loaded image: %s (%dx%d, %d channels, %.2f MB)%s", path,
351
             image->width, image->height, image->channels,
352
             (double)image_size / (1024.0 * 1024.0),
353
             should_downsample ? " (downsampled)" : "");
354
355
  return CHROMA_OK;
356
}
357
358
// Free image data
359
void chroma_image_free(chroma_image_t *image) {
360
  if (!image) {
361
    return;
362
  }
363
364
  // Free animated frames first
365
  if (image->is_animated) {
366
    chroma_anim_free_frames(image);
367
  }
368
369
  if (image->data) {
370
    // Log memory deallocation before freeing
371
    size_t image_size =
372
        (size_t)image->width * (size_t)image->height * (size_t)image->channels;
373
374
    if (strlen(image->path) > 0) {
375
      chroma_log("DEBUG", "Freed image: %s", image->path);
376
    }
377
378
    chroma_log_resource_deallocation("image_data", image_size, image->path);
379
380
    if (image->is_animated) {
381
      // frames already freed above; data is just a pointer into frames array
382
    } else if (image->data_from_stbi) {
383
      stbi_image_free(image->data);
384
    } else {
385
      free(image->data);
386
    }
387
    image->data = NULL;
388
  }
389
390
  image->width = 0;
391
  image->height = 0;
392
  image->channels = 0;
393
  image->loaded = false;
394
  image->ref_count = 0;
395
396
  if (strlen(image->path) > 0) {
397
    chroma_log("DEBUG", "Freed image: %s", image->path);
398
  }
399
400
  memset(image->path, 0, sizeof(image->path));
401
}
402
403
// Release a reference to an image; free when ref_count reaches zero
404
void chroma_image_release(chroma_image_t *image) {
405
  if (!image || !image->loaded) {
406
    return;
407
  }
408
409
  image->ref_count--;
410
  if (image->ref_count <= 0) {
411
    chroma_image_free(image);
412
  }
413
}
414
415
// Find image by path in state
416
chroma_image_t *chroma_image_find_by_path(chroma_state_t *state,
417
                                          const char *path) {
418
  if (!state || !path) {
419
    return NULL;
420
  }
421
422
  for (int i = 0; i < state->image_count; i++) {
423
    if (strcmp(state->images[i].path, path) == 0) {
424
      return &state->images[i];
425
    }
426
  }
427
428
  return NULL;
429
}
430
431
// Load image if not already loaded
432
// output_width/output_height: actual output dimensions for intelligent
433
// downsampling
434
chroma_image_t *chroma_image_get_or_load(chroma_state_t *state,
435
                                         const char *path, int output_width,
436
                                         int output_height) {
437
  if (!state || !path) {
438
    return NULL;
439
  }
440
441
  // Check if already loaded
442
  chroma_image_t *existing = chroma_image_find_by_path(state, path);
443
  if (existing && existing->loaded) {
444
    chroma_log("DEBUG", "Using cached image: %s (ref_count: %d)", path,
445
               existing->ref_count);
446
    existing->ref_count++;
447
    return existing;
448
  }
449
450
  // Find empty slot or reuse existing
451
  chroma_image_t *image = existing;
452
  if (!image) {
453
    if (state->image_count >= MAX_OUTPUTS) {
454
      chroma_log("ERROR", "Maximum number of images reached");
455
      return NULL;
456
    }
457
    image = &state->images[state->image_count];
458
    state->image_count++;
459
  }
460
461
  // Load the image with configuration and output dimensions
462
  if (chroma_image_load(image, path, &state->config, output_width,
463
                        output_height) != CHROMA_OK) {
464
    // If this was a new slot, decrement count
465
    if (!existing) {
466
      state->image_count--;
467
    }
468
    return NULL;
469
  }
470
471
  return image;
472
}
473
474
// Validate image file format
475
int chroma_image_validate(const char *path) {
476
  if (!path || !file_exists(path)) {
477
    return CHROMA_ERROR_IMAGE;
478
  }
479
480
  // Check file extension (basic validation)
481
  const char *ext = strrchr(path, '.');
482
  if (!ext) {
483
    return CHROMA_ERROR_IMAGE;
484
  }
485
486
  ext++; // Skip the dot
487
488
  // Check supported extensions
489
  if (strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0 ||
490
      strcasecmp(ext, "png") == 0 || strcasecmp(ext, "bmp") == 0 ||
491
      strcasecmp(ext, "tga") == 0 || strcasecmp(ext, "psd") == 0 ||
492
      strcasecmp(ext, "gif") == 0 || strcasecmp(ext, "hdr") == 0 ||
493
      strcasecmp(ext, "pic") == 0 || strcasecmp(ext, "ppm") == 0 ||
494
      strcasecmp(ext, "pgm") == 0 || strcasecmp(ext, "ff") == 0 ||
495
      strcasecmp(ext, "farbfeld") == 0 || strcasecmp(ext, "svg") == 0 ||
496
      strcasecmp(ext, "webp") == 0 || strcasecmp(ext, "tif") == 0 ||
497
      strcasecmp(ext, "tiff") == 0 || strcasecmp(ext, "avif") == 0 ||
498
      strcasecmp(ext, "jxl") == 0 || strcasecmp(ext, "jpegxl") == 0) {
499
    return CHROMA_OK;
500
  }
501
502
  chroma_log("WARN", "Potentially unsupported image format: %s", ext);
503
  return CHROMA_ERROR_IMAGE;
504
}
505
506
// Get image info without loading full data
507
int chroma_image_get_info(const char *path, int *width, int *height,
508
                          int *channels) {
509
  if (!path || !width || !height || !channels) {
510
    return CHROMA_ERROR_INIT;
511
  }
512
513
  if (!file_exists(path)) {
514
    return CHROMA_ERROR_IMAGE;
515
  }
516
517
  if (!stbi_info(path, width, height, channels)) {
518
    chroma_log("ERROR", "Failed to get image info for %s: %s", path,
519
               stbi_failure_reason());
520
    return CHROMA_ERROR_IMAGE;
521
  }
522
523
  return CHROMA_OK;
524
}
525
526
// Cleanup all images in state
527
void chroma_images_cleanup(chroma_state_t *state) {
528
  if (!state) {
529
    return;
530
  }
531
532
  chroma_log("DEBUG", "Cleaning up %d images", state->image_count);
533
534
  for (int i = 0; i < state->image_count; i++) {
535
    chroma_image_release(&state->images[i]);
536
  }
537
538
  state->image_count = 0;
539
  chroma_log("INFO", "Cleaned up all images");
540
  chroma_log_memory_stats("post-image-cleanup");
541
}
542
543
// Preload common image formats for validation
544
void chroma_image_init_stb(void) {
545
  // Set stb_image options
546
  stbi_set_flip_vertically_on_load(0);
547
548
  // FIXME: these could be made configurable
549
  stbi_ldr_to_hdr_gamma(2.2f);
550
  stbi_ldr_to_hdr_scale(1.0f);
551
552
  chroma_log("DEBUG", "Initialized stb_image library");
553
}