io-png.c 40.4 KB
Newer Older
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
2
/* GdkPixbuf library - PNG image loader
3
 *
4
 * Copyright (C) 1999 Mark Crichton
5 6 7 8
 * Copyright (C) 1999 The Free Software Foundation
 *
 * Authors: Mark Crichton <crichton@gimp.org>
 *          Federico Mena-Quintero <federico@gimp.org>
9
 *
10
 * This library is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12 13 14 15 16 17
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22
 */
23

24
#include "config.h"
25
#include <stdio.h>
26
#include <stdlib.h>
Matthias Clasen's avatar
Matthias Clasen committed
27
#include <string.h>
28
#include <png.h>
29
#include "gdk-pixbuf-private.h"
30 31 32



33
static gboolean
34
setup_png_transformations(png_structp png_read_ptr, png_infop png_info_ptr,
35
                          GError **error,
36 37 38 39 40 41 42 43 44
                          png_uint_32* width_p, png_uint_32* height_p,
                          int* color_type_p)
{
        png_uint_32 width, height;
        int bit_depth, color_type, interlace_type, compression_type, filter_type;
        int channels;
        
        /* Get the image info */

45 46 47 48 49
        /* Must check bit depth, since png_get_IHDR generates an 
           FPE on bit_depth 0.
        */
        bit_depth = png_get_bit_depth (png_read_ptr, png_info_ptr);
        if (bit_depth < 1 || bit_depth > 16) {
50 51 52 53
                g_set_error_literal (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                     _("Bits per channel of PNG image is invalid."));
54 55
                return FALSE;
        }
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        png_get_IHDR (png_read_ptr, png_info_ptr,
                      &width, &height,
                      &bit_depth,
                      &color_type,
                      &interlace_type,
                      &compression_type,
                      &filter_type);

        /* set_expand() basically needs to be called unless
           we are already in RGB/RGBA mode
        */
        if (color_type == PNG_COLOR_TYPE_PALETTE &&
            bit_depth <= 8) {

                /* Convert indexed images to RGB */
                png_set_expand (png_read_ptr);

        } else if (color_type == PNG_COLOR_TYPE_GRAY &&
                   bit_depth < 8) {

                /* Convert grayscale to RGB */
                png_set_expand (png_read_ptr);

        } else if (png_get_valid (png_read_ptr, 
                                  png_info_ptr, PNG_INFO_tRNS)) {

                /* If we have transparency header, convert it to alpha
                   channel */
                png_set_expand(png_read_ptr);
                
        } else if (bit_depth < 8) {

                /* If we have < 8 scale it up to 8 */
                png_set_expand(png_read_ptr);


                /* Conceivably, png_set_packing() is a better idea;
                 * God only knows how libpng works
                 */
        }

        /* If we are 16-bit, convert to 8-bit */
        if (bit_depth == 16) {
                png_set_strip_16(png_read_ptr);
        }

        /* If gray scale, convert to RGB */
        if (color_type == PNG_COLOR_TYPE_GRAY ||
            color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
                png_set_gray_to_rgb(png_read_ptr);
        }
        
        /* If interlaced, handle that */
        if (interlace_type != PNG_INTERLACE_NONE) {
                png_set_interlace_handling(png_read_ptr);
        }
        
        /* Update the info the reflect our transformations */
        png_read_update_info(png_read_ptr, png_info_ptr);
        
        png_get_IHDR (png_read_ptr, png_info_ptr,
                      &width, &height,
                      &bit_depth,
                      &color_type,
                      &interlace_type,
                      &compression_type,
                      &filter_type);

        *width_p = width;
        *height_p = height;
        *color_type_p = color_type;
        
        /* Check that the new info is what we want */
        
130
        if (width == 0 || height == 0) {
131 132 133 134
                g_set_error_literal (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                     _("Transformed PNG has zero width or height."));
135 136 137
                return FALSE;
        }

138
        if (bit_depth != 8) {
139 140 141 142
                g_set_error_literal (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                     _("Bits per channel of transformed PNG is not 8."));
143
                return FALSE;
144 145 146 147
        }

        if ( ! (color_type == PNG_COLOR_TYPE_RGB ||
                color_type == PNG_COLOR_TYPE_RGB_ALPHA) ) {
148 149 150 151
                g_set_error_literal (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                     _("Transformed PNG not RGB or RGBA."));
152
                return FALSE;
153 154 155 156
        }

        channels = png_get_channels(png_read_ptr, png_info_ptr);
        if ( ! (channels == 3 || channels == 4) ) {
157 158 159 160
                g_set_error_literal (error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                     _("Transformed PNG has unsupported number of channels, must be 3 or 4."));
161
                return FALSE;
162
        }
163
        return TRUE;
164 165
}

Havoc Pennington's avatar
Havoc Pennington committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
static void
png_simple_error_callback(png_structp png_save_ptr,
                          png_const_charp error_msg)
{
        GError **error;
        
        error = png_get_error_ptr(png_save_ptr);

        /* I don't trust libpng to call the error callback only once,
         * so check for already-set error
         */
        if (error && *error == NULL) {
                g_set_error (error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_FAILED,
181
                             _("Fatal error in PNG image file: %s"),
Havoc Pennington's avatar
Havoc Pennington committed
182 183
                             error_msg);
        }
184

Maarten Bosmans's avatar
Maarten Bosmans committed
185
        longjmp (png_jmpbuf(png_save_ptr), 1);
Havoc Pennington's avatar
Havoc Pennington committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199
}

