Back to index

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