brewery
notashelf /
5258a0b492c3c1c298ea19f120d4b539d97162d9

chroma

public

Lightweight wallpaper daemon for Wayland

Star0tarball
clone
ssh://git@git.notashelf.dev:33/notashelf/chroma.git
src/image.cC397 lines12.2 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, 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 / (float)dst_width;
68
  float y_ratio = (float)src_height / (float)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)((float)x * x_ratio);
74
      int src_y = (int)((float)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 / (float)original_width;
164
    float scale_y = (float)optimal_height / (float)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)((float)original_width * scale);
170
      optimal_height = (int)((float)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
    double reduction_ratio = (double)(optimal_width * optimal_height) /
184
                             (double)(original_width * original_height) * 100.0;
185
    chroma_log("INFO",
186
               "Downsampling image from %dx%d to %dx%d (%.1f%% of original)",
187
               original_width, original_height, optimal_width, optimal_height,
188
               reduction_ratio);
189
190
    size_t optimal_size = (size_t)optimal_width * (size_t)optimal_height * 4;
191
    unsigned char *downsampled_data = malloc(optimal_size);
192
    if (!downsampled_data) {
193
      chroma_log("ERROR", "Failed to allocate memory for downsampled image");
194
      chroma_image_free(image);
195
      return CHROMA_ERROR_MEMORY;
196
    }
197
198
    if (downsample_image(image->data, original_width, original_height,
199
                         downsampled_data, optimal_width,
200
                         optimal_height) != 0) {
201
      chroma_log("ERROR", "Failed to downsample image");
202
      free(downsampled_data);
203
      chroma_image_free(image);
204
      return CHROMA_ERROR_IMAGE;
205
    }
206
207
    stbi_image_free(image->data);
208
    image->data = downsampled_data;
209
    image->width = optimal_width;
210
    image->height = optimal_height;
211
212
    chroma_log("DEBUG", "Successfully downsampled image to %dx%d",
213
               optimal_width, optimal_height);
214
  } else if (config && !config->enable_downsampling) {
215
    chroma_log("DEBUG",
216
               "Downsampling disabled, keeping original resolution %dx%d",
217
               original_width, original_height);
218
  }
219
220
  image->loaded = true;
221
222
  // Calculate and log memory allocation
223
  size_t image_size =
224
      (size_t)image->width * (size_t)image->height * (size_t)image->channels;
225
  chroma_log_resource_allocation("image_data", image_size, path);
226
227
  chroma_log("INFO", "Loaded image: %s (%dx%d, %d channels, %.2f MB)%s", path,
228
             image->width, image->height, image->channels,
229
             (double)image_size / (1024.0 * 1024.0),
230
             should_downsample ? " (downsampled)" : "");
231
232
  return CHROMA_OK;