static void
png_simple_warning_callback(png_structp png_save_ptr,
                            png_const_charp warning_msg)
{
        /* Don't print anything; we should not be dumping junk to
         * stderr, since that may be bad for some apps. If it's
         * important enough to display, we need to add a GError
         * **warning return location wherever we have an error return
         * location.
         */
}

200 201 202 203 204
static gboolean
png_text_to_pixbuf_option (png_text   text_ptr,
                           gchar    **key,
                           gchar    **value)
{
205 206 207 208 209 210 211 212 213 214 215
        gboolean is_ascii = TRUE;
        int i;

        /* Avoid loading iconv if the text is plain ASCII */
        for (i = 0; i < text_ptr.text_length; i++)
                if (text_ptr.text[i] & 0x80) {
                        is_ascii = FALSE;
                        break;
                }

        if (is_ascii) {
216
                *value = g_strdup (text_ptr.text);
217 218 219 220
        } else {
                *value = g_convert (text_ptr.text, -1,
                                     "UTF-8", "ISO-8859-1",
                                     NULL, NULL, NULL);
221
        }
222

223 224 225 226
        if (*value) {
                *key = g_strconcat ("tEXt::", text_ptr.key, NULL);
                return TRUE;
        } else {
227
                g_warning ("Couldn't convert text chunk value to UTF-8.");
228 229 230 231 232
                *key = NULL;
                return FALSE;
        }
}

233 234 235 236 237 238 239 240 241 242 243 244
static png_voidp
png_malloc_callback (png_structp o, png_size_t size)
{
        return g_try_malloc (size);
}

static void
png_free_callback (png_structp o, png_voidp x)
{
        g_free (x);
}

245
/* Shared library entry point */
246
static GdkPixbuf *
Havoc Pennington's avatar
Havoc Pennington committed
247
gdk_pixbuf__png_image_load (FILE *f, GError **error)
248
{
249
        GdkPixbuf * volatile pixbuf = NULL;
250
	png_structp png_ptr;
Matthias Clasen's avatar
Matthias Clasen committed
251
	png_infop info_ptr;
252
        png_textp text_ptr;
253
	gint i, ctype;
254
	png_uint_32 w, h;
255
	png_bytepp volatile rows = NULL;
256
        gint    num_texts;
257 258
        gchar *key;
        gchar *value;
259 260 261
        gchar *icc_profile_base64;
        const gchar *icc_profile_title;
        const gchar *icc_profile;
262
        png_uint_32 icc_profile_size;
263 264
        guint32 retval;
        gint compression_type;
265

266 267 268 269 270 271 272 273 274
#ifdef PNG_USER_MEM_SUPPORTED
	png_ptr = png_create_read_struct_2 (PNG_LIBPNG_VER_STRING,
                                            error,
                                            png_simple_error_callback,
                                            png_simple_warning_callback,
                                            NULL, 
                                            png_malloc_callback, 
                                            png_free_callback);
#else
Havoc Pennington's avatar
Havoc Pennington committed
275 276 277 278
	png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
                                          error,
                                          png_simple_error_callback,
                                          png_simple_warning_callback);
279
#endif
280 281 282 283 284 285 286 287 288
	if (!png_ptr)
		return NULL;

	info_ptr = png_create_info_struct (png_ptr);
	if (!info_ptr) {
		png_destroy_read_struct (&png_ptr, NULL, NULL);
		return NULL;
	}

Maarten Bosmans's avatar
Maarten Bosmans committed
289
	if (setjmp (png_jmpbuf(png_ptr))) {
290
	    	g_free (rows);
291

292 293
		if (pixbuf)
			g_object_unref (pixbuf);
294

Matthias Clasen's avatar
Matthias Clasen committed
295
		png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
296 297 298
		return NULL;
	}

299
	png_init_io (png_ptr, f);
300
	png_read_info (png_ptr, info_ptr);
301

302
        if (!setup_png_transformations(png_ptr, info_ptr, error, &w, &h, &ctype)) {
Matthias Clasen's avatar
Matthias Clasen committed
303
                png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
304 305 306
                return NULL;
        }
        
307 308 309
        pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, ctype & PNG_COLOR_MASK_ALPHA, 8, w, h);

	if (!pixbuf) {
Havoc Pennington's avatar
Havoc Pennington committed
310
                if (error && *error == NULL) {
311 312 313 314
                        g_set_error_literal (error,
                                             GDK_PIXBUF_ERROR,
                                             GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
                                             _("Insufficient memory to load PNG file"));
Havoc Pennington's avatar
Havoc Pennington committed
315 316
                }
                
317

Matthias Clasen's avatar
Matthias Clasen committed
318
		png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
319 320
		return NULL;
	}
321

322
	rows = g_new (png_bytep, h);
323

324
	for (i = 0; i < h; i++)
325
		rows[i] = pixbuf->pixels + i * pixbuf->rowstride;
