pngwutil.c

Go to the documentation of this file.
00001 
00002 /* pngwutil.c - utilities to write a PNG file
00003  *
00004  * Last changed in libpng 1.2.20 Septhember 3, 2007
00005  * For conditions of distribution and use, see copyright notice in png.h
00006  * Copyright (c) 1998-2007 Glenn Randers-Pehrson
00007  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
00008  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
00009  */
00010 
00011 #define PNG_INTERNAL
00012 #include "png.h"
00013 #ifdef PNG_WRITE_SUPPORTED
00014 
00015 /* Place a 32-bit number into a buffer in PNG byte order.  We work
00016  * with unsigned numbers for convenience, although one supported
00017  * ancillary chunk uses signed (two's complement) numbers.
00018  */
00019 void PNGAPI
00020 png_save_uint_32(png_bytep buf, png_uint_32 i)
00021 {
00022    buf[0] = (png_byte)((i >> 24) & 0xff);
00023    buf[1] = (png_byte)((i >> 16) & 0xff);
00024    buf[2] = (png_byte)((i >> 8) & 0xff);
00025    buf[3] = (png_byte)(i & 0xff);
00026 }
00027 
00028 /* The png_save_int_32 function assumes integers are stored in two's
00029  * complement format.  If this isn't the case, then this routine needs to
00030  * be modified to write data in two's complement format.
00031  */
00032 void PNGAPI
00033 png_save_int_32(png_bytep buf, png_int_32 i)
00034 {
00035    buf[0] = (png_byte)((i >> 24) & 0xff);
00036    buf[1] = (png_byte)((i >> 16) & 0xff);
00037    buf[2] = (png_byte)((i >> 8) & 0xff);
00038    buf[3] = (png_byte)(i & 0xff);
00039 }
00040 
00041 /* Place a 16-bit number into a buffer in PNG byte order.
00042  * The parameter is declared unsigned int, not png_uint_16,
00043  * just to avoid potential problems on pre-ANSI C compilers.
00044  */
00045 void PNGAPI
00046 png_save_uint_16(png_bytep buf, unsigned int i)
00047 {
00048    buf[0] = (png_byte)((i >> 8) & 0xff);
00049    buf[1] = (png_byte)(i & 0xff);
00050 }
00051 
00052 /* Write a PNG chunk all at once.  The type is an array of ASCII characters
00053  * representing the chunk name.  The array must be at least 4 bytes in
00054  * length, and does not need to be null terminated.  To be safe, pass the
00055  * pre-defined chunk names here, and if you need a new one, define it
00056  * where the others are defined.  The length is the length of the data.
00057  * All the data must be present.  If that is not possible, use the
00058  * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
00059  * functions instead.
00060  */
00061 void PNGAPI
00062 png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
00063    png_bytep data, png_size_t length)
00064 {
00065    if(png_ptr == NULL) return;
00066    png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
00067    png_write_chunk_data(png_ptr, data, length);
00068    png_write_chunk_end(png_ptr);
00069 }
00070 
00071 /* Write the start of a PNG chunk.  The type is the chunk type.
00072  * The total_length is the sum of the lengths of all the data you will be
00073  * passing in png_write_chunk_data().
00074  */
00075 void PNGAPI
00076 png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
00077    png_uint_32 length)
00078 {
00079    png_byte buf[4];
00080    png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
00081    if(png_ptr == NULL) return;
00082 
00083    /* write the length */
00084    png_save_uint_32(buf, length);
00085    png_write_data(png_ptr, buf, (png_size_t)4);
00086 
00087    /* write the chunk name */
00088    png_write_data(png_ptr, chunk_name, (png_size_t)4);
00089    /* reset the crc and run it over the chunk name */
00090    png_reset_crc(png_ptr);
00091    png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
00092 }
00093 
00094 /* Write the data of a PNG chunk started with png_write_chunk_start().
00095  * Note that multiple calls to this function are allowed, and that the
00096  * sum of the lengths from these calls *must* add up to the total_length
00097  * given to png_write_chunk_start().
00098  */
00099 void PNGAPI
00100 png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
00101 {
00102    /* write the data, and run the CRC over it */
00103    if(png_ptr == NULL) return;
00104    if (data != NULL && length > 0)
00105    {
00106       png_calculate_crc(png_ptr, data, length);
00107       png_write_data(png_ptr, data, length);
00108    }
00109 }
00110 
00111 /* Finish a chunk started with png_write_chunk_start(). */
00112 void PNGAPI
00113 png_write_chunk_end(png_structp png_ptr)
00114 {
00115    png_byte buf[4];
00116 
00117    if(png_ptr == NULL) return;
00118 
00119    /* write the crc */
00120    png_save_uint_32(buf, png_ptr->crc);
00121 
00122    png_write_data(png_ptr, buf, (png_size_t)4);
00123 }
00124 
00125 /* Simple function to write the signature.  If we have already written
00126  * the magic bytes of the signature, or more likely, the PNG stream is
00127  * being embedded into another stream and doesn't need its own signature,
00128  * we should call png_set_sig_bytes() to tell libpng how many of the
00129  * bytes have already been written.
00130  */
00131 void /* PRIVATE */
00132 png_write_sig(png_structp png_ptr)
00133 {
00134    png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
00135    /* write the rest of the 8 byte signature */
00136    png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
00137       (png_size_t)8 - png_ptr->sig_bytes);
00138    if(png_ptr->sig_bytes < 3)
00139       png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
00140 }
00141 
00142 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
00143 /*
00144  * This pair of functions encapsulates the operation of (a) compressing a
00145  * text string, and (b) issuing it later as a series of chunk data writes.
00146  * The compression_state structure is shared context for these functions
00147  * set up by the caller in order to make the whole mess thread-safe.
00148  */
00149 
00150 typedef struct
00151 {
00152     char *input;   /* the uncompressed input data */
00153     int input_len;   /* its length */
00154     int num_output_ptr; /* number of output pointers used */
00155     int max_output_ptr; /* size of output_ptr */
00156     png_charpp output_ptr; /* array of pointers to output */
00157 } compression_state;
00158 
00159 /* compress given text into storage in the png_ptr structure */
00160 static int /* PRIVATE */
00161 png_text_compress(png_structp png_ptr,
00162         png_charp text, png_size_t text_len, int compression,
00163         compression_state *comp)
00164 {
00165    int ret;
00166 
00167    comp->num_output_ptr = 0;
00168    comp->max_output_ptr = 0;
00169    comp->output_ptr = NULL;
00170    comp->input = NULL;
00171    comp->input_len = 0;
00172 
00173    /* we may just want to pass the text right through */
00174    if (compression == PNG_TEXT_COMPRESSION_NONE)
00175    {
00176        comp->input = text;
00177        comp->input_len = text_len;
00178        return((int)text_len);
00179    }
00180 
00181    if (compression >= PNG_TEXT_COMPRESSION_LAST)
00182    {
00183 #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
00184       char msg[50];
00185       png_snprintf(msg, 50, "Unknown compression type %d", compression);
00186       png_warning(png_ptr, msg);
00187 #else
00188       png_warning(png_ptr, "Unknown compression type");
00189 #endif
00190    }
00191 
00192    /* We can't write the chunk until we find out how much data we have,
00193     * which means we need to run the compressor first and save the
00194     * output.  This shouldn't be a problem, as the vast majority of
00195     * comments should be reasonable, but we will set up an array of
00196     * malloc'd pointers to be sure.
00197     *
00198     * If we knew the application was well behaved, we could simplify this
00199     * greatly by assuming we can always malloc an output buffer large
00200     * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
00201     * and malloc this directly.  The only time this would be a bad idea is
00202     * if we can't malloc more than 64K and we have 64K of random input
00203     * data, or if the input string is incredibly large (although this
00204     * wouldn't cause a failure, just a slowdown due to swapping).
00205     */
00206 
00207    /* set up the compression buffers */
00208    png_ptr->zstream.avail_in = (uInt)text_len;
00209    png_ptr->zstream.next_in = (Bytef *)text;
00210    png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
00211    png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
00212 
00213    /* this is the same compression loop as in png_write_row() */
00214    do
00215    {
00216       /* compress the data */
00217       ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
00218       if (ret != Z_OK)
00219       {
00220          /* error */
00221          if (png_ptr->zstream.msg != NULL)
00222             png_error(png_ptr, png_ptr->zstream.msg);
00223          else
00224             png_error(png_ptr, "zlib error");
00225       }
00226       /* check to see if we need more room */
00227       if (!(png_ptr->zstream.avail_out))
00228       {
00229          /* make sure the output array has room */
00230          if (comp->num_output_ptr >= comp->max_output_ptr)
00231          {
00232             int old_max;
00233 
00234             old_max = comp->max_output_ptr;
00235             comp->max_output_ptr = comp->num_output_ptr + 4;
00236             if (comp->output_ptr != NULL)
00237             {
00238                png_charpp old_ptr;
00239 
00240                old_ptr = comp->output_ptr;
00241                comp->output_ptr = (png_charpp)png_malloc(png_ptr,
00242                   (png_uint_32)(comp->max_output_ptr *
00243                   png_sizeof (png_charpp)));
00244                png_memcpy(comp->output_ptr, old_ptr, old_max
00245                   * png_sizeof (png_charp));
00246                png_free(png_ptr, old_ptr);
00247             }
00248             else
00249                comp->output_ptr = (png_charpp)png_malloc(png_ptr,
00250                   (png_uint_32)(comp->max_output_ptr *
00251                   png_sizeof (png_charp)));
00252          }
00253 
00254          /* save the data */
00255          comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
00256             (png_uint_32)png_ptr->zbuf_size);
00257          png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
00258             png_ptr->zbuf_size);
00259          comp->num_output_ptr++;
00260 
00261          /* and reset the buffer */
00262          png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
00263          png_ptr->zstream.next_out = png_ptr->zbuf;
00264       }
00265    /* continue until we don't have any more to compress */
00266    } while (png_ptr->zstream.avail_in);
00267 
00268    /* finish the compression */
00269    do
00270    {
00271       /* tell zlib we are finished */
00272       ret = deflate(&png_ptr->zstream, Z_FINISH);
00273 
00274       if (ret == Z_OK)
00275       {
00276          /* check to see if we need more room */
00277          if (!(png_ptr->zstream.avail_out))
00278          {
00279             /* check to make sure our output array has room */
00280             if (comp->num_output_ptr >= comp->max_output_ptr)
00281             {
00282                int old_max;
00283 
00284                old_max = comp->max_output_ptr;
00285                comp->max_output_ptr = comp->num_output_ptr + 4;
00286                if (comp->output_ptr != NULL)
00287                {
00288                   png_charpp old_ptr;
00289 
00290                   old_ptr = comp->output_ptr;
00291                   /* This could be optimized to realloc() */
00292                   comp->output_ptr = (png_charpp)png_malloc(png_ptr,
00293                      (png_uint_32)(comp->max_output_ptr *
00294                      png_sizeof (png_charpp)));
00295                   png_memcpy(comp->output_ptr, old_ptr,
00296                      old_max * png_sizeof (png_charp));
00297                   png_free(png_ptr, old_ptr);
00298                }
00299                else
00300                   comp->output_ptr = (png_charpp)png_malloc(png_ptr,
00301                      (png_uint_32)(comp->max_output_ptr *
00302                      png_sizeof (png_charp)));
00303             }
00304 
00305             /* save off the data */
00306             comp->output_ptr[comp->num_output_ptr] =
00307                (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
00308             png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
00309                png_ptr->zbuf_size);
00310             comp->num_output_ptr++;
00311 
00312             /* and reset the buffer pointers */
00313             png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
00314             png_ptr->zstream.next_out = png_ptr->zbuf;
00315          }
00316       }
00317       else if (ret != Z_STREAM_END)
00318       {
00319          /* we got an error */
00320          if (png_ptr->zstream.msg != NULL)
00321             png_error(png_ptr, png_ptr->zstream.msg);
00322          else
00323             png_error(png_ptr, "zlib error");
00324       }
00325    } while (ret != Z_STREAM_END);
00326 
00327    /* text length is number of buffers plus last buffer */
00328    text_len = png_ptr->zbuf_size * comp->num_output_ptr;
00329    if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
00330       text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
00331 
00332    return((int)text_len);
00333 }
00334 
00335 /* ship the compressed text out via chunk writes */
00336 static void /* PRIVATE */
00337 png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
00338 {
00339    int i;
00340 
00341    /* handle the no-compression case */
00342    if (comp->input)
00343    {
00344        png_write_chunk_data(png_ptr, (png_bytep)comp->input,
00345                             (png_size_t)comp->input_len);
00346        return;
00347    }
00348 
00349    /* write saved output buffers, if any */
00350    for (i = 0; i < comp->num_output_ptr; i++)
00351    {
00352       png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
00353          png_ptr->zbuf_size);
00354       png_free(png_ptr, comp->output_ptr[i]);
00355       comp->output_ptr[i]=NULL;
00356    }
00357    if (comp->max_output_ptr != 0)
00358       png_free(png_ptr, comp->output_ptr);
00359       comp->output_ptr=NULL;
00360    /* write anything left in zbuf */
00361    if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
00362       png_write_chunk_data(png_ptr, png_ptr->zbuf,
00363          png_ptr->zbuf_size - png_ptr->zstream.avail_out);
00364 
00365    /* reset zlib for another zTXt/iTXt or image data */
00366    deflateReset(&png_ptr->zstream);
00367    png_ptr->zstream.data_type = Z_BINARY;
00368 }
00369 #endif
00370 
00371 /* Write the IHDR chunk, and update the png_struct with the necessary
00372  * information.  Note that the rest of this code depends upon this
00373  * information being correct.
00374  */
00375 void /* PRIVATE */
00376 png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
00377    int bit_depth, int color_type, int compression_type, int filter_type,
00378    int interlace_type)
00379 {
00380 #ifdef PNG_USE_LOCAL_ARRAYS
00381    PNG_IHDR;
00382 #endif
00383    png_byte buf[13]; /* buffer to store the IHDR info */
00384 
00385    png_debug(1, "in png_write_IHDR\n");
00386    /* Check that we have valid input data from the application info */
00387    switch (color_type)
00388    {
00389       case PNG_COLOR_TYPE_GRAY:
00390          switch (bit_depth)
00391          {
00392             case 1:
00393             case 2:
00394             case 4:
00395             case 8:
00396             case 16: png_ptr->channels = 1; break;
00397             default: png_error(png_ptr,"Invalid bit depth for grayscale image");
00398          }
00399          break;
00400       case PNG_COLOR_TYPE_RGB:
00401          if (bit_depth != 8 && bit_depth != 16)
00402             png_error(png_ptr, "Invalid bit depth for RGB image");
00403          png_ptr->channels = 3;
00404          break;
00405       case PNG_COLOR_TYPE_PALETTE:
00406          switch (bit_depth)
00407          {
00408             case 1:
00409             case 2:
00410             case 4:
00411             case 8: png_ptr->channels = 1; break;
00412             default: png_error(png_ptr, "Invalid bit depth for paletted image");
00413          }
00414          break;
00415       case PNG_COLOR_TYPE_GRAY_ALPHA:
00416          if (bit_depth != 8 && bit_depth != 16)
00417             png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
00418          png_ptr->channels = 2;
00419          break;
00420       case PNG_COLOR_TYPE_RGB_ALPHA:
00421          if (bit_depth != 8 && bit_depth != 16)
00422             png_error(png_ptr, "Invalid bit depth for RGBA image");
00423          png_ptr->channels = 4;
00424          break;
00425       default:
00426          png_error(png_ptr, "Invalid image color type specified");
00427    }
00428 
00429    if (compression_type != PNG_COMPRESSION_TYPE_BASE)
00430    {
00431       png_warning(png_ptr, "Invalid compression type specified");
00432       compression_type = PNG_COMPRESSION_TYPE_BASE;
00433    }
00434 
00435    /* Write filter_method 64 (intrapixel differencing) only if
00436     * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
00437     * 2. Libpng did not write a PNG signature (this filter_method is only
00438     *    used in PNG datastreams that are embedded in MNG datastreams) and
00439     * 3. The application called png_permit_mng_features with a mask that
00440     *    included PNG_FLAG_MNG_FILTER_64 and
00441     * 4. The filter_method is 64 and
00442     * 5. The color_type is RGB or RGBA
00443     */
00444    if (
00445 #if defined(PNG_MNG_FEATURES_SUPPORTED)
00446       !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
00447       ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
00448       (color_type == PNG_COLOR_TYPE_RGB ||
00449        color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
00450       (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
00451 #endif
00452       filter_type != PNG_FILTER_TYPE_BASE)
00453    {
00454       png_warning(png_ptr, "Invalid filter type specified");
00455       filter_type = PNG_FILTER_TYPE_BASE;
00456    }
00457 
00458 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
00459    if (interlace_type != PNG_INTERLACE_NONE &&
00460       interlace_type != PNG_INTERLACE_ADAM7)
00461    {
00462       png_warning(png_ptr, "Invalid interlace type specified");
00463       interlace_type = PNG_INTERLACE_ADAM7;
00464    }
00465 #else
00466    interlace_type=PNG_INTERLACE_NONE;
00467 #endif
00468 
00469    /* save off the relevent information */
00470    png_ptr->bit_depth = (png_byte)bit_depth;
00471    png_ptr->color_type = (png_byte)color_type;
00472    png_ptr->interlaced = (png_byte)interlace_type;
00473 #if defined(PNG_MNG_FEATURES_SUPPORTED)
00474    png_ptr->filter_type = (png_byte)filter_type;
00475 #endif
00476    png_ptr->compression_type = (png_byte)compression_type;
00477    png_ptr->width = width;
00478    png_ptr->height = height;
00479 
00480    png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
00481    png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
00482    /* set the usr info, so any transformations can modify it */
00483    png_ptr->usr_width = png_ptr->width;
00484    png_ptr->usr_bit_depth = png_ptr->bit_depth;
00485    png_ptr->usr_channels = png_ptr->channels;
00486 
00487    /* pack the header information into the buffer */
00488    png_save_uint_32(buf, width);
00489    png_save_uint_32(buf + 4, height);
00490    buf[8] = (png_byte)bit_depth;
00491    buf[9] = (png_byte)color_type;
00492    buf[10] = (png_byte)compression_type;
00493    buf[11] = (png_byte)filter_type;
00494    buf[12] = (png_byte)interlace_type;
00495 
00496    /* write the chunk */
00497    png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
00498 
00499    /* initialize zlib with PNG info */
00500    png_ptr->zstream.zalloc = png_zalloc;
00501    png_ptr->zstream.zfree = png_zfree;
00502    png_ptr->zstream.opaque = (voidpf)png_ptr;
00503    if (!(png_ptr->do_filter))
00504    {
00505       if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
00506          png_ptr->bit_depth < 8)
00507          png_ptr->do_filter = PNG_FILTER_NONE;
00508       else
00509          png_ptr->do_filter = PNG_ALL_FILTERS;
00510    }
00511    if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
00512    {
00513       if (png_ptr->do_filter != PNG_FILTER_NONE)
00514          png_ptr->zlib_strategy = Z_FILTERED;
00515       else
00516          png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
00517    }
00518    if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
00519       png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
00520    if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
00521       png_ptr->zlib_mem_level = 8;
00522    if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
00523       png_ptr->zlib_window_bits = 15;
00524    if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
00525       png_ptr->zlib_method = 8;
00526    if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
00527       png_ptr->zlib_method, png_ptr->zlib_window_bits,
00528       png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
00529        png_error(png_ptr, "zlib failed to initialize compressor");
00530    png_ptr->zstream.next_out = png_ptr->zbuf;
00531    png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
00532    /* libpng is not interested in zstream.data_type */
00533    /* set it to a predefined value, to avoid its evaluation inside zlib */
00534    png_ptr->zstream.data_type = Z_BINARY;
00535 
00536    png_ptr->mode = PNG_HAVE_IHDR;
00537 }
00538 
00539 /* write the palette.  We are careful not to trust png_color to be in the
00540  * correct order for PNG, so people can redefine it to any convenient
00541  * structure.
00542  */
00543 void /* PRIVATE */
00544 png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
00545 {
00546 #ifdef PNG_USE_LOCAL_ARRAYS
00547    PNG_PLTE;
00548 #endif
00549    png_uint_32 i;
00550    png_colorp pal_ptr;
00551    png_byte buf[3];
00552 
00553    png_debug(1, "in png_write_PLTE\n");
00554    if ((
00555 #if defined(PNG_MNG_FEATURES_SUPPORTED)
00556         !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
00557 #endif
00558         num_pal == 0) || num_pal > 256)
00559    {
00560      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
00561      {
00562         png_error(png_ptr, "Invalid number of colors in palette");
00563      }
00564      else
00565      {
00566         png_warning(png_ptr, "Invalid number of colors in palette");
00567         return;
00568      }
00569    }
00570 
00571    if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
00572    {
00573       png_warning(png_ptr,
00574         "Ignoring request to write a PLTE chunk in grayscale PNG");
00575       return;
00576    }
00577 
00578    png_ptr->num_palette = (png_uint_16)num_pal;
00579    png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
00580 
00581    png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
00582 #ifndef PNG_NO_POINTER_INDEXING
00583    for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
00584    {
00585       buf[0] = pal_ptr->red;
00586       buf[1] = pal_ptr->green;
00587       buf[2] = pal_ptr->blue;
00588       png_write_chunk_data(png_ptr, buf, (png_size_t)3);
00589    }
00590 #else
00591    /* This is a little slower but some buggy compilers need to do this instead */
00592    pal_ptr=palette;
00593    for (i = 0; i < num_pal; i++)
00594    {
00595       buf[0] = pal_ptr[i].red;
00596       buf[1] = pal_ptr[i].green;
00597       buf[2] = pal_ptr[i].blue;
00598       png_write_chunk_data(png_ptr, buf, (png_size_t)3);
00599    }
00600 #endif
00601    png_write_chunk_end(png_ptr);
00602    png_ptr->mode |= PNG_HAVE_PLTE;
00603 }
00604 
00605 /* write an IDAT chunk */
00606 void /* PRIVATE */
00607 png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
00608 {
00609 #ifdef PNG_USE_LOCAL_ARRAYS
00610    PNG_IDAT;
00611 #endif
00612    png_debug(1, "in png_write_IDAT\n");
00613 
00614    /* Optimize the CMF field in the zlib stream. */
00615    /* This hack of the zlib stream is compliant to the stream specification. */
00616    if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
00617        png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
00618    {
00619       unsigned int z_cmf = data[0];  /* zlib compression method and flags */
00620       if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
00621       {
00622          /* Avoid memory underflows and multiplication overflows. */
00623          /* The conditions below are practically always satisfied;
00624             however, they still must be checked. */
00625          if (length >= 2 &&
00626              png_ptr->height < 16384 && png_ptr->width < 16384)
00627          {
00628             png_uint_32 uncompressed_idat_size = png_ptr->height *
00629                ((png_ptr->width *
00630                png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
00631             unsigned int z_cinfo = z_cmf >> 4;
00632             unsigned int half_z_window_size = 1 << (z_cinfo + 7);
00633             while (uncompressed_idat_size <= half_z_window_size &&
00634                    half_z_window_size >= 256)
00635             {
00636                z_cinfo--;
00637                half_z_window_size >>= 1;
00638             }
00639             z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
00640             if (data[0] != (png_byte)z_cmf)
00641             {
00642                data[0] = (png_byte)z_cmf;
00643                data[1] &= 0xe0;
00644                data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
00645             }
00646          }
00647       }
00648       else
00649          png_error(png_ptr,
00650             "Invalid zlib compression method or flags in IDAT");
00651    }
00652 
00653    png_write_chunk(png_ptr, png_IDAT, data, length);
00654    png_ptr->mode |= PNG_HAVE_IDAT;
00655 }
00656 
00657 /* write an IEND chunk */
00658 void /* PRIVATE */
00659 png_write_IEND(png_structp png_ptr)
00660 {
00661 #ifdef PNG_USE_LOCAL_ARRAYS
00662    PNG_IEND;
00663 #endif
00664    png_debug(1, "in png_write_IEND\n");
00665    png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
00666      (png_size_t)0);
00667    png_ptr->mode |= PNG_HAVE_IEND;
00668 }
00669 
00670 #if defined(PNG_WRITE_gAMA_SUPPORTED)
00671 /* write a gAMA chunk */
00672 #ifdef PNG_FLOATING_POINT_SUPPORTED
00673 void /* PRIVATE */
00674 png_write_gAMA(png_structp png_ptr, double file_gamma)
00675 {
00676 #ifdef PNG_USE_LOCAL_ARRAYS
00677    PNG_gAMA;
00678 #endif
00679    png_uint_32 igamma;
00680    png_byte buf[4];
00681 
00682    png_debug(1, "in png_write_gAMA\n");
00683    /* file_gamma is saved in 1/100,000ths */
00684    igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
00685    png_save_uint_32(buf, igamma);
00686    png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
00687 }
00688 #endif
00689 #ifdef PNG_FIXED_POINT_SUPPORTED
00690 void /* PRIVATE */
00691 png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
00692 {
00693 #ifdef PNG_USE_LOCAL_ARRAYS
00694    PNG_gAMA;
00695 #endif
00696    png_byte buf[4];
00697 
00698    png_debug(1, "in png_write_gAMA\n");
00699    /* file_gamma is saved in 1/100,000ths */
00700    png_save_uint_32(buf, (png_uint_32)file_gamma);
00701    png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
00702 }
00703 #endif
00704 #endif
00705 
00706 #if defined(PNG_WRITE_sRGB_SUPPORTED)
00707 /* write a sRGB chunk */
00708 void /* PRIVATE */
00709 png_write_sRGB(png_structp png_ptr, int srgb_intent)
00710 {
00711 #ifdef PNG_USE_LOCAL_ARRAYS
00712    PNG_sRGB;
00713 #endif
00714    png_byte buf[1];
00715 
00716    png_debug(1, "in png_write_sRGB\n");
00717    if(srgb_intent >= PNG_sRGB_INTENT_LAST)
00718          png_warning(png_ptr,
00719             "Invalid sRGB rendering intent specified");
00720    buf[0]=(png_byte)srgb_intent;
00721    png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
00722 }
00723 #endif
00724 
00725 #if defined(PNG_WRITE_iCCP_SUPPORTED)
00726 /* write an iCCP chunk */
00727 void /* PRIVATE */
00728 png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
00729    png_charp profile, int profile_len)
00730 {
00731 #ifdef PNG_USE_LOCAL_ARRAYS
00732    PNG_iCCP;
00733 #endif
00734    png_size_t name_len;
00735    png_charp new_name;
00736    compression_state comp;
00737    int embedded_profile_len = 0;
00738 
00739    png_debug(1, "in png_write_iCCP\n");
00740 
00741    comp.num_output_ptr = 0;
00742    comp.max_output_ptr = 0;
00743    comp.output_ptr = NULL;
00744    comp.input = NULL;
00745    comp.input_len = 0;
00746 
00747    if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
00748       &new_name)) == 0)
00749    {
00750       png_warning(png_ptr, "Empty keyword in iCCP chunk");
00751       return;
00752    }
00753 
00754    if (compression_type != PNG_COMPRESSION_TYPE_BASE)
00755       png_warning(png_ptr, "Unknown compression type in iCCP chunk");
00756 
00757    if (profile == NULL)
00758       profile_len = 0;
00759 
00760    if (profile_len > 3)
00761       embedded_profile_len =
00762           ((*( (png_bytep)profile  ))<<24) |
00763           ((*( (png_bytep)profile+1))<<16) |
00764           ((*( (png_bytep)profile+2))<< 8) |
00765           ((*( (png_bytep)profile+3))    );
00766 
00767    if (profile_len < embedded_profile_len)
00768      {
00769         png_warning(png_ptr,
00770           "Embedded profile length too large in iCCP chunk");
00771         return;
00772      }
00773 
00774    if (profile_len > embedded_profile_len)
00775      {
00776         png_warning(png_ptr,
00777           "Truncating profile to actual length in iCCP chunk");
00778         profile_len = embedded_profile_len;
00779      }
00780 
00781    if (profile_len)
00782        profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
00783           PNG_COMPRESSION_TYPE_BASE, &comp);
00784 
00785    /* make sure we include the NULL after the name and the compression type */
00786    png_write_chunk_start(png_ptr, png_iCCP,
00787           (png_uint_32)name_len+profile_len+2);
00788    new_name[name_len+1]=0x00;
00789    png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
00790 
00791    if (profile_len)
00792       png_write_compressed_data_out(png_ptr, &comp);
00793 
00794    png_write_chunk_end(png_ptr);
00795    png_free(png_ptr, new_name);
00796 }
00797 #endif
00798 
00799 #if defined(PNG_WRITE_sPLT_SUPPORTED)
00800 /* write a sPLT chunk */
00801 void /* PRIVATE */
00802 png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
00803 {
00804 #ifdef PNG_USE_LOCAL_ARRAYS
00805    PNG_sPLT;
00806 #endif
00807    png_size_t name_len;
00808    png_charp new_name;
00809    png_byte entrybuf[10];
00810    int entry_size = (spalette->depth == 8 ? 6 : 10);
00811    int palette_size = entry_size * spalette->nentries;
00812    png_sPLT_entryp ep;
00813 #ifdef PNG_NO_POINTER_INDEXING
00814    int i;
00815 #endif
00816 
00817    png_debug(1, "in png_write_sPLT\n");
00818    if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
00819       spalette->name, &new_name))==0)
00820    {
00821       png_warning(png_ptr, "Empty keyword in sPLT chunk");
00822       return;
00823    }
00824 
00825    /* make sure we include the NULL after the name */
00826    png_write_chunk_start(png_ptr, png_sPLT,
00827           (png_uint_32)(name_len + 2 + palette_size));
00828    png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
00829    png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
00830 
00831    /* loop through each palette entry, writing appropriately */
00832 #ifndef PNG_NO_POINTER_INDEXING
00833    for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
00834    {
00835        if (spalette->depth == 8)
00836        {
00837            entrybuf[0] = (png_byte)ep->red;
00838            entrybuf[1] = (png_byte)ep->green;
00839            entrybuf[2] = (png_byte)ep->blue;
00840            entrybuf[3] = (png_byte)ep->alpha;
00841            png_save_uint_16(entrybuf + 4, ep->frequency);
00842        }
00843        else
00844        {
00845            png_save_uint_16(entrybuf + 0, ep->red);
00846            png_save_uint_16(entrybuf + 2, ep->green);
00847            png_save_uint_16(entrybuf + 4, ep->blue);
00848            png_save_uint_16(entrybuf + 6, ep->alpha);
00849            png_save_uint_16(entrybuf + 8, ep->frequency);
00850        }
00851        png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
00852    }
00853 #else
00854    ep=spalette->entries;
00855    for (i=0; i>spalette->nentries; i++)
00856    {
00857        if (spalette->depth == 8)
00858        {
00859            entrybuf[0] = (png_byte)ep[i].red;
00860            entrybuf[1] = (png_byte)ep[i].green;
00861            entrybuf[2] = (png_byte)ep[i].blue;
00862            entrybuf[3] = (png_byte)ep[i].alpha;
00863            png_save_uint_16(entrybuf + 4, ep[i].frequency);
00864        }
00865        else
00866        {
00867            png_save_uint_16(entrybuf + 0, ep[i].red);
00868            png_save_uint_16(entrybuf + 2, ep[i].green);
00869            png_save_uint_16(entrybuf + 4, ep[i].blue);
00870            png_save_uint_16(entrybuf + 6, ep[i].alpha);
00871            png_save_uint_16(entrybuf + 8, ep[i].frequency);
00872        }
00873        png_write_chunk_data(png_ptr, entrybuf, entry_size);
00874    }
00875 #endif
00876 
00877    png_write_chunk_end(png_ptr);
00878    png_free(png_ptr, new_name);
00879 }
00880 #endif
00881 
00882 #if defined(PNG_WRITE_sBIT_SUPPORTED)
00883 /* write the sBIT chunk */
00884 void /* PRIVATE */
00885 png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
00886 {
00887 #ifdef PNG_USE_LOCAL_ARRAYS
00888    PNG_sBIT;
00889 #endif
00890    png_byte buf[4];
00891    png_size_t size;
00892 
00893    png_debug(1, "in png_write_sBIT\n");
00894    /* make sure we don't depend upon the order of PNG_COLOR_8 */
00895    if (color_type & PNG_COLOR_MASK_COLOR)
00896    {
00897       png_byte maxbits;
00898 
00899       maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
00900                 png_ptr->usr_bit_depth);
00901       if (sbit->red == 0 || sbit->red > maxbits ||
00902           sbit->green == 0 || sbit->green > maxbits ||
00903           sbit->blue == 0 || sbit->blue > maxbits)
00904       {
00905          png_warning(png_ptr, "Invalid sBIT depth specified");
00906          return;
00907       }
00908       buf[0] = sbit->red;
00909       buf[1] = sbit->green;
00910       buf[2] = sbit->blue;
00911       size = 3;
00912    }
00913    else
00914    {
00915       if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
00916       {
00917          png_warning(png_ptr, "Invalid sBIT depth specified");
00918          return;
00919       }
00920       buf[0] = sbit->gray;
00921       size = 1;
00922    }
00923 
00924    if (color_type & PNG_COLOR_MASK_ALPHA)
00925    {
00926       if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
00927       {
00928          png_warning(png_ptr, "Invalid sBIT depth specified");
00929          return;
00930       }
00931       buf[size++] = sbit->alpha;
00932    }
00933 
00934    png_write_chunk(png_ptr, png_sBIT, buf, size);
00935 }
00936 #endif
00937 
00938 #if defined(PNG_WRITE_cHRM_SUPPORTED)
00939 /* write the cHRM chunk */
00940 #ifdef PNG_FLOATING_POINT_SUPPORTED
00941 void /* PRIVATE */
00942 png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
00943    double red_x, double red_y, double green_x, double green_y,
00944    double blue_x, double blue_y)
00945 {
00946 #ifdef PNG_USE_LOCAL_ARRAYS
00947    PNG_cHRM;
00948 #endif
00949    png_byte buf[32];
00950    png_uint_32 itemp;
00951 
00952    png_debug(1, "in png_write_cHRM\n");
00953    /* each value is saved in 1/100,000ths */
00954    if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
00955        white_x + white_y > 1.0)
00956    {
00957       png_warning(png_ptr, "Invalid cHRM white point specified");
00958 #if !defined(PNG_NO_CONSOLE_IO)
00959       fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
00960 #endif
00961       return;
00962    }
00963    itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
00964    png_save_uint_32(buf, itemp);
00965    itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
00966    png_save_uint_32(buf + 4, itemp);
00967 
00968    if (red_x < 0 ||  red_y < 0 || red_x + red_y > 1.0)
00969    {
00970       png_warning(png_ptr, "Invalid cHRM red point specified");
00971       return;
00972    }
00973    itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
00974    png_save_uint_32(buf + 8, itemp);
00975    itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
00976    png_save_uint_32(buf + 12, itemp);
00977 
00978    if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
00979    {
00980       png_warning(png_ptr, "Invalid cHRM green point specified");
00981       return;
00982    }
00983    itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
00984    png_save_uint_32(buf + 16, itemp);
00985    itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
00986    png_save_uint_32(buf + 20, itemp);
00987 
00988    if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
00989    {
00990       png_warning(png_ptr, "Invalid cHRM blue point specified");
00991       return;
00992    }
00993    itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
00994    png_save_uint_32(buf + 24, itemp);
00995    itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
00996    png_save_uint_32(buf + 28, itemp);
00997 
00998    png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
00999 }
01000 #endif
01001 #ifdef PNG_FIXED_POINT_SUPPORTED
01002 void /* PRIVATE */
01003 png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
01004    png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
01005    png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
01006    png_fixed_point blue_y)
01007 {
01008 #ifdef PNG_USE_LOCAL_ARRAYS
01009    PNG_cHRM;
01010 #endif
01011    png_byte buf[32];
01012 
01013    png_debug(1, "in png_write_cHRM\n");
01014    /* each value is saved in 1/100,000ths */
01015    if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
01016    {
01017       png_warning(png_ptr, "Invalid fixed cHRM white point specified");
01018 #if !defined(PNG_NO_CONSOLE_IO)
01019       fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
01020 #endif
01021       return;
01022    }
01023    png_save_uint_32(buf, (png_uint_32)white_x);
01024    png_save_uint_32(buf + 4, (png_uint_32)white_y);
01025 
01026    if (red_x + red_y > 100000L)
01027    {
01028       png_warning(png_ptr, "Invalid cHRM fixed red point specified");
01029       return;
01030    }
01031    png_save_uint_32(buf + 8, (png_uint_32)red_x);
01032    png_save_uint_32(buf + 12, (png_uint_32)red_y);
01033 
01034    if (green_x + green_y > 100000L)
01035    {
01036       png_warning(png_ptr, "Invalid fixed cHRM green point specified");
01037       return;
01038    }
01039    png_save_uint_32(buf + 16, (png_uint_32)green_x);
01040    png_save_uint_32(buf + 20, (png_uint_32)green_y);
01041 
01042    if (blue_x + blue_y > 100000L)
01043    {
01044       png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
01045       return;
01046    }
01047    png_save_uint_32(buf + 24, (png_uint_32)blue_x);
01048    png_save_uint_32(buf + 28, (png_uint_32)blue_y);
01049 
01050    png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
01051 }
01052 #endif
01053 #endif
01054 
01055 #if defined(PNG_WRITE_tRNS_SUPPORTED)
01056 /* write the tRNS chunk */
01057 void /* PRIVATE */
01058 png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
01059    int num_trans, int color_type)
01060 {
01061 #ifdef PNG_USE_LOCAL_ARRAYS
01062    PNG_tRNS;
01063 #endif
01064    png_byte buf[6];
01065 
01066    png_debug(1, "in png_write_tRNS\n");
01067    if (color_type == PNG_COLOR_TYPE_PALETTE)
01068    {
01069       if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
01070       {
01071          png_warning(png_ptr,"Invalid number of transparent colors specified");
01072          return;
01073       }
01074       /* write the chunk out as it is */
01075       png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
01076    }
01077    else if (color_type == PNG_COLOR_TYPE_GRAY)
01078    {
01079       /* one 16 bit value */
01080       if(tran->gray >= (1 << png_ptr->bit_depth))
01081       {
01082          png_warning(png_ptr,
01083            "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
01084          return;
01085       }
01086       png_save_uint_16(buf, tran->gray);
01087       png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
01088    }
01089    else if (color_type == PNG_COLOR_TYPE_RGB)
01090    {
01091       /* three 16 bit values */
01092       png_save_uint_16(buf, tran->red);
01093       png_save_uint_16(buf + 2, tran->green);
01094       png_save_uint_16(buf + 4, tran->blue);
01095       if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
01096          {
01097             png_warning(png_ptr,
01098               "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
01099             return;
01100          }
01101       png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
01102    }
01103    else
01104    {
01105       png_warning(png_ptr, "Can't write tRNS with an alpha channel");
01106    }
01107 }
01108 #endif
01109 
01110 #if defined(PNG_WRITE_bKGD_SUPPORTED)
01111 /* write the background chunk */
01112 void /* PRIVATE */
01113 png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
01114 {
01115 #ifdef PNG_USE_LOCAL_ARRAYS
01116    PNG_bKGD;
01117 #endif
01118    png_byte buf[6];
01119 
01120    png_debug(1, "in png_write_bKGD\n");
01121    if (color_type == PNG_COLOR_TYPE_PALETTE)
01122    {
01123       if (
01124 #if defined(PNG_MNG_FEATURES_SUPPORTED)
01125           (png_ptr->num_palette ||
01126           (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
01127 #endif
01128          back->index > png_ptr->num_palette)
01129       {
01130          png_warning(png_ptr, "Invalid background palette index");
01131          return;
01132       }
01133       buf[0] = back->index;
01134       png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
01135    }
01136    else if (color_type & PNG_COLOR_MASK_COLOR)
01137    {
01138       png_save_uint_16(buf, back->red);
01139       png_save_uint_16(buf + 2, back->green);
01140       png_save_uint_16(buf + 4, back->blue);
01141       if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
01142          {
01143             png_warning(png_ptr,
01144               "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
01145             return;
01146          }
01147       png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
01148    }
01149    else
01150    {
01151       if(back->gray >= (1 << png_ptr->bit_depth))
01152       {
01153          png_warning(png_ptr,
01154            "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
01155          return;
01156       }
01157       png_save_uint_16(buf, back->gray);
01158       png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
01159    }
01160 }
01161 #endif
01162 
01163 #if defined(PNG_WRITE_hIST_SUPPORTED)
01164 /* write the histogram */
01165 void /* PRIVATE */
01166 png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
01167 {
01168 #ifdef PNG_USE_LOCAL_ARRAYS
01169    PNG_hIST;
01170 #endif
01171    int i;
01172    png_byte buf[3];
01173 
01174    png_debug(1, "in png_write_hIST\n");
01175    if (num_hist > (int)png_ptr->num_palette)
01176    {
01177       png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
01178          png_ptr->num_palette);
01179       png_warning(png_ptr, "Invalid number of histogram entries specified");
01180       return;
01181    }
01182 
01183    png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
01184    for (i = 0; i < num_hist; i++)
01185    {
01186       png_save_uint_16(buf, hist[i]);
01187       png_write_chunk_data(png_ptr, buf, (png_size_t)2);
01188    }
01189    png_write_chunk_end(png_ptr);
01190 }
01191 #endif
01192 
01193 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
01194     defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
01195 /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
01196  * and if invalid, correct the keyword rather than discarding the entire
01197  * chunk.  The PNG 1.0 specification requires keywords 1-79 characters in
01198  * length, forbids leading or trailing whitespace, multiple internal spaces,
01199  * and the non-break space (0x80) from ISO 8859-1.  Returns keyword length.
01200  *
01201  * The new_key is allocated to hold the corrected keyword and must be freed
01202  * by the calling routine.  This avoids problems with trying to write to
01203  * static keywords without having to have duplicate copies of the strings.
01204  */
01205 png_size_t /* PRIVATE */
01206 png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
01207 {
01208    png_size_t key_len;
01209    png_charp kp, dp;
01210    int kflag;
01211    int kwarn=0;
01212 
01213    png_debug(1, "in png_check_keyword\n");
01214    *new_key = NULL;
01215 
01216    if (key == NULL || (key_len = png_strlen(key)) == 0)
01217    {
01218       png_warning(png_ptr, "zero length keyword");
01219       return ((png_size_t)0);
01220    }
01221 
01222    png_debug1(2, "Keyword to be checked is '%s'\n", key);
01223 
01224    *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
01225    if (*new_key == NULL)
01226    {
01227       png_warning(png_ptr, "Out of memory while procesing keyword");
01228       return ((png_size_t)0);
01229    }
01230 
01231    /* Replace non-printing characters with a blank and print a warning */
01232    for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
01233    {
01234       if ((png_byte)*kp < 0x20 ||
01235          ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
01236       {
01237 #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
01238          char msg[40];
01239 
01240          png_snprintf(msg, 40,
01241            "invalid keyword character 0x%02X", (png_byte)*kp);
01242          png_warning(png_ptr, msg);
01243 #else
01244          png_warning(png_ptr, "invalid character in keyword");
01245 #endif
01246          *dp = ' ';
01247       }
01248       else
01249       {
01250          *dp = *kp;
01251       }
01252    }
01253    *dp = '\0';
01254 
01255    /* Remove any trailing white space. */
01256    kp = *new_key + key_len - 1;
01257    if (*kp == ' ')
01258    {
01259       png_warning(png_ptr, "trailing spaces removed from keyword");
01260 
01261       while (*kp == ' ')
01262       {
01263         *(kp--) = '\0';
01264         key_len--;
01265       }
01266    }
01267 
01268    /* Remove any leading white space. */
01269    kp = *new_key;
01270    if (*kp == ' ')
01271    {
01272       png_warning(png_ptr, "leading spaces removed from keyword");
01273 
01274       while (*kp == ' ')
01275       {
01276         kp++;
01277         key_len--;
01278       }
01279    }
01280 
01281    png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
01282 
01283    /* Remove multiple internal spaces. */
01284    for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
01285    {
01286       if (*kp == ' ' && kflag == 0)
01287       {
01288          *(dp++) = *kp;
01289          kflag = 1;
01290       }
01291       else if (*kp == ' ')
01292       {
01293          key_len--;
01294          kwarn=1;
01295       }
01296       else
01297       {
01298          *(dp++) = *kp;
01299          kflag = 0;
01300       }
01301    }
01302    *dp = '\0';
01303    if(kwarn)
01304       png_warning(png_ptr, "extra interior spaces removed from keyword");
01305 
01306    if (key_len == 0)
01307    {
01308       png_free(png_ptr, *new_key);
01309       *new_key=NULL;
01310       png_warning(png_ptr, "Zero length keyword");
01311    }
01312 
01313    if (key_len > 79)
01314    {
01315       png_warning(png_ptr, "keyword length must be 1 - 79 characters");
01316       new_key[79] = '\0';
01317       key_len = 79;
01318    }
01319 
01320    return (key_len);
01321 }
01322 #endif
01323 
01324 #if defined(PNG_WRITE_tEXt_SUPPORTED)
01325 /* write a tEXt chunk */
01326 void /* PRIVATE */
01327 png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
01328    png_size_t text_len)
01329 {
01330 #ifdef PNG_USE_LOCAL_ARRAYS
01331    PNG_tEXt;
01332 #endif
01333    png_size_t key_len;
01334    png_charp new_key;
01335 
01336    png_debug(1, "in png_write_tEXt\n");
01337    if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
01338    {
01339       png_warning(png_ptr, "Empty keyword in tEXt chunk");
01340       return;
01341    }
01342 
01343    if (text == NULL || *text == '\0')
01344       text_len = 0;
01345    else
01346       text_len = png_strlen(text);
01347 
01348    /* make sure we include the 0 after the key */
01349    png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
01350    /*
01351     * We leave it to the application to meet PNG-1.0 requirements on the
01352     * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
01353     * any non-Latin-1 characters except for NEWLINE.  ISO PNG will forbid them.
01354     * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
01355     */
01356    png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
01357    if (text_len)
01358       png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
01359 
01360    png_write_chunk_end(png_ptr);
01361    png_free(png_ptr, new_key);
01362 }
01363 #endif
01364 
01365 #if defined(PNG_WRITE_zTXt_SUPPORTED)
01366 /* write a compressed text chunk */
01367 void /* PRIVATE */
01368 png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
01369    png_size_t text_len, int compression)
01370 {
01371 #ifdef PNG_USE_LOCAL_ARRAYS
01372    PNG_zTXt;
01373 #endif
01374    png_size_t key_len;
01375    char buf[1];
01376    png_charp new_key;
01377    compression_state comp;
01378 
01379    png_debug(1, "in png_write_zTXt\n");
01380 
01381    comp.num_output_ptr = 0;
01382    comp.max_output_ptr = 0;
01383    comp.output_ptr = NULL;
01384    comp.input = NULL;
01385    comp.input_len = 0;
01386 
01387    if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
01388    {
01389       png_warning(png_ptr, "Empty keyword in zTXt chunk");
01390       return;
01391    }
01392 
01393    if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
01394    {
01395       png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
01396       png_free(png_ptr, new_key);
01397       return;
01398    }
01399 
01400    text_len = png_strlen(text);
01401 
01402    /* compute the compressed data; do it now for the length */
01403    text_len = png_text_compress(png_ptr, text, text_len, compression,
01404        &comp);
01405 
01406    /* write start of chunk */
01407    png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
01408       (key_len+text_len+2));
01409    /* write key */
01410    png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
01411    png_free(png_ptr, new_key);
01412 
01413    buf[0] = (png_byte)compression;
01414    /* write compression */
01415    png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
01416    /* write the compressed data */
01417    png_write_compressed_data_out(png_ptr, &comp);
01418 
01419    /* close the chunk */
01420    png_write_chunk_end(png_ptr);
01421 }
01422 #endif
01423 
01424 #if defined(PNG_WRITE_iTXt_SUPPORTED)
01425 /* write an iTXt chunk */
01426 void /* PRIVATE */
01427 png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
01428     png_charp lang, png_charp lang_key, png_charp text)
01429 {
01430 #ifdef PNG_USE_LOCAL_ARRAYS
01431    PNG_iTXt;
01432 #endif
01433    png_size_t lang_len, key_len, lang_key_len, text_len;
01434    png_charp new_lang, new_key;
01435    png_byte cbuf[2];
01436    compression_state comp;
01437 
01438    png_debug(1, "in png_write_iTXt\n");
01439 
01440    comp.num_output_ptr = 0;
01441    comp.max_output_ptr = 0;
01442    comp.output_ptr = NULL;
01443    comp.input = NULL;
01444 
01445    if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
01446    {
01447       png_warning(png_ptr, "Empty keyword in iTXt chunk");
01448       return;
01449    }
01450    if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
01451    {
01452       png_warning(png_ptr, "Empty language field in iTXt chunk");
01453       new_lang = NULL;
01454       lang_len = 0;
01455    }
01456 
01457    if (lang_key == NULL)
01458      lang_key_len = 0;
01459    else
01460      lang_key_len = png_strlen(lang_key);
01461 
01462    if (text == NULL)
01463       text_len = 0;
01464    else
01465      text_len = png_strlen(text);
01466 
01467    /* compute the compressed data; do it now for the length */
01468    text_len = png_text_compress(png_ptr, text, text_len, compression-2,
01469       &comp);
01470 
01471 
01472    /* make sure we include the compression flag, the compression byte,
01473     * and the NULs after the key, lang, and lang_key parts */
01474 
01475    png_write_chunk_start(png_ptr, png_iTXt,
01476           (png_uint_32)(
01477         5 /* comp byte, comp flag, terminators for key, lang and lang_key */
01478         + key_len
01479         + lang_len
01480         + lang_key_len
01481         + text_len));
01482 
01483    /*
01484     * We leave it to the application to meet PNG-1.0 requirements on the
01485     * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
01486     * any non-Latin-1 characters except for NEWLINE.  ISO PNG will forbid them.
01487     * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
01488     */
01489    png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
01490 
01491    /* set the compression flag */
01492    if (compression == PNG_ITXT_COMPRESSION_NONE || \
01493        compression == PNG_TEXT_COMPRESSION_NONE)
01494        cbuf[0] = 0;
01495    else /* compression == PNG_ITXT_COMPRESSION_zTXt */
01496        cbuf[0] = 1;
01497    /* set the compression method */
01498    cbuf[1] = 0;
01499    png_write_chunk_data(png_ptr, cbuf, 2);
01500 
01501    cbuf[0] = 0;
01502    png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
01503    png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
01504    png_write_compressed_data_out(png_ptr, &comp);
01505 
01506    png_write_chunk_end(png_ptr);
01507    png_free(png_ptr, new_key);
01508    if (new_lang)
01509      png_free(png_ptr, new_lang);
01510 }
01511 #endif
01512 
01513 #if defined(PNG_WRITE_oFFs_SUPPORTED)
01514 /* write the oFFs chunk */
01515 void /* PRIVATE */
01516 png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
01517    int unit_type)
01518 {
01519 #ifdef PNG_USE_LOCAL_ARRAYS
01520    PNG_oFFs;
01521 #endif
01522    png_byte buf[9];
01523 
01524    png_debug(1, "in png_write_oFFs\n");
01525    if (unit_type >= PNG_OFFSET_LAST)
01526       png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
01527 
01528    png_save_int_32(buf, x_offset);
01529    png_save_int_32(buf + 4, y_offset);
01530    buf[8] = (png_byte)unit_type;
01531 
01532    png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
01533 }
01534 #endif
01535 #if defined(PNG_WRITE_pCAL_SUPPORTED)
01536 /* write the pCAL chunk (described in the PNG extensions document) */
01537 void /* PRIVATE */
01538 png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
01539    png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
01540 {
01541 #ifdef PNG_USE_LOCAL_ARRAYS
01542    PNG_pCAL;
01543 #endif
01544    png_size_t purpose_len, units_len, total_len;
01545    png_uint_32p params_len;
01546    png_byte buf[10];
01547    png_charp new_purpose;
01548    int i;
01549 
01550    png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
01551    if (type >= PNG_EQUATION_LAST)
01552       png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
01553 
01554    purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
01555    png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
01556    units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
01557    png_debug1(3, "pCAL units length = %d\n", (int)units_len);
01558    total_len = purpose_len + units_len + 10;
01559 
01560    params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
01561       *png_sizeof(png_uint_32)));
01562 
01563    /* Find the length of each parameter, making sure we don't count the
01564       null terminator for the last parameter. */
01565    for (i = 0; i < nparams; i++)
01566    {
01567       params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
01568       png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
01569       total_len += (png_size_t)params_len[i];
01570    }
01571 
01572    png_debug1(3, "pCAL total length = %d\n", (int)total_len);
01573    png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
01574    png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
01575    png_save_int_32(buf, X0);
01576    png_save_int_32(buf + 4, X1);
01577    buf[8] = (png_byte)type;
01578    buf[9] = (png_byte)nparams;
01579    png_write_chunk_data(png_ptr, buf, (png_size_t)10);
01580    png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
01581 
01582    png_free(png_ptr, new_purpose);
01583 
01584    for (i = 0; i < nparams; i++)
01585    {
01586       png_write_chunk_data(png_ptr, (png_bytep)params[i],
01587          (png_size_t)params_len[i]);
01588    }
01589 
01590    png_free(png_ptr, params_len);
01591    png_write_chunk_end(png_ptr);
01592 }
01593 #endif
01594 
01595 #if defined(PNG_WRITE_sCAL_SUPPORTED)
01596 /* write the sCAL chunk */
01597 #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
01598 void /* PRIVATE */
01599 png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
01600 {
01601 #ifdef PNG_USE_LOCAL_ARRAYS
01602    PNG_sCAL;
01603 #endif
01604    char buf[64];
01605    png_size_t total_len;
01606 
01607    png_debug(1, "in png_write_sCAL\n");
01608 
01609    buf[0] = (char)unit;
01610 #if defined(_WIN32_WCE)
01611 /* sprintf() function is not supported on WindowsCE */
01612    {
01613       wchar_t wc_buf[32];
01614       size_t wc_len;
01615       swprintf(wc_buf, TEXT("%12.12e"), width);
01616       wc_len = wcslen(wc_buf);
01617       WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
01618       total_len = wc_len + 2;
01619       swprintf(wc_buf, TEXT("%12.12e"), height);
01620       wc_len = wcslen(wc_buf);
01621       WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
01622          NULL, NULL);
01623       total_len += wc_len;
01624    }
01625 #else
01626    png_snprintf(buf + 1, 63, "%12.12e", width);
01627    total_len = 1 + png_strlen(buf + 1) + 1;
01628    png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
01629    total_len += png_strlen(buf + total_len);
01630 #endif
01631 
01632    png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
01633    png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
01634 }
01635 #else
01636 #ifdef PNG_FIXED_POINT_SUPPORTED
01637 void /* PRIVATE */
01638 png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
01639    png_charp height)
01640 {
01641 #ifdef PNG_USE_LOCAL_ARRAYS
01642    PNG_sCAL;
01643 #endif
01644    png_byte buf[64];
01645    png_size_t wlen, hlen, total_len;
01646 
01647    png_debug(1, "in png_write_sCAL_s\n");
01648 
01649    wlen = png_strlen(width);
01650    hlen = png_strlen(height);
01651    total_len = wlen + hlen + 2;
01652    if (total_len > 64)
01653    {
01654       png_warning(png_ptr, "Can't write sCAL (buffer too small)");
01655       return;
01656    }
01657 
01658    buf[0] = (png_byte)unit;
01659    png_memcpy(buf + 1, width, wlen + 1);      /* append the '\0' here */
01660    png_memcpy(buf + wlen + 2, height, hlen);  /* do NOT append the '\0' here */
01661 
01662    png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
01663    png_write_chunk(png_ptr, png_sCAL, buf, total_len);
01664 }
01665 #endif
01666 #endif
01667 #endif
01668 
01669 #if defined(PNG_WRITE_pHYs_SUPPORTED)
01670 /* write the pHYs chunk */
01671 void /* PRIVATE */
01672 png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
01673    png_uint_32 y_pixels_per_unit,
01674    int unit_type)
01675 {
01676 #ifdef PNG_USE_LOCAL_ARRAYS
01677    PNG_pHYs;
01678 #endif
01679    png_byte buf[9];
01680 
01681    png_debug(1, "in png_write_pHYs\n");
01682    if (unit_type >= PNG_RESOLUTION_LAST)
01683       png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
01684 
01685    png_save_uint_32(buf, x_pixels_per_unit);
01686    png_save_uint_32(buf + 4, y_pixels_per_unit);
01687    buf[8] = (png_byte)unit_type;
01688 
01689    png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
01690 }
01691 #endif
01692 
01693 #if defined(PNG_WRITE_tIME_SUPPORTED)
01694 /* Write the tIME chunk.  Use either png_convert_from_struct_tm()
01695  * or png_convert_from_time_t(), or fill in the structure yourself.
01696  */
01697 void /* PRIVATE */
01698 png_write_tIME(png_structp png_ptr, png_timep mod_time)
01699 {
01700 #ifdef PNG_USE_LOCAL_ARRAYS
01701    PNG_tIME;
01702 #endif
01703    png_byte buf[7];
01704 
01705    png_debug(1, "in png_write_tIME\n");
01706    if (mod_time->month  > 12 || mod_time->month  < 1 ||
01707        mod_time->day    > 31 || mod_time->day    < 1 ||
01708        mod_time->hour   > 23 || mod_time->second > 60)
01709    {
01710       png_warning(png_ptr, "Invalid time specified for tIME chunk");
01711       return;
01712    }
01713 
01714    png_save_uint_16(buf, mod_time->year);
01715    buf[2] = mod_time->month;
01716    buf[3] = mod_time->day;
01717    buf[4] = mod_time->hour;
01718    buf[5] = mod_time->minute;
01719    buf[6] = mod_time->second;
01720 
01721    png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
01722 }
01723 #endif
01724 
01725 /* initializes the row writing capability of libpng */
01726 void /* PRIVATE */
01727 png_write_start_row(png_structp png_ptr)
01728 {
01729 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
01730 #ifdef PNG_USE_LOCAL_ARRAYS
01731    /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
01732 
01733    /* start of interlace block */
01734    int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
01735 
01736    /* offset to next interlace block */
01737    int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
01738 
01739    /* start of interlace block in the y direction */
01740    int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
01741 
01742    /* offset to next interlace block in the y direction */
01743    int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
01744 #endif
01745 #endif
01746 
01747    png_size_t buf_size;
01748 
01749    png_debug(1, "in png_write_start_row\n");
01750    buf_size = (png_size_t)(PNG_ROWBYTES(
01751       png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
01752 
01753    /* set up row buffer */
01754    png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
01755    png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
01756 
01757 #ifndef PNG_NO_WRITE_FILTERING
01758    /* set up filtering buffer, if using this filter */
01759    if (png_ptr->do_filter & PNG_FILTER_SUB)
01760    {
01761       png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
01762          (png_ptr->rowbytes + 1));
01763       png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
01764    }
01765 
01766    /* We only need to keep the previous row if we are using one of these. */
01767    if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
01768    {
01769      /* set up previous row buffer */
01770       png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
01771       png_memset(png_ptr->prev_row, 0, buf_size);
01772 
01773       if (png_ptr->do_filter & PNG_FILTER_UP)
01774       {
01775          png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
01776             (png_ptr->rowbytes + 1));
01777          png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
01778       }
01779 
01780       if (png_ptr->do_filter & PNG_FILTER_AVG)
01781       {
01782          png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
01783             (png_ptr->rowbytes + 1));
01784          png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
01785       }
01786 
01787       if (png_ptr->do_filter & PNG_FILTER_PAETH)
01788       {
01789          png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
01790             (png_ptr->rowbytes + 1));
01791          png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
01792       }
01793 #endif /* PNG_NO_WRITE_FILTERING */
01794    }
01795 
01796 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
01797    /* if interlaced, we need to set up width and height of pass */
01798    if (png_ptr->interlaced)
01799    {
01800       if (!(png_ptr->transformations & PNG_INTERLACE))
01801       {
01802          png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
01803             png_pass_ystart[0]) / png_pass_yinc[0];
01804          png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
01805             png_pass_start[0]) / png_pass_inc[0];
01806       }
01807       else
01808       {
01809          png_ptr->num_rows = png_ptr->height;
01810          png_ptr->usr_width = png_ptr->width;
01811       }
01812    }
01813    else
01814 #endif
01815    {
01816       png_ptr->num_rows = png_ptr->height;
01817       png_ptr->usr_width = png_ptr->width;
01818    }
01819    png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
01820    png_ptr->zstream.next_out = png_ptr->zbuf;
01821 }
01822 
01823 /* Internal use only.  Called when finished processing a row of data. */
01824 void /* PRIVATE */
01825 png_write_finish_row(png_structp png_ptr)
01826 {
01827 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
01828 #ifdef PNG_USE_LOCAL_ARRAYS
01829    /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
01830 
01831    /* start of interlace block */
01832    int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
01833 
01834    /* offset to next interlace block */
01835    int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
01836 
01837    /* start of interlace block in the y direction */
01838    int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
01839 
01840    /* offset to next interlace block in the y direction */
01841    int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
01842 #endif
01843 #endif
01844 
01845    int ret;
01846 
01847    png_debug(1, "in png_write_finish_row\n");
01848    /* next row */
01849    png_ptr->row_number++;
01850 
01851    /* see if we are done */
01852    if (png_ptr->row_number < png_ptr->num_rows)
01853       return;
01854 
01855 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
01856    /* if interlaced, go to next pass */
01857    if (png_ptr->interlaced)
01858    {
01859       png_ptr->row_number = 0;
01860       if (png_ptr->transformations & PNG_INTERLACE)
01861       {
01862          png_ptr->pass++;
01863       }
01864       else
01865       {
01866          /* loop until we find a non-zero width or height pass */
01867          do
01868          {
01869             png_ptr->pass++;
01870             if (png_ptr->pass >= 7)
01871                break;
01872             png_ptr->usr_width = (png_ptr->width +
01873                png_pass_inc[png_ptr->pass] - 1 -
01874                png_pass_start[png_ptr->pass]) /
01875                png_pass_inc[png_ptr->pass];
01876             png_ptr->num_rows = (png_ptr->height +
01877                png_pass_yinc[png_ptr->pass] - 1 -
01878                png_pass_ystart[png_ptr->pass]) /
01879                png_pass_yinc[png_ptr->pass];
01880             if (png_ptr->transformations & PNG_INTERLACE)
01881                break;
01882          } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
01883 
01884       }
01885 
01886       /* reset the row above the image for the next pass */
01887       if (png_ptr->pass < 7)
01888       {
01889          if (png_ptr->prev_row != NULL)
01890             png_memset(png_ptr->prev_row, 0,
01891                (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
01892                png_ptr->usr_bit_depth,png_ptr->width))+1);
01893          return;
01894       }
01895    }
01896 #endif
01897 
01898    /* if we get here, we've just written the last row, so we need
01899       to flush the compressor */
01900    do
01901    {
01902       /* tell the compressor we are done */
01903       ret = deflate(&png_ptr->zstream, Z_FINISH);
01904       /* check for an error */
01905       if (ret == Z_OK)
01906       {
01907          /* check to see if we need more room */
01908          if (!(png_ptr->zstream.avail_out))
01909          {
01910             png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
01911             png_ptr->zstream.next_out = png_ptr->zbuf;
01912             png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
01913          }
01914       }
01915       else if (ret != Z_STREAM_END)
01916       {
01917          if (png_ptr->zstream.msg != NULL)
01918             png_error(png_ptr, png_ptr->zstream.msg);
01919          else
01920             png_error(png_ptr, "zlib error");
01921       }
01922    } while (ret != Z_STREAM_END);
01923 
01924    /* write any extra space */
01925    if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
01926    {
01927       png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
01928          png_ptr->zstream.avail_out);
01929    }
01930 
01931    deflateReset(&png_ptr->zstream);
01932    png_ptr->zstream.data_type = Z_BINARY;
01933 }
01934 
01935 #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
01936 /* Pick out the correct pixels for the interlace pass.
01937  * The basic idea here is to go through the row with a source
01938  * pointer and a destination pointer (sp and dp), and copy the
01939  * correct pixels for the pass.  As the row gets compacted,
01940  * sp will always be >= dp, so we should never overwrite anything.
01941  * See the default: case for the easiest code to understand.
01942  */
01943 void /* PRIVATE */
01944 png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
01945 {
01946 #ifdef PNG_USE_LOCAL_ARRAYS
01947    /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
01948 
01949    /* start of interlace block */
01950    int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
01951 
01952    /* offset to next interlace block */
01953    int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
01954 #endif
01955 
01956    png_debug(1, "in png_do_write_interlace\n");
01957    /* we don't have to do anything on the last pass (6) */
01958 #if defined(PNG_USELESS_TESTS_SUPPORTED)
01959    if (row != NULL && row_info != NULL && pass < 6)
01960 #else
01961    if (pass < 6)
01962 #endif
01963    {
01964       /* each pixel depth is handled separately */
01965       switch (row_info->pixel_depth)
01966       {
01967          case 1:
01968          {
01969             png_bytep sp;
01970             png_bytep dp;
01971             int shift;
01972             int d;
01973             int value;
01974             png_uint_32 i;
01975             png_uint_32 row_width = row_info->width;
01976 
01977             dp = row;
01978             d = 0;
01979             shift = 7;
01980             for (i = png_pass_start[pass]; i < row_width;
01981                i += png_pass_inc[pass])
01982             {
01983                sp = row + (png_size_t)(i >> 3);
01984                value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
01985                d |= (value << shift);
01986 
01987                if (shift == 0)
01988                {
01989                   shift = 7;
01990                   *dp++ = (png_byte)d;
01991                   d = 0;
01992                }
01993                else
01994                   shift--;
01995 
01996             }
01997             if (shift != 7)
01998                *dp = (png_byte)d;
01999             break;
02000          }
02001          case 2:
02002          {
02003             png_bytep sp;
02004             png_bytep dp;
02005             int shift;
02006             int d;
02007             int value;
02008             png_uint_32 i;
02009             png_uint_32 row_width = row_info->width;
02010 
02011             dp = row;
02012             shift = 6;
02013             d = 0;
02014             for (i = png_pass_start[pass]; i < row_width;
02015                i += png_pass_inc[pass])
02016             {
02017                sp = row + (png_size_t)(i >> 2);
02018                value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
02019                d |= (value << shift);
02020 
02021                if (shift == 0)
02022                {
02023                   shift = 6;
02024                   *dp++ = (png_byte)d;
02025                   d = 0;
02026                }
02027                else
02028                   shift -= 2;
02029             }
02030             if (shift != 6)
02031                    *dp = (png_byte)d;
02032             break;
02033          }
02034          case 4:
02035          {
02036             png_bytep sp;
02037             png_bytep dp;
02038             int shift;
02039             int d;
02040             int value;
02041             png_uint_32 i;
02042             png_uint_32 row_width = row_info->width;
02043 
02044             dp = row;
02045             shift = 4;
02046             d = 0;
02047             for (i = png_pass_start[pass]; i < row_width;
02048                i += png_pass_inc[pass])
02049             {
02050                sp = row + (png_size_t)(i >> 1);
02051                value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
02052                d |= (value << shift);
02053 
02054                if (shift == 0)
02055                {
02056                   shift = 4;
02057                   *dp++ = (png_byte)d;
02058                   d = 0;
02059                }
02060                else
02061                   shift -= 4;
02062             }
02063             if (shift != 4)
02064                *dp = (png_byte)d;
02065             break;
02066          }
02067          default:
02068          {
02069             png_bytep sp;
02070             png_bytep dp;
02071             png_uint_32 i;
02072             png_uint_32 row_width = row_info->width;
02073             png_size_t pixel_bytes;
02074 
02075             /* start at the beginning */
02076             dp = row;
02077             /* find out how many bytes each pixel takes up */
02078             pixel_bytes = (row_info->pixel_depth >> 3);
02079             /* loop through the row, only looking at the pixels that
02080                matter */
02081             for (i = png_pass_start[pass]; i < row_width;
02082                i += png_pass_inc[pass])
02083             {
02084                /* find out where the original pixel is */
02085                sp = row + (png_size_t)i * pixel_bytes;
02086                /* move the pixel */
02087                if (dp != sp)
02088                   png_memcpy(dp, sp, pixel_bytes);
02089                /* next pixel */
02090                dp += pixel_bytes;
02091             }
02092             break;
02093          }
02094       }
02095       /* set new row width */
02096       row_info->width = (row_info->width +
02097          png_pass_inc[pass] - 1 -
02098          png_pass_start[pass]) /
02099          png_pass_inc[pass];
02100          row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
02101             row_info->width);
02102    }
02103 }
02104 #endif
02105 
02106 /* This filters the row, chooses which filter to use, if it has not already
02107  * been specified by the application, and then writes the row out with the
02108  * chosen filter.
02109  */
02110 #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
02111 #define PNG_HISHIFT 10
02112 #define PNG_LOMASK ((png_uint_32)0xffffL)
02113 #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
02114 void /* PRIVATE */
02115 png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
02116 {
02117    png_bytep best_row;
02118 #ifndef PNG_NO_WRITE_FILTER
02119    png_bytep prev_row, row_buf;
02120    png_uint_32 mins, bpp;
02121    png_byte filter_to_do = png_ptr->do_filter;
02122    png_uint_32 row_bytes = row_info->rowbytes;
02123 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02124    int num_p_filters = (int)png_ptr->num_prev_filters;
02125 #endif
02126 
02127    png_debug(1, "in png_write_find_filter\n");
02128    /* find out how many bytes offset each pixel is */
02129    bpp = (row_info->pixel_depth + 7) >> 3;
02130 
02131    prev_row = png_ptr->prev_row;
02132 #endif
02133    best_row = png_ptr->row_buf;
02134 #ifndef PNG_NO_WRITE_FILTER
02135    row_buf = best_row;
02136    mins = PNG_MAXSUM;
02137 
02138    /* The prediction method we use is to find which method provides the
02139     * smallest value when summing the absolute values of the distances
02140     * from zero, using anything >= 128 as negative numbers.  This is known
02141     * as the "minimum sum of absolute differences" heuristic.  Other
02142     * heuristics are the "weighted minimum sum of absolute differences"
02143     * (experimental and can in theory improve compression), and the "zlib
02144     * predictive" method (not implemented yet), which does test compressions
02145     * of lines using different filter methods, and then chooses the
02146     * (series of) filter(s) that give minimum compressed data size (VERY
02147     * computationally expensive).
02148     *
02149     * GRR 980525:  consider also
02150     *   (1) minimum sum of absolute differences from running average (i.e.,
02151     *       keep running sum of non-absolute differences & count of bytes)
02152     *       [track dispersion, too?  restart average if dispersion too large?]
02153     *  (1b) minimum sum of absolute differences from sliding average, probably
02154     *       with window size <= deflate window (usually 32K)
02155     *   (2) minimum sum of squared differences from zero or running average
02156     *       (i.e., ~ root-mean-square approach)
02157     */
02158 
02159 
02160    /* We don't need to test the 'no filter' case if this is the only filter
02161     * that has been chosen, as it doesn't actually do anything to the data.
02162     */
02163    if ((filter_to_do & PNG_FILTER_NONE) &&
02164        filter_to_do != PNG_FILTER_NONE)
02165    {
02166       png_bytep rp;
02167       png_uint_32 sum = 0;
02168       png_uint_32 i;
02169       int v;
02170 
02171       for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
02172       {
02173          v = *rp;
02174          sum += (v < 128) ? v : 256 - v;
02175       }
02176 
02177 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02178       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02179       {
02180          png_uint_32 sumhi, sumlo;
02181          int j;
02182          sumlo = sum & PNG_LOMASK;
02183          sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
02184 
02185          /* Reduce the sum if we match any of the previous rows */
02186          for (j = 0; j < num_p_filters; j++)
02187          {
02188             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
02189             {
02190                sumlo = (sumlo * png_ptr->filter_weights[j]) >>
02191                   PNG_WEIGHT_SHIFT;
02192                sumhi = (sumhi * png_ptr->filter_weights[j]) >>
02193                   PNG_WEIGHT_SHIFT;
02194             }
02195          }
02196 
02197          /* Factor in the cost of this filter (this is here for completeness,
02198           * but it makes no sense to have a "cost" for the NONE filter, as
02199           * it has the minimum possible computational cost - none).
02200           */
02201          sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
02202             PNG_COST_SHIFT;
02203          sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
02204             PNG_COST_SHIFT;
02205 
02206          if (sumhi > PNG_HIMASK)
02207             sum = PNG_MAXSUM;
02208          else
02209             sum = (sumhi << PNG_HISHIFT) + sumlo;
02210       }
02211 #endif
02212       mins = sum;
02213    }
02214 
02215    /* sub filter */
02216    if (filter_to_do == PNG_FILTER_SUB)
02217    /* it's the only filter so no testing is needed */
02218    {
02219       png_bytep rp, lp, dp;
02220       png_uint_32 i;
02221       for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
02222            i++, rp++, dp++)
02223       {
02224          *dp = *rp;
02225       }
02226       for (lp = row_buf + 1; i < row_bytes;
02227          i++, rp++, lp++, dp++)
02228       {
02229          *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
02230       }
02231       best_row = png_ptr->sub_row;
02232    }
02233 
02234    else if (filter_to_do & PNG_FILTER_SUB)
02235    {
02236       png_bytep rp, dp, lp;
02237       png_uint_32 sum = 0, lmins = mins;
02238       png_uint_32 i;
02239       int v;
02240 
02241 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02242       /* We temporarily increase the "minimum sum" by the factor we
02243        * would reduce the sum of this filter, so that we can do the
02244        * early exit comparison without scaling the sum each time.
02245        */
02246       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02247       {
02248          int j;
02249          png_uint_32 lmhi, lmlo;
02250          lmlo = lmins & PNG_LOMASK;
02251          lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
02252 
02253          for (j = 0; j < num_p_filters; j++)
02254          {
02255             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
02256             {
02257                lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
02258                   PNG_WEIGHT_SHIFT;
02259                lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
02260                   PNG_WEIGHT_SHIFT;
02261             }
02262          }
02263 
02264          lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
02265             PNG_COST_SHIFT;
02266          lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
02267             PNG_COST_SHIFT;
02268 
02269          if (lmhi > PNG_HIMASK)
02270             lmins = PNG_MAXSUM;
02271          else
02272             lmins = (lmhi << PNG_HISHIFT) + lmlo;
02273       }
02274 #endif
02275 
02276       for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
02277            i++, rp++, dp++)
02278       {
02279          v = *dp = *rp;
02280 
02281          sum += (v < 128) ? v : 256 - v;
02282       }
02283       for (lp = row_buf + 1; i < row_bytes;
02284          i++, rp++, lp++, dp++)
02285       {
02286          v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
02287 
02288          sum += (v < 128) ? v : 256 - v;
02289 
02290          if (sum > lmins)  /* We are already worse, don't continue. */
02291             break;
02292       }
02293 
02294 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02295       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02296       {
02297          int j;
02298          png_uint_32 sumhi, sumlo;
02299          sumlo = sum & PNG_LOMASK;
02300          sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
02301 
02302          for (j = 0; j < num_p_filters; j++)
02303          {
02304             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
02305             {
02306                sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
02307                   PNG_WEIGHT_SHIFT;
02308                sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
02309                   PNG_WEIGHT_SHIFT;
02310             }
02311          }
02312 
02313          sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
02314             PNG_COST_SHIFT;
02315          sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
02316             PNG_COST_SHIFT;
02317 
02318          if (sumhi > PNG_HIMASK)
02319             sum = PNG_MAXSUM;
02320          else
02321             sum = (sumhi << PNG_HISHIFT) + sumlo;
02322       }
02323 #endif
02324 
02325       if (sum < mins)
02326       {
02327          mins = sum;
02328          best_row = png_ptr->sub_row;
02329       }
02330    }
02331 
02332    /* up filter */
02333    if (filter_to_do == PNG_FILTER_UP)
02334    {
02335       png_bytep rp, dp, pp;
02336       png_uint_32 i;
02337 
02338       for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
02339            pp = prev_row + 1; i < row_bytes;
02340            i++, rp++, pp++, dp++)
02341       {
02342          *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
02343       }
02344       best_row = png_ptr->up_row;
02345    }
02346 
02347    else if (filter_to_do & PNG_FILTER_UP)
02348    {
02349       png_bytep rp, dp, pp;
02350       png_uint_32 sum = 0, lmins = mins;
02351       png_uint_32 i;
02352       int v;
02353 
02354 
02355 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02356       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02357       {
02358          int j;
02359          png_uint_32 lmhi, lmlo;
02360          lmlo = lmins & PNG_LOMASK;
02361          lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
02362 
02363          for (j = 0; j < num_p_filters; j++)
02364          {
02365             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
02366             {
02367                lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
02368                   PNG_WEIGHT_SHIFT;
02369                lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
02370                   PNG_WEIGHT_SHIFT;
02371             }
02372          }
02373 
02374          lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
02375             PNG_COST_SHIFT;
02376          lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
02377             PNG_COST_SHIFT;
02378 
02379          if (lmhi > PNG_HIMASK)
02380             lmins = PNG_MAXSUM;
02381          else
02382             lmins = (lmhi << PNG_HISHIFT) + lmlo;
02383       }
02384 #endif
02385 
02386       for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
02387            pp = prev_row + 1; i < row_bytes; i++)
02388       {
02389          v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
02390 
02391          sum += (v < 128) ? v : 256 - v;
02392 
02393          if (sum > lmins)  /* We are already worse, don't continue. */
02394             break;
02395       }
02396 
02397 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02398       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02399       {
02400          int j;
02401          png_uint_32 sumhi, sumlo;
02402          sumlo = sum & PNG_LOMASK;
02403          sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
02404 
02405          for (j = 0; j < num_p_filters; j++)
02406          {
02407             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
02408             {
02409                sumlo = (sumlo * png_ptr->filter_weights[j]) >>
02410                   PNG_WEIGHT_SHIFT;
02411                sumhi = (sumhi * png_ptr->filter_weights[j]) >>
02412                   PNG_WEIGHT_SHIFT;
02413             }
02414          }
02415 
02416          sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
02417             PNG_COST_SHIFT;
02418          sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
02419             PNG_COST_SHIFT;
02420 
02421          if (sumhi > PNG_HIMASK)
02422             sum = PNG_MAXSUM;
02423          else
02424             sum = (sumhi << PNG_HISHIFT) + sumlo;
02425       }
02426 #endif
02427 
02428       if (sum < mins)
02429       {
02430          mins = sum;
02431          best_row = png_ptr->up_row;
02432       }
02433    }
02434 
02435    /* avg filter */
02436    if (filter_to_do == PNG_FILTER_AVG)
02437    {
02438       png_bytep rp, dp, pp, lp;
02439       png_uint_32 i;
02440       for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
02441            pp = prev_row + 1; i < bpp; i++)
02442       {
02443          *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
02444       }
02445       for (lp = row_buf + 1; i < row_bytes; i++)
02446       {
02447          *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
02448                  & 0xff);
02449       }
02450       best_row = png_ptr->avg_row;
02451    }
02452 
02453    else if (filter_to_do & PNG_FILTER_AVG)
02454    {
02455       png_bytep rp, dp, pp, lp;
02456       png_uint_32 sum = 0, lmins = mins;
02457       png_uint_32 i;
02458       int v;
02459 
02460 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02461       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02462       {
02463          int j;
02464          png_uint_32 lmhi, lmlo;
02465          lmlo = lmins & PNG_LOMASK;
02466          lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
02467 
02468          for (j = 0; j < num_p_filters; j++)
02469          {
02470             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
02471             {
02472                lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
02473                   PNG_WEIGHT_SHIFT;
02474                lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
02475                   PNG_WEIGHT_SHIFT;
02476             }
02477          }
02478 
02479          lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
02480             PNG_COST_SHIFT;
02481          lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
02482             PNG_COST_SHIFT;
02483 
02484          if (lmhi > PNG_HIMASK)
02485             lmins = PNG_MAXSUM;
02486          else
02487             lmins = (lmhi << PNG_HISHIFT) + lmlo;
02488       }
02489 #endif
02490 
02491       for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
02492            pp = prev_row + 1; i < bpp; i++)
02493       {
02494          v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
02495 
02496          sum += (v < 128) ? v : 256 - v;
02497       }
02498       for (lp = row_buf + 1; i < row_bytes; i++)
02499       {
02500          v = *dp++ =
02501           (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
02502 
02503          sum += (v < 128) ? v : 256 - v;
02504 
02505          if (sum > lmins)  /* We are already worse, don't continue. */
02506             break;
02507       }
02508 
02509 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02510       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02511       {
02512          int j;
02513          png_uint_32 sumhi, sumlo;
02514          sumlo = sum & PNG_LOMASK;
02515          sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
02516 
02517          for (j = 0; j < num_p_filters; j++)
02518          {
02519             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
02520             {
02521                sumlo = (sumlo * png_ptr->filter_weights[j]) >>
02522                   PNG_WEIGHT_SHIFT;
02523                sumhi = (sumhi * png_ptr->filter_weights[j]) >>
02524                   PNG_WEIGHT_SHIFT;
02525             }
02526          }
02527 
02528          sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
02529             PNG_COST_SHIFT;
02530          sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
02531             PNG_COST_SHIFT;
02532 
02533          if (sumhi > PNG_HIMASK)
02534             sum = PNG_MAXSUM;
02535          else
02536             sum = (sumhi << PNG_HISHIFT) + sumlo;
02537       }
02538 #endif
02539 
02540       if (sum < mins)
02541       {
02542          mins = sum;
02543          best_row = png_ptr->avg_row;
02544       }
02545    }
02546 
02547    /* Paeth filter */
02548    if (filter_to_do == PNG_FILTER_PAETH)
02549    {
02550       png_bytep rp, dp, pp, cp, lp;
02551       png_uint_32 i;
02552       for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
02553            pp = prev_row + 1; i < bpp; i++)
02554       {
02555          *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
02556       }
02557 
02558       for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
02559       {
02560          int a, b, c, pa, pb, pc, p;
02561 
02562          b = *pp++;
02563          c = *cp++;
02564          a = *lp++;
02565 
02566          p = b - c;
02567          pc = a - c;
02568 
02569 #ifdef PNG_USE_ABS
02570          pa = abs(p);
02571          pb = abs(pc);
02572          pc = abs(p + pc);
02573 #else
02574          pa = p < 0 ? -p : p;
02575          pb = pc < 0 ? -pc : pc;
02576          pc = (p + pc) < 0 ? -(p + pc) : p + pc;
02577 #endif
02578 
02579          p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
02580 
02581          *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
02582       }
02583       best_row = png_ptr->paeth_row;
02584    }
02585 
02586    else if (filter_to_do & PNG_FILTER_PAETH)
02587    {
02588       png_bytep rp, dp, pp, cp, lp;
02589       png_uint_32 sum = 0, lmins = mins;
02590       png_uint_32 i;
02591       int v;
02592 
02593 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02594       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02595       {
02596          int j;
02597          png_uint_32 lmhi, lmlo;
02598          lmlo = lmins & PNG_LOMASK;
02599          lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
02600 
02601          for (j = 0; j < num_p_filters; j++)
02602          {
02603             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
02604             {
02605                lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
02606                   PNG_WEIGHT_SHIFT;
02607                lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
02608                   PNG_WEIGHT_SHIFT;
02609             }
02610          }
02611 
02612          lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
02613             PNG_COST_SHIFT;
02614          lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
02615             PNG_COST_SHIFT;
02616 
02617          if (lmhi > PNG_HIMASK)
02618             lmins = PNG_MAXSUM;
02619          else
02620             lmins = (lmhi << PNG_HISHIFT) + lmlo;
02621       }
02622 #endif
02623 
02624       for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
02625            pp = prev_row + 1; i < bpp; i++)
02626       {
02627          v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
02628 
02629          sum += (v < 128) ? v : 256 - v;
02630       }
02631 
02632       for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
02633       {
02634          int a, b, c, pa, pb, pc, p;
02635 
02636          b = *pp++;
02637          c = *cp++;
02638          a = *lp++;
02639 
02640 #ifndef PNG_SLOW_PAETH
02641          p = b - c;
02642          pc = a - c;
02643 #ifdef PNG_USE_ABS
02644          pa = abs(p);
02645          pb = abs(pc);
02646          pc = abs(p + pc);
02647 #else
02648          pa = p < 0 ? -p : p;
02649          pb = pc < 0 ? -pc : pc;
02650          pc = (p + pc) < 0 ? -(p + pc) : p + pc;
02651 #endif
02652          p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
02653 #else /* PNG_SLOW_PAETH */
02654          p = a + b - c;
02655          pa = abs(p - a);
02656          pb = abs(p - b);
02657          pc = abs(p - c);
02658          if (pa <= pb && pa <= pc)
02659             p = a;
02660          else if (pb <= pc)
02661             p = b;
02662          else
02663             p = c;
02664 #endif /* PNG_SLOW_PAETH */
02665 
02666          v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
02667 
02668          sum += (v < 128) ? v : 256 - v;
02669 
02670          if (sum > lmins)  /* We are already worse, don't continue. */
02671             break;
02672       }
02673 
02674 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02675       if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
02676       {
02677          int j;
02678          png_uint_32 sumhi, sumlo;
02679          sumlo = sum & PNG_LOMASK;
02680          sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
02681 
02682          for (j = 0; j < num_p_filters; j++)
02683          {
02684             if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
02685             {
02686                sumlo = (sumlo * png_ptr->filter_weights[j]) >>
02687                   PNG_WEIGHT_SHIFT;
02688                sumhi = (sumhi * png_ptr->filter_weights[j]) >>
02689                   PNG_WEIGHT_SHIFT;
02690             }
02691          }
02692 
02693          sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
02694             PNG_COST_SHIFT;
02695          sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
02696             PNG_COST_SHIFT;
02697 
02698          if (sumhi > PNG_HIMASK)
02699             sum = PNG_MAXSUM;
02700          else
02701             sum = (sumhi << PNG_HISHIFT) + sumlo;
02702       }
02703 #endif
02704 
02705       if (sum < mins)
02706       {
02707          best_row = png_ptr->paeth_row;
02708       }
02709    }
02710 #endif /* PNG_NO_WRITE_FILTER */
02711    /* Do the actual writing of the filtered row data from the chosen filter. */
02712 
02713    png_write_filtered_row(png_ptr, best_row);
02714 
02715 #ifndef PNG_NO_WRITE_FILTER
02716 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
02717    /* Save the type of filter we picked this time for future calculations */
02718    if (png_ptr->num_prev_filters > 0)
02719    {
02720       int j;
02721       for (j = 1; j < num_p_filters; j++)
02722       {
02723          png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
02724       }
02725       png_ptr->prev_filters[j] = best_row[0];
02726    }
02727 #endif
02728 #endif /* PNG_NO_WRITE_FILTER */
02729 }
02730 
02731 
02732 /* Do the actual writing of a previously filtered row. */
02733 void /* PRIVATE */
02734 png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
02735 {
02736    png_debug(1, "in png_write_filtered_row\n");
02737    png_debug1(2, "filter = %d\n", filtered_row[0]);
02738    /* set up the zlib input buffer */
02739 
02740    png_ptr->zstream.next_in = filtered_row;
02741    png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
02742    /* repeat until we have compressed all the data */
02743    do
02744    {
02745       int ret; /* return of zlib */
02746 
02747       /* compress the data */
02748       ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
02749       /* check for compression errors */
02750       if (ret != Z_OK)
02751       {
02752          if (png_ptr->zstream.msg != NULL)
02753             png_error(png_ptr, png_ptr->zstream.msg);
02754          else
02755             png_error(png_ptr, "zlib error");
02756       }
02757 
02758       /* see if it is time to write another IDAT */
02759       if (!(png_ptr->zstream.avail_out))
02760       {
02761          /* write the IDAT and reset the zlib output buffer */
02762          png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
02763          png_ptr->zstream.next_out = png_ptr->zbuf;
02764          png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
02765       }
02766    /* repeat until all data has been compressed */
02767    } while (png_ptr->zstream.avail_in);
02768 
02769    /* swap the current and previous rows */
02770    if (png_ptr->prev_row != NULL)
02771    {
02772       png_bytep tptr;
02773 
02774       tptr = png_ptr->prev_row;
02775       png_ptr->prev_row = png_ptr->row_buf;
02776       png_ptr->row_buf = tptr;
02777    }
02778 
02779    /* finish row - updates counters and flushes zlib if last row */
02780    png_write_finish_row(png_ptr);
02781 
02782 #if defined(PNG_WRITE_FLUSH_SUPPORTED)
02783    png_ptr->flush_rows++;
02784 
02785    if (png_ptr->flush_dist > 0 &&
02786        png_ptr->flush_rows >= png_ptr->flush_dist)
02787    {
02788       png_write_flush(png_ptr);
02789    }
02790 #endif
02791 }
02792 #endif /* PNG_WRITE_SUPPORTED */

Generated on Tue Jul 5 14:13:31 2011 for ROOT_528-00b_version by  doxygen 1.5.1