brewery
notashelf /
3db813fcc2349a6440e1ab958cbd3ab67961dcb1

chroma

public

Lightweight wallpaper daemon for Wayland

Star0tarball
clone
ssh://git@git.notashelf.dev:33/notashelf/chroma.git
src/image.cC394 lines12.0 KB
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
243
    if (strlen(image->path) > 0) {
244
      chroma_log("DEBUG", "Freed image: %s", image->path);
245
    }
246
247
    chroma_log_resource_deallocation("image_data", image_size, image->path);
248
249
    // Always use stbi_image_free since we load directly with stbi_load
250
    stbi_image_free(image->data);
251
    image->data = NULL;
252
  }
253
254
  image->width = 0;
255
  image->height = 0;
256
  image->channels = 0;
257
  image->loaded = false;
258
259
  if (strlen(image->path) > 0) {
260
    chroma_log("DEBUG", "Freed image: %s", image->path);
261
  }
262
263
  memset(image->path, 0, sizeof(image->path));
264
}
265
266
// Find image by path in state
267
chroma_image_t *chroma_image_find_by_path(chroma_state_t *state,
268
                                          const char *path) {
269
  if (!state || !path) {
270
    return NULL;
271
  }
272
273
  for (int i = 0; i < state->image_count; i++) {
274
    if (strcmp(state->images[i].path, path) == 0) {
275
      return &state->images[i];
276
    }
277
  }
278
279
  return NULL;
280
}
281
282
// Load image if not already loaded
283
chroma_image_t *chroma_image_get_or_load(chroma_state_t *state,
284
                                         const char *path) {
285
  if (!state || !path) {
286
    return NULL;
287
  }
288
289
  // Check if already loaded
290
  chroma_image_t *existing = chroma_image_find_by_path(state, path);
291
  if (existing && existing->loaded) {
292
    chroma_log("DEBUG", "Using cached image: %s", path);
293
    return existing;
294
  }
295
296
  // Find empty slot or reuse existing
297
  chroma_image_t *image = existing;
298
  if (!image) {
299
    if (state->image_count >= MAX_OUTPUTS) {
300
      chroma_log("ERROR", "Maximum number of images reached");
301
      return NULL;
302
    }
303
    image = &state->images[state->image_count];
304
    state->image_count++;
305
  }
306
307
  // Load the image with configuration
308
  if (chroma_image_load(image, path, &state->config) != CHROMA_OK) {
309
    // If this was a new slot, decrement count
310
    if (!existing) {
311
      state->image_count--;
312
    }
313
    return NULL;
314
  }
315
316
  return image;
317
}
318
319
// Validate image file format
320
int chroma_image_validate(const char *path) {
321
  if (!path || !file_exists(path)) {
322
    return CHROMA_ERROR_IMAGE;
323
  }
324
325
  // Check file extension (basic validation)
326
  const char *ext = strrchr(path, '.');
327
  if (!ext) {
328
    return CHROMA_ERROR_IMAGE;
329
  }
330
331
  ext++; // Skip the dot
332
333
  // Check supported extensions
334
  if (strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0 ||
335
      strcasecmp(ext, "png") == 0 || strcasecmp(ext, "bmp") == 0 ||
336
      strcasecmp(ext, "tga") == 0 || strcasecmp(ext, "psd") == 0 ||
337
      strcasecmp(ext, "gif") == 0 || strcasecmp(ext, "hdr") == 0 ||
338
      strcasecmp(ext, "pic") == 0 || strcasecmp(ext, "ppm") == 0 ||
339
      strcasecmp(ext, "pgm") == 0) {
340
    return CHROMA_OK;
341
  }
342
343
  chroma_log("WARN", "Potentially unsupported image format: %s", ext);
344
  return CHROMA_ERROR_IMAGE;
345
}
346
347
// Get image info without loading full data
348
int chroma_image_get_info(const char *path, int *width, int *height,
349
                          int *channels) {
350
  if (!path || !width || !height || !channels) {
351
    return CHROMA_ERROR_INIT;
352
  }
353
354
  if (!file_exists(path)) {
355
    return CHROMA_ERROR_IMAGE;
356
  }
357
358
  if (!stbi_info(path, width, height, channels)) {
359
    chroma_log("ERROR", "Failed to get image info for %s: %s", path,
360
               stbi_failure_reason());
361
    return CHROMA_ERROR_IMAGE;
362
  }
363
364
  return CHROMA_OK;
365
}
366
367
// Cleanup all images in state
368
void chroma_images_cleanup(chroma_state_t *state) {
369
  if (!state) {
370
    return;
371
  }
372
373
  chroma_log("DEBUG", "Cleaning up %d images", state->image_count);
374
375
  for (int i = 0; i < state->image_count; i++) {
376
    chroma_image_free(&state->images[i]);
377
  }
378
379
  state->image_count = 0;
380
  chroma_log("INFO", "Cleaned up all images");
381
  chroma_log_memory_stats("post-image-cleanup");
382
}
383
384
// Preload common image formats for validation
385
void chroma_image_init_stb(void) {
386
  // Set stb_image options
387
  stbi_set_flip_vertically_on_load(0);
388
389
  // FIXME: these could be made configurable
390
  stbi_ldr_to_hdr_gamma(2.2f);
391
  stbi_ldr_to_hdr_scale(1.0f);
392
393
  chroma_log("DEBUG", "Initialized stb_image library");
394
}