326

327
	png_read_image (png_ptr, rows);
Matthias Clasen's avatar
Matthias Clasen committed
328
        png_read_end (png_ptr, info_ptr);
329 330 331

        if (png_get_text (png_ptr, info_ptr, &text_ptr, &num_texts)) {
                for (i = 0; i < num_texts; i++) {
332
                        png_text_to_pixbuf_option (text_ptr[i], &key, &value);
333
                        gdk_pixbuf_set_option (pixbuf, key, value);
334 335
                        g_free (key);
                        g_free (value);
336 337 338
                }
        }

339 340 341 342
#if defined(PNG_cHRM_SUPPORTED)
        /* Extract embedded ICC profile */
        retval = png_get_iCCP (png_ptr, info_ptr,
                               (png_charpp) &icc_profile_title, &compression_type,
343
                               (png_bytepp) &icc_profile, (png_uint_32*) &icc_profile_size);
344
        if (retval != 0) {
345
                icc_profile_base64 = g_base64_encode ((const guchar *) icc_profile, (gsize)icc_profile_size);
346 347 348 349 350
                gdk_pixbuf_set_option (pixbuf, "icc-profile", icc_profile_base64);
                g_free (icc_profile_base64);
        }
#endif

351 352
	g_free (rows);
	png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
353 354

        return pixbuf;
355
}
356

357 358
/* I wish these avoided the setjmp()/longjmp() crap in libpng instead
   just allow you to change the error reporting. */
359 360 361
static void png_error_callback  (png_structp png_read_ptr,
                                 png_const_charp error_msg);

362 363
static void png_warning_callback (png_structp png_read_ptr,
                                  png_const_charp warning_msg);
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

/* Called at the start of the progressive load */
static void png_info_callback   (png_structp png_read_ptr,
                                 png_infop   png_info_ptr);

/* Called for each row; note that you will get duplicate row numbers
   for interlaced PNGs */
static void png_row_callback   (png_structp png_read_ptr,
                                png_bytep   new_row,
                                png_uint_32 row_num,
                                int pass_num);

/* Called after reading the entire image */
static void png_end_callback   (png_structp png_read_ptr,
                                png_infop   png_info_ptr);

typedef struct _LoadContext LoadContext;

struct _LoadContext {
        png_structp png_read_ptr;
        png_infop   png_info_ptr;

386
        GdkPixbufModuleSizeFunc size_func;
387 388
        GdkPixbufModulePreparedFunc prepare_func;
        GdkPixbufModuleUpdatedFunc update_func;
389 390 391
        gpointer notify_user_data;

        GdkPixbuf* pixbuf;
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

        /* row number of first row seen, or -1 if none yet seen */

        gint first_row_seen_in_chunk;

        /* pass number for the first row seen */

        gint first_pass_seen_in_chunk;
        
        /* row number of last row seen */
        gint last_row_seen_in_chunk;

        gint last_pass_seen_in_chunk;

        /* highest row number seen */
        gint max_row_seen_in_chunk;
408 409 410
        
        guint fatal_error_occurred : 1;

Havoc Pennington's avatar
Havoc Pennington committed
411
        GError **error;
412 413
};

414
static gpointer
415 416 417
gdk_pixbuf__png_image_begin_load (GdkPixbufModuleSizeFunc size_func,
                                  GdkPixbufModulePreparedFunc prepare_func,
				  GdkPixbufModuleUpdatedFunc update_func,
Havoc Pennington's avatar
Havoc Pennington committed
418 419
				  gpointer user_data,
                                  GError **error)
420 421 422 423 424 425 426
{
        LoadContext* lc;
        
        lc = g_new0(LoadContext, 1);
        
        lc->fatal_error_occurred = FALSE;

427
        lc->size_func = size_func;
428 429
        lc->prepare_func = prepare_func;
        lc->update_func = update_func;
430 431
        lc->notify_user_data = user_data;

432 433 434 435 436
        lc->first_row_seen_in_chunk = -1;
        lc->last_row_seen_in_chunk = -1;
        lc->first_pass_seen_in_chunk = -1;
        lc->last_pass_seen_in_chunk = -1;
        lc->max_row_seen_in_chunk = -1;
Havoc Pennington's avatar
Havoc Pennington committed
437
        lc->error = error;
438
        
439 440
        /* Create the main PNG context struct */

441 442 443 444 445 446 447 448 449
#ifdef PNG_USER_MEM_SUPPORTED
        lc->png_read_ptr = png_create_read_struct_2 (PNG_LIBPNG_VER_STRING,
                                                     lc, /* error/warning callback data */
                                                     png_error_callback,
                                                     png_warning_callback,
                                                     NULL,
                                                     png_malloc_callback,
                                                     png_free_callback);
#else
450 451 452 453
        lc->png_read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
                                                  lc, /* error/warning callback data */
                                                  png_error_callback,
                                                  png_warning_callback);
454
#endif
455 456
        if (lc->png_read_ptr == NULL) {
                g_free(lc);
Havoc Pennington's avatar
Havoc Pennington committed
457
                /* error callback should have set the error */
458 459
                return NULL;
        }
Havoc Pennington's avatar
Havoc Pennington committed
460
        