233
}
234
235
// Free image data
236
void chroma_image_free(chroma_image_t *image) {
237
  if (!image) {
238
    return;
239
  }
240
241
  if (image->data) {
242
    // Log memory deallocation before freeing
243
    size_t image_size =
244
        (size_t)image->width * (size_t)image->height * (size_t)image->channels;
245
246
    if (strlen(image->path) > 0) {
247
      chroma_log("DEBUG", "Freed image: %s", image->path);
248
    }
249
250
    chroma_log_resource_deallocation("image_data", image_size, image->path);
251
252
    // Always use stbi_image_free since we load directly with stbi_load
253
    stbi_image_free(image->data);
254
    image->data = NULL;
255
  }
256
257
  image->width = 0;
258
  image->height = 0;
259
  image->channels = 0;
260
  image->loaded = false;
261
262
  if (strlen(image->path) > 0) {
263
    chroma_log("DEBUG", "Freed image: %s", image->path);
264
  }
265
266
  memset(image->path, 0, sizeof(image->path));
267
}
268
269
// Find image by path in state
270
chroma_image_t *chroma_image_find_by_path(chroma_state_t *state,
271
                                          const char *path) {
272
  if (!state || !path) {
273
    return NULL;
274
  }
275
276
  for (int i = 0; i < state->image_count; i++) {
277
    if (strcmp(state->images[i].path, path) == 0) {
278
      return &state->images[i];
279
    }
280
  }
281
282
  return NULL;
283
}
284
285
// Load image if not already loaded
286
chroma_image_t *chroma_image_get_or_load(chroma_state_t *state,
287
                                         const char *path) {
288
  if (!state || !path) {
289
    return NULL;
290
  }
291
292
  // Check if already loaded
293
  chroma_image_t *existing = chroma_image_find_by_path(state, path);
294
  if (existing && existing->loaded) {
295
    chroma_log("DEBUG", "Using cached image: %s", path);
296
    return existing;
297
  }
298
299
  // Find empty slot or reuse existing
300
  chroma_image_t *image = existing;
301
  if (!image) {
302
    if (state->image_count >= MAX_OUTPUTS) {
303
      chroma_log("ERROR", "Maximum number of images reached");
304
      return NULL;
305
    }
306
    image = &state->images[state->image_count];
307
    state->image_count++;
308
  }
309
310
  // Load the image with configuration
311
  if (chroma_image_load(image, path, &state->config) != CHROMA_OK) {
312
    // If this was a new slot, decrement count
313
    if (!existing) {
314
      state->image_count--;
315
    }
316
    return NULL;
317
  }
318
319
  return image;
320
}
321
322
// Validate image file format
323
int chroma_image_validate(const char *path) {
324
  if (!path || !file_exists(path)) {
325
    return CHROMA_ERROR_IMAGE;
326
  }
327
328
  // Check file extension (basic validation)
329
  const char *ext = strrchr(path, '.');
330
  if (!ext) {
331
    return CHROMA_ERROR_IMAGE;
332
  }
333
334
  ext++; // Skip the dot
335
336
  // Check supported extensions
337
  if (strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0 ||
338
      strcasecmp(ext, "png") == 0 || strcasecmp(ext, "bmp") == 0 ||
339
      strcasecmp(ext, "tga") == 0 || strcasecmp(ext, "psd") == 0 ||
340
      strcasecmp(ext, "gif") == 0 || strcasecmp(ext, "hdr") == 0 ||
341
      strcasecmp(ext, "pic") == 0 || strcasecmp(ext, "ppm") == 0 ||
342
      strcasecmp(ext, "pgm") == 0) {
343
    return CHROMA_OK;
344
  }
345
346
  chroma_log("WARN", "Potentially unsupported image format: %s", ext);
347
  return CHROMA_ERROR_IMAGE;
348
}
349
350
// Get image info without loading full data
351
int chroma_image_get_info(const char *path, int *width, int *height,
352
                          int *channels) {
353
  if (!path || !width || !height || !channels) {
354
    return CHROMA_ERROR_INIT;
355
  }
356
357
  if (!file_exists(path)) {
358
    return CHROMA_ERROR_IMAGE;
359
  }
360
361
  if (!stbi_info(path, width, height, channels)) {
362
    chroma_log("ERROR", "Failed to get image info for %s: %s", path,
363
               stbi_failure_reason());
364
    return CHROMA_ERROR_IMAGE;
365
  }
366
367
  return CHROMA_OK;
368
}
369
370
// Cleanup all images in state
371
void chroma_images_cleanup(chroma_state_t *state) {
372
  if (!state) {
373
    return;
374
  }
375
376
  chroma_log("DEBUG", "Cleaning up %d images", state->image_count);
377
378
  for (int i = 0; i < state->image_count; i++) {
379
    chroma_image_free(&state->images[i]);
380
  }
381
382
  state->image_count = 0;
383
  chroma_log("INFO", "Cleaned up all images");
384
  chroma_log_memory_stats("post-image-cleanup");
385
}
386
387
// Preload common image formats for validation
388
void chroma_image_init_stb(void) {
389
  // Set stb_image options
390
  stbi_set_flip_vertically_on_load(0);
391
392
  // FIXME: these could be made configurable
393
  stbi_ldr_to_hdr_gamma(2.2f);
394
  stbi_ldr_to_hdr_scale(1.0f);
395
396
  chroma_log("DEBUG", "Initialized stb_image library");
397
}