Debian Codegraph @

addons/image/png.c

raw
1 /* loadpng, Allegro wrapper routines for libpng
2 * by Peter Wang ([email protected]).
3 */
4
5
6 #include <png.h>
7 #include <zlib.h>
8
9 #include "allegro5/allegro.h"
10 #include "allegro5/allegro_image.h"
11 #include "allegro5/internal/aintern_image.h"
12
13 #include "iio.h"
14
15 ALLEGRO_DEBUG_CHANNEL("image")
16
17
18 /* get_gamma:
19 * Get screen gamma value one of three ways.
20 */
21 static double get_gamma(void)
22 {
23 double gamma = -1.0;
24 const char* config = al_get_config_value(al_get_system_config(), "image", "png_screen_gamma");
25 if (config) {
26 gamma = strtod(config, NULL);
27 }
28 if (gamma == -1.0) {
29 /* Use the environment variable if available.
30 * 2.2 is a good guess for PC monitors.
31 * 1.1 is good for my laptop.
32 */
33 const char *gamma_str = getenv("SCREEN_GAMMA");
34 return (gamma_str) ? strtod(gamma_str, NULL) : 2.2;
35 }
36
37 return gamma;
38 }
39
40
41
42 static void user_error_fn(png_structp png_ptr, png_const_charp message)
43 {
44 jmp_buf *jmpbuf = (jmp_buf *)png_get_error_ptr(png_ptr);
45 ALLEGRO_DEBUG("PNG error: %s\n", message);
46 longjmp(*jmpbuf, 1);
47 }
48
49
50
51 /*****************************************************************************
52 * Loading routines
53 ****************************************************************************/
54
55
56
57 /* read_data:
58 * Custom read function to use Allegro packfile routines,
59 * rather than C streams (so we can read from datafiles!)
60 */
61 static void read_data(png_structp png_ptr, png_bytep data, size_t length)
62 {
63 ALLEGRO_FILE *f = (ALLEGRO_FILE *)png_get_io_ptr(png_ptr);
64 if ((png_uint_32) al_fread(f, data, length) != length)
65 png_error(png_ptr, "read error (loadpng calling al_fs_entry_read)");
66 }
67
68
69
70 /* check_if_png:
71 * Check if input file is really PNG format.
72 */
73 #define PNG_BYTES_TO_CHECK 4
74
75 static int check_if_png(ALLEGRO_FILE *fp)
76 {
77 unsigned char buf[PNG_BYTES_TO_CHECK];
78
79 ALLEGRO_ASSERT(fp);
80
81 if (al_fread(fp, buf, PNG_BYTES_TO_CHECK) != PNG_BYTES_TO_CHECK)
82 return 0;
83
84 return (png_sig_cmp(buf, (png_size_t) 0, PNG_BYTES_TO_CHECK) == 0);
85 }
86
87
88
89 /* really_load_png:
90 * Worker routine, used by load_png and load_memory_png.
91 */
92 static ALLEGRO_BITMAP *really_load_png(png_structp png_ptr, png_infop info_ptr,
93 int flags)
94 {
95 ALLEGRO_BITMAP *bmp;
96 png_uint_32 width, height, rowbytes, real_rowbytes;
97 int bit_depth, color_type, interlace_type;
98 double image_gamma, screen_gamma;
99 int intent;
100 int bpp;
101 int number_passes, pass;
102 int num_trans = 0;
103 PalEntry pal[256];
104 png_bytep trans;
105 ALLEGRO_LOCKED_REGION *lock;
106 unsigned char *buf;
107 unsigned char *dest;
108 bool premul = !(flags & ALLEGRO_NO_PREMULTIPLIED_ALPHA);
109 bool index_only;
110
111 ALLEGRO_ASSERT(png_ptr && info_ptr);
112
113 /* The call to png_read_info() gives us all of the information from the
114 * PNG file before the first IDAT (image data chunk).
115 */
116 png_read_info(png_ptr, info_ptr);
117
118 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
119 &color_type, &interlace_type, NULL, NULL);
120
121 /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
122 * byte into separate bytes (useful for paletted and grayscale images).
123 */
124 png_set_packing(png_ptr);
125
126 /* Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
127 if ((color_type == PNG_COLOR_TYPE_GRAY) && (bit_depth < 8))
128 png_set_expand(png_ptr);
129
130 /* Adds a full alpha channel if there is transparency information
131 * in a tRNS chunk.
132 */
133 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
134 if (!(color_type & PNG_COLOR_MASK_PALETTE))
135 png_set_tRNS_to_alpha(png_ptr);
136 png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
137 }
138
139 /* Convert 16-bits per colour component to 8-bits per colour component. */
140 if (bit_depth == 16)
141 png_set_strip_16(png_ptr);
142
143 /* Convert grayscale to RGB triplets */
144 if ((color_type == PNG_COLOR_TYPE_GRAY) ||
145 (color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
146 png_set_gray_to_rgb(png_ptr);
147
148 /* Optionally, tell libpng to handle the gamma correction for us. */
149 screen_gamma = get_gamma();
150 if (screen_gamma != 0.0) {
151 if (png_get_sRGB(png_ptr, info_ptr, &intent))
152 png_set_gamma(png_ptr, screen_gamma, 0.45455);
153 else {
154 if (png_get_gAMA(png_ptr, info_ptr, &image_gamma))
155 png_set_gamma(png_ptr, screen_gamma, image_gamma);
156 else
157 png_set_gamma(png_ptr, screen_gamma, 0.45455);
158 }
159 }
160
161 /* Turn on interlace handling. */
162 number_passes = png_set_interlace_handling(png_ptr);
163
164 /* Call to gamma correct and add the background to the palette
165 * and update info structure.
166 */
167 png_read_update_info(png_ptr, info_ptr);
168
169 /* Palettes. */
170 if (color_type & PNG_COLOR_MASK_PALETTE) {
171 int num_palette, i;
172 png_colorp palette;
173
174 if (png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)) {
175 /* We don't actually dither, we just copy the palette. */
176 for (i = 0; ((i < num_palette) && (i < 256)); i++) {
177 pal[i].r = palette[i].red;
178 pal[i].g = palette[i].green;
179 pal[i].b = palette[i].blue;
180 }
181
182 for (; i < 256; i++)
183 pal[i].r = pal[i].g = pal[i].b = 0;
184 }
185 }
186
187 rowbytes = png_get_rowbytes(png_ptr, info_ptr);
188
189 /* Allocate the memory to hold the image using the fields of info_ptr. */
190 bpp = rowbytes * 8 / width;
191
192 /* Allegro cannot handle less than 8 bpp. */
193 if (bpp < 8)
194 bpp = 8;
195
196
197 if ((bpp == 24) || (bpp == 32)) {
198 #ifdef ALLEGRO_BIG_ENDIAN
199 png_set_bgr(png_ptr);
200 png_set_swap_alpha(png_ptr);
201 #endif
202 }
203
204 bmp = al_create_bitmap(width, height);
205 if (!bmp) {
206 ALLEGRO_ERROR("al_create_bitmap failed while loading PNG.\n");
207 return NULL;
208 }
209
210 // TODO: can this be different from rowbytes?
211 real_rowbytes = ((bpp + 7) / 8) * width;
212 if (interlace_type == PNG_INTERLACE_ADAM7)
213 buf = al_malloc(real_rowbytes * height);
214 else
215 buf = al_malloc(real_rowbytes);
216
217 if (bpp == 8 && (color_type & PNG_COLOR_MASK_PALETTE) &&
218 (flags & ALLEGRO_KEEP_INDEX))
219 {
220 lock = al_lock_bitmap(bmp, ALLEGRO_PIXEL_FORMAT_SINGLE_CHANNEL_8,
221 ALLEGRO_LOCK_WRITEONLY);
222 index_only = true;
223 }
224 else {
225 lock = al_lock_bitmap(bmp, ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE,
226 ALLEGRO_LOCK_WRITEONLY);
227 index_only = false;
228 }
229
230 /* Read the image, one line at a time (easier to debug!) */
231 for (pass = 0; pass < number_passes; pass++) {
232 png_uint_32 y;
233 unsigned int i;
234 unsigned char *ptr;
235 dest = lock->data;
236
237 for (y = 0; y < height; y++) {
238 unsigned char *dest_row_start = dest;
239 /* For interlaced pictures, the row needs to be initialized with
240 * the contents of the previous pass.
241 */
242 if (interlace_type == PNG_INTERLACE_ADAM7)
243 ptr = buf + y * real_rowbytes;
244 else
245 ptr = buf;
246 png_read_row(png_ptr, NULL, ptr);
247
248 switch (bpp) {
249 case 8:
250 if (index_only) {
251 for (i = 0; i < width; i++) {
252 *(dest++) = *(ptr++);
253 }
254 }
255 else if (color_type & PNG_COLOR_MASK_PALETTE) {
256 for (i = 0; i < width; i++) {
257 int pix = ptr[0];
258 ptr++;
259 dest[0] = pal[pix].r;
260 dest[1] = pal[pix].g;
261 dest[2] = pal[pix].b;
262 if (pix < num_trans) {
263 int a = trans[pix];
264 dest[3] = a;
265 if (premul) {
266 dest[0] = dest[0] * a / 255;
267 dest[1] = dest[1] * a / 255;
268 dest[2] = dest[2] * a / 255;
269 }
270 } else {
271 dest[3] = 255;
272 }
273 dest += 4;
274 }
275 }
276 else {
277 for (i = 0; i < width; i++) {
278 int pix = ptr[0];
279 ptr++;
280 *(dest++) = pix;
281 *(dest++) = pix;
282 *(dest++) = pix;
283 *(dest++) = 255;
284 }
285 }
286 break;
287
288 case 24:
289 for (i = 0; i < width; i++) {
290 uint32_t pix = _AL_READ3BYTES(ptr);
291 ptr += 3;
292 *(dest++) = pix & 0xff;
293 *(dest++) = (pix >> 8) & 0xff;
294 *(dest++) = (pix >> 16) & 0xff;
295 *(dest++) = 255;
296 }
297 break;
298
299 case 32:
300 for (i = 0; i < width; i++) {
301 uint32_t pix = *(uint32_t*)ptr;
302 int r = pix & 0xff;
303 int g = (pix >> 8) & 0xff;
304 int b = (pix >> 16) & 0xff;
305 int a = (pix >> 24) & 0xff;
306 ptr += 4;
307
308 if (premul) {
309 r = r * a / 255;
310 g = g * a / 255;
311 b = b * a / 255;
312 }
313
314 *(dest++) = r;
315 *(dest++) = g;
316 *(dest++) = b;
317 *(dest++) = a;
318 }
319 break;
320
321 default:
322 ALLEGRO_ASSERT(bpp == 8 || bpp == 24 || bpp == 32);
323 break;
324 }
325 dest = dest_row_start + lock->pitch;
326 }
327 }
328
329 al_unlock_bitmap(bmp);
330
331 al_free(buf);
332
333 /* Read rest of file, and get additional chunks in info_ptr. */
334 png_read_end(png_ptr, info_ptr);
335
336 return bmp;
337 }
338
339
340 /* Load a PNG file from disk, doing colour coversion if required.
341 */
342 ALLEGRO_BITMAP *_al_load_png_f(ALLEGRO_FILE *fp, int flags)
343 {
344 jmp_buf jmpbuf;
345 ALLEGRO_BITMAP *bmp;
346 png_structp png_ptr;
347 png_infop info_ptr;
348
349 ALLEGRO_ASSERT(fp);
350
351 if (!check_if_png(fp)) {
352 ALLEGRO_ERROR("Not a png.\n");
353 return NULL;
354 }
355
356 /* Create and initialize the png_struct with the desired error handler
357 * functions. If you want to use the default stderr and longjump method,
358 * you can supply NULL for the last three parameters. We also supply the
359 * the compiler header file version, so that we know if the application
360 * was compiled with a compatible version of the library.
361 */
362 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
363 (void *)NULL, NULL, NULL);
364 if (!png_ptr) {
365 ALLEGRO_ERROR("png_ptr == NULL\n");
366 return NULL;
367 }
368
369 /* Allocate/initialize the memory for image information. */
370 info_ptr = png_create_info_struct(png_ptr);
371 if (!info_ptr) {
372 png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
373 ALLEGRO_ERROR("png_create_info_struct failed\n");
374 return NULL;
375 }
376
377 /* Set error handling. */
378 if (setjmp(jmpbuf)) {
379 /* Free all of the memory associated with the png_ptr and info_ptr */
380 png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
381 /* If we get here, we had a problem reading the file */
382 ALLEGRO_ERROR("Error reading PNG file\n");
383 return NULL;
384 }
385 png_set_error_fn(png_ptr, jmpbuf, user_error_fn, NULL);
386
387 /* Use Allegro packfile routines. */
388 png_set_read_fn(png_ptr, fp, (png_rw_ptr) read_data);
389
390 /* We have already read some of the signature. */
391 png_set_sig_bytes(png_ptr, PNG_BYTES_TO_CHECK);
392
393 /* Really load the image now. */
394 bmp = really_load_png(png_ptr, info_ptr, flags);
395
396 /* Clean up after the read, and free any memory allocated. */
397 png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
398
399 return bmp;
400 }
401
402
403
404
405
406 ALLEGRO_BITMAP *_al_load_png(const char *filename, int flags)
407 {
408 ALLEGRO_FILE *fp;
409 ALLEGRO_BITMAP *bmp;
410
411 ALLEGRO_ASSERT(filename);
412
413 fp = al_fopen(filename, "rb");
414 if (!fp) {
415 ALLEGRO_ERROR("Unable to open %s for reading.\n", filename);
416 return NULL;
417 }
418
419 bmp = _al_load_png_f(fp, flags);
420
421 al_fclose(fp);
422
423 return bmp;
424 }
425
426
427
428
429 /*****************************************************************************
430 * Saving routines
431 ****************************************************************************/
432
433
434
435 /* write_data:
436 * Custom write function to use Allegro packfile routines,
437 * rather than C streams.
438 */
439 static void write_data(png_structp png_ptr, png_bytep data, size_t length)
440 {
441 ALLEGRO_FILE *f = (ALLEGRO_FILE *)png_get_io_ptr(png_ptr);
442 if ((png_uint_32) al_fwrite(f, data, length) != length)
443 png_error(png_ptr, "write error (loadpng calling al_fs_entry_write)");
444 }
445
446 /* Don't think Allegro has any problem with buffering
447 * (rather, Allegro provides no way to flush packfiles).
448 */
449 static void flush_data(png_structp png_ptr)
450 {
451 (void)png_ptr;
452 }
453
454 /* translate_compression_level:
455 * Translate string with config value into proper zlib's
456 * compression level. Assumes default on NULL.
457 */
458 static int translate_compression_level(const char* value) {
459 if (!value || strcmp(value, "default") == 0) {
460 return Z_DEFAULT_COMPRESSION;
461 }
462 if (strcmp(value, "best") == 0) {
463 return Z_BEST_COMPRESSION;
464 }
465 if (strcmp(value, "fastest") == 0) {
466 return Z_BEST_SPEED;
467 }
468 if (strcmp(value, "none") == 0) {
469 return Z_NO_COMPRESSION;
470 }
471 return strtol(value, NULL, 10);
472 }
473
474 /* save_rgba:
475 * Core save routine for 32 bpp images.
476 */
477 static int save_rgba(png_structp png_ptr, ALLEGRO_BITMAP *bmp)
478 {
479 const int bmp_h = al_get_bitmap_height(bmp);
480 ALLEGRO_LOCKED_REGION *lock;
481 int y;
482
483 lock = al_lock_bitmap(bmp, ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE,
484 ALLEGRO_LOCK_READONLY);
485 if (!lock)
486 return 0;
487
488 for (y = 0; y < bmp_h; y++) {
489 unsigned char *p = (unsigned char *)lock->data + lock->pitch * y;
490 png_write_row(png_ptr, p);
491 }
492
493 al_unlock_bitmap(bmp);
494
495 return 1;
496 }
497
498
499
500 /* Writes a non-interlaced, no-frills PNG, taking the usual save_xyz
501 * parameters. Returns non-zero on error.
502 */
503 bool _al_save_png_f(ALLEGRO_FILE *fp, ALLEGRO_BITMAP *bmp)
504 {
505 jmp_buf jmpbuf;
506 png_structp png_ptr = NULL;
507 png_infop info_ptr = NULL;
508 int colour_type;
509
510 /* Create and initialize the png_struct with the
511 * desired error handler functions.
512 */
513 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
514 (void *)NULL, NULL, NULL);
515 if (!png_ptr) {
516 ALLEGRO_ERROR("Unable to create PNG write struct.\n");
517 goto Error;
518 }
519
520 /* Allocate/initialize the image information data. */
521 info_ptr = png_create_info_struct(png_ptr);
522 if (!info_ptr) {
523 ALLEGRO_ERROR("Unable to create PNG info struct.\n");
524 goto Error;
525 }
526
527 /* Set error handling. */
528 if (setjmp(jmpbuf)) {
529 ALLEGRO_ERROR("Failed to call setjmp.\n");
530 goto Error;
531 }
532 png_set_error_fn(png_ptr, jmpbuf, user_error_fn, NULL);
533
534 /* Use packfile routines. */
535 png_set_write_fn(png_ptr, fp, (png_rw_ptr) write_data, flush_data);
536
537 /* Set the image information here. Width and height are up to 2^31,
538 * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
539 * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
540 * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
541 * or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
542 * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
543 * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
544 */
545 colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
546
547 /* Set compression level. */
548 int z_level = translate_compression_level(
549 al_get_config_value(al_get_system_config(), "image", "png_compression_level")
550 );
551 png_set_compression_level(png_ptr, z_level);
552
553 png_set_IHDR(png_ptr, info_ptr,
554 al_get_bitmap_width(bmp), al_get_bitmap_height(bmp),
555 8, colour_type,
556 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
557 PNG_FILTER_TYPE_BASE);
558
559 /* Optionally write comments into the image ... Nah. */
560
561 /* Write the file header information. */
562 png_write_info(png_ptr, info_ptr);
563
564 /* Once we write out the header, the compression type on the text
565 * chunks gets changed to PNG_TEXT_COMPRESSION_NONE_WR or
566 * PNG_TEXT_COMPRESSION_zTXt_WR, so it doesn't get written out again
567 * at the end.
568 */
569 if (!save_rgba(png_ptr, bmp)) {
570 ALLEGRO_ERROR("save_rgba failed.\n");
571 goto Error;
572 }
573
574 png_write_end(png_ptr, info_ptr);
575
576 png_destroy_write_struct(&png_ptr, &info_ptr);
577
578 return true;
579
580 Error:
581
582 if (png_ptr) {
583 if (info_ptr)
584 png_destroy_write_struct(&png_ptr, &info_ptr);
585 else
586 png_destroy_write_struct(&png_ptr, NULL);
587 }
588
589 return false;
590 }
591
592
593 bool _al_save_png(const char *filename, ALLEGRO_BITMAP *bmp)
594 {
595 ALLEGRO_FILE *fp;
596 bool retsave;
597 bool retclose;
598
599 ALLEGRO_ASSERT(filename);
600 ALLEGRO_ASSERT(bmp);
601
602 fp = al_fopen(filename, "wb");
603 if (!fp) {
604 ALLEGRO_ERROR("Unable to open file %s for writing\n", filename);
605 return false;
606 }
607
608 retsave = _al_save_png_f(fp, bmp);
609 retclose = al_fclose(fp);
610
611 return retsave && retclose;
612 }
613
614 /* vim: set sts=3 sw=3 et: */