Maarten Bosmans's avatar
Maarten Bosmans committed
461
	if (setjmp (png_jmpbuf(lc->png_read_ptr))) {
462 463 464
		if (lc->png_info_ptr)
			png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL);
                g_free(lc);
Havoc Pennington's avatar
Havoc Pennington committed
465
                /* error callback should have set the error */
466 467 468
                return NULL;
	}

469
        /* Create the auxiliary context struct */
470 471 472 473 474 475

        lc->png_info_ptr = png_create_info_struct(lc->png_read_ptr);

        if (lc->png_info_ptr == NULL) {
                png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL);
                g_free(lc);
Havoc Pennington's avatar
Havoc Pennington committed
476
                /* error callback should have set the error */
477 478 479 480 481 482 483 484 485 486
                return NULL;
        }

        png_set_progressive_read_fn(lc->png_read_ptr,
                                    lc, /* callback data */
                                    png_info_callback,
                                    png_row_callback,
                                    png_end_callback);
        

Havoc Pennington's avatar
Havoc Pennington committed
487 488 489 490 491
        /* We don't want to keep modifying error after returning here,
         * it may no longer be valid.
         */
        lc->error = NULL;
        
492 493 494
        return lc;
}

495 496
static gboolean
gdk_pixbuf__png_image_stop_load (gpointer context, GError **error)
497 498 499
{
        LoadContext* lc = context;

500
        g_return_val_if_fail(lc != NULL, TRUE);
501

502 503 504 505
        /* FIXME this thing needs to report errors if
         * we have unused image data
         */
        
506
        if (lc->pixbuf)
507
                g_object_unref (lc->pixbuf);
508
        
Matthias Clasen's avatar
Matthias Clasen committed
509
        png_destroy_read_struct(&lc->png_read_ptr, &lc->png_info_ptr, NULL);
510
        g_free(lc);
511 512

        return TRUE;
513 514
}

515 516 517
static gboolean
gdk_pixbuf__png_image_load_increment(gpointer context,
                                     const guchar *buf, guint size,
Havoc Pennington's avatar
Havoc Pennington committed
518
                                     GError **error)
519 520 521 522 523
{
        LoadContext* lc = context;

        g_return_val_if_fail(lc != NULL, FALSE);

524 525 526 527 528 529
        /* reset */
        lc->first_row_seen_in_chunk = -1;
        lc->last_row_seen_in_chunk = -1;
        lc->first_pass_seen_in_chunk = -1;
        lc->last_pass_seen_in_chunk = -1;
        lc->max_row_seen_in_chunk = -1;
Havoc Pennington's avatar
Havoc Pennington committed
530
        lc->error = error;
531
        
532
        /* Invokes our callbacks as needed */
Maarten Bosmans's avatar
Maarten Bosmans committed
533
	if (setjmp (png_jmpbuf(lc->png_read_ptr))) {
Havoc Pennington's avatar
Havoc Pennington committed
534
                lc->error = NULL;
535 536
		return FALSE;
	} else {
537 538
		png_process_data(lc->png_read_ptr, lc->png_info_ptr,
                                 (guchar*) buf, size);
539
	}
540

Havoc Pennington's avatar
Havoc Pennington committed
541 542
        if (lc->fatal_error_occurred) {
                lc->error = NULL;
543
                return FALSE;
Havoc Pennington's avatar
Havoc Pennington committed
544
        } else {
545
                if (lc->first_row_seen_in_chunk >= 0 && lc->update_func) {
546 547 548 549 550 551 552
                        /* We saw at least one row */
                        gint pass_diff = lc->last_pass_seen_in_chunk - lc->first_pass_seen_in_chunk;
                        
                        g_assert(pass_diff >= 0);
                        
                        if (pass_diff == 0) {
                                /* start and end row were in the same pass */
553
                                (lc->update_func)(lc->pixbuf, 0,
554
                                                  lc->first_row_seen_in_chunk,
555
                                                  lc->pixbuf->width,
556
                                                  (lc->last_row_seen_in_chunk -
557 558
                                                   lc->first_row_seen_in_chunk) + 1,
						  lc->notify_user_data);
559 560 561 562 563 564
                        } else if (pass_diff == 1) {
                                /* We have from the first row seen to
                                   the end of the image (max row
                                   seen), then from the top of the
                                   image to the last row seen */
                                /* first row to end */
565
                                (lc->update_func)(lc->pixbuf, 0,
566
                                                  lc->first_row_seen_in_chunk,
567
                                                  lc->pixbuf->width,
568
                                                  (lc->max_row_seen_in_chunk -
569 570
                                                   lc->first_row_seen_in_chunk) + 1,
						  lc->notify_user_data);
571
                                /* top to last row */
572
                                (lc->update_func)(lc->pixbuf,
573
                                                  0, 0, 
574
                                                  lc->pixbuf->width,
575 576
                                                  lc->last_row_seen_in_chunk + 1,
						  lc->notify_user_data);
577 578 579
                        } else {
                                /* We made at least one entire pass, so update the
                                   whole image */
580
                                (lc->update_func)(lc->pixbuf,
581
                                                  0, 0, 
582
                                                  lc->pixbuf->width,
583 584
                                                  lc->max_row_seen_in_chunk + 1,
						  lc->notify_user_data);
585 586
                        }
                }
Havoc Pennington's avatar
Havoc Pennington committed
587 588

                lc->error = NULL;
589
                
590
                return TRUE;
591
        }
592 593 594 595 596 597 598 599 600
}

/* Called at the start of the progressive load, once we have image info */
static void
png_info_callback   (png_structp png_read_ptr,
                     png_infop   png_info_ptr)
{
        LoadContext* lc;
        png_uint_32 width, height;
601 602
        png_textp png_text_ptr;
        int i, num_texts;
603
        int color_type;
604
        gboolean have_alpha = FALSE;
605 606 607
        gchar *icc_profile_base64;
        const gchar *icc_profile_title;
        const gchar *icc_profile;
608
        png_uint_32 icc_profile_size;
609 610 611
        guint32 retval;
        gint compression_type;

612 613 614 615 616
        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;

617 618 619 620
        if (!setup_png_transformations(lc->png_read_ptr,
                                       lc->png_info_ptr,
                                       lc->error,
                                       &width, &height, &color_type)) {
621 622
                lc->fatal_error_occurred = TRUE;
                return;
623 624 625 626
        }

        /* If we have alpha, set a flag */
        if (color_type & PNG_COLOR_MASK_ALPHA)
627
                have_alpha = TRUE;
628
        
629 630 631 632 633 634 635
        if (lc->size_func) {
                gint w = width;
                gint h = height;
                (* lc->size_func) (&w, &h, lc->notify_user_data);
                
                if (w == 0 || h == 0) {
                        lc->fatal_error_occurred = TRUE;
636
                        if (lc->error && *lc->error == NULL) {
637 638 639 640
                                g_set_error_literal (lc->error,
                                                     GDK_PIXBUF_ERROR,
                                                     GDK_PIXBUF_ERROR_FAILED,
                                                     _("Transformed PNG has zero width or height."));
641
                        }
642 643 644 645 646
                        return;
                }
        }

        lc->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, have_alpha, 8, width, height);
647 648 649 650

        if (lc->pixbuf == NULL) {
                /* Failed to allocate memory */
                lc->fatal_error_occurred = TRUE;
Havoc Pennington's avatar
Havoc Pennington committed
651 652 653 654
                if (lc->error && *lc->error == NULL) {
                        g_set_error (lc->error,
                                     GDK_PIXBUF_ERROR,
                                     GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
655 656
                                     _("Insufficient memory to store a %lu by %lu image; try exiting some applications to reduce memory usage"),
                                     (gulong) width, (gulong) height);
Havoc Pennington's avatar
Havoc Pennington committed
657
                }
658 659
                return;
        }
660

661
        /* Extract text chunks and attach them as pixbuf options */
662
        
663 664 665 666 667 668
        if (png_get_text (png_read_ptr, png_info_ptr, &png_text_ptr, &num_texts)) {
                for (i = 0; i < num_texts; i++) {
                        gchar *key, *value;

                        if (png_text_to_pixbuf_option (png_text_ptr[i],
                                                       &key, &value)) {
669
                                gdk_pixbuf_set_option (lc->pixbuf, key, value);
670 671 672 673 674 675
                                g_free (key);
                                g_free (value);
                        }
                }
        }

676 677 678 679
#if defined(PNG_cHRM_SUPPORTED)
        /* Extract embedded ICC profile */
        retval = png_get_iCCP (png_read_ptr, png_info_ptr,
                               (png_charpp) &icc_profile_title, &compression_type,
680
                               (png_bytepp) &icc_profile, &icc_profile_size);
681
        if (retval != 0) {
682
                icc_profile_base64 = g_base64_encode ((const guchar *) icc_profile, (gsize)icc_profile_size);
683 684 685 686 687
                gdk_pixbuf_set_option (lc->pixbuf, "icc-profile", icc_profile_base64);
                g_free (icc_profile_base64);
        }
#endif

688 689
        /* Notify the client that we are ready to go */

690
        if (lc->prepare_func)
Havoc Pennington's avatar
Havoc Pennington committed
691
                (* lc->prepare_func) (lc->pixbuf, NULL, lc->notify_user_data);
692

693 694 695 696 697 698 699 700 701 702 703 704 705
        return;
}

/* Called for each row; note that you will get duplicate row numbers
   for interlaced PNGs */
static void
png_row_callback   (png_structp png_read_ptr,
                    png_bytep   new_row,
                    png_uint_32 row_num,
                    int pass_num)
{
        LoadContext* lc;
        guchar* old_row = NULL;
706

707 708 709 710
        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;
711

Matthias Clasen's avatar
Matthias Clasen committed
712
        if (row_num >= lc->pixbuf->height) {
713 714
                lc->fatal_error_occurred = TRUE;
                if (lc->error && *lc->error == NULL) {
715 716 717 718
                        g_set_error_literal (lc->error,
                                             GDK_PIXBUF_ERROR,
                                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                                             _("Fatal error reading PNG image file"));
719 720 721 722
                }
                return;
        }

723 724 725 726 727 728 729 730 731
        if (lc->first_row_seen_in_chunk < 0) {
                lc->first_row_seen_in_chunk = row_num;
                lc->first_pass_seen_in_chunk = pass_num;
        }

        lc->max_row_seen_in_chunk = MAX(lc->max_row_seen_in_chunk, ((gint)row_num));
        lc->last_row_seen_in_chunk = row_num;
        lc->last_pass_seen_in_chunk = pass_num;
        
732
        old_row = lc->pixbuf->pixels + (row_num * lc->pixbuf->rowstride);
733

734 735 736 737 738 739 740
        png_progressive_combine_row(lc->png_read_ptr, old_row, new_row);
}

/* Called after reading the entire image */
static void
png_end_callback   (png_structp png_read_ptr,
                    png_infop   png_info_ptr)
741
{
742 743 744 745 746 747
        LoadContext* lc;

        lc = png_get_progressive_ptr(png_read_ptr);

        if (lc->fatal_error_occurred)
                return;
748
}
749 750 751 752 753 754 755 756 757 758

static void
png_error_callback(png_structp png_read_ptr,
                   png_const_charp error_msg)
{
        LoadContext* lc;
        
        lc = png_get_error_ptr(png_read_ptr);
        
        lc->fatal_error_occurred = TRUE;
Havoc Pennington's avatar
Havoc Pennington committed
759 760 761 762 763 764 765 766 767 768 769

        /* I don't trust libpng to call the error callback only once,
         * so check for already-set error
         */
        if (lc->error && *lc->error == NULL) {
                g_set_error (lc->error,
                             GDK_PIXBUF_ERROR,
                             GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
                             _("Fatal error reading PNG image file: %s"),
                             error_msg);
        }
770

Maarten Bosmans's avatar
Maarten Bosmans committed
771
        longjmp (png_jmpbuf(png_read_ptr), 1);
772 773 774
}

static void
775 776
png_warning_callback (png_structp png_read_ptr,
                      png_const_charp warning_msg)
777
{
Havoc Pennington's avatar
Havoc Pennington committed
778 779 780 781 782 783
        /* Don't print anything; we should not be dumping junk to
         * stderr, since that may be bad for some apps. If it's
         * important enough to display, we need to add a GError
         * **warning return location wherever we have an error return
         * location.
         */
784
}
785 786


787
/* Save */
Havoc Pennington's avatar
Havoc Pennington committed
788

789 790 791 792 793 794 795 796 797 798 799 800 801
typedef struct {
        GdkPixbufSaveFunc save_func;
        gpointer user_data;
        GError **error;
} SaveToFunctionIoPtr;

static void
png_save_to_callback_write_func (png_structp png_ptr,
                                 png_bytep   data,
                                 png_size_t  length)
{
        SaveToFunctionIoPtr *ioptr = png_get_io_ptr (png_ptr);

802
        if (!ioptr->save_func ((gchar *)data, length, ioptr->error, ioptr->user_data)) {
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
                /* If save_func has already set an error, which it
                   should have done, this won't overwrite it. */
                png_error (png_ptr, "write function failed");
        }
}

static void
png_save_to_callback_flush_func (png_structp png_ptr)
{
        ;
}

static gboolean real_save_png (GdkPixbuf        *pixbuf, 
                               gchar           **keys,
                               gchar           **values,
                               GError          **error,
                               gboolean          to_callback,
                               FILE             *f,
                               GdkPixbufSaveFunc save_func,
                               gpointer          user_data)
823
{
824
       png_structp png_ptr = NULL;
825
       png_infop info_ptr;
826
       png_textp text_ptr = NULL;
827 828
       guchar *ptr;
       guchar *pixels;
829 830
       int y;
       int i;
831
       png_bytep row_ptr;
832 833 834 835
       png_color_8 sig_bit;
       int w, h, rowstride;
       int has_alpha;
       int bpc;
836
       int num_keys;
837
       int compression = -1;
838
       gboolean success = TRUE;
839 840
       guchar *icc_profile = NULL;
       gsize icc_profile_size = 0;
841
       SaveToFunctionIoPtr to_callback_ioptr;
842 843

       num_keys = 0;
844 845

       if (keys && *keys) {
846 847 848 849 850 851 852
               gchar **kiter = keys;
               gchar **viter = values;

               while (*kiter) {
                       if (strncmp (*kiter, "tEXt::", 6) == 0) {
                               gchar  *key = *kiter + 6;
                               int     len = strlen (key);
853
                               if (len < 1 || len > 79) {
854 855 856 857
                                       g_set_error_literal (error,
                                                            GDK_PIXBUF_ERROR,
                                                            GDK_PIXBUF_ERROR_BAD_OPTION,
                                                            _("Keys for PNG text chunks must have at least 1 and at most 79 characters."));
858 859
                                       success = FALSE;
                                       goto cleanup;
860 861 862
                               }
                               for (i = 0; i < len; i++) {
                                       if ((guchar) key[i] > 127) {
863 864 865 866
                                               g_set_error_literal (error,
                                                                    GDK_PIXBUF_ERROR,
                                                                    GDK_PIXBUF_ERROR_BAD_OPTION,
                                                                    _("Keys for PNG text chunks must be ASCII characters."));
867 868
                                               success = FALSE;
                                               goto cleanup;
869 870 871
                                       }
                               }
                               num_keys++;
872 873 874 875 876 877 878 879
                       } else if (strcmp (*kiter, "icc-profile") == 0) {
                               /* decode from base64 */
                               icc_profile = g_base64_decode (*viter, &icc_profile_size);
                               if (icc_profile_size < 127) {
                                       /* This is a user-visible error */
                                       g_set_error (error,
                                                    GDK_PIXBUF_ERROR,
                                                    GDK_PIXBUF_ERROR_BAD_OPTION,
880 881
                                                    _("Color profile has invalid length %d."),
                                                    (gint)icc_profile_size);
882 883 884
                                       success = FALSE;
                                       goto cleanup;
                               }
885 886 887
                       } else if (strcmp (*kiter, "compression") == 0) {
                               char *endptr = NULL;
                               compression = strtol (*viter, &endptr, 10);
888

889 890 891 892 893 894
                               if (endptr == *viter) {
                                       g_set_error (error,
                                                    GDK_PIXBUF_ERROR,
                                                    GDK_PIXBUF_ERROR_BAD_OPTION,
                                                    _("PNG compression level must be a value between 0 and 9; value '%s' could not be parsed."),
                                                    *viter);
895 896
                                       success = FALSE;
                                       goto cleanup;
897 898 899 900 901 902
                               }
                               if (compression < 0 || compression > 9) {
                                       /* This is a user-visible error;
                                        * lets people skip the range-checking
                                        * in their app.
                                        */
903 904 905
                                       g_set_error (error,
                                                    GDK_PIXBUF_ERROR,
                                                    GDK_PIXBUF_ERROR_BAD_OPTION,
906 907
                                                    _("PNG compression level must be a value between 0 and 9; value '%d' is not allowed."),
                                                    compression);
908 909
                                       success = FALSE;
                                       goto cleanup;
910
                               }
911
                       } else {
912
                               g_warning ("Unrecognized parameter (%s) passed to PNG saver.", *kiter);
913
                       }
914 915 916

                       ++kiter;
                       ++viter;
917 918 919 920
               }
       }

       if (num_keys > 0) {
921 922 923
               gchar **kiter = keys;
               gchar **viter = values;

924 925
               text_ptr = g_new0 (png_text, num_keys);
               for (i = 0; i < num_keys; i++) {
926 927 928 929 930
                       if (strncmp (*kiter, "tEXt::", 6) != 0) {
                                kiter++;
                                viter++;
                       }

931
                       text_ptr[i].compression = PNG_TEXT_COMPRESSION_NONE;
932 933
                       text_ptr[i].key  = *kiter + 6;
                       text_ptr[i].text = g_convert (*viter, -1, 
934 935 936
                                                     "ISO-8859-1", "UTF-8", 
                                                     NULL, &text_ptr[i].text_length, 
                                                     NULL);
937 938 939 940

#ifdef PNG_iTXt_SUPPORTED 
                       if (!text_ptr[i].text) {
                               text_ptr[i].compression = PNG_ITXT_COMPRESSION_NONE;
941
                               text_ptr[i].text = g_strdup (*viter);
942 943 944 945 946 947 948
                               text_ptr[i].text_length = 0;
                               text_ptr[i].itxt_length = strlen (text_ptr[i].text);
                               text_ptr[i].lang = NULL;
                               text_ptr[i].lang_key = NULL;
                       }
#endif

949
                       if (!text_ptr[i].text) {
950
                               gint j;
951 952 953
                               g_set_error (error,
                                            GDK_PIXBUF_ERROR,
                                            GDK_PIXBUF_ERROR_BAD_OPTION,
954 955 956
                                            _("Value for PNG text chunk %s cannot be converted to ISO-8859-1 encoding."), *kiter + 6);
                               for (j = 0; j < i; j++)
                                       g_free (text_ptr[j].text);
957 958 959
                               g_free (text_ptr);
                               return FALSE;
                       }
960 961 962

                        kiter++;
                        viter++;
963 964
               }
       }
965

966 967 968 969 970 971 972 973
       bpc = gdk_pixbuf_get_bits_per_sample (pixbuf);
       w = gdk_pixbuf_get_width (pixbuf);
       h = gdk_pixbuf_get_height (pixbuf);
       rowstride = gdk_pixbuf_get_rowstride (pixbuf);
       has_alpha = gdk_pixbuf_get_has_alpha (pixbuf);
       pixels = gdk_pixbuf_get_pixels (pixbuf);

       png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING,
Havoc Pennington's avatar
Havoc Pennington committed
974 975 976
                                          error,
                                          png_simple_error_callback,
                                          png_simple_warning_callback);
977 978 979 980
       if (png_ptr == NULL) {
	       success = FALSE;
	       goto cleanup;
       }
981 982 983

       info_ptr = png_create_info_struct (png_ptr);
       if (info_ptr == NULL) {
984 985
	       success = FALSE;
	       goto cleanup;
986
       }
Maarten Bosmans's avatar
Maarten Bosmans committed
987
       if (setjmp (png_jmpbuf(png_ptr))) {
988 989
	       success = FALSE;
	       goto cleanup;
990
       }
991 992 993 994 995

       if (num_keys > 0) {
               png_set_text (png_ptr, info_ptr, text_ptr, num_keys);
       }

996 997 998 999 1000 1001 1002 1003 1004 1005
       if (to_callback) {
               to_callback_ioptr.save_func = save_func;
               to_callback_ioptr.user_data = user_data;
               to_callback_ioptr.error = error;
               png_set_write_fn (png_ptr, &to_callback_ioptr,
                                 png_save_to_callback_write_func,
                                 png_save_to_callback_flush_func);
       } else {
               png_init_io (png_ptr, f);
       }
1006

1007 1008 1009
       if (compression >= 0)
               png_set_compression_level (png_ptr, compression);

1010 1011 1012 1013 1014
#if defined(PNG_iCCP_SUPPORTED)
        /* the proper ICC profile title is encoded in the profile */
        if (icc_profile != NULL) {
                png_set_iCCP (png_ptr, info_ptr,
                              "ICC profile", PNG_COMPRESSION_TYPE_BASE,
1015
                              (png_bytep) icc_profile, icc_profile_size);
1016 1017 1018
        }
#endif

1019 1020
       if (has_alpha) {
               png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
Havoc Pennington's avatar
Havoc Pennington committed
1021 1022
                             PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
                             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1023 1024
       } else {
               png_set_IHDR (png_ptr, info_ptr, w, h, bpc,
Havoc Pennington's avatar
Havoc Pennington committed
1025 1026
                             PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
                             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
       }
       sig_bit.red = bpc;
       sig_bit.green = bpc;
       sig_bit.blue = bpc;
       sig_bit.alpha = bpc;
       png_set_sBIT (png_ptr, info_ptr, &sig_bit);
       png_write_info (png_ptr, info_ptr);
       png_set_shift (png_ptr, &sig_bit);
       png_set_packing (png_ptr);

       ptr = pixels;
       for (y = 0; y < h; y++) {
1039
               row_ptr = (png_bytep)ptr;
1040 1041 1042 1043 1044
               png_write_rows (png_ptr, &row_ptr, 1);
               ptr += rowstride;
       }

       png_write_end (png_ptr, info_ptr);
1045 1046

cleanup:
1047 1048
        if (png_ptr != NULL)
                png_destroy_write_struct (&png_ptr, &info_ptr);
1049

1050 1051 1052 1053 1054 1055 1056
        g_free (icc_profile);

        if (text_ptr != NULL) {
                for (i = 0; i < num_keys; i++)
                        g_free (text_ptr[i].text);
                g_free (text_ptr);
        }
1057

1058
       return success;
1059 1060
}

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
static gboolean
gdk_pixbuf__png_image_save (FILE          *f, 
                            GdkPixbuf     *pixbuf, 
                            gchar        **keys,
                            gchar        **values,
                            GError       **error)
{
        return real_save_png (pixbuf, keys, values, error,
                              FALSE, f, NULL, NULL);
}

static gboolean
gdk_pixbuf__png_image_save_to_callback (GdkPixbufSaveFunc   save_func,
                                        gpointer            user_data,
                                        GdkPixbuf          *pixbuf, 
                                        gchar             **keys,
                                        gchar             **values,
                                        GError            **error)
{
        return real_save_png (pixbuf, keys, values, error,
                              TRUE, NULL, save_func, user_data);
}

1084
#ifndef INCLUDE_png
1085
#define MODULE_ENTRY(function) G_MODULE_EXPORT void function
1086
#else
1087
#define MODULE_ENTRY(function) void _gdk_pixbuf__png_ ## function
1088 1089
#endif

1090
MODULE_ENTRY (fill_vtable) (GdkPixbufModule *module)
1091 1092 1093 1094 1095 1096
{
        module->load = gdk_pixbuf__png_image_load;
        module->begin_load = gdk_pixbuf__png_image_begin_load;
        module->stop_load = gdk_pixbuf__png_image_stop_load;
        module->load_increment = gdk_pixbuf__png_image_load_increment;
        module->save = gdk_pixbuf__png_image_save;
1097
        module->save_to_callback = gdk_pixbuf__png_image_save_to_callback;
1098
}
1099

1100
MODULE_ENTRY (fill_info) (GdkPixbufFormat *info)
1101
{
1102
        static const GdkPixbufModulePattern signature[] = {
1103 1104 1105
                { "\x89PNG\r\n\x1a\x0a", NULL, 100 },
                { NULL, NULL, 0 }
        };
1106
	static const gchar *mime_types[] = {
1107 1108 1109
		"image/png",
		NULL
	};
1110
	static const gchar *extensions[] = {
1111 1112 1113 1114 1115
		"png",
		NULL
	};

	info->name = "png";
1116
        info->signature = (GdkPixbufModulePattern *) signature;
1117
	info->description = N_("The PNG image format");
1118 1119
	info->mime_types = (gchar **) mime_types;
	info->extensions = (gchar **) extensions;
1120
	info->flags = GDK_PIXBUF_FORMAT_WRITABLE | GDK_PIXBUF_FORMAT_THREADSAFE;
1121
	info->license = "LGPL";
1122
}