CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/ext/libpng17/pngwutil.c
Views: 1401
#ifdef _MSC_VER1#pragma warning (disable:4018)2#pragma warning (disable:4028)3#pragma warning (disable:4146)4#pragma warning (disable:4334)5#endif67/* pngwutil.c - utilities to write a PNG file8*9* Last changed in libpng 1.7.0 [(PENDING RELEASE)]10* Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson11* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)12* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)13*14* This code is released under the libpng license.15* For conditions of distribution and use, see the disclaimer16* and license in png.h17*/1819#include "pngpriv.h"20#define PNG_SRC_FILE PNG_SRC_FILE_pngwutil2122#ifdef PNG_WRITE_SUPPORTED2324#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED25/* Place a 32-bit number into a buffer in PNG byte order. We work26* with unsigned numbers for convenience, although one supported27* ancillary chunk uses signed (two's complement) numbers.28*/29void PNGAPI30png_save_uint_32(png_bytep buf, png_uint_32 i)31{32buf[0] = PNG_BYTE(i >> 24);33buf[1] = PNG_BYTE(i >> 16);34buf[2] = PNG_BYTE(i >> 8);35buf[3] = PNG_BYTE(i);36}3738/* Place a 16-bit number into a buffer in PNG byte order.39* The parameter is declared unsigned int, not png_uint_16,40* just to avoid potential problems on pre-ANSI C compilers.41*/42void PNGAPI43png_save_uint_16(png_bytep buf, unsigned int i)44{45buf[0] = PNG_BYTE(i >> 8);46buf[1] = PNG_BYTE(i);47}48#endif /* WRITE_INT_FUNCTIONS */4950/* Simple function to write the signature. If we have already written51* the magic bytes of the signature, or more likely, the PNG stream is52* being embedded into another stream and doesn't need its own signature,53* we should call png_set_sig_bytes() to tell libpng how many of the54* bytes have already been written.55*/56void PNGAPI57png_write_sig(png_structrp png_ptr)58{59png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};6061#ifdef PNG_IO_STATE_SUPPORTED62/* Inform the I/O callback that the signature is being written */63png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;64#endif6566/* Write the rest of the 8 byte signature */67png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],68(png_size_t)(8 - png_ptr->sig_bytes));6970if (png_ptr->sig_bytes < 3)71png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;72}7374/* Write the start of a PNG chunk. The type is the chunk type.75* The total_length is the sum of the lengths of all the data you will be76* passing in png_write_chunk_data().77*/78static void79png_write_chunk_header(png_structrp png_ptr, png_uint_32 chunk_name,80png_uint_32 length)81{82png_byte buf[8];8384#if defined(PNG_DEBUG) && (PNG_DEBUG > 0)85PNG_CSTRING_FROM_CHUNK(buf, chunk_name);86png_debug2(0, "Writing %s chunk, length = %lu", buf, (unsigned long)length);87#endif8889if (png_ptr == NULL)90return;9192#ifdef PNG_IO_STATE_SUPPORTED93/* Inform the I/O callback that the chunk header is being written.94* PNG_IO_CHUNK_HDR requires a single I/O call.95*/96png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;97#endif9899/* Write the length and the chunk name */100png_save_uint_32(buf, length);101png_save_uint_32(buf + 4, chunk_name);102png_write_data(png_ptr, buf, 8);103104/* Put the chunk name into png_ptr->chunk_name */105png_ptr->chunk_name = chunk_name;106107/* Reset the crc and run it over the chunk name */108png_reset_crc(png_ptr, buf+4);109110#ifdef PNG_IO_STATE_SUPPORTED111/* Inform the I/O callback that chunk data will (possibly) be written.112* PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.113*/114png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;115#endif116}117118void PNGAPI119png_write_chunk_start(png_structrp png_ptr, png_const_bytep chunk_string,120png_uint_32 length)121{122png_write_chunk_header(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), length);123}124125/* Write the data of a PNG chunk started with png_write_chunk_header().126* Note that multiple calls to this function are allowed, and that the127* sum of the lengths from these calls *must* add up to the total_length128* given to png_write_chunk_header().129*/130void PNGAPI131png_write_chunk_data(png_structrp png_ptr, png_const_voidp data,132png_size_t length)133{134/* Write the data, and run the CRC over it */135if (png_ptr == NULL)136return;137138if (data != NULL && length > 0)139{140png_write_data(png_ptr, data, length);141142/* Update the CRC after writing the data,143* in case the user I/O routine alters it.144*/145png_calculate_crc(png_ptr, data, length);146}147}148149/* Finish a chunk started with png_write_chunk_header(). */150void PNGAPI151png_write_chunk_end(png_structrp png_ptr)152{153png_byte buf[4];154155if (png_ptr == NULL) return;156157#ifdef PNG_IO_STATE_SUPPORTED158/* Inform the I/O callback that the chunk CRC is being written.159* PNG_IO_CHUNK_CRC requires a single I/O function call.160*/161png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;162#endif163164/* Write the crc in a single operation */165png_save_uint_32(buf, png_ptr->crc);166167png_write_data(png_ptr, buf, (png_size_t)4);168}169170/* Write a PNG chunk all at once. The type is an array of ASCII characters171* representing the chunk name. The array must be at least 4 bytes in172* length, and does not need to be null terminated. To be safe, pass the173* pre-defined chunk names here, and if you need a new one, define it174* where the others are defined. The length is the length of the data.175* All the data must be present. If that is not possible, use the176* png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()177* functions instead.178*/179static void180png_write_complete_chunk(png_structrp png_ptr, png_uint_32 chunk_name,181png_const_voidp data, png_size_t length)182{183if (png_ptr == NULL)184return;185186/* On 64 bit architectures 'length' may not fit in a png_uint_32. */187if (length > PNG_UINT_31_MAX)188png_error(png_ptr, "length exceeds PNG maximum");189190png_write_chunk_header(png_ptr, chunk_name, (png_uint_32)/*SAFE*/length);191png_write_chunk_data(png_ptr, data, length);192png_write_chunk_end(png_ptr);193}194195/* This is the API that calls the internal function above. */196void PNGAPI197png_write_chunk(png_structrp png_ptr, png_const_bytep chunk_string,198png_const_voidp data, png_size_t length)199{200png_write_complete_chunk(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), data,201length);202}203204static png_alloc_size_t205png_write_row_buffer_size(png_const_structrp png_ptr)206/* Returns the width of the widest pass in the first row of an interlaced207* image. Passes in the first row are: 0.5.3.5.1.5.3.5, so the widest row is208* normally the one from pass 5. The only exception is if the image is only209* one pixel wide, so:210*/211#define PNG_FIRST_ROW_MAX_WIDTH(w) (w > 1U ? PNG_PASS_COLS(w, 5U) : 1U)212213/* For interlaced images the count of pixels is rounded up to a the number of214* pixels in the first pass (numbered 0). This ensures that passes before215* the last can be packed in the buffer without overflow.216*/217{218png_alloc_size_t w;219220/* If the image is interlaced adjust 'w' for the interlacing: */221if (png_ptr->interlaced != PNG_INTERLACE_NONE)222{223/* Take advantage of the fact that 1-row interlaced PNGs require half the224* normal row width:225*/226if (png_ptr->height == 1U) /* no pass 6 */227w = PNG_FIRST_ROW_MAX_WIDTH(png_ptr->width);228229/* Otherwise round up to a multiple of 8. This may waste a few (less230* than 8) bytes for PNGs with a height less than 57 but this hardly231* matters.232*/233else234w = (png_ptr->width + 7U) & ~7U;235}236237else238w = png_ptr->width;239240/* The rounding above may leave 'w' exactly 2^31 */241debug(w <= 0x80000000U);242243switch (png_ptr->row_output_pixel_depth)244{245/* This would happen if the function is called before png_write_IHDR. */246default: NOT_REACHED; return 0;247248case 1: w = (w+7) >> 3; break;249case 2: w = (w+3) >> 2; break;250case 4: w = (w+1) >> 1; break;251case 8: break;252case 16: w <<= 1; break; /* overflow: w is set to 0, which is OK */253254/* For the remaining cases the answer is w*bytes; where bytes is 3,4,6255* or 8. This may overflow 32 bits. There is no way to compute the256* result on an arbitrary platform, so test the maximum of a (size_t)257* against w for each possible byte depth:258*/259# define CASE(b)\260case b*8:\261if (w <= (PNG_SIZE_MAX/b)/*compile-time constant*/)\262return w * b;\263return 0;264265CASE(3)266CASE(4)267CASE(6)268CASE(8)269270# undef CASE271}272273/* This is the low bit depth case. The following can never be false on274* systems with a 32-bit or greater size_t:275*/276if (w <= PNG_SIZE_MAX)277return w;278279return 0U;280}281282/* Release memory used by the deflate mechanism */283static void284png_deflateEnd(png_const_structrp png_ptr, z_stream *zs, int check)285{286if (zs->state != NULL)287{288int ret = deflateEnd(zs);289290/* Z_DATA_ERROR means there was pending output. */291if ((ret != Z_OK && (check || ret != Z_DATA_ERROR)) || zs->state != NULL)292{293png_zstream_error(zs, ret);294295if (check)296png_error(png_ptr, zs->msg);297298else299png_warning(png_ptr, zs->msg);300301zs->state = NULL;302}303}304}305306/* compression_buffer (new in 1.6.0) is just a linked list of temporary buffers. * From 1.6.0 it is retained in png_struct so that it will be correctly freed in307* the event of a write error (previous implementations just leaked memory.)308*309* From 1.7.0 the size is fixed to the same as the (uncompressed) row buffer310* size. This avoids allocating a large chunk of memory when compressing small311* images. This type is also opaque outside this file.312*/313typedef struct png_compression_buffer314{315struct png_compression_buffer *next;316png_byte output[PNG_ROW_BUFFER_SIZE];317} png_compression_buffer, *png_compression_bufferp;318319/* png_compression_buffer methods */320/* Deleting a compression buffer deletes the whole list: */321static void322png_free_compression_buffer(png_const_structrp png_ptr,323png_compression_bufferp *listp)324{325png_compression_bufferp list = *listp;326327if (list != NULL)328{329*listp = NULL;330331do332{333png_compression_bufferp next = list->next;334335png_free(png_ptr, list);336list = next;337}338while (list != NULL);339}340}341342/* Return the next compression buffer in the list, allocating it if necessary.343* The caller must update 'end' if required; this just moves down the list.344*/345static png_compression_bufferp346png_get_compression_buffer(png_const_structrp png_ptr,347png_compression_bufferp *end)348{349png_compression_bufferp next = *end;350351if (next == NULL)352{353next = png_voidcast(png_compression_bufferp, png_malloc_base(png_ptr,354sizeof *next));355356/* Check for OOM: this is a recoverable error for non-critical chunks, let357* the caller decide what to do rather than issuing a png_error here.358*/359if (next != NULL)360{361next->next = NULL; /* initialize the buffer */362*end = next;363}364}365366return next; /* may still be NULL on OOM */367}368369/* This structure is used to hold all the data for zlib compression of a single370* stream of data. It may be re-used, it stores the compressed data internally371* and can handle arbitrary input and output.372*373* 'list' is the output data contained in compression buffers, 'end' points to374* list at the start and is advanced down the compression buffer list (extending375* it as required) as the data is written. If 'end' points into a compression376* buffer (does not point to 'list') that is the buffer in use in377* z_stream::{next,avail}_out.378*379* Compression may be performed in multiple steps, '*end' always points to the380* compression buffer *after* the one that is in use, so 'end' is pointing381* *into* the one in use.382*383* end(on entry) .... end ....... end(on exit)384* | | |385* | | |386* V +----V-----+ +-----V----+ +----------+387* list ---> | next --+--> | next --+--> | next |388* | output[] | | output[] | | output[] |389* +----------+ +----------+ +----------+390* [in use] [unused]391*392* These invariants should always hold:393*394* 1) If zs.state is NULL decompression is not in progress, list may be non-NULL395* but end could be anything;396*397* 2) Otherwise if zs.next_out is NULL list will be NULL and end will point at398* list, len, overflow and start will be 0;399*400* 3) Otherwise list is non-NULL and end points at the 'next' element of an401* in-use compression buffer. zs.next_out points into the 'output' element402* of the same buffer. {overflow, len} is the amount of compressed data, len403* being the low 31 bits, overflow being the higher bits. start is used for404* writing and is the index of the first byte in list->output to write,405* {overflow, len} does not include start.406*/407typedef struct408{409z_stream zs; /* zlib compression data */410png_compression_bufferp list; /* Head of the buffer list */411png_compression_bufferp *end; /* Pointer to last 'next' pointer */412png_uint_32 len; /* Bottom 31 bits of data length */413unsigned int overflow; /* Top bits of data length */414unsigned int start; /* Start of data in first block */415} png_zlib_compress, *png_zlib_compressp;416417/* png_zlib_compress methods */418/* Initialize the compress structure. The z_stream itself is not initialized,419* however the the 'user' fields are set, including {next,avail}_{in,out}. The420* initialization does not change 'list', however it does set 'end' to point to421* it, effectively truncating the list.422*/423static void424png_zlib_compress_init(png_structrp png_ptr, png_zlib_compressp pz)425{426/* png_zlib_compress z_stream: */427pz->zs.zalloc = png_zalloc;428pz->zs.zfree = png_zfree;429/* NOTE: this does not destroy 'restrict' because in all the functions herein430* *png_ptr is only ever accessed via *either* pz->zs.opaque *or* a passed in431* png_ptr.432*/433pz->zs.opaque = png_ptr;434435pz->zs.next_in = NULL;436pz->zs.avail_in = 0U;437pz->zs.total_in = 0U;438439pz->zs.next_out = NULL;440pz->zs.avail_out = 0U;441pz->zs.total_out = 0U;442443pz->zs.msg = PNGZ_MSG_CAST("zlib success"); /* safety */444445/* pz->list preserved */446pz->end = &pz->list;447pz->len = 0U;448pz->overflow = 0U;449pz->start = 0U;450}451452/* Return the png_ptr: this is defined here for all the remaining453* png_zlib_compress methods because they are only ever called with zs454* initialized.455*/456#define png_ptr png_voidcast(png_const_structrp, pz->zs.opaque)457458#if PNG_RELEASE_BUILD459# define png_zlib_compress_validate(pz, in_use) ((void)0)460#else /* !RELEASE_BUILD */461static void462png_zlib_compress_validate(png_zlib_compressp pz, int in_use)463{464const uInt o_size = sizeof pz->list->output;465466affirm(pz->end != NULL && (in_use || (pz->zs.next_in == NULL &&467pz->zs.avail_in == 0U && *pz->end == NULL)));468469if (pz->overflow == 0U && pz->len == 0U && pz->start == 0U) /* empty */470{471affirm((pz->end == &pz->list && pz->zs.next_out == NULL472&& pz->zs.avail_out == 0U) ||473(pz->list != NULL && pz->end == &pz->list->next &&474pz->zs.next_out == pz->list->output &&475pz->zs.avail_out == o_size));476}477478else /* not empty */479{480png_compression_bufferp *ep = &pz->list, list;481png_uint_32 o, l;482483affirm(*ep != NULL && pz->zs.next_out != NULL);484485/* Check the list length: */486o = pz->overflow;487l = pz->len;488affirm((l & 0x80000000U) == 0U && (o & 0x80000000U) == 0U);489490do491{492list = *ep;493l -= o_size;494if (l & 0x80000000U) --o, l &= 0x7FFFFFFFU;495ep = &list->next;496}497while (ep != pz->end);498499l += pz->start;500l += pz->zs.avail_out;501if (l & 0x80000000U) ++o, l &= 0x7FFFFFFFU;502503affirm(o == 0U && l == 0U && pz->zs.next_out >= list->output &&504pz->zs.next_out + pz->zs.avail_out == list->output + o_size);505}506}507#endif /* !RELEASE_BUILD */508509/* Destroy one zlib compress structure. */510static void511png_zlib_compress_destroy(png_zlib_compressp pz, int check)512{513/* If the 'opaque' pointer is NULL this png_zlib_compress was never514* initialized, so do nothing.515*/516if (png_ptr != NULL)517{518if (pz->zs.state != NULL)519{520if (check)521png_zlib_compress_validate(pz, 0/*in_use*/);522523png_deflateEnd(png_ptr, &pz->zs, check);524}525526pz->end = &pz->list; /* safety */527png_free_compression_buffer(png_ptr, &pz->list);528}529}530531/* Ensure that space is available for output, returns the amount of space532* available, 0 on OOM. This updates pz->zs.avail_out (etc) as required.533*/534static uInt535png_zlib_compress_avail_out(png_zlib_compressp pz)536{537uInt avail_out = pz->zs.avail_out;538539png_zlib_compress_validate(pz, 1/*in_use*/);540541if (avail_out == 0U)542{543png_compression_bufferp next;544545affirm(pz->end == &pz->list || (pz->end != NULL && pz->list != NULL));546next = png_get_compression_buffer(png_ptr, pz->end);547548if (next != NULL)549{550pz->zs.next_out = next->output;551pz->zs.avail_out = avail_out = sizeof next->output;552pz->end = &next->next;553}554555/* else return 0: OOM */556}557558else559affirm(pz->end != NULL && pz->list != NULL);560561return avail_out;562}563564/* Compress the given data given an initialized png_zlib_compress structure.565* This may be called multiple times, interleaved with writes as required.566*567* The input data is passed in in pz->zs.next_in, however the length of the data568* is in 'input_len' (to avoid the zlib uInt limit) and pz->zs.avail_in is569* overwritten (and left at 0).570*571* The output information is used and the amount of compressed data is added on572* to pz->{overflow,len}.573*574* If 'limit' is a limit on the amount of data to add to the output (not the575* total amount). The function will retun Z_BUF_ERROR if the limit is reached576* and the function will never produce more (additional) compressed data than577* the limit.578*579* All of zstream::next_in[input] is consumed if a success code is returned580* (Z_OK or Z_STREAM_END if flush is Z_FINISH), otherwise next_in may be used to581* determine how much was compressed.582*583* pz->overflow is not checked for overflow, so if 'limit' is not set overflow584* is possible. The caller must guard against this when supplying a limit of 0.585*/586static int587png_compress(588png_zlib_compressp pz,589png_alloc_size_t input_len, /* Length of data to be compressed */590png_uint_32 limit, /* Limit on amount of compressed data made */591int flush) /* Flush parameter at end of input */592{593const int unlimited = (limit == 0U);594595/* Sanity checking: */596affirm(pz->zs.state != NULL &&597(pz->zs.next_out == NULL598? pz->end == &pz->list && pz->len == 0U && pz->overflow == 0U599: pz->list != NULL && pz->end != NULL));600implies(pz->zs.next_out == NULL, pz->zs.avail_out == 0);601602for (;;)603{604uInt extra;605606/* OUTPUT: make sure some space is available: */607if (png_zlib_compress_avail_out(pz) == 0U)608return Z_MEM_ERROR;609610/* INPUT: limit the deflate call input to ZLIB_IO_MAX: */611/* Adjust the input counters: */612{613uInt avail_in = ZLIB_IO_MAX;614615if (avail_in > input_len)616avail_in = (uInt)/*SAFE*/input_len;617618input_len -= avail_in;619pz->zs.avail_in = avail_in;620}621622if (!unlimited && pz->zs.avail_out > limit)623{624extra = (uInt)/*SAFE*/(pz->zs.avail_out - limit); /* unused bytes */625pz->zs.avail_out = (uInt)/*SAFE*/limit;626limit = 0U;627}628629else630{631extra = 0U;632limit -= pz->zs.avail_out; /* limit >= 0U */633}634635pz->len += pz->zs.avail_out; /* maximum that can be produced */636637/* Compress the data */638{639int ret = deflate(&pz->zs, input_len > 0U ? Z_NO_FLUSH : flush);640641/* Claw back input data that was not consumed (because avail_in is642* reset above every time round the loop) and correct the output643* length.644*/645input_len += pz->zs.avail_in;646pz->zs.avail_in = 0; /* safety */647pz->len -= pz->zs.avail_out;648649if (pz->len & 0x80000000U)650++pz->overflow, pz->len &= 0x7FFFFFFFU;651652limit += pz->zs.avail_out;653pz->zs.avail_out += extra;654655/* Check the error code: */656switch (ret)657{658case Z_OK:659if (pz->zs.avail_out > extra)660{661/* zlib had output space, so all the input should have been662* consumed:663*/664affirm(input_len == 0U /* else unexpected stop */ &&665flush != Z_FINISH/* ret != Z_STREAM_END */);666return Z_OK;667}668669else670{671/* zlib ran out of output space, produce some more. If the672* limit is 0 at this point, however, no more space is673* available.674*/675if (unlimited || limit > 0U)676break; /* Allocate more output */677678/* No more output space available, but the input may have all679* been consumed.680*/681if (input_len == 0U && flush != Z_FINISH)682return Z_OK;683684/* Input all consumed, but insufficient space to flush the685* output; this is the Z_BUF_ERROR case.686*/687return Z_BUF_ERROR;688}689690case Z_STREAM_END:691affirm(input_len == 0U && flush == Z_FINISH);692return Z_STREAM_END;693694case Z_BUF_ERROR:695/* This means that we are flushing all the output; expect696* avail_out and input_len to be 0.697*698* NOTE: if png_compress is called with input_len 0 and flush set699* to Z_NO_FLUSH this affirm will fire because zlib will have no700* work to do.701*/702affirm(input_len == 0U && pz->zs.avail_out == extra);703/* Allocate another buffer */704break;705706default:707/* An error */708return ret;709}710}711}712}713714#undef png_ptr /* remove definition using a png_zlib_compressp */715716/* All the compression state is held here, it is allocated when required. This717* ensures that the read code doesn't carry the overhead of the much less718* frequently used write stuff.719*720* TODO: make png_create_write_struct allocate this stuff after the main721* png_struct.722*/723struct filter_selector; /* Used only for filter selection */724725typedef struct png_zlib_state726{727png_zlib_compress s; /* Primary compression state */728png_compression_bufferp stash; /* Unused compression buffers */729730# define ps_png_ptr(ps) png_upcast(png_const_structrp, (ps)->s.zs.opaque)731/* A png_ptr, used below in functions that only have a png_zlib_state.732* NOTE: the png_zlib_compress must have been initialized!733*/734735png_uint_32 zlib_max_pixels;736/* Maximum number of pixels that zlib can handle at once; the lesser of737* the PNG maximum and the maximum that will fit in (uInt)-1 bytes. This738* number of pixels may not be byte aligned.739*/740png_uint_32 zlib_max_aligned_pixels;741/* The maximum number of pixels that zlib can handle while maintaining a742* buffer byte alignment of PNG_ROW_BUFFER_BYTE_ALIGN; <= the previous743* value.744*/745746png_alloc_size_t write_row_size;747/* Size of the PNG row (without the filter byte) in bytes or 0 if it is748* too large to be cached.749*/750751# ifdef PNG_WRITE_FILTER_SUPPORTED752/* During write libpng needs the previous row when writing a new row with753* up, avg or paeth and one or more image rows when performing filter754* selection. So if performing filter selection typically two or more755* rows are required while if no filter selection is to be done only the756* previous row pointer is required.757*/758png_bytep previous_write_row; /* Last row written, if any */759# ifdef PNG_SELECT_FILTER_SUPPORTED760png_bytep current_write_row; /* Row being written */761struct filter_selector *selector; /* Data for filter selection */762png_uint_32 filter_select_window;763/* The number of bytes of uncompressed PNG data which are assumed to764* be relevant when doing filter selection. Limited to 8453377765* (about 2^23); the maximum number of bytes that can be encoded in766* the largest deflate window.767*/768# define PNG_FILTER_SELECT_WINDOW_MAX 8453377U769png_byte filter_select_threshold;770/* If the number of distinct codes seen in the PNG data are below771* this threshold the PNG data will not be filtered (if the 'none'772* filter is allowed). If this is still true and a particular773* filter does not add new codes that filter will be used.774*/775png_byte filter_select_threshold2;776/* If the number of distinct codes that result by using a particular777* filter is below this second threshold that filter will be used.778* (When multiple filters pass this criterion the lowest numbered779* one producing the lowest number of new codes will be780* chosen.)781*/782# endif /* SELECT_FILTER */783784unsigned int row_buffer_max_pixels;785/* The maximum number of pixels that can fit in PNG_ROW_BUFFER_SIZE786* bytes; not necessary a whole number of bytes.787*/788unsigned int row_buffer_max_aligned_pixels;789/* The maximum number of pixels that can fit in PNG_ROW_BUFFER_SIZE790* bytes while maintaining PNG_ROW_BUFFER_BYTE_ALIGN alignment.791*/792793unsigned int filter_mask :8; /* mask of filters to consider on NEXT row */794# define PREVIOUS_ROW_FILTERS\795(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)796unsigned int filters :8; /* Filters for current row */797unsigned int save_row :2; /* As below: */798# define SAVE_ROW_UNSET 0U799# define SAVE_ROW_OFF 1U /* Previous-row filters will be ignored */800# define SAVE_ROW_DEFAULT 2U /* Default to save rows set by libpng */801# define SAVE_ROW_ON 3U /* Force rows to be saved */802# define SAVE_ROW(ps) ((ps)->save_row >= SAVE_ROW_DEFAULT)803# endif /* WRITE_FILTER */804805/* Compression settings: see below for how these are encoded. */806png_uint_32 pz_IDAT; /* Settings for the image */807png_uint_32 pz_iCCP; /* Settings for iCCP chunks */808png_uint_32 pz_text; /* Settings for text chunks */809png_uint_32 pz_current; /* Last set settings */810811# ifdef PNG_WRITE_FLUSH_SUPPORTED812png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */813png_uint_32 flush_rows; /* number of rows written since last flush */814# endif /* WRITE_FLUSH */815} png_zlib_state;816817/* Create the zlib state: */818static void819png_create_zlib_state(png_structrp png_ptr)820{821png_zlib_statep ps = png_voidcast(png_zlib_state*,822png_malloc(png_ptr, sizeof *ps));823824/* Clear to NULL/0: */825memset(ps, 0, sizeof *ps);826827debug(png_ptr->zlib_state == NULL);828png_ptr->zlib_state = ps;829png_zlib_compress_init(png_ptr, &ps->s);830831# ifdef PNG_WRITE_FILTER_SUPPORTED832ps->previous_write_row = NULL;833# ifdef PNG_SELECT_FILTER_SUPPORTED834ps->current_write_row = NULL;835ps->selector = NULL;836# endif /* SELECT_FILTER */837# endif /* WRITE_FILTER */838# ifdef PNG_WRITE_FLUSH_SUPPORTED839/* Set this to prevent flushing by making it larger than the number840* of rows in the largest interlaced PNG; PNG_UINT_31_MAX times841* (1/8+1/8+1/8+1/4+1/4+1/2+1/2); 1.875, or 15/8842*/843ps->flush_dist = 0xEFFFFFFFU;844# endif /* WRITE_FLUSH */845}846847static void848png_zlib_state_set_buffer_limits(png_const_structrp png_ptr, png_zlib_statep ps)849/* Delayed initialization of the zlib state maxima; this is not done above in850* case the zlib_state is created before the IHDR has been written, which851* would lead to the various png_struct fields used below being852* uninitialized.853*/854{855/* Initialization of the buffer size constants. */856const unsigned int bpp = PNG_PIXEL_DEPTH(*png_ptr);857const unsigned int byte_pp = bpp >> 3; /* May be 0 */858const unsigned int pixel_block =859/* Number of pixels required to maintain PNG_ROW_BUFFER_BYTE_ALIGN860* alignment. For multi-byte pixels use the first set bit to determine861* if the pixels have a greater alignment already.862*/863bpp < 8U ?864PNG_ROW_BUFFER_BYTE_ALIGN * (8U/bpp) :865PNG_ROW_BUFFER_BYTE_ALIGN <= (byte_pp & -byte_pp) ?8661U :867PNG_ROW_BUFFER_BYTE_ALIGN / (byte_pp & -byte_pp);868869/* pixel_block must always be a power of two: */870debug(bpp > 0 && pixel_block > 0 &&871(pixel_block & -pixel_block) == pixel_block &&872((8U*PNG_ROW_BUFFER_BYTE_ALIGN-1U) & (pixel_block*bpp)) == 0U);873874/* Zlib maxima */875{876png_uint_32 max = (uInt)-1; /* max bytes */877878if (bpp <= 8U)879{880/* Maximum number of bytes PNG can generate in the lower bit depth881* cases:882*/883png_uint_32 png_max =884(0x7FFFFFFF + PNG_ADDOF(bpp)) >> PNG_SHIFTOF(bpp);885886if (png_max < max)887max = 0x7FFFFFFF;888}889890else /* bpp > 8U */891{892max /= byte_pp;893if (max > 0x7FFFFFFF)894max = 0x7FFFFFFF;895}896897/* So this is the maximum number of pixels regardless of alignment: */898ps->zlib_max_pixels = max;899900/* For byte alignment the value has to be a multiple of pixel_block and901* that is a power of 2, so:902*/903ps->zlib_max_aligned_pixels = max & ~(pixel_block-1U);904}905906# ifdef PNG_WRITE_FILTER_SUPPORTED907/* PNG_ROW_BUFFER maxima; this is easier because PNG_ROW_BUFFER_SIZE is908* limited so that the number of bits fits in any ANSI-C (unsigned int).909*/910{911const unsigned int max = (8U * PNG_ROW_BUFFER_SIZE) / bpp;912913ps->row_buffer_max_pixels = max;914ps->row_buffer_max_aligned_pixels = max & ~(pixel_block-1U);915}916# endif /* WRITE_FILTER */917918/* NOTE: this will be 0 for very long rows on 32-bit or less systems */919ps->write_row_size = png_write_row_buffer_size(png_ptr);920}921922static png_zlib_statep923get_zlib_state(png_structrp png_ptr)924{925if (png_ptr->zlib_state == NULL)926png_create_zlib_state(png_ptr);927928return png_ptr->zlib_state;929}930931/* Internal API to clean up all the deflate related stuff, including the buffer932* lists.933*/934static void /* PRIVATE */935png_deflate_release(png_structrp png_ptr, png_zlib_statep ps, int check)936{937# ifdef PNG_WRITE_FILTER_SUPPORTED938/* Free any mode-specific data that is owned here: */939if (ps->previous_write_row != NULL)940{941png_bytep p = ps->previous_write_row;942ps->previous_write_row = NULL;943png_free(png_ptr, p);944}945946# ifdef PNG_SELECT_FILTER_SUPPORTED947if (ps->current_write_row != NULL)948{949png_bytep p = ps->current_write_row;950ps->current_write_row = NULL;951png_free(png_ptr, p);952}953954if (ps->selector != NULL)955{956struct filter_selector *s = ps->selector;957ps->selector = NULL;958png_free(png_ptr, s);959}960# endif /* SELECT_FILTER */961# endif /* WRITE_FILTER */962963/* The main z_stream opaque pointer needs to remain set to png_ptr; it is964* only set once.965*/966png_zlib_compress_destroy(&ps->s, check);967png_free_compression_buffer(png_ptr, &ps->stash);968}969970void /* PRIVATE */971png_deflate_destroy(png_structrp png_ptr)972{973png_zlib_statep ps = png_ptr->zlib_state;974975if (ps != NULL)976{977png_deflate_release(png_ptr, ps, 0/*check*/);978png_ptr->zlib_state = NULL;979png_free(png_ptr, ps);980}981}982983/* Compression settings.984*985* These are stored packed into a png_uint_32 to make comparison with the986* current setting quick. The packing method uses four bits for each setting987* and reserves '0' for unset.988*989* ps_<setting>_base: The lowest valid value (encoded as 1).990* ps_<setting>_max: The highest valid value.991* ps_<setting>_pos: The position in the range 0..3 (shift of 0..12).992*993* The low 16 bits are the zlib compression parameters:994*/995#define pz_level_base (-1)996#define pz_level_max 9997#define pz_level_pos 0998#define pz_windowBits_base 8999#define pz_windowBits_max 151000#define pz_windowBits_pos 11001#define pz_memLevel_base 11002#define pz_memLevel_max 91003#define pz_memLevel_pos 21004#define pz_strategy_base 01005#define pz_strategy_max 41006#define pz_strategy_pos 31007#define pz_zlib_bits 0xFFFFU1008/* Anything below this is not used directly by zlib: */1009#define pz_png_level_base 01010#define pz_png_level_max 61011#define pz_png_level_pos 410121013#define pz_offset(name) (pz_ ## name ## _base - 1)1014/* setting_value == pz_offset(setting)+encoded_value */1015#define pz_min(name) pz_ ## name ## _base1016#define pz_max(name) pz_ ## name ## _max1017#define pz_shift(name) (4 * pz_ ## name ## _pos)10181019#define pz_bits(name,x) ((int)(((x)>>pz_shift(name))&0xF))1020/* the encoded value, or 0 if unset */10211022/* Enquiries: */1023#define pz_isset(name,x) (pz_bits(name,x) != 0)1024#define pz_value(name,x) (pz_bits(name,x)+pz_offset(name))10251026/* Assignments: */1027#define pz_clear(name,x) ((x)&~((png_uint_32)0xFU<<pz_shift(name)))1028#define pz_encode(name,v) ((png_uint_32)((v)-pz_offset(name))<<pz_shift(name))1029#define pz_change(name,x,v) (pz_clear(name,x) | pz_encode(name, v))10301031/* Direct use/modification: */1032#define pz_var(ps, type) ((ps)->pz_ ## type)1033#define pz_get(ps, type, name, def)\1034(pz_isset(name, pz_var(ps, type)) ? pz_value(name, pz_var(ps, type)) : (def))1035/* pz_assign checks for out-of-range values and clears the setting if these are1036* given. No warning or error is generated.1037*/1038#define pz_assign(ps, type, name, value)\1039(pz_var(ps, type) = pz_clear(name, pz_var(ps, type)) |\1040((value) >= pz_min(name) && (value) <= pz_max(name) ?\1041pz_encode(name, value) : 0))10421043static png_int_321044pz_compression_setting(png_structrp png_ptr, png_uint_32 owner,1045int min, int max, int shift, png_int_32 value, int only_get, int unset)1046/* This is a support function for png_write_setting below. */1047{1048png_zlib_statep ps;1049png_uint_32p psettings;10501051/* The value is only required for a 'set', eliminate out-of-range values1052* first:1053*/1054if (!only_get && (value < min || value > max))1055return PNG_EDOM;10561057/* If setting a value make sure the state exists: */1058if (!only_get)1059ps = get_zlib_state(png_ptr);10601061else if (owner != 0U) /* ps may be NULL */1062ps = png_ptr->zlib_state;10631064else /* get and owner is 0U */1065return 0; /* supported */10661067psettings = NULL;1068switch (owner)1069{1070png_int_32 res;10711072case png_IDAT:1073if (ps != NULL) psettings = &ps->pz_IDAT;1074break;10751076case png_iCCP:1077if (ps != NULL) psettings = &ps->pz_iCCP;1078break;10791080case 0U:1081/* All the settings. At this point the 'get' case has returned 01082* above, the value has been checked and the paramter is 0, therefore1083* valid. Each of the following calls should succeed and it would be1084* reasonable to eliminate the PNG_FAILED tests in a world where1085* software engineers never made mistakes.1086*/1087res = pz_compression_setting(png_ptr, png_IDAT, min, max, shift,1088value, 0/*set*/, 1/*iff unset*/);10891090if (PNG_FAILED(res))1091return res;10921093res = pz_compression_setting(png_ptr, png_iCCP, min, max, shift,1094value, 0/*set*/, 1/*iff unset*/);10951096if (PNG_FAILED(res))1097return res;10981099/* The text settings are changed regardless of the customize support1100* because if WRITE_CUSTOMIZE_ZTXT_COMPRESSION is not supported the old1101* behavior was to use the WRITE_CUSTOMIZE_COMPRESSION setting.1102*1103* However, when we get png_zTXt directly (from png_write_setting) and1104* the support is not compiled in return PNG_ENOSYS.1105*/1106unset = 1; /* i.e. only if not already set */11071108# ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED1109case png_zTXt:1110case png_iTXt:1111# endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */1112if (ps != NULL) psettings = &ps->pz_text;1113break;11141115default:1116/* Return PNG_ENOSYS, not PNG_EINVAL, to support future addition of new1117* compressed chunks and the fact that zTXt and iTXt customization can1118* be disabled.1119*/1120return PNG_ENOSYS;1121}11221123if (psettings == NULL)1124return PNG_UNSET; /* valid setting that is not set */11251126{1127png_uint_32 settings = *psettings;1128png_uint_32 mask = 0xFU << shift;11291130/* Do not set it if 'only_get' was passed in or if 'unset' is true and the1131* setting is not currently set:1132*/1133if (!only_get && ((settings & mask) == 0U || !unset))1134*psettings = (settings & ~mask) +1135((png_uint_32)/*SAFE*/(value-min+1) << shift);11361137settings &= mask;11381139if (settings == 0U)1140return PNG_UNSET;11411142else1143return (int)/*SAFE*/((settings >> shift)-1U) + min;1144}1145}11461147#define compression_setting(pp, owner, setting, value, get)\1148pz_compression_setting(pp, owner, pz_min(setting), pz_max(setting),\1149pz_shift(setting), value, get, 0/*always*/)11501151/* There is (as of zlib 1.2.8) a bug in the implementation of compression with a1152* window size of 256 which zlib works round by resetting windowBits from 8 to 91153* whenever deflateInit2 is called with that value. Fix this up here.1154*/1155static void1156fix_cinfo(png_zlib_statep ps, png_bytep data, png_alloc_size_t data_size)1157{1158/* Do this if the CINFO field is '1', meaning windowBits of 9. The first1159* byte of the stream is the CMF value, CINFO is in the upper four bits.1160*1161* If zlib didn't futz with the value then it should match the value in1162* pz_current; check this is debug. (See below for why this works in the1163* pz_default_settings call.)1164*/1165# define png_ptr png_voidcast(png_const_structrp, ps->s.zs.opaque)1166if (data[0] == 0x18U &&1167pz_get(ps, current, windowBits, 0) == 8 /* i.e. it was requested */)1168{1169/* Double check this here; the fixup only works if the data was 256 bytes1170* or shorter *or* the window is never used. For safety repeat the checks1171* done in pz_default_settings; technically we should be able to just skip1172* this test.1173*1174* TODO: set a 'fixup' flag in zlib_state to make this quicker?1175*/1176if (data_size <= 256U ||1177pz_get(ps, current, strategy, Z_RLE) == Z_HUFFMAN_ONLY ||1178pz_get(ps, current, level, 1) == Z_NO_COMPRESSION)1179{1180unsigned int d1;11811182data[0] = 0x08U;1183/* The header checksum must be fixed too. The FCHECK (low 5 bits) make1184* CMF.FLG a multiple of 31:1185*/1186d1 = data[1] & 0xE0U; /* top three bits */1187d1 += 31U - (0x0800U + d1) % 31U;1188data[1] = PNG_BYTE(d1);1189}11901191else /* pz_default_settings is expected to guarantee the above */1192NOT_REACHED;1193}11941195else if (data_size > 0U)1196{1197/* Prior to 1.7.0 libpng would shrink the windowBits even if the1198* application requested a particular value, so:1199*/1200unsigned int z_cinfo = data[0] >> 4;1201unsigned int half_z_window_size = 1U << (z_cinfo + 7);12021203if (data_size <= half_z_window_size && z_cinfo > 0)1204{1205unsigned int tmp;12061207do1208{1209half_z_window_size >>= 1;1210--z_cinfo;1211}1212while (z_cinfo > 0 && data_size <= half_z_window_size);12131214data[0] = PNG_BYTE((z_cinfo << 4) + 0x8U);1215tmp = data[1] & 0xE0U; /* top three bits */1216tmp += 31U - ((data[0] << 8) + tmp) % 31U;1217data[1] = PNG_BYTE(tmp);1218}1219}12201221else1222NOT_REACHED; /* invalid data size (0) */1223# undef png_ptr1224}12251226static png_uint_321227pz_default_settings(png_uint_32 settings, const png_uint_32 owner,1228const png_alloc_size_t data_size, const unsigned int filters/*for IDAT*/)1229{1230int png_level, strategy, zlib_level, windowBits;12311232/* The png 'level' parameter controls the defaults below. It uses the same1233* numbering scheme as the Zlib compression level except that -1 invokes the1234* set of options and, in some cases, libpng behavior of libpng 1.6 and1235* earlier.1236*1237* In the comments below reference is made to the differences beteen the1238* legacy compression sizes from libpng 1.6 and earlier and the result of1239* using the various options. These are quoted as an overall size change in1240* the compression of 147323 PNG test files. The set of test files is1241* slightly restricted because pre-1.7 versions of png_read_png leave random1242* bits into the final byte of a row which ends with a partial byte. This1243* affects the compression unpredictably so such files were omitted from the1244* measurements.1245*/1246if (!pz_isset(png_level, settings))1247{1248png_level = PNG_DEFAULT_COMPRESSION_LEVEL;1249settings |= pz_encode(png_level, png_level);1250}12511252else1253png_level = pz_value(png_level, settings);12541255/* First default the strategy. At lower data sizes other strategies do as1256* well as the zlib default compression strategy but they never seem to1257* improve on it with the 1.7 filtering.1258*/1259if (!pz_isset(strategy, settings))1260{1261switch (png_level)1262{1263case PNG_COMPRESSION_COMPAT: /* Legacy setting */1264/* The pre-1.7 code used Z_FILTERED normally but uses1265* Z_DEFAULT_STRATEGY for palette or low-bit-depth images.1266*1267* In fact Z_DEFAULT_STRATEGY works best for filtered images as1268* well, however the change in results is small:1269*1270* Z_DEFAULT_STRATEGY: -0.1%1271* Z_FILTERED: +0.1%1272*1273* NOTE: this happened even if WRITE_FILTER was *not* supported.1274*/1275if (owner != png_IDAT || filters == PNG_FILTER_NONE)1276strategy = Z_DEFAULT_STRATEGY;12771278else1279strategy = Z_FILTERED;1280break;12811282case PNG_COMPRESSION_HIGH_SPEED:1283/* RLE is as fast as HUFFMAN_ONLY and can reduce size a lot in a few1284* cases.1285*/1286strategy = Z_RLE;1287break;12881289default: /* For GCC */1290case PNG_COMPRESSION_LOW:1291case PNG_COMPRESSION_MEDIUM:1292/* Z_FILTERED is almost as good as the default and can be1293* significantly faster. It biases the algorithm towards smaller1294* byte values.1295*1296* Using Z_DEFAULT_STRATEGY here, rather than Z_FILTERED, benefits1297* smaller 8 and 16-bit gray and larger 8 and 16-bit RGB images,1298* however the overall gain is only 0.1% because it is offset by1299* losses in larger 8-bit gray and alpha images. It is extremely1300* difficult to deduce a pattern other than biases in the test set1301* of images.1302*1303* Looking at the pattern of behavior with the 1.6 filter selection1304* algorithm (none of palette or low-bit-depth, else all) produces1305* results as follows:1306*/1307if (owner == png_IDAT)1308{1309if (filters == PNG_FILTER_NONE)1310strategy = Z_DEFAULT_STRATEGY;13111312else1313strategy = Z_FILTERED;1314}13151316else if (owner == png_iCCP)1317strategy = Z_DEFAULT_STRATEGY;13181319/* TODO: investigate this, the observed behavior is suspicious: */1320else /* text chunk */1321strategy = Z_FILTERED; /* Always better for some reason */1322break;13231324case PNG_COMPRESSION_LOW_MEMORY:1325/* Reduce memory at all costs, speed doesn't matter. */1326case PNG_COMPRESSION_HIGH_READ_SPEED:1327case PNG_COMPRESSION_HIGH:1328if (owner == png_IDAT || owner == png_iCCP)1329strategy = Z_DEFAULT_STRATEGY;13301331else1332strategy = Z_FILTERED;1333break;1334}13351336settings |= pz_encode(strategy, strategy);1337}13381339else1340strategy = pz_value(strategy, settings);13411342/* Next the zlib level; this just defaults to the png level, except that for1343* Huffman or RLE encoding the level setting for Zlib doesn't matter.1344*/1345if (!pz_isset(level, settings))1346{1347switch (strategy)1348{1349case Z_HUFFMAN_ONLY:1350case Z_RLE:1351/* The 'level' doesn't make any significant difference to the1352* compression with these strategies; in a test set of about 3GByte1353* of PNG files the total compressed size changed under 20 bytes1354* with libpng 1.6!1355*/1356zlib_level = 1;1357break;13581359default: /* Z_FIXED, Z_FILTERED, Z_DEFAULT_STRATEGY */1360/* Everything that uses the window seems to show rapidly diminishing1361* returns above level 6 (at least with libpng 1.6).1362* Z_DEFAULT_COMPRESSION is, in fact, level 6 so Mark seems to1363* concur. With libpng 1.6 the following results were obtained1364* using the full test set of files (including those with a partial1365* byte at the end of the row) and just varying the zlib level:1366*1367* LEVEL SIZE(bytes) CHANGE TIME(s) CHANGE METRIC1368* 9 2550246600 -1.19% 1972 +227% -77%1369* 8 2556675866 -0.94% 1215 +101% -59%1370* 7 2572685552 -0.32% 679 +12% -15%1371* 6 2581196708 0% 604 0% 0%1372* 5 2602831249 +0.84% 414 -30% +87%1373* 4 2625206800 +1.71% 358 -40% +153%1374* 3 2674752349 +3.62% 298 -50% +303%1375* 2 2716261483 +5.23% 262 -56% +537%1376* 1 2749875805 +6.53% 251 -57% +662%1377* 0 7174488347 202 -66%1378*1379* The CHANGE columns express the change in compressed size1380* (positive is an increase; a decrease in compression) and time1381* (positive is an increase; an increase in time) relative to level1382* 6. The METRIC column is a measure of the compression-per-second1383* relative to level 6; positive is an increase in1384* compression-per-second.1385*1386* The metric is derived by assuming the difference in time between1387* level 0 (which does no compression) and the level being1388* considered is spent doing the compression. (Reasonable, since1389* only the level changed). Just the inverse of the product of the1390* size and the time difference is a measure of compression per1391* second. It can be seen that time dominates the metric;1392* compression only varies slightly (under 8%) across the level1393* range.1394*/1395switch (png_level)1396{1397case PNG_COMPRESSION_COMPAT:1398zlib_level = Z_DEFAULT_COMPRESSION; /* NOTE: -1 */1399break;14001401case PNG_COMPRESSION_HIGH_SPEED:1402zlib_level = 1;1403break;14041405default: /* For GCC */1406case PNG_COMPRESSION_LOW:1407zlib_level = 3;1408break;14091410case PNG_COMPRESSION_MEDIUM:1411zlib_level = 6; /* Old default! */1412break;14131414case PNG_COMPRESSION_LOW_MEMORY:1415case PNG_COMPRESSION_HIGH_READ_SPEED:1416case PNG_COMPRESSION_HIGH:1417zlib_level = 9;1418break;1419}1420break;1421}14221423settings |= pz_encode(level, zlib_level);1424}14251426else1427zlib_level = pz_value(level, settings);14281429/* Now default windowBits. This is probably the most important of the1430* settings because it is pretty much the only one that affects decode1431* performance. The smaller the better:1432*/1433if (!pz_isset(windowBits, settings))1434{1435if (png_level == PNG_COMPRESSION_COMPAT/* Legacy */)1436{1437/* This is the libpng16 calculation (it is wrong; a misunderstanding of1438* what zlib actually requires!)1439*1440* Using the code below with the legacy choice of Z_FILTERED or1441* Z_DEFAULT_STRATEGY increases the size of the test files by only1442* 0.04%, however the settings below considerably reduce the windowBits1443* used potentially benefitting read code a lot.1444*1445* NOTE: the algorithm below was determined by experiment and1446* observation with the same set of test files; there is some1447* considerable possibility that a different set might show different1448* results. Obtaining large, representative, test sets is both a1449* considerable amount of work and very error prone. [JB 20160518]1450*/1451windowBits = 15;14521453if (data_size <= 16384U)1454{1455unsigned int half_window_size = 1U << (windowBits-1);14561457while (data_size + 262U <= half_window_size)1458{1459half_window_size >>= 1;1460--windowBits;1461}1462}1463}14641465/* The window size affects the memory used on both read and write but also1466* the time on write (but not normally read). Handle the low memory1467* requirement first:1468*/1469else if (zlib_level == Z_NO_COMPRESSION ||1470png_level == PNG_COMPRESSION_LOW_MEMORY)1471windowBits = 8;14721473/* If the strategy has been set to something that doesn't benefit from1474* higher windowBits values take advantage of this. Note that pz_value1475* returns an invalid value if pz_isset is false.1476*1477* The only png_level that affects this decision is HIGH_SPEED, because1478* a smaller windowBits should speed up the search, however the code above1479* chose zlib_level based on this so ignore that consideration and just1480* use zlib_level below.1481*/1482else switch (strategy)1483{1484png_alloc_size_t test_size;14851486case Z_HUFFMAN_ONLY:1487/* Use the minimum; the window doesn't get used */1488windowBits = 8;1489break;14901491case Z_RLE:1492/* The longest length code is 258 bytes, the shortest string that1493* can achieve this is 259 bytes long; 259 copies of the same byte1494* which can be encoded as a code for the byte value then a string1495* of length 258 starting at the first byte. So if the data is1496* longer than 256 bytes use '9' for the windowBits, otherwise use1497* 8:1498*/1499if (data_size <= 256U)1500windowBits = 8;15011502else1503windowBits = 9;1504break;15051506/* By experiment using about 150,000 files the optimal windowBits1507* value across a range of files is somewhat less than implied by1508* the data size and depends on the zlib level and the strategy1509* used, the following values were determined by experiment using1510* those files:1511*/1512case Z_FILTERED:1513/* The Z_FILTERED case changes suddenly at (zlib) level 4 to1514* benefit from looking at all the data:1515*/1516if (zlib_level < 4 && zlib_level != Z_DEFAULT_COMPRESSION/*-1: 6*/)1517test_size = data_size / 8U;15181519else1520test_size = data_size;15211522goto check_test_size;15231524case Z_FIXED:1525/* With the fixed Huffman tables better compression only ever comes1526* from looking for matches, so, logically:1527*/1528test_size = data_size;1529goto check_test_size;15301531default:1532/* The default algorithm always does better with a window smaller1533* than all the data and shows jumps at level 4 and level 8. The1534* net effect with the test set of images is a very minor overall1535* improvement compared to the pre-1.7 calculation (data size +1536* 262). The benefit is less than 0.01%, however smaller window1537* sizes reduce the memory zlib has to allocate in the decoder.1538*/1539switch (zlib_level)1540{1541case 1: case 2: case 3:1542test_size = data_size / 8U;1543break;15441545default: /* -1(Z_DEFAULT_COMPRESSION) == 6, 4..7 */1546/* This includes, implicitly, ZLIB_NO_COMPRESSION, but that1547* was eliminated in the 'if' above.1548*/1549test_size = data_size / 4U;1550break;15511552case 8: case 9:1553test_size = data_size / 3U;1554break;1555}15561557goto check_test_size;15581559check_test_size:1560/* Find the smallest window that covers 'test_size' bytes, subject1561* to the constraint that if the actual data size is more than 2561562* bytes the minimum windowBits that can be supported is 9:1563*/1564if (data_size <= 256U)1565windowBits = 8;15661567else1568windowBits = 9;15691570while (windowBits < 15 && (1U << windowBits) < test_size)1571++windowBits;15721573break;1574}15751576settings |= pz_encode(windowBits, windowBits);1577}15781579else1580windowBits = pz_value(windowBits, settings);15811582/* zlib has a problem with 256 byte windows; 512 is used instead.1583* We can't work round this if the data size is more than 256 bytes and1584* the strategy actually uses the window (everything except huffman-only)1585* so fix the problem here.1586*/1587if (windowBits == 8 && data_size > 256U && strategy != Z_HUFFMAN_ONLY &&1588zlib_level != Z_NO_COMPRESSION)1589settings = pz_change(windowBits, settings, 9);15901591/* For memLevel this just increases the memory used but can help with the1592* Huffman code generation even to level 9 (the maximum), so just set the1593* max. This affects memory used, not (apparently) compression speed so1594* the only relevant png_level is LOW_MEMORY.1595*1596* The legacy setting is '8'; this is the level that Zlib defaults to because1597* 16-bit iAPX86 systems could not handle '9'. Because MAX_MEM_LEVEL is used1598* below this does not matter; zconf.h selects 8 or 9 as appropriate.1599*1600* In fact using '9' with the legacy settings increases the size of the test1601* set minutely; +0.007%. This is hardly significant; 0.007% of the test1602* images equals 10 images. (Nevertheless it is interesting, just as the1603* observation that decreasing windowBits can result in smaller compressed1604* sizes is interesting.)1605*/1606if (!pz_isset(memLevel, settings))1607{1608int memLevel;16091610switch (png_level)1611{1612case PNG_COMPRESSION_COMPAT:1613memLevel = 8;1614break;16151616case PNG_COMPRESSION_LOW_MEMORY:1617memLevel = 1;1618break;16191620default:1621memLevel = MAX_MEM_LEVEL/*from zconf.h*/;1622break;1623}16241625settings |= pz_encode(memLevel, memLevel);1626}16271628return settings;1629}16301631/* This is used below to find the size of an image to pass to png_deflate_claim.1632* It returns 0 for images whose size would overflow a 32-bit integer or have1633* rows which cannot be allocated.1634*/1635static png_alloc_size_t1636png_image_size(png_const_structrp png_ptr)1637{1638/* The size returned here is limited to PNG_SIZE_MAX, if the size would1639* exceed that (or is close to exceeding that) 0 is returned. See below for1640* a variant that limits the size of 0xFFFFFFFFU.1641*/1642const png_alloc_size_t rowbytes = png_ptr->zlib_state->write_row_size;16431644/* NON-INTERLACED: (1+rowbytes) * h1645* INTERLACED: Each pixel is transmitted exactly once, so the size is1646* (rowbytes * h) + the count of filter bytes. Each complete1647* block of 8 image rows generates at most 15 output rows1648* (less for narrow images), so the filter byte count is1649* at most (15*h/8)+14. Because the original rows are split1650* extra byte passing may be introduced. Account for this by1651* allowing an extra 1 byte per output row; that's two bytes1652* including the filer byte.1653*1654* So:1655* NON-INTERLACED: (rowbytes * h) + h1656* INTERLACED: < (rowbytes * h) + 2*(15 * h/8) + 2*151657*1658* Hence:1659*/1660if (rowbytes != 0)1661{1662const png_uint_32 h = png_ptr->height;16631664if (png_ptr->interlaced == PNG_INTERLACE_NONE)1665{1666const png_alloc_size_t limit = PNG_SIZE_MAX / h;16671668/* On 16-bit systems the above might be 0, so: */1669if (rowbytes </*allow 1 for filter byte*/ limit)1670return (rowbytes+1U) * h;1671}16721673else /* INTERLACED */1674{1675const png_uint_32 w = png_ptr->width;16761677/* Interlacing makes the image larger because of the replication of1678* both the filter byte and the padding to a byte boundary.1679*/1680png_alloc_size_t cb_base;1681int pass;16821683for (cb_base=0, pass=0; pass<PNG_INTERLACE_ADAM7_PASSES; ++pass)1684{1685const png_uint_32 pass_w = PNG_PASS_COLS(w, pass);16861687if (pass_w > 0)1688{1689const png_uint_32 pass_h = PNG_PASS_ROWS(h, pass);16901691if (pass_h > 0)1692{1693/* This is the number of bytes available for each row of this1694* pass:1695*/1696const png_alloc_size_t limit = (PNG_SIZE_MAX - cb_base)/pass_h;1697/* This cannot overflow because if it did rowbytes would1698* have been 0 above.1699*/1700const png_alloc_size_t pass_bytes =1701PNG_ROWBYTES(png_ptr->row_output_pixel_depth, pass_w);17021703if (pass_bytes </*allow 1 for filter byte*/ limit)1704cb_base += (pass_bytes+1U) * pass_h;17051706else1707return 0U; /* insufficient address space left */1708}1709}1710}17111712return cb_base;1713}1714}17151716/* Failure case: */1717return 0U;1718}17191720/* Initialize the compressor for the appropriate type of compression. */1721static png_zlib_statep1722png_deflate_claim(png_structrp png_ptr, png_uint_32 owner,1723png_alloc_size_t data_size)1724{1725png_zlib_statep ps = get_zlib_state(png_ptr);17261727affirm(png_ptr->zowner == 0);17281729{1730int ret; /* zlib return code */1731unsigned int filters = 0U;1732png_uint_32 settings;17331734switch (owner)1735{1736case png_IDAT:1737debug(data_size == 0U);1738data_size = png_image_size(png_ptr);17391740if (data_size == 0U)1741data_size = PNG_SIZE_MAX;17421743settings = ps->pz_IDAT;1744# ifdef PNG_WRITE_FILTER_SUPPORTED1745filters = ps->filter_mask;1746debug(filters != 0U);1747# else /* !WRITE_FILTER */1748filters = PNG_FILTER_NONE;1749# endif /* !WRITE_FILTER */1750break;17511752case png_iCCP:1753settings = ps->pz_iCCP;1754break;17551756default: /* text chunk */1757settings = ps->pz_text;1758break;1759}17601761settings = pz_default_settings(settings, owner, data_size, filters);17621763/* Check against the previous initialized values, if any. The relevant1764* settings are in the low 16 bits.1765*/1766if (ps->s.zs.state != NULL &&1767((settings ^ ps->pz_current) & pz_zlib_bits) != 0U)1768png_deflateEnd(png_ptr, &ps->s.zs, 0/*check*/);17691770/* For safety clear out the input and output pointers (currently zlib1771* doesn't use them on Init, but it might in the future).1772*/1773ps->s.zs.next_in = NULL;1774ps->s.zs.avail_in = 0;1775ps->s.zs.next_out = NULL;1776ps->s.zs.avail_out = 0;17771778/* The length fields must be cleared too and the lists reset: */1779ps->s.overflow = ps->s.len = ps->s.start = 0U;17801781if (ps->s.list != NULL) /* error in prior chunk writing */1782{1783debug(ps->stash == NULL);1784ps->stash = ps->s.list;1785ps->s.list = NULL;1786}17871788ps->s.end = &ps->s.list;17891790/* Now initialize if required, setting the new parameters, otherwise just1791* do a simple reset to the previous parameters.1792*/1793if (ps->s.zs.state != NULL)1794ret = deflateReset(&ps->s.zs);17951796else1797ret = deflateInit2(&ps->s.zs, pz_value(level, settings), Z_DEFLATED,1798pz_value(windowBits, settings), pz_value(memLevel, settings),1799pz_value(strategy, settings));18001801ps->pz_current = settings;18021803/* The return code is from either deflateReset or deflateInit2; they have1804* pretty much the same set of error codes.1805*/1806if (ret == Z_OK && ps->s.zs.state != NULL)1807png_ptr->zowner = owner;18081809else1810{1811png_zstream_error(&ps->s.zs, ret);1812png_error(png_ptr, ps->s.zs.msg);1813}1814}18151816return ps;1817}18181819#ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED /* includes iCCP */1820/* Compress the block of data at the end of a chunk. This claims and releases1821* png_struct::z_stream. It returns the amount of data in the chunk list or1822* zero on error (a zlib stream always contains some bytes!)1823*1824* prefix_len is the amount of (uncompressed) data before the start of the1825* compressed data. The routine will return 0 if the total of the compressed1826* data and the prefix exceeds PNG_UINT_MAX_31.1827*1828* NOTE: this function may not return; it only returns 0 if1829* png_chunk_report(PNG_CHUNK_WRITE_ERROR) returns (not the default).1830*/1831static int /* success */1832png_compress_chunk_data(png_structrp png_ptr, png_uint_32 chunk_name,1833png_uint_32 prefix_len, png_const_voidp input, png_alloc_size_t input_len)1834{1835/* To find the length of the output it is necessary to first compress the1836* input. The result is buffered rather than using the two-pass algorithm1837* that is used on the inflate side; deflate is assumed to be slower and a1838* PNG writer is assumed to have more memory available than a PNG reader.1839*1840* IMPLEMENTATION NOTE: the zlib API deflateBound() can be used to find an1841* upper limit on the output size, but it is always bigger than the input1842* size so it is likely to be more efficient to use this linked-list1843* approach.1844*/1845png_zlib_statep ps = png_deflate_claim(png_ptr, chunk_name, input_len);18461847affirm(ps != NULL);18481849/* The data compression function always returns so that we can clean up. */1850ps->s.zs.next_in = PNGZ_INPUT_CAST(png_voidcast(const Bytef*, input));18511852/* Use the stash, if available: */1853debug(ps->s.list == NULL);1854ps->s.list = ps->stash;1855ps->stash = NULL;18561857{1858int ret = png_compress(&ps->s, input_len, PNG_UINT_31_MAX-prefix_len,1859Z_FINISH);18601861ps->s.zs.next_out = NULL; /* safety */1862ps->s.zs.avail_out = 0;1863ps->s.zs.next_in = NULL;1864ps->s.zs.avail_in = 0;1865png_ptr->zowner = 0; /* release png_ptr::zstream */18661867/* Since Z_FINISH was passed as the flush parameter any result other than1868* Z_STREAM_END is an error. In any case in the event of an error free1869* the whole compression state; the only expected error is Z_MEM_ERROR.1870*/1871if (ret != Z_STREAM_END)1872{1873png_zlib_compress_destroy(&ps->s, 0/*check*/);18741875/* This is not very likely given the PNG_UINT_31_MAX limit above, but1876* if code is added to limit the size of the chunks produced it can1877* start to happen.1878*/1879if (ret == Z_BUF_ERROR)1880ps->s.zs.msg = PNGZ_MSG_CAST("compressed chunk too long");18811882else1883png_zstream_error(&ps->s.zs, ret);18841885png_chunk_report(png_ptr, ps->s.zs.msg, PNG_CHUNK_WRITE_ERROR);1886return 0;1887}1888}18891890/* png_compress is meant to guarantee this on a successful return: */1891affirm(ps->s.overflow == 0U && ps->s.len <= PNG_UINT_31_MAX - prefix_len);18921893/* Correct the zlib CINFO field: */1894if (ps->s.len >= 2U)1895fix_cinfo(ps, ps->s.list->output, input_len);18961897return 1;1898}18991900/* Return the length of the compressed data; this is effectively a debug1901* function to catch inconsistencies caused by internal errors. It will1902* disappear in a release build.1903*/1904#if PNG_RELEASE_BUILD1905# define png_length_compressed_chunk_data(pp, p) ((pp)->zlib_state->s.len)1906#else /* !RELEASE_BUILD */1907static png_uint_321908png_length_compressed_chunk_data(png_structrp png_ptr, png_uint_32 p)1909{1910png_zlib_statep ps = png_ptr->zlib_state;19111912debug(ps != NULL && ps->s.overflow == 0U && ps->s.len <= PNG_UINT_31_MAX-p);1913return ps->s.len;1914}1915#endif /* !RELEASE_BUILD */19161917/* Write all the data produced by the above function; the caller must write the1918* prefix and chunk header.1919*/1920static void1921png_write_compressed_chunk_data(png_structrp png_ptr)1922{1923png_zlib_statep ps = png_ptr->zlib_state;1924png_compression_bufferp next;1925png_uint_32 output_len;19261927affirm(ps != NULL && ps->s.overflow == 0U);1928next = ps->s.list;19291930for (output_len = ps->s.len; output_len > 0U; next = next->next)1931{1932png_uint_32 size = PNG_ROW_BUFFER_SIZE;19331934/* If this affirm fails there is a bug in the calculation of1935* output_length above, or in the buffer_limit code in png_compress.1936*/1937affirm(next != NULL && output_len > 0U);19381939if (size > output_len)1940size = output_len;19411942png_write_chunk_data(png_ptr, next->output, size);19431944output_len -= size;1945}19461947/* Release the list back to the stash. */1948debug(ps->stash == NULL);1949ps->stash = ps->s.list;1950ps->s.list = NULL;1951ps->s.end = &ps->s.list;1952}1953#endif /* WRITE_COMPRESSED_TEXT */19541955#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \1956defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)1957/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,1958* and if invalid, correct the keyword rather than discarding the entire1959* chunk. The PNG 1.0 specification requires keywords 1-79 characters in1960* length, forbids leading or trailing whitespace, multiple internal spaces,1961* and the non-break space (0x80) from ISO 8859-1. Returns keyword length.1962*1963* The 'new_key' buffer must be at least 80 characters in size (for the keyword1964* plus a trailing '\0'). If this routine returns 0 then there was no keyword,1965* or a valid one could not be generated, and the caller must CHUNK_WRITE_ERROR.1966*/1967static unsigned int1968png_check_keyword(png_structrp png_ptr, png_const_charp key, png_bytep new_key)1969{1970png_const_charp orig_key = key;1971unsigned int key_len = 0;1972int bad_character = 0;1973int space = 1;19741975png_debug(1, "in png_check_keyword");19761977if (key == NULL)1978{1979*new_key = 0;1980return 0;1981}19821983while (*key && key_len < 79)1984{1985png_byte ch = (png_byte)(0xff & *key++);19861987if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/))1988*new_key++ = ch, ++key_len, space = 0;19891990else if (space == 0)1991{1992/* A space or an invalid character when one wasn't seen immediately1993* before; output just a space.1994*/1995*new_key++ = 32, ++key_len, space = 1;19961997/* If the character was not a space then it is invalid. */1998if (ch != 32)1999bad_character = ch;2000}20012002else if (bad_character == 0)2003bad_character = ch; /* just skip it, record the first error */2004}20052006if (key_len > 0 && space != 0) /* trailing space */2007{2008--key_len, --new_key;2009if (bad_character == 0)2010bad_character = 32;2011}20122013/* Terminate the keyword */2014*new_key = 0;20152016if (key_len == 0)2017return 0;20182019#ifdef PNG_WARNINGS_SUPPORTED2020/* Try to only output one warning per keyword: */2021if (*key != 0) /* keyword too long */2022png_app_warning(png_ptr, "keyword truncated");20232024else if (bad_character != 0)2025{2026PNG_WARNING_PARAMETERS(p)20272028png_warning_parameter(p, 1, orig_key);2029png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_02x, bad_character);20302031png_formatted_warning(png_ptr, p, "keyword \"@1\": bad character '0x@2'");2032}2033#endif /* WARNINGS */20342035return key_len;2036}2037#endif /* WRITE_TEXT || WRITE_pCAL || WRITE_iCCP || WRITE_sPLT */20382039/* Write the IHDR chunk, and update the png_struct with the necessary2040* information. Note that the rest of this code depends upon this2041* information being correct.2042*/2043void /* PRIVATE */2044png_write_IHDR(png_structrp png_ptr, png_uint_32 width, png_uint_32 height,2045int bit_depth, int color_type, int compression_type, int filter_method,2046int interlace_type)2047{2048png_byte buf[13]; /* Buffer to store the IHDR info */20492050png_debug(1, "in png_write_IHDR");20512052/* Check that we have valid input data from the application info */2053switch (color_type)2054{2055case PNG_COLOR_TYPE_GRAY:2056switch (bit_depth)2057{2058case 1:2059case 2:2060case 4:2061case 8:2062#ifdef PNG_WRITE_16BIT_SUPPORTED2063case 16:2064#endif2065break;20662067default:2068png_error(png_ptr, "Invalid bit depth for grayscale image");2069}2070break;20712072case PNG_COLOR_TYPE_RGB:2073#ifdef PNG_WRITE_16BIT_SUPPORTED2074if (bit_depth != 8 && bit_depth != 16)2075#else2076if (bit_depth != 8)2077#endif2078png_error(png_ptr, "Invalid bit depth for RGB image");20792080break;20812082case PNG_COLOR_TYPE_PALETTE:2083switch (bit_depth)2084{2085case 1:2086case 2:2087case 4:2088case 8:2089break;20902091default:2092png_error(png_ptr, "Invalid bit depth for paletted image");2093}2094break;20952096case PNG_COLOR_TYPE_GRAY_ALPHA:2097if (bit_depth != 8 && bit_depth != 16)2098png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");20992100break;21012102case PNG_COLOR_TYPE_RGB_ALPHA:2103#ifdef PNG_WRITE_16BIT_SUPPORTED2104if (bit_depth != 8 && bit_depth != 16)2105#else2106if (bit_depth != 8)2107#endif2108png_error(png_ptr, "Invalid bit depth for RGBA image");21092110break;21112112default:2113png_error(png_ptr, "Invalid image color type specified");2114}21152116if (compression_type != PNG_COMPRESSION_TYPE_BASE)2117{2118png_app_error(png_ptr, "Invalid compression type specified");2119compression_type = PNG_COMPRESSION_TYPE_BASE;2120}21212122/* Write filter_method 64 (intrapixel differencing) only if2123* 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and2124* 2. Libpng did not write a PNG signature (this filter_method is only2125* used in PNG datastreams that are embedded in MNG datastreams) and2126* 3. The application called png_permit_mng_features with a mask that2127* included PNG_FLAG_MNG_FILTER_64 and2128* 4. The filter_method is 64 and2129* 5. The color_type is RGB or RGBA2130*/2131if (2132# ifdef PNG_MNG_FEATURES_SUPPORTED2133!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&2134((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&2135(color_type == PNG_COLOR_TYPE_RGB ||2136color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&2137(filter_method == PNG_INTRAPIXEL_DIFFERENCING)) &&2138# endif /* MNG_FEATURES */2139filter_method != PNG_FILTER_TYPE_BASE)2140{2141png_app_error(png_ptr, "Invalid filter type specified");2142filter_method = PNG_FILTER_TYPE_BASE;2143}21442145if (interlace_type != PNG_INTERLACE_NONE &&2146interlace_type != PNG_INTERLACE_ADAM7)2147{2148png_app_error(png_ptr, "Invalid interlace type specified");2149interlace_type = PNG_INTERLACE_ADAM7;2150}21512152/* Save the relevant information */2153png_ptr->bit_depth = png_check_byte(png_ptr, bit_depth);2154png_ptr->color_type = png_check_byte(png_ptr, color_type);2155png_ptr->interlaced = png_check_byte(png_ptr, interlace_type);2156png_ptr->filter_method = png_check_byte(png_ptr, filter_method);2157png_ptr->width = width;2158png_ptr->height = height;21592160/* Pack the header information into the buffer */2161png_save_uint_32(buf, width);2162png_save_uint_32(buf + 4, height);2163buf[8] = png_check_byte(png_ptr, bit_depth);2164buf[9] = png_check_byte(png_ptr, color_type);2165buf[10] = png_check_byte(png_ptr, compression_type);2166buf[11] = png_check_byte(png_ptr, filter_method);2167buf[12] = png_check_byte(png_ptr, interlace_type);21682169/* Write the chunk */2170png_write_complete_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);2171png_ptr->mode |= PNG_HAVE_IHDR;2172}21732174/* Write the palette. We are careful not to trust png_color to be in the2175* correct order for PNG, so people can redefine it to any convenient2176* structure.2177*/2178void /* PRIVATE */2179png_write_PLTE(png_structrp png_ptr, png_const_colorp palette,2180unsigned int num_pal)2181{2182png_uint_32 max_palette_length, i;2183png_const_colorp pal_ptr;2184png_byte buf[3];21852186png_debug(1, "in png_write_PLTE");21872188max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?2189(1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;21902191if ((2192# ifdef PNG_MNG_FEATURES_SUPPORTED2193(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 &&2194# endif /* MNG_FEATURES */2195num_pal == 0) || num_pal > max_palette_length)2196{2197if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)2198{2199png_error(png_ptr, "Invalid number of colors in palette");2200}22012202else2203{2204png_warning(png_ptr, "Invalid number of colors in palette");2205return;2206}2207}22082209if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)2210{2211png_warning(png_ptr,2212"Ignoring request to write a PLTE chunk in grayscale PNG");22132214return;2215}22162217png_ptr->num_palette = png_check_bits(png_ptr, num_pal, 9);2218png_debug1(3, "num_palette = %d", png_ptr->num_palette);22192220png_write_chunk_header(png_ptr, png_PLTE, num_pal * 3U);22212222for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)2223{2224buf[0] = pal_ptr->red;2225buf[1] = pal_ptr->green;2226buf[2] = pal_ptr->blue;2227png_write_chunk_data(png_ptr, buf, 3U);2228}22292230png_write_chunk_end(png_ptr);2231png_ptr->mode |= PNG_HAVE_PLTE;2232}22332234/* Write an IEND chunk */2235void /* PRIVATE */2236png_write_IEND(png_structrp png_ptr)2237{2238png_debug(1, "in png_write_IEND");22392240png_write_complete_chunk(png_ptr, png_IEND, NULL, (png_size_t)0);2241png_ptr->mode |= PNG_HAVE_IEND;2242}22432244#if defined(PNG_WRITE_gAMA_SUPPORTED) || defined(PNG_WRITE_cHRM_SUPPORTED)2245static int2246png_save_int_31(png_structrp png_ptr, png_bytep buf, png_int_32 i)2247/* Save a signed value as a PNG unsigned value; the argument is required to2248* be in the range 0..0x7FFFFFFFU. If not a *warning* is produced and false2249* is returned. Because this is only called from png_write_cHRM_fixed and2250* png_write_gAMA_fixed below this is safe (we don't need either chunk,2251* particularly if the value is bogus.)2252*2253* The warning is png_app_error; it may return if the app tells it to but the2254* app can have it error out. JB 20150821: I believe the checking in png.c2255* actually makes this error impossible, but this is safe.2256*/2257{2258#ifndef __COVERITY__2259if (i >= 0 && i <= 0x7FFFFFFF)2260#else2261/* Supress bogus Coverity complaint */2262if (i >= 0)2263#endif2264{2265png_save_uint_32(buf, (png_uint_32)/*SAFE*/i);2266return 1;2267}22682269else2270{2271png_chunk_report(png_ptr, "negative value in cHRM or gAMA",2272PNG_CHUNK_WRITE_ERROR);2273return 0;2274}2275}2276#endif /* WRITE_gAMA || WRITE_cHRM */22772278#ifdef PNG_WRITE_gAMA_SUPPORTED2279/* Write a gAMA chunk */2280void /* PRIVATE */2281png_write_gAMA_fixed(png_structrp png_ptr, png_fixed_point file_gamma)2282{2283png_byte buf[4];22842285png_debug(1, "in png_write_gAMA");22862287/* file_gamma is saved in 1/100,000ths */2288if (png_save_int_31(png_ptr, buf, file_gamma))2289png_write_complete_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);2290}2291#endif22922293#ifdef PNG_WRITE_sRGB_SUPPORTED2294/* Write a sRGB chunk */2295void /* PRIVATE */2296png_write_sRGB(png_structrp png_ptr, int srgb_intent)2297{2298png_byte buf[1];22992300png_debug(1, "in png_write_sRGB");23012302if (srgb_intent >= PNG_sRGB_INTENT_LAST)2303png_chunk_report(png_ptr, "Invalid sRGB rendering intent specified",2304PNG_CHUNK_WRITE_ERROR);23052306buf[0] = png_check_byte(png_ptr, srgb_intent);2307png_write_complete_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);2308}2309#endif23102311#ifdef PNG_WRITE_iCCP_SUPPORTED2312/* Write an iCCP chunk */2313void /* PRIVATE */2314png_write_iCCP(png_structrp png_ptr, png_const_charp name,2315png_const_voidp profile)2316{2317png_uint_32 name_len;2318png_uint_32 profile_len;2319png_byte new_name[81]; /* 1 byte for the compression byte */23202321png_debug(1, "in png_write_iCCP");23222323affirm(profile != NULL);23242325profile_len = png_get_uint_32(profile);2326name_len = png_check_keyword(png_ptr, name, new_name);23272328if (name_len == 0)2329{2330png_chunk_report(png_ptr, "iCCP: invalid keyword", PNG_CHUNK_WRITE_ERROR);2331return;2332}23332334++name_len; /* trailing '\0' */2335new_name[name_len++] = PNG_COMPRESSION_TYPE_BASE;23362337if (png_compress_chunk_data(png_ptr, png_iCCP, name_len, profile,2338profile_len))2339{2340png_write_chunk_header(png_ptr, png_iCCP,2341name_len+png_length_compressed_chunk_data(png_ptr, name_len));2342png_write_chunk_data(png_ptr, new_name, name_len);2343png_write_compressed_chunk_data(png_ptr);2344png_write_chunk_end(png_ptr);2345}2346}2347#endif23482349#ifdef PNG_WRITE_sPLT_SUPPORTED2350/* Write a sPLT chunk */2351void /* PRIVATE */2352png_write_sPLT(png_structrp png_ptr, png_const_sPLT_tp spalette)2353{2354png_uint_32 name_len;2355png_byte new_name[80];2356png_byte entrybuf[10];2357png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);2358png_size_t palette_size = entry_size * spalette->nentries;2359png_sPLT_entryp ep;23602361png_debug(1, "in png_write_sPLT");23622363name_len = png_check_keyword(png_ptr, spalette->name, new_name);23642365if (name_len == 0)2366png_error(png_ptr, "sPLT: invalid keyword");23672368/* Make sure we include the NULL after the name */2369png_write_chunk_header(png_ptr, png_sPLT,2370(png_uint_32)(name_len + 2 + palette_size));23712372png_write_chunk_data(png_ptr, new_name, name_len + 1);23732374png_write_chunk_data(png_ptr, &spalette->depth, 1);23752376/* Loop through each palette entry, writing appropriately */2377for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)2378{2379if (spalette->depth == 8)2380{2381entrybuf[0] = png_check_byte(png_ptr, ep->red);2382entrybuf[1] = png_check_byte(png_ptr, ep->green);2383entrybuf[2] = png_check_byte(png_ptr, ep->blue);2384entrybuf[3] = png_check_byte(png_ptr, ep->alpha);2385png_save_uint_16(entrybuf + 4, ep->frequency);2386}23872388else2389{2390png_save_uint_16(entrybuf + 0, ep->red);2391png_save_uint_16(entrybuf + 2, ep->green);2392png_save_uint_16(entrybuf + 4, ep->blue);2393png_save_uint_16(entrybuf + 6, ep->alpha);2394png_save_uint_16(entrybuf + 8, ep->frequency);2395}23962397png_write_chunk_data(png_ptr, entrybuf, entry_size);2398}23992400png_write_chunk_end(png_ptr);2401}2402#endif24032404#ifdef PNG_WRITE_sBIT_SUPPORTED2405/* Write the sBIT chunk */2406void /* PRIVATE */2407png_write_sBIT(png_structrp png_ptr, png_const_color_8p sbit, int color_type)2408{2409png_byte buf[4];2410png_size_t size;24112412png_debug(1, "in png_write_sBIT");24132414/* Make sure we don't depend upon the order of PNG_COLOR_8 */2415if ((color_type & PNG_COLOR_MASK_COLOR) != 0)2416{2417unsigned int maxbits;24182419maxbits = color_type==PNG_COLOR_TYPE_PALETTE ? 8 : png_ptr->bit_depth;24202421if (sbit->red == 0 || sbit->red > maxbits ||2422sbit->green == 0 || sbit->green > maxbits ||2423sbit->blue == 0 || sbit->blue > maxbits)2424{2425png_app_error(png_ptr, "Invalid sBIT depth specified");2426return;2427}24282429buf[0] = sbit->red;2430buf[1] = sbit->green;2431buf[2] = sbit->blue;2432size = 3;2433}24342435else2436{2437if (sbit->gray == 0 || sbit->gray > png_ptr->bit_depth)2438{2439png_app_error(png_ptr, "Invalid sBIT depth specified");2440return;2441}24422443buf[0] = sbit->gray;2444size = 1;2445}24462447if ((color_type & PNG_COLOR_MASK_ALPHA) != 0)2448{2449if (sbit->alpha == 0 || sbit->alpha > png_ptr->bit_depth)2450{2451png_app_error(png_ptr, "Invalid sBIT depth specified");2452return;2453}24542455buf[size++] = sbit->alpha;2456}24572458png_write_complete_chunk(png_ptr, png_sBIT, buf, size);2459}2460#endif24612462#ifdef PNG_WRITE_cHRM_SUPPORTED2463/* Write the cHRM chunk */2464void /* PRIVATE */2465png_write_cHRM_fixed(png_structrp png_ptr, const png_xy *xy)2466{2467png_byte buf[32];24682469png_debug(1, "in png_write_cHRM");24702471/* Each value is saved in 1/100,000ths */2472if (png_save_int_31(png_ptr, buf, xy->whitex) &&2473png_save_int_31(png_ptr, buf + 4, xy->whitey) &&2474png_save_int_31(png_ptr, buf + 8, xy->redx) &&2475png_save_int_31(png_ptr, buf + 12, xy->redy) &&2476png_save_int_31(png_ptr, buf + 16, xy->greenx) &&2477png_save_int_31(png_ptr, buf + 20, xy->greeny) &&2478png_save_int_31(png_ptr, buf + 24, xy->bluex) &&2479png_save_int_31(png_ptr, buf + 28, xy->bluey))2480png_write_complete_chunk(png_ptr, png_cHRM, buf, 32);2481}2482#endif24832484#ifdef PNG_WRITE_tRNS_SUPPORTED2485/* Write the tRNS chunk */2486void /* PRIVATE */2487png_write_tRNS(png_structrp png_ptr, png_const_bytep trans_alpha,2488png_const_color_16p tran, int num_trans, int color_type)2489{2490png_byte buf[6];24912492png_debug(1, "in png_write_tRNS");24932494if (color_type == PNG_COLOR_TYPE_PALETTE)2495{2496affirm(num_trans > 0 && num_trans <= PNG_MAX_PALETTE_LENGTH);2497{2498# ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED2499union2500{2501png_uint_32 u32[1];2502png_byte b8[PNG_MAX_PALETTE_LENGTH];2503} inverted_alpha;25042505/* Invert the alpha channel (in tRNS) if required */2506if (png_ptr->write_invert_alpha)2507{2508int i;25092510memcpy(inverted_alpha.b8, trans_alpha, num_trans);25112512for (i=0; 4*i<num_trans; ++i)2513inverted_alpha.u32[i] = ~inverted_alpha.u32[i];25142515trans_alpha = inverted_alpha.b8;2516}2517# endif /* WRITE_INVERT_ALPHA */25182519png_write_complete_chunk(png_ptr, png_tRNS, trans_alpha, num_trans);2520}2521}25222523else if (color_type == PNG_COLOR_TYPE_GRAY)2524{2525/* One 16 bit value */2526affirm(tran->gray < (1 << png_ptr->bit_depth));2527png_save_uint_16(buf, tran->gray);2528png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);2529}25302531else if (color_type == PNG_COLOR_TYPE_RGB)2532{2533/* Three 16 bit values */2534png_save_uint_16(buf, tran->red);2535png_save_uint_16(buf + 2, tran->green);2536png_save_uint_16(buf + 4, tran->blue);2537affirm(png_ptr->bit_depth == 8 || (buf[0] | buf[2] | buf[4]) == 0);2538png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);2539}25402541else /* Already checked in png_set_tRNS */2542impossible("invalid tRNS");2543}2544#endif25452546#ifdef PNG_WRITE_bKGD_SUPPORTED2547/* Write the background chunk */2548void /* PRIVATE */2549png_write_bKGD(png_structrp png_ptr, png_const_color_16p back, int color_type)2550{2551png_byte buf[6];25522553png_debug(1, "in png_write_bKGD");25542555if (color_type == PNG_COLOR_TYPE_PALETTE)2556{2557if (2558# ifdef PNG_MNG_FEATURES_SUPPORTED2559(png_ptr->num_palette != 0 ||2560(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0) &&2561# endif /* MNG_FEATURES */2562back->index >= png_ptr->num_palette)2563{2564png_app_error(png_ptr, "Invalid background palette index");2565return;2566}25672568buf[0] = back->index;2569png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);2570}25712572else if ((color_type & PNG_COLOR_MASK_COLOR) != 0)2573{2574png_save_uint_16(buf, back->red);2575png_save_uint_16(buf + 2, back->green);2576png_save_uint_16(buf + 4, back->blue);2577#ifdef PNG_WRITE_16BIT_SUPPORTED2578if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]) != 0)2579#else2580if ((buf[0] | buf[2] | buf[4]) != 0)2581#endif2582{2583png_app_error(png_ptr,2584"Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");25852586return;2587}25882589png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);2590}25912592else2593{2594if (back->gray >= (1 << png_ptr->bit_depth))2595{2596png_app_error(png_ptr,2597"Ignoring attempt to write bKGD chunk out-of-range for bit_depth");25982599return;2600}26012602png_save_uint_16(buf, back->gray);2603png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);2604}2605}2606#endif26072608#ifdef PNG_WRITE_hIST_SUPPORTED2609/* Write the histogram */2610void /* PRIVATE */2611png_write_hIST(png_structrp png_ptr, png_const_uint_16p hist, int num_hist)2612{2613int i;2614png_byte buf[3];26152616png_debug(1, "in png_write_hIST");26172618if (num_hist > (int)png_ptr->num_palette)2619{2620png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,2621png_ptr->num_palette);26222623png_warning(png_ptr, "Invalid number of histogram entries specified");2624return;2625}26262627png_write_chunk_header(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));26282629for (i = 0; i < num_hist; i++)2630{2631png_save_uint_16(buf, hist[i]);2632png_write_chunk_data(png_ptr, buf, (png_size_t)2);2633}26342635png_write_chunk_end(png_ptr);2636}2637#endif26382639#ifdef PNG_WRITE_tEXt_SUPPORTED2640/* Write a tEXt chunk */2641void /* PRIVATE */2642png_write_tEXt(png_structrp png_ptr, png_const_charp key, png_const_charp text,2643png_size_t text_len)2644{2645unsigned int key_len;2646png_byte new_key[80];26472648png_debug(1, "in png_write_tEXt");26492650key_len = png_check_keyword(png_ptr, key, new_key);26512652if (key_len == 0)2653{2654png_chunk_report(png_ptr, "tEXt: invalid keyword", PNG_CHUNK_WRITE_ERROR);2655return;2656}26572658if (text == NULL || *text == '\0')2659text_len = 0;26602661else2662text_len = strlen(text);26632664if (text_len > PNG_UINT_31_MAX - (key_len+1))2665{2666png_chunk_report(png_ptr, "tEXt: text too long", PNG_CHUNK_WRITE_ERROR);2667return;2668}26692670/* Make sure we include the 0 after the key */2671png_write_chunk_header(png_ptr, png_tEXt,2672(png_uint_32)/*checked above*/(key_len + text_len + 1));2673/*2674* We leave it to the application to meet PNG-1.0 requirements on the2675* contents of the text. PNG-1.0 through PNG-1.2 discourage the use of2676* any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.2677* The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.2678*/2679png_write_chunk_data(png_ptr, new_key, key_len + 1);26802681if (text_len != 0)2682png_write_chunk_data(png_ptr, (png_const_bytep)text, text_len);26832684png_write_chunk_end(png_ptr);2685}2686#endif26872688#ifdef PNG_WRITE_zTXt_SUPPORTED2689/* Write a compressed text chunk */2690void /* PRIVATE */2691png_write_zTXt(png_structrp png_ptr, png_const_charp key, png_const_charp text,2692int compression)2693{2694unsigned int key_len;2695png_byte new_key[81];26962697png_debug(1, "in png_write_zTXt");26982699if (compression != PNG_TEXT_COMPRESSION_zTXt)2700png_app_warning(png_ptr, "zTXt: invalid compression type ignored");27012702key_len = png_check_keyword(png_ptr, key, new_key);27032704if (key_len == 0)2705{2706png_chunk_report(png_ptr, "zTXt: invalid keyword", PNG_CHUNK_WRITE_ERROR);2707return;2708}27092710/* Add the compression method and 1 for the keyword separator. */2711++key_len;2712new_key[key_len++] = PNG_COMPRESSION_TYPE_BASE;27132714if (png_compress_chunk_data(png_ptr, png_zTXt, key_len, text, strlen(text)))2715{2716png_write_chunk_header(png_ptr, png_zTXt,2717key_len+png_length_compressed_chunk_data(png_ptr, key_len));2718png_write_chunk_data(png_ptr, new_key, key_len);2719png_write_compressed_chunk_data(png_ptr);2720png_write_chunk_end(png_ptr);2721}27222723/* else chunk report already issued and ignored */2724}2725#endif27262727#ifdef PNG_WRITE_iTXt_SUPPORTED2728/* Write an iTXt chunk */2729void /* PRIVATE */2730png_write_iTXt(png_structrp png_ptr, int compression, png_const_charp key,2731png_const_charp lang, png_const_charp lang_key, png_const_charp text)2732{2733png_uint_32 key_len, prefix_len, data_len;2734png_size_t lang_len, lang_key_len, text_len;2735png_byte new_key[82]; /* 80 bytes for the key, 2 byte compression info */27362737png_debug(1, "in png_write_iTXt");27382739key_len = png_check_keyword(png_ptr, key, new_key);27402741if (key_len == 0)2742{2743png_chunk_report(png_ptr, "iTXt: invalid keyword", PNG_CHUNK_WRITE_ERROR);2744return;2745}27462747debug(new_key[key_len] == 0);2748++key_len; /* terminating 0 added by png_check_keyword */27492750/* Set the compression flag */2751switch (compression)2752{2753case PNG_ITXT_COMPRESSION_NONE:2754case PNG_TEXT_COMPRESSION_NONE:2755compression = new_key[key_len++] = 0; /* no compression */2756break;27572758case PNG_TEXT_COMPRESSION_zTXt:2759case PNG_ITXT_COMPRESSION_zTXt:2760compression = new_key[key_len++] = 1; /* compressed */2761break;27622763default:2764png_chunk_report(png_ptr, "iTXt: invalid compression",2765PNG_CHUNK_WRITE_ERROR);2766return;2767}27682769new_key[key_len++] = PNG_COMPRESSION_TYPE_BASE;27702771/* We leave it to the application to meet PNG-1.0 requirements on the2772* contents of the text. PNG-1.0 through PNG-1.2 discourage the use of2773* any non-Latin-1 characters except for NEWLINE (yes, this is really weird2774* in an 'international' text string. ISO PNG, however, specifies that the2775* text is UTF-8 and this *IS NOT YET CHECKED*, so invalid sequences may be2776* present.2777*2778* The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.2779*2780* TODO: validate the language tag correctly (see the spec.)2781*/2782if (lang == NULL) lang = ""; /* empty language is valid */2783lang_len = strlen(lang)+1U;2784if (lang_key == NULL) lang_key = ""; /* may be empty */2785lang_key_len = strlen(lang_key)+1U;2786if (text == NULL) text = ""; /* may be empty */27872788if (lang_len > PNG_UINT_31_MAX-key_len ||2789lang_key_len > PNG_UINT_31_MAX-key_len-lang_len)2790{2791png_chunk_report(png_ptr, "iTXt: prefix too long", PNG_CHUNK_WRITE_ERROR);2792return;2793}27942795prefix_len = (png_uint_32)/*SAFE*/(key_len+lang_len+lang_key_len);2796text_len = strlen(text); /* no trailing '\0' */27972798if (compression != 0)2799{2800if (png_compress_chunk_data(png_ptr, png_iTXt, prefix_len, text,2801text_len))2802data_len = png_length_compressed_chunk_data(png_ptr, prefix_len);28032804else2805return; /* chunk report already issued and ignored */2806}28072808else2809{2810if (text_len > PNG_UINT_31_MAX-prefix_len)2811{2812png_chunk_report(png_ptr, "iTXt: text too long",2813PNG_CHUNK_WRITE_ERROR);2814return;2815}28162817data_len = (png_uint_32)/*SAFE*/text_len;2818}28192820png_write_chunk_header(png_ptr, png_iTXt, prefix_len+data_len);2821png_write_chunk_data(png_ptr, new_key, key_len);2822png_write_chunk_data(png_ptr, lang, lang_len);2823png_write_chunk_data(png_ptr, lang_key, lang_key_len);28242825if (compression != 0)2826png_write_compressed_chunk_data(png_ptr);28272828else2829png_write_chunk_data(png_ptr, text, data_len);28302831png_write_chunk_end(png_ptr);2832}2833#endif /* WRITE_iTXt */28342835#if defined(PNG_WRITE_oFFs_SUPPORTED) ||\2836defined(PNG_WRITE_pCAL_SUPPORTED)2837/* PNG signed integers are saved in 32-bit 2's complement format. ANSI C-902838* defines a cast of a signed integer to an unsigned integer either to preserve2839* the value, if it is positive, or to calculate:2840*2841* (UNSIGNED_MAX+1) + integer2842*2843* Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the2844* negative integral value is added the result will be an unsigned value2845* correspnding to the 2's complement representation.2846*/2847static int2848save_int_32(png_structrp png_ptr, png_bytep buf, png_int_32 j)2849{2850png_uint_32 i = 0xFFFFFFFFU & (png_uint_32)/*SAFE & CORRECT*/j;28512852if (i != 0x80000000U/*value not permitted*/)2853{2854png_save_uint_32(buf, i);2855return 1;2856}28572858else2859{2860png_chunk_report(png_ptr, "invalid value in oFFS or pCAL",2861PNG_CHUNK_WRITE_ERROR);2862return 0;2863}2864}2865#endif /* WRITE_oFFs || WRITE_pCAL */28662867#ifdef PNG_WRITE_oFFs_SUPPORTED2868/* Write the oFFs chunk */2869void /* PRIVATE */2870png_write_oFFs(png_structrp png_ptr, png_int_32 x_offset, png_int_32 y_offset,2871int unit_type)2872{2873png_byte buf[9];28742875png_debug(1, "in png_write_oFFs");28762877if (unit_type >= PNG_OFFSET_LAST)2878png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");28792880if (save_int_32(png_ptr, buf, x_offset) &&2881save_int_32(png_ptr, buf + 4, y_offset))2882{2883/* unit type is 0 or 1, this has been checked already so the following2884* is safe:2885*/2886buf[8] = unit_type != 0;2887png_write_complete_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);2888}2889}2890#endif /* WRITE_oFFs */28912892#ifdef PNG_WRITE_pCAL_SUPPORTED2893/* Write the pCAL chunk (described in the PNG extensions document) */2894void /* PRIVATE */2895png_write_pCAL(png_structrp png_ptr, png_charp purpose, png_int_32 X0,2896png_int_32 X1, int type, int nparams, png_const_charp units,2897png_charpp params)2898{2899png_uint_32 purpose_len;2900size_t units_len;2901png_byte buf[10];2902png_byte new_purpose[80];29032904png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);29052906if (type >= PNG_EQUATION_LAST)2907png_error(png_ptr, "Unrecognized equation type for pCAL chunk");29082909purpose_len = png_check_keyword(png_ptr, purpose, new_purpose);29102911if (purpose_len == 0)2912png_error(png_ptr, "pCAL: invalid keyword");29132914++purpose_len; /* terminator */29152916png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);2917units_len = strlen(units) + (nparams == 0 ? 0 : 1);2918png_debug1(3, "pCAL units length = %d", (int)units_len);29192920if (save_int_32(png_ptr, buf, X0) &&2921save_int_32(png_ptr, buf + 4, X1))2922{2923png_size_tp params_len = png_voidcast(png_size_tp,2924png_malloc(png_ptr, nparams * sizeof (png_size_t)));2925int i;2926size_t total_len = purpose_len + units_len + 10;29272928/* Find the length of each parameter, making sure we don't count the2929* null terminator for the last parameter.2930*/2931for (i = 0; i < nparams; i++)2932{2933params_len[i] = strlen(params[i]) + (i == nparams - 1 ? 0 : 1);2934png_debug2(3, "pCAL parameter %d length = %lu", i,2935(unsigned long)params_len[i]);2936total_len += params_len[i];2937}29382939png_debug1(3, "pCAL total length = %d", (int)total_len);2940png_write_chunk_header(png_ptr, png_pCAL, (png_uint_32)total_len);2941png_write_chunk_data(png_ptr, new_purpose, purpose_len);2942buf[8] = png_check_byte(png_ptr, type);2943buf[9] = png_check_byte(png_ptr, nparams);2944png_write_chunk_data(png_ptr, buf, (png_size_t)10);2945png_write_chunk_data(png_ptr, (png_const_bytep)units,2946(png_size_t)units_len);29472948for (i = 0; i < nparams; i++)2949png_write_chunk_data(png_ptr, (png_const_bytep)params[i],2950params_len[i]);29512952png_free(png_ptr, params_len);2953png_write_chunk_end(png_ptr);2954}2955}2956#endif /* WRITE_pCAL */29572958#ifdef PNG_WRITE_sCAL_SUPPORTED2959/* Write the sCAL chunk */2960void /* PRIVATE */2961png_write_sCAL_s(png_structrp png_ptr, int unit, png_const_charp width,2962png_const_charp height)2963{2964png_byte buf[64];2965png_size_t wlen, hlen, total_len;29662967png_debug(1, "in png_write_sCAL_s");29682969wlen = strlen(width);2970hlen = strlen(height);2971total_len = wlen + hlen + 2;29722973if (total_len > 64)2974{2975png_warning(png_ptr, "Can't write sCAL (buffer too small)");2976return;2977}29782979buf[0] = png_check_byte(png_ptr, unit);2980memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */2981memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */29822983png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);2984png_write_complete_chunk(png_ptr, png_sCAL, buf, total_len);2985}2986#endif29872988#ifdef PNG_WRITE_pHYs_SUPPORTED2989/* Write the pHYs chunk */2990void /* PRIVATE */2991png_write_pHYs(png_structrp png_ptr, png_uint_32 x_pixels_per_unit,2992png_uint_32 y_pixels_per_unit,2993int unit_type)2994{2995png_byte buf[9];29962997png_debug(1, "in png_write_pHYs");29982999if (unit_type >= PNG_RESOLUTION_LAST)3000png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");30013002png_save_uint_32(buf, x_pixels_per_unit);3003png_save_uint_32(buf + 4, y_pixels_per_unit);3004buf[8] = png_check_byte(png_ptr, unit_type);30053006png_write_complete_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);3007}3008#endif30093010#ifdef PNG_WRITE_tIME_SUPPORTED3011/* Write the tIME chunk. Use either png_convert_from_struct_tm()3012* or png_convert_from_time_t(), or fill in the structure yourself.3013*/3014void /* PRIVATE */3015png_write_tIME(png_structrp png_ptr, png_const_timep mod_time)3016{3017png_byte buf[7];30183019png_debug(1, "in png_write_tIME");30203021if (mod_time->month > 12 || mod_time->month < 1 ||3022mod_time->day > 31 || mod_time->day < 1 ||3023mod_time->hour > 23 || mod_time->second > 60)3024{3025png_warning(png_ptr, "Invalid time specified for tIME chunk");3026return;3027}30283029png_save_uint_16(buf, mod_time->year);3030buf[2] = mod_time->month;3031buf[3] = mod_time->day;3032buf[4] = mod_time->hour;3033buf[5] = mod_time->minute;3034buf[6] = mod_time->second;30353036png_write_complete_chunk(png_ptr, png_tIME, buf, (png_size_t)7);3037}3038#endif30393040static void3041png_end_IDAT(png_structrp png_ptr)3042{3043png_zlib_statep ps = png_ptr->zlib_state;30443045png_ptr->zowner = 0U; /* release the stream */30463047if (ps != NULL)3048png_deflate_release(png_ptr, ps, 1/*check*/);3049}30503051static void3052png_write_IDAT(png_structrp png_ptr, int flush)3053{3054png_zlib_statep ps = png_ptr->zlib_state;3055png_uint_32 IDAT_size;30563057/* Check for a correctly initialized list, the requirement that the end3058* pointer is NULL means that the end of the list can be easily detected.3059*/3060affirm(ps != NULL && ps->s.end != NULL && *ps->s.end == NULL);3061png_zlib_compress_validate(&png_ptr->zlib_state->s, 0/*in_use*/);30623063IDAT_size = png_ptr->IDAT_size;3064if (IDAT_size == 0U)3065{3066switch (pz_get(ps, IDAT, png_level, PNG_DEFAULT_COMPRESSION_LEVEL))3067{3068case PNG_COMPRESSION_COMPAT: /* Legacy */3069IDAT_size = 8192U;3070break;30713072case PNG_COMPRESSION_LOW_MEMORY:3073case PNG_COMPRESSION_HIGH_SPEED:3074case PNG_COMPRESSION_LOW:3075/* png_compress uses PNG_ROW_BUFFER_SIZE buffers for the compressed3076* data. Optimize to allocate only one of these:3077*/3078IDAT_size = PNG_ROW_BUFFER_SIZE;3079break;30803081default:3082case PNG_COMPRESSION_MEDIUM:3083IDAT_size = PNG_ZBUF_SIZE;3084break;30853086case PNG_COMPRESSION_HIGH_READ_SPEED:3087/* Assume the reader reads partial IDAT chunks (pretty much a3088* requirement given that some PNG encoders produce just one IDAT)3089*/3090case PNG_COMPRESSION_HIGH:3091/* This doesn't control the amount of memory allocated unless the3092* PNG IDAT data really is this big.3093*3094* TODO: review handling out-of-memory from png_compress() by3095* flushing an IDAT.3096*/3097IDAT_size = PNG_UINT_31_MAX;3098break;3099}3100}31013102/* Write IDAT chunks while either 'flush' is true or there are at3103* least png_ptr->IDAT_size bytes available to be written.3104*/3105for (;;)3106{3107png_uint_32 len = IDAT_size;31083109if (ps->s.overflow == 0U)3110{3111png_uint_32 avail = ps->s.len;31123113if (avail < len)3114{3115/* When end_of_image is true everything gets written, otherwise3116* there must be at least IDAT_size bytes available.3117*/3118if (!flush)3119return;31203121if (avail == 0U)3122break;31233124len = avail;3125}3126}31273128png_write_chunk_header(png_ptr, png_IDAT, len);31293130/* Write bytes from the buffer list, adjusting {overflow,len} as they are3131* written.3132*/3133do3134{3135png_compression_bufferp next = ps->s.list;3136unsigned int avail = sizeof next->output;3137unsigned int start = ps->s.start;3138unsigned int written;31393140affirm(next != NULL);31413142if (next->next == NULL) /* end of list */3143{3144/* The z_stream should always be pointing into this output buffer,3145* the buffer may not be full:3146*/3147debug(ps->s.zs.next_out + ps->s.zs.avail_out ==3148next->output + sizeof next->output);3149avail -= ps->s.zs.avail_out;3150}31513152else /* not end of list */3153debug((ps->s.zs.next_out < next->output ||3154ps->s.zs.next_out > next->output + sizeof next->output) &&3155(ps->s.overflow > 0 ||3156ps->s.start + ps->s.len >= sizeof next->output));31573158/* First, if this is the very first IDAT (PNG_HAVE_IDAT not set)3159* fix the Zlib CINFO field if required:3160*/3161if ((png_ptr->mode & PNG_HAVE_IDAT) == 0U &&3162avail >= start+2U /* enough for the zlib header */)3163{3164debug(start == 0U);3165fix_cinfo(ps, next->output+start, png_image_size(png_ptr));3166}31673168else /* always expect to see at least 2 bytes: */3169debug((png_ptr->mode & PNG_HAVE_IDAT) != 0U);31703171/* Set this now to prevent the above happening again second time round3172* the loop:3173*/3174png_ptr->mode |= PNG_HAVE_IDAT;31753176if (avail <= start+len)3177{3178/* Write all of this buffer: */3179affirm(avail > start); /* else overflow on the subtract */3180written = avail-start;3181png_write_chunk_data(png_ptr, next->output+start, written);31823183/* At the end there are no buffers in the list but the z_stream3184* still points into the old (just released) buffer. This can3185* happen when the old buffer is not full if the compressed bytes3186* exactly match the IDAT length; it should always happen when3187* end_of_image is set.3188*/3189ps->s.list = next->next;31903191if (next->next == NULL)3192{3193debug(avail == start+len);3194ps->s.end = &ps->s.list;3195ps->s.zs.next_out = NULL;3196ps->s.zs.avail_out = 0U;3197}31983199next->next = ps->stash;3200ps->stash = next;3201ps->s.start = 0U;3202}32033204else /* write only part of this buffer */3205{3206written = len;3207png_write_chunk_data(png_ptr, next->output+start, written);3208ps->s.start = (unsigned int)/*SAFE*/(start + written);3209}32103211/* 'written' bytes were written: */3212len -= written;32133214if (written <= ps->s.len)3215ps->s.len -= written;32163217else3218{3219affirm(ps->s.overflow > 0U);3220--ps->s.overflow;3221ps->s.len += 0x80000000U - written;3222UNTESTED3223}3224}3225while (len > 0U);32263227png_write_chunk_end(png_ptr);3228}32293230/* avail == 0 && flush */3231png_end_IDAT(png_ptr);3232png_ptr->mode |= PNG_AFTER_IDAT;3233}32343235/* This is is a convenience wrapper to handle IDAT compression; it takes a3236* pointer to the input data and places no limit on the size of the output but3237* is otherwise the same as png_compress(). It also handles the use of the3238* stash (only used for IDAT compression.)3239*/3240static int3241png_compress_IDAT_data(png_structrp png_ptr, png_zlib_statep ps,3242png_zlib_compressp pz, png_const_voidp input, uInt input_len, int flush)3243{3244/* Delay initialize the z_stream. */3245if (png_ptr->zowner != png_IDAT)3246png_deflate_claim(png_ptr, png_IDAT, 0U);32473248affirm(png_ptr->zowner == png_IDAT && pz->end != NULL && *pz->end == NULL);32493250/* z_stream::{next,avail}_out are set by png_compress to point into the3251* buffer list. next_in must be set here, avail_in comes from the input_len3252* parameter:3253*/3254pz->zs.next_in = PNGZ_INPUT_CAST(png_voidcast(const Bytef*, input));3255*pz->end = ps->stash; /* May be NULL */3256ps->stash = NULL;32573258/* zlib buffers the output, the maximum amount of compressed data that can be3259* produced here is governed by the amount of buffering.3260*/3261{3262int ret = png_compress(pz, input_len, 0U/*unlimited*/, flush);32633264affirm(pz->end != NULL && ps->stash == NULL);3265ps->stash = *pz->end; /* May be NULL */3266*pz->end = NULL;32673268/* Z_FINISH should give Z_STREAM_END, everything else should give Z_OK, in3269* either case all the input should have been consumed:3270*/3271implies(ret == Z_OK || ret == Z_FINISH, pz->zs.avail_in == 0U &&3272(ret == Z_STREAM_END) == (flush == Z_FINISH));3273pz->zs.next_in = NULL;3274pz->zs.avail_in = 0U; /* safety */3275png_zlib_compress_validate(pz, 0/*in_use*/);32763277return ret;3278}3279}32803281/* Compress some image data using the main png_zlib_compress. Write the result3282* out if there is sufficient data.3283*/3284static void3285png_compress_IDAT(png_structrp png_ptr, png_const_voidp input, uInt input_len,3286int flush)3287{3288png_zlib_statep ps = png_ptr->zlib_state;3289int ret = png_compress_IDAT_data(png_ptr, ps, &ps->s, input, input_len,3290flush);32913292/* Check the return code. */3293if (ret == Z_OK || ret == Z_STREAM_END)3294png_write_IDAT(png_ptr, flush == Z_FINISH);32953296else /* ret != Z_OK && ret != Z_STREAM_END */3297{3298/* This is an error condition. It is fatal. */3299png_end_IDAT(png_ptr);3300png_zstream_error(&ps->s.zs, ret);3301png_error(png_ptr, ps->s.zs.msg);3302}3303}33043305/* This is called at the end of every row to handle the required callbacks and3306* advance png_struct::row_number and png_struct::pass.3307*/3308static void3309png_write_end_row(png_structrp png_ptr, int flush)3310{3311png_uint_32 row_number = png_ptr->row_number;3312unsigned int pass = png_ptr->pass;33133314debug(pass < 7U);3315implies(flush == Z_FINISH, png_ptr->zowner == 0U);33163317/* API NOTE: the write callback is made before any changes to the row number3318* or pass however, in 1.7.0, the zlib stream can be closed before the3319* callback is made (this is new). The application flush function happens3320* afterward as was the case before. In 1.7.0 this is solely determined by3321* the order of the code that follows.3322*/3323if (png_ptr->write_row_fn != NULL)3324png_ptr->write_row_fn(png_ptr, row_number, pass);33253326# ifdef PNG_WRITE_FLUSH_SUPPORTED3327if (flush == Z_SYNC_FLUSH)3328{3329if (png_ptr->output_flush_fn != NULL)3330png_ptr->output_flush_fn(png_ptr);3331png_ptr->zlib_state->flush_rows = 0U;3332}3333# else /* !WRITE_FLUSH */3334PNG_UNUSED(flush)3335# endif /* !WRITE_FLUSH */33363337/* Finally advance to the next row/pass: */3338if (png_ptr->interlaced == PNG_INTERLACE_NONE)3339{3340debug(row_number < png_ptr->height);33413342if (++row_number == png_ptr->height) /* last row */3343{3344row_number = 0U;3345debug(flush == Z_FINISH);3346png_ptr->pass = 7U;3347}3348}33493350# ifdef PNG_WRITE_INTERLACING_SUPPORTED3351else /* interlaced */ if (png_ptr->do_interlace)3352{3353/* This gets called only for rows that are processed; i.e. rows that3354* are in the pass of a pass which is itself in the output.3355*/3356debug(row_number < png_ptr->height &&3357PNG_PASS_IN_IMAGE(png_ptr->width, png_ptr->height, pass) &&3358pass <= PNG_LAST_PASS(png_ptr->width, png_ptr->height) &&3359PNG_ROW_IN_INTERLACE_PASS(row_number, pass));33603361/* NOTE: the last row of the original image may not be in the pass, in3362* this case the code which skipped the row must do the increment3363* below! See 'interlace_row' in pngwrite.c and the code in3364* png_write_png_rows below.3365*3366* In that case an earlier row will be the last one in the pass (if the3367* pass is in the output), check this here:3368*/3369implies(pass == PNG_LAST_PASS(png_ptr->width, png_ptr->height) &&3370PNG_LAST_PASS_ROW(row_number, pass, png_ptr->height),3371flush == Z_FINISH);33723373if (++row_number == png_ptr->height) /* last row */3374{3375row_number = 0U;3376png_ptr->pass = 0x7U & ++pass;3377}3378}3379# endif /* WRITE_INTERLACING */33803381else /* application does interlace */3382{3383implies(png_ptr->height == 1U, pass != 6U);3384debug(PNG_PASS_IN_IMAGE(png_ptr->width, png_ptr->height, pass) &&3385row_number < PNG_PASS_ROWS(png_ptr->height, pass));33863387if (++row_number == PNG_PASS_ROWS(png_ptr->height, pass))3388{3389/* last row in this pass, next one may be empty. */3390row_number = 0U;33913392do3393++pass;3394while (pass < 7U &&3395!PNG_PASS_IN_IMAGE(png_ptr->width, png_ptr->height, pass));33963397implies(png_ptr->height == 1U, pass != 6U);3398implies(pass == 7U, flush == Z_FINISH);3399png_ptr->pass = 0x7U & pass;3400}3401}34023403png_ptr->row_number = row_number;3404}34053406#ifdef PNG_WRITE_FLUSH_SUPPORTED3407/* Flush the current output buffers now */3408void PNGAPI3409png_write_flush(png_structrp png_ptr)3410{3411png_debug(1, "in png_write_flush");34123413/* Force a flush at the end of the current row by setting 'flush_rows' to the3414* maximum:3415*/3416if (png_ptr != NULL && png_ptr->zlib_state != NULL)3417png_ptr->zlib_state->flush_rows = 0xEFFFFFFF;3418}34193420/* Return the correct flush to use */3421static int3422row_flush(png_zlib_statep ps, unsigned int row_info_flags)3423{3424if (PNG_IDAT_END(row_info_flags))3425return Z_FINISH;34263427else if ((row_info_flags & png_row_end) != 0 &&3428++ps->flush_rows >= ps->flush_dist)3429return Z_SYNC_FLUSH;34303431else3432return Z_NO_FLUSH;3433}3434#else /* !WRITE_FLUSH */3435# define row_flush(ps, ri) (PNG_IDAT_END(ri) ? Z_FINISH : Z_NO_FLUSH)3436#endif /* !WRITE_FLUSH */34373438static void3439write_filtered_row(png_structrp png_ptr, png_const_voidp filtered_row,3440unsigned int row_bytes, unsigned int filter /*if at start of row*/,3441int flush)3442{3443/* This handles writing a row that has been filtered, or did not need to be3444* filtered. If the data row has a partial pixel it must have been handled3445* correctly in the caller; filters generate a full 8 bits even if the pixel3446* only has one significant bit!3447*/3448debug(row_bytes > 0);3449affirm(row_bytes <= ZLIB_IO_MAX); /* I.e. it fits in a uInt */34503451if (filter < PNG_FILTER_VALUE_LAST) /* start of row */3452{3453png_byte buffer[1];34543455buffer[0] = PNG_BYTE(filter);3456png_compress_IDAT(png_ptr, buffer, 1U/*len*/, Z_NO_FLUSH);3457}34583459png_compress_IDAT(png_ptr, filtered_row, row_bytes, flush);3460}34613462static void3463write_unfiltered_rowbits(png_structrp png_ptr, png_const_bytep filtered_row,3464unsigned int row_bits, png_byte filter /*if at start of row*/,3465int flush)3466{3467/* Same as above, but it correctly clears the unused bits in a partial3468* byte.3469*/3470const png_uint_32 row_bytes = row_bits >> 3;34713472debug(filter == PNG_FILTER_VALUE_NONE || filter == PNG_FILTER_VALUE_LAST);34733474if (row_bytes > 0U)3475{3476row_bits -= row_bytes << 3;3477write_filtered_row(png_ptr, filtered_row, row_bytes, filter,3478row_bits == 0U ? flush : Z_NO_FLUSH);3479filter = PNG_FILTER_VALUE_LAST; /* written */3480}34813482/* Handle a partial byte. */3483if (row_bits > 0U)3484{3485png_byte buffer[1];34863487buffer[0] = PNG_BYTE(filtered_row[row_bytes] & ~(0xFFU >> row_bits));3488write_filtered_row(png_ptr, buffer, 1U, filter, flush);3489}3490}34913492#ifdef PNG_WRITE_FILTER_SUPPORTED3493static void3494filter_block_singlebyte(unsigned int row_bytes, png_bytep sub_row,3495png_bytep up_row, png_bytep avg_row, png_bytep paeth_row,3496png_const_bytep row, png_const_bytep prev_row, png_bytep prev_pixels)3497{3498/* Calculate rows for all four filters where the input has one byte per pixel3499* (more accurately per filter-unit).3500*/3501png_byte a = prev_pixels[0];3502png_byte c = prev_pixels[1];35033504while (row_bytes-- > 0U)3505{3506const png_byte x = *row++;3507const png_byte b = prev_row == NULL ? 0U : *prev_row++;35083509/* Calculate each filtered byte in turn: */3510if (sub_row != NULL) *sub_row++ = 0xFFU & (x - a);3511if (up_row != NULL) *up_row++ = 0xFFU & (x - b);3512if (avg_row != NULL) *avg_row++ = 0xFFU & (x - (a+b)/2U);35133514/* Paeth is a little more difficult: */3515if (paeth_row != NULL)3516{3517int pa = b-c; /* a+b-c - a */3518int pb = a-c; /* a+b-c - b */3519int pc = pa+pb; /* a+b-c - c = b-c + a-c */3520png_byte p = a;35213522pa = abs(pa);3523pb = abs(pb);3524if (pa > pb) pa = pb, p = b;3525if (pa > abs(pc)) p = c;35263527*paeth_row++ = 0xFFU & (x - p);3528}35293530/* And set a and c for the next pixel: */3531a = x;3532c = b;3533}35343535/* Store a and c for the next block: */3536prev_pixels[0] = a;3537prev_pixels[1] = c;3538}35393540static void3541filter_block_multibyte(unsigned int row_bytes,3542const unsigned int bpp, png_bytep sub_row, png_bytep up_row,3543png_bytep avg_row, png_bytep paeth_row, png_const_bytep row,3544png_const_bytep prev_row, png_bytep prev_pixels)3545{3546/* Calculate rows for all four filters, the input is a block of bytes such3547* that row_bytes is a multiple of bpp. bpp can be 2, 3, 4, 6 or 8.3548* prev_pixels will be updated to the last pixels processed.3549*/3550while (row_bytes >= bpp)3551{3552unsigned int i;35533554for (i=0; i<bpp; ++i)3555{3556const png_byte a = prev_pixels[i];3557const png_byte c = prev_pixels[i+bpp];3558const png_byte b = prev_row == NULL ? 0U : *prev_row++;3559const png_byte x = *row++;35603561/* Save for the next pixel: */3562prev_pixels[i] = x;3563prev_pixels[i+bpp] = b;35643565/* Calculate each filtered byte in turn: */3566if (sub_row != NULL) *sub_row++ = 0xFFU & (x - a);3567if (up_row != NULL) *up_row++ = 0xFFU & (x - b);3568if (avg_row != NULL) *avg_row++ = 0xFFU & (x - (a+b)/2U);35693570/* Paeth is a little more difficult: */3571if (paeth_row != NULL)3572{3573int pa = b-c; /* a+b-c - a */3574int pb = a-c; /* a+b-c - b */3575int pc = pa+pb; /* a+b-c - c = b-c + a-c */3576png_byte p = a;35773578pa = abs(pa);3579pb = abs(pb);3580if (pa > pb) pa = pb, p = b;3581if (pa > abs(pc)) p = c;35823583*paeth_row++ = 0xFFU & (x - p);3584}3585}35863587row_bytes -= i;3588}3589}35903591static void3592filter_block(png_const_bytep prev_row, png_bytep prev_pixels,3593png_const_bytep unfiltered_row, unsigned int row_bits,3594const unsigned int bpp, png_bytep sub_row, png_bytep up_row,3595png_bytep avg_row, png_bytep paeth_row)3596{3597const unsigned int row_bytes = row_bits >> 3; /* complete bytes */35983599if (bpp <= 8U)3600{3601/* There may be a partial byte at the end. */3602if (row_bytes > 0)3603filter_block_singlebyte(row_bytes, sub_row, up_row, avg_row, paeth_row,3604unfiltered_row, prev_row, prev_pixels);36053606/* The partial byte must be handled correctly here; both the previous row3607* value and the current value need to have non-present bits cleared.3608*/3609if ((row_bits & 7U) != 0)3610{3611const png_byte mask = PNG_BYTE(~(0xFFU >> (row_bits & 7U)));3612png_byte buffer[2];36133614buffer[0] = unfiltered_row[row_bytes] & mask;36153616if (prev_row != NULL)3617buffer[1U] = prev_row[row_bytes] & mask;36183619else3620buffer[1U] = 0U;36213622filter_block_singlebyte(1U,3623sub_row == NULL ? NULL : sub_row+row_bytes,3624up_row == NULL ? NULL : up_row+row_bytes,3625avg_row == NULL ? NULL : avg_row+row_bytes,3626paeth_row == NULL ? NULL : paeth_row+row_bytes,3627buffer, buffer+1U, prev_pixels);3628}3629}36303631else3632filter_block_multibyte(row_bytes, bpp >> 3,3633sub_row, up_row, avg_row, paeth_row,3634unfiltered_row, prev_row, prev_pixels);3635}36363637static void3638filter_row(png_structrp png_ptr, png_const_bytep prev_row,3639png_bytep prev_pixels, png_const_bytep unfiltered_row,3640unsigned int row_bits, unsigned int bpp, unsigned int filter,3641int start_of_row, int flush)3642{3643/* filters_to_try identifies a single filter and it is not PNG_FILTER_NONE.3644*/3645png_byte filtered_row[PNG_ROW_BUFFER_SIZE];36463647affirm((row_bits+7U) >> 3 <= PNG_ROW_BUFFER_SIZE &&3648filter >= PNG_FILTER_VALUE_SUB && filter <= PNG_FILTER_VALUE_PAETH);3649debug((row_bits % bpp) == 0U);36503651filter_block(prev_row, prev_pixels, unfiltered_row, row_bits, bpp,3652filter == PNG_FILTER_VALUE_SUB ? filtered_row : NULL,3653filter == PNG_FILTER_VALUE_UP ? filtered_row : NULL,3654filter == PNG_FILTER_VALUE_AVG ? filtered_row : NULL,3655filter == PNG_FILTER_VALUE_PAETH ? filtered_row : NULL);36563657write_filtered_row(png_ptr, filtered_row, (row_bits+7U)>>3,3658start_of_row ? filter : PNG_FILTER_VALUE_LAST, flush);3659}36603661/* Allow the application to select one or more row filters to use. */3662static png_int_323663set_filter(png_zlib_statep ps, unsigned int filtersIn)3664{3665/* Notice that PNG_NO_FILTERS is 0 and passes this test; this is OK because3666* filters then gets set to PNG_FILTER_NONE, as is required.3667*3668* The argument to this routine is actually an (int), but conversion to3669* (unsigned int) is safe because it leaves the top bits set which results in3670* PNG_EDOM below.3671*/3672if (filtersIn < PNG_FILTER_NONE)3673filtersIn = PNG_FILTER_MASK(filtersIn);36743675/* PNG_ALL_FILTERS is a constant, unfortunately it is nominally signed, for3676* historical reasons, hence the PNG_BIC_MASK here.3677*/3678if ((filtersIn & PNG_BIC_MASK(PNG_ALL_FILTERS)) == 0U)3679{3680# ifndef PNG_SELECT_FILTER_SUPPORTED3681filtersIn &= -filtersIn; /* Use lowest set bit */3682# endif /* !SELECT_FILTER */36833684return ps->filter_mask = filtersIn & PNG_ALL_FILTERS;3685}36863687else /* Out-of-range filtersIn: */3688return PNG_EDOM;3689}3690#endif /* WRITE_FILTER */36913692#ifdef PNG_WRITE_FILTER_SUPPORTED3693void /* PRIVATE */3694png_write_start_IDAT(png_structrp png_ptr)3695{3696png_zlib_statep ps = get_zlib_state(png_ptr);36973698/* Set up the IDAT compression state. Expect the state to have been released3699* by the previous owner, but it doesn't much matter if there was an error.3700* Note that the stream is not claimed yet.3701*/3702debug(png_ptr->zowner == 0U);37033704/* This sets the buffer limits and write_row_size, which is used below. */3705png_zlib_state_set_buffer_limits(png_ptr, ps);37063707if (ps->filter_mask == 0)3708{3709# ifdef PNG_SELECT_FILTER_SUPPORTED3710/* Now default the filter mask if it hasn't been set already: */3711int png_level =3712pz_get(ps, IDAT, png_level, PNG_DEFAULT_COMPRESSION_LEVEL);37133714/* If the bit depth is less than 8, so pixels are not byte aligned, PNG3715* filtering hardly ever helps because there is no correlation between3716* the bytes on which the filter works and the actual pixel values.3717* Note that GIF is a whole lot better at this because it uses LZW to3718* compress a bit-stream, not a byte stream as in the deflate3719* implementation of LZ77.3720*3721* If the row size is less than 256 bytes filter selection algorithms3722* are flakey because the restricted range of codes in each row can3723* lead to poor selection of filters, particularly if the bytes in the3724* image are themselves limited. (This happens when a low bit-depth3725* image is encoded with 8-bit channels.)3726*3727* By experiment with the test set of images the breakpoint between3728* not filtering and filtering based on which gives best compression by3729* row size is as follows:3730*3731* NONE FAST ALL3732* PAL <=anything [even 8-bit palette images larger if filtered]3733* G<8 <=anything [low bit depth gray images]3734* G8 <=16 [+~1%] >163735* G16 <=128 [+~1%] >1283736* GA8 <=64 [+~1%] >643737* GA16 <=anything [always better without filtering!]3738* RGB8 <=32 [+0-2%(1)] >323739* RGB16 <=1024 [+~1%] >10243740* RGBA8 <=64 [+~~1%] >643741* RGBA16 <=128 {+~0.5%] >1283742*3743* (1) The largest 24-bit RGB image (RGB8) faired better, by 1.3%,3744* with 'fast' filters. This is assumed to be random.3745*3746* Aggregated across all color types and bit depths the breakpoint for3747* filtering is >16 bytes, but the size increase only exceeds 0.5% for3748* images with rows between 64 and 128 bytes, hence the choices below.3749*3750* Across all the test images that change (not including selecting just3751* the 'fast' filters by default) does not change the compressed size3752* significantly (+0.06% across the whole test set), however it does3753* substantially increase the number of images without filtering.3754*3755* Using just none and sub filters results in overall compressed sizes3756* somewhere around the geometric mean of no filtering and 'fast'.3757*3758* The image size also plays a part. Filtering is not an advantage for3759* images of size <= 512 bytes. This is also reflected below.3760*3761* NOTE: the libpng 1.6 (and earlier) algorithm seems to work3762* because it biases the byte codes in the output towards 0 and 255.3763* Zlib doesn't care what the codes are, but Huffman encoding always3764* benefits from a biased distribution and the filters themselves were3765* designed to produce values in this range.3766*3767* In a raw comparison with the legacy code selection of specific sets3768* of filters always increased the compressed size of the test set, as3769* follows:3770*3771* PNG_ALL_FILTERS: +0.26%3772* PNG_FAST_FILTERS: +1.9%3773* NONE+SUB: +5.8%3774* PNG_NO_FILTERS: +14%3775*3776* This mainly proves that a static selection of filters (without3777* considering the PNG format) is always worse than the legacy3778* algorithm below.3779*3780* NOTE: ps->filter_mask must be set to a mask value, not a simple3781* PNG_FILTER_VALUE_ number.3782*/3783if (ps->write_row_size == 0U /* row cannot be buffered */)3784ps->filter_mask = PNG_FILTER_NONE;37853786else if (png_level == PNG_COMPRESSION_COMPAT/* Legacy */)3787{3788if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||3789png_ptr->bit_depth < 8U)3790ps->filter_mask = PNG_FILTER_NONE;37913792else3793ps->filter_mask = PNG_ALL_FILTERS;3794}37953796/* NOTE: overall with the following size tests (row and image size) the3797* test set of images end up 0.06% larger, however some color types are3798* smaller and some larger; the differences are minute. If the test is3799* <=128 (which means <=129 bytes per row with the filter byte) the3800* resultant inclusion of 32x32 RGBA images results in significantly3801* increased compressed size.3802*3803* The test on png_level captures the following settings:3804*3805* PNG_COMPRESSION_LOW_MEMORY3806* PNG_COMPRESSION_HIGH_SPEED3807* PNG_COMPRESSION_HIGH_READ_SPEED3808*3809* NOTE: this relies on the exact values in png.h!3810*/3811else if (png_level <= PNG_COMPRESSION_HIGH_READ_SPEED3812|| png_ptr->color_type == PNG_COLOR_TYPE_PALETTE3813|| png_ptr->bit_depth < 8U3814|| ps->write_row_size/*does not include filter*/ < 128U3815|| png_image_size(png_ptr) <= 512U)3816ps->filter_mask = PNG_FILTER_NONE;38173818/* ELSE: there are at least 128 bytes in every row and the pixels3819* are multiples of a byte.3820*/3821else switch (png_level)3822{3823default: /* For GCC */3824case PNG_COMPRESSION_LOW:3825ps->filter_mask = PNG_FILTER_NONE+PNG_FILTER_SUB;3826break;38273828case PNG_COMPRESSION_MEDIUM:3829ps->filter_mask = PNG_FAST_FILTERS;3830break;38313832case PNG_COMPRESSION_HIGH:3833ps->filter_mask = PNG_ALL_FILTERS;3834break;3835}3836# else /* !SELECT_FILTER */3837ps->filter_mask = PNG_FILTER_NONE;3838# endif /* !SELECT_FILTER */3839}3840}38413842static png_byte3843png_write_start_row(png_zlib_statep ps, int start_of_pass, int no_previous_row)3844/* Called at the start of a row to set up anything required for filter3845* handling in the row. Sets png_zlib_state::filters to a single filter.3846*/3847{3848unsigned int mask = ps->filter_mask;38493850/* If we see a previous-row filter in mask and png_zlib_state::save_row is3851* still unset set it. This means that the first time a previous-row filter3852* is seen row-saving gets turned on.3853*/3854if (ps->save_row == SAVE_ROW_UNSET && (mask & PREVIOUS_ROW_FILTERS) != 0U)3855ps->save_row = SAVE_ROW_DEFAULT;38563857if ((no_previous_row /* row not stored */ && !start_of_pass) ||3858ps->save_row == SAVE_ROW_OFF /* disabled by app */ ||3859ps->write_row_size == 0U /* row too large to buffer */)3860mask &= PNG_BIC_MASK(PREVIOUS_ROW_FILTERS);38613862/* On the first row of a pass Paeth is equivalent to sub and up is equivalent3863* to none, so try to simplify the mask in in this case.3864*/3865else if (start_of_pass) {3866# define MATCH(flags) ((mask & (flags)) == (flags))3867if (MATCH(PNG_FILTER_NONE|PNG_FILTER_UP))3868mask &= PNG_BIC_MASK(PNG_FILTER_UP);38693870if (MATCH(PNG_FILTER_SUB|PNG_FILTER_PAETH))3871mask &= PNG_BIC_MASK(PNG_FILTER_PAETH);3872# undef MATCH3873}38743875# ifdef PNG_SELECT_FILTER_SUPPORTED3876if ((mask & (mask-1U)) == 0U /* single bit set */ ||3877ps->write_row_size == 0U /* row cannot be buffered */)3878# endif /* SELECT_FILTER */3879/* Convert the lowest set bit into the corresponding value. If no bits3880* are set select NONE. After this switch statement the value of3881* ps->filters is guaranteed to just be a single filter.3882*/3883switch (mask & -mask)3884{3885default: mask = PNG_FILTER_VALUE_NONE; break;3886case PNG_FILTER_SUB: mask = PNG_FILTER_VALUE_SUB; break;3887case PNG_FILTER_UP: mask = PNG_FILTER_VALUE_UP; break;3888case PNG_FILTER_AVG: mask = PNG_FILTER_VALUE_AVG; break;3889case PNG_FILTER_PAETH: mask = PNG_FILTER_VALUE_PAETH; break;3890}38913892return ps->filters = PNG_BYTE(mask);3893}38943895static png_bytep3896allocate_row(png_structrp png_ptr, png_const_bytep data, png_alloc_size_t size)3897/* Utility to allocate and save some row bytes. If the result is NULL the3898* allocation failed and the png_zlib_struct will have been updated to3899* prevent further allocation attempts.3900*/3901{3902const png_zlib_statep ps = png_ptr->zlib_state;3903png_bytep buffer;39043905debug(ps->write_row_size > 0U);39063907/* OOM is handled silently, as is the case where the row is too large to3908* buffer.3909*/3910buffer = png_voidcast(png_bytep,3911png_malloc_base(png_ptr, ps->write_row_size));39123913/* Setting write_row_size to 0 switches on the code for handling a row that3914* is too large to buffer. This will kick in next time round, i.e. on the3915* next row.3916*/3917if (buffer == NULL)3918ps->write_row_size = 0U;39193920else3921memcpy(buffer, data, size);39223923return buffer;3924}3925#endif /* WRITE_FILTER */39263927#ifdef PNG_SELECT_FILTER_SUPPORTED3928/* Bit set operations. Not in ANSI C-90 but commonly available in highly3929* optimized versions, hence the ifndef. These operations just work on bitsets3930* of size 256. The second argument (the code index) may be evaluated multiple3931* times.3932*/3933#ifndef PNG_CODE_SET /* Can be set in pngpriv.h */3934typedef png_uint_32 png_codeset[8];3935# define PNG_CODE_MASK(i) (((png_uint_32)1U) << ((i) & 0x1FU))3936# define PNG_CODE_IS_SET(c,i) (((c)[(i) >> 5] & PNG_CODE_MASK(i)))3937# define PNG_CODE_SET(c,i) (((c)[(i) >> 5] |= PNG_CODE_MASK(i)))3938# define PNG_CODE_CLEAR(c,i) (((c)[(i) >> 5] &= ~PNG_CODE_MASK(i)))3939#endif /* !PNG_CODE_SET */39403941typedef struct filter_selector3942{3943/* Persistent filter selection information (stored across row boundaries).3944* A code is not considered if it last occured more than 'window' bytes ago.3945* The deflate algorithm means that 'window' cannot exceed 8453377, however3946* practical versions may be far less. When 'distance' reaches 'window' any3947* code where:3948*3949* distance - code_distance[code] > window3950*3951* at the end of a row 'code' is removed from codeset. Otherwise3952* (rearranging the above):3953*3954* distance - window <= code_distance[code]3955*3956* and so the distances of the still active codes can be reduced:3957*3958* code_distance[code] -= distance-window3959* distance = window3960*3961* This prevents any wrap of 'distance' on a row which is shorter than3962* 2^32-window.3963*3964* However when then row is 2^32-window or more bytes long (the row can be up3965* to just under 2^34 bytes long) this algorithm doesn't work; 'distance'3966* will overflow in the middle of the row and all codes are relevant. This3967* is handled below simply by reseting the set of present codes at the start3968* of the row and ignoring the overflow.3969*/3970unsigned int code_count; /* Number of distinct codes seen */3971int png_level; /* Cached compression level */3972png_uint_32 filter_select_max_width;3973/* The maximum number of pixels which can be fitted in the window without3974* filling the entire window (i.e. the maximum number that can be fitted3975* in (window-1) bytes).3976*/3977png_uint_32 sum_bias[PNG_FILTER_VALUE_LAST];3978/* For each filter a measure of its cost in the filter sum calculation.3979* This allows filter selection based on the sum-of-absolute-dfferences3980* method to be biased to favour particular filters. There was no such3981* bias before 1.7 and the filter byte was ignored.3982*/3983png_uint_32 distance; /* Distance from beginning */3984png_codeset codeset; /* Set of seen codes */3985png_uint_32 code_distance[256]; /* Distance at last occurence */3986} filter_selector;39873988static const filter_selector *3989png_start_filter_select(png_zlib_statep ps, unsigned int bpp)3990{3991# define png_ptr ps_png_ptr(ps)3992filter_selector *fs = ps->selector;39933994if (fs == NULL)3995{3996fs = png_voidcast(filter_selector*, png_malloc_base(png_ptr, sizeof *fs));39973998if (fs != NULL)3999{4000png_uint_32 window = ps->filter_select_window;4001fs->png_level = pz_get(ps, IDAT, png_level,4002PNG_DEFAULT_COMPRESSION_LEVEL);40034004/* Delay initialize this here: */4005if (window < 3U || window > PNG_FILTER_SELECT_WINDOW_MAX)4006ps->filter_select_window = window = PNG_FILTER_SELECT_WINDOW_MAX;40074008fs->code_count = 0;40094010switch (fs->png_level)4011{4012default:4013/* TODO: investigate other settings */4014{4015unsigned int f;40164017for (f=0; f<PNG_FILTER_VALUE_LAST; ++f)4018fs->sum_bias[f] = f;4019}4020ps->filter_select_threshold = 64U; /* 6bit RGB */4021ps->filter_select_threshold2 = 50U; /* TODO: experiment! */4022break;40234024case PNG_COMPRESSION_COMPAT: /* Legacy */4025memset(fs->sum_bias, 0U, sizeof fs->sum_bias);4026ps->filter_select_threshold = 1U; /* disabled */4027ps->filter_select_threshold2 = 1U;4028break;4029}40304031/* This is the maximum row width, in pixels, of a row which fits and4032* leaves 1 byte free in the window. For any bigger row filter4033* selection ignores the previous rows.4034*/4035fs->filter_select_max_width = ((window-2U/*filter+last byte*/)*8U)/bpp;4036fs->distance = 0U;4037memset(fs->codeset, 0U, sizeof fs->codeset);4038/* fs->code_distance is left uninitialized because fs->codeset says4039* whether or not each entry has been initialized.4040*/4041ps->selector = fs;4042}40434044else4045ps->write_row_size = 0U; /* OOM */4046}4047# undef png_ptr40484049return fs;4050}40514052typedef struct4053{4054/* Per-filter data. This remains separate from the above until the filter4055* selection has been made. It reflects the above however the codeset only4056* records codes present in this row.4057*4058* The 'sum' fields are the sum of the absolute deviation of each code from4059* 0, the algorithm from 1.6 and earlier. In other words:4060*4061* if (code >= 128)4062* sum += code;4063* else4064* sum += 256-code;4065*/4066unsigned int code_count; /* Number of distinct codes seen in row */4067unsigned int new_code_count; /* Number of new codes seen in row */4068png_uint_32 sum_low; /* Low 31 bits of code sum */4069png_uint_32 sum_high; /* High 32 bits of code sum */4070png_codeset codeset; /* Set of codes seen in this row */4071png_uint_32 code_distance[256]; /* Distance at last occurence in this row */4072} filter_data;40734074static void4075filter_data_init(filter_data *fd, png_uint_32 distance, unsigned int filter,4076unsigned int code_is_set, png_uint_32 bias)4077{4078fd->code_count = 1U;4079fd->new_code_count = !code_is_set;4080fd->sum_low = bias;4081fd->sum_high = 0U;4082memset(&fd->codeset, 0U, sizeof fd->codeset);4083PNG_CODE_SET(fd->codeset, filter);4084fd->code_distance[filter] = distance;4085}40864087static void4088add_code(const filter_selector *fs, filter_data *fd, png_uint_32 distance,4089unsigned int code)4090{4091if (!PNG_CODE_IS_SET(fd->codeset, code))4092{4093PNG_CODE_SET(fd->codeset, code);4094++(fd->code_count);4095fd->code_distance[code] = distance;4096if (!PNG_CODE_IS_SET(fs->codeset, code))4097++(fd->new_code_count);4098}40994100{4101png_uint_32 low = fd->sum_low;41024103if (code <= 128U)4104low += code;41054106else4107low += 256U-code;41084109/* Handle overflow into the top bit: */4110if (low & 0x80000000U)4111fd->sum_low = low & 0x7FFFFFFFU, ++fd->sum_high;41124113else4114fd->sum_low = low;4115}4116}41174118static png_byte4119filter_data_select(png_zlib_statep ps, filter_data fd[PNG_FILTER_VALUE_LAST],4120unsigned int filter, png_uint_32 distance, png_uint_32 w)4121{4122# define png_ptr ps_png_ptr(ps)4123/* Choose how to do this depending on the row and window size. */4124filter_selector *fs = ps->selector;4125png_uint_32 window = ps->filter_select_window;41264127affirm(fs != NULL);41284129/* Check the width against the maximum number of pixels that can fit in a4130* window without filling it:4131*/4132if (w > fs->filter_select_max_width)4133{4134/* The cache is not used */4135fs->distance = 0U; /* for next row */4136fs->code_count = 0U;4137memset(fs->codeset, 0U, sizeof fs->codeset);4138}41394140else4141{4142/* Merge the two code sets, discounting codes that last occurred before4143* the start of the window.4144*/4145png_uint_32 adjust, code_count;4146unsigned int code;41474148/* filter_selector::distance is the distance of the first byte in the row4149* (the filter byte), but 'distance' can wrap on long rows. The above4150* test is meant to exclude the wrap case by excluding any case where the4151* row has as many bytes as the window, so:4152*/4153affirm(distance > fs->distance && distance - fs->distance < window);41544155/* Set 'adjust' to the current distance of the start of the window. I.e:4156*4157* +---------------+--------+4158* | before window | window | future data4159* +---------------+--------+4160* A A4161* | |4162* adjust + + distance4163*4164* If the window isn't full yet 'adjust' will be zero, otherwise all the4165* distances will be reduced by 'adjust' so that the first byte of the4166* window has distance 0.4167*/4168if (distance > window)4169adjust = distance-window;41704171else4172adjust = 0;417341744175/* This may be decreased below if some old codes only occured before the4176* start of the window.4177*/4178code_count = fs->code_count + fd->new_code_count;41794180for (code=0U; code<256U; ++code)4181{4182if (PNG_CODE_IS_SET(fd[filter].codeset, code))4183{4184PNG_CODE_SET(fs->codeset, code);4185debug(fd[filter].code_distance[code] >= adjust);4186fs->code_distance[code] = fd[filter].code_distance[code] - adjust;4187}41884189else if (PNG_CODE_IS_SET(fs->codeset, code) && adjust > 0)4190{4191/* The code did not occur in this row, the old distance may now be4192* outside the window (because adjust is non-zero).4193*/4194const png_uint_32 d = fs->code_distance[code];41954196if (d >= adjust)4197fs->code_distance[code] = d-adjust;41984199else4200PNG_CODE_CLEAR(fs->codeset, code), --code_count;4201}4202}42034204fs->code_count = code_count;4205fs->distance = distance - adjust; /* I.e. either distance or window! */4206}42074208return ps->filters = PNG_BYTE(filter);4209# undef png_ptr4210}42114212static png_byte4213select_filter(png_zlib_statep ps, png_const_bytep row,4214png_const_bytep prev, unsigned int bpp, png_uint_32 width, int start_of_pass)4215/* Select a filter from the list provided by png_write_start_row. */4216{4217png_byte filters = png_write_start_row(ps, start_of_pass, prev == NULL);42184219# define png_ptr ps_png_ptr(ps)4220if (filters >= PNG_FILTER_NONE) /* multiple filters to test */4221{4222const png_uint_32 max_pixels = ps->row_buffer_max_pixels;4223const png_uint_32 block_pixels = ps->row_buffer_max_aligned_pixels;4224const filter_selector *fs = ps->selector;4225png_uint_32 pixels_to_go = width;4226png_uint_32 distance;4227unsigned int bits_at_end = 0U;4228png_byte prev_pixels[4*2*2]; /* 2 pixels up to 4x2-bytes each */4229filter_data fd[PNG_FILTER_VALUE_LAST];42304231debug((filters & (filters-1)) != 0U); /* Expect more than one bit! */42324233if (fs == NULL)4234{4235/* Delay initialize with a quiet OOM handler */4236fs = png_start_filter_select(ps, bpp);4237if (fs == NULL)4238{4239ps->filters = PNG_FILTER_VALUE_NONE;4240return PNG_FILTER_VALUE_NONE;4241}4242}42434244/* If PNG_FILTER_NONE is in the list check it first. */4245if (filters & PNG_FILTER_NONE)4246{4247png_const_bytep rp = row;4248png_uint_32 w = width;42494250distance = fs->distance;4251filter_data_init(fd+PNG_FILTER_VALUE_NONE, distance++,4252PNG_FILTER_VALUE_NONE,4253PNG_CODE_IS_SET(fs->codeset, PNG_FILTER_VALUE_NONE),4254fs->sum_bias[PNG_FILTER_VALUE_NONE]);42554256if (bpp >= 8) /* complete bytes */4257{4258const unsigned int bytes = bpp/8U;42594260while (w > 0)4261{4262unsigned int b;4263for (b=0; b<bytes; ++b)4264add_code(fs, fd+PNG_FILTER_VALUE_NONE, distance++, *rp++);4265--w;4266}4267}42684269else /* multiple pixels per byte */4270{4271const unsigned int ppb = 8U/bpp;42724273debug(ppb * bpp == 8U); /* Expect bpp to be a power of 2 */42744275while (w >= ppb)4276{4277add_code(fs, fd+PNG_FILTER_VALUE_NONE, distance++, *rp++);4278w -= ppb;4279}42804281if (w > 0) /* partial byte at end */4282add_code(fs, fd+PNG_FILTER_VALUE_NONE, distance++,4283*rp & (0xFFU >> (w*bpp) /* zero unused bits */));4284}42854286/* For PNG data with a small number of codes it is worth skipping the4287* filtering because it almost always increases the code count4288* significantly. This is controlled by4289* png_zlib_state::filter_select_threshold and causes an early return4290* here.4291*/4292if (fd[PNG_FILTER_VALUE_NONE].new_code_count +4293fs->code_count < ps->filter_select_threshold)4294return filter_data_select(ps, fd, PNG_FILTER_VALUE_NONE, distance,4295width);4296} /* PNG_FILTER_NONE */42974298memset(prev_pixels, 0U, sizeof prev_pixels);4299distance = fs->distance;43004301{4302unsigned int i;43034304for (i=PNG_FILTER_VALUE_NONE+1U; i<PNG_FILTER_VALUE_LAST; ++i)4305if (PNG_FILTER_MASK(i) & filters)4306filter_data_init(fd+i, distance, i,4307PNG_CODE_IS_SET(fs->codeset, i), fs->sum_bias[i]);4308}43094310++distance;43114312while (pixels_to_go || bits_at_end)4313{4314unsigned int bits, i;4315union4316{4317PNG_ROW_BUFFER_ALIGN_TYPE force_buffer_alignment;4318png_byte row[4][PNG_ROW_BUFFER_SIZE];4319} filtered;4320union4321{4322PNG_ROW_BUFFER_ALIGN_TYPE force_buffer_alignment;4323png_byte byte;4324} last;43254326if (pixels_to_go)4327{4328if (pixels_to_go > max_pixels)4329{4330/* Maintain alignment by consuming on block_pixels at once */4331bits = block_pixels * bpp;4332pixels_to_go -= block_pixels; /* May be 0 */4333}43344335else4336{4337bits = pixels_to_go * bpp;4338bits_at_end = bits & 0x7U;4339bits -= bits_at_end;4340pixels_to_go = 0U; /* +bits_at_end */4341}4342}43434344else /* incomplete byte at the end of the pixel */4345{4346/* Make sure the unused bits are cleared (to zero, although this is4347* an arbitrary choice):4348*/4349last.byte = PNG_BYTE(*row & ~(0xFFU >> bits_at_end));4350row = &last.byte;4351bits = bits_at_end;4352bits_at_end = 0U;4353}43544355filter_block(prev, prev_pixels, row, bits, bpp,4356filtered.row[0/*sub*/], filtered.row[1/*up*/],4357filtered.row[2/*avg*/], filtered.row[3/*Paeth*/]);43584359/* A block of (bits+7)/8 bytes is now available to process. */4360for (i=0; 8U*i < bits; ++i, ++distance)4361{4362unsigned int f;43634364for (f=PNG_FILTER_VALUE_NONE+1U; f<PNG_FILTER_VALUE_LAST; ++f)4365if (PNG_FILTER_MASK(f) & filters)4366add_code(fs, fd+f, distance, filtered.row[f-1U][i]);4367}43684369if (prev != NULL)4370prev += bits >> 3;43714372row += bits >> 3;4373}43744375/* Now look at the candidate filters, including 'none' and select the4376* best. We know that 'none' increases the code count beyond the4377* threshold, so if the old code count is below the threshold and there is4378* a filter which does not increase the code count select it; doing so4379* should do no harm to the overall compression.4380*/4381if (fs->code_count < ps->filter_select_threshold)4382{4383unsigned int f, min_new_count = 257U, min_f = PNG_FILTER_VALUE_NONE;43844385for (f=PNG_FILTER_VALUE_NONE+1U; f<PNG_FILTER_VALUE_LAST; ++f)4386if ((PNG_FILTER_MASK(f) & filters) != 0)4387{4388unsigned int new_code_count = fd[f].new_code_count;43894390if (new_code_count == 0U)4391return filter_data_select(ps, fd, f, distance, width);43924393else if (new_code_count < min_new_count)4394min_new_count = new_code_count, min_f = f;4395}43964397/* Use the second threshold to decide whether to select the best filter4398* on this basis alone:4399*/4400if (min_f != PNG_FILTER_VALUE_NONE &&4401fs->code_count + min_new_count < ps->filter_select_threshold2)4402return filter_data_select(ps, fd, min_f, distance, width);4403}44044405/* Now fall back to the libpng 1.6 and earlier algorithm. This favours4406* the filter which produces least deviation in the codes from 0. When4407* this works it does so by reducing the distribution of code values. The4408* filters implicitly encode the difference between a predictor based on4409* adjacent values, the assumption is that this will result in values4410* close to 0.4411*/4412{4413png_uint_32 high = -1;4414png_uint_32 low = -1;4415unsigned int min_f = 0 /*unset, but safe*/;4416unsigned int f;44174418for (f=PNG_FILTER_VALUE_NONE; f<PNG_FILTER_VALUE_LAST; ++f)4419if ((PNG_FILTER_MASK(f) & filters) != 0 &&4420(fd[f].sum_high < high ||4421(fd[f].sum_high == high && fd[f].sum_low < low)))4422{4423high = fd[f].sum_high;4424low = fd[f].sum_low;44254426if (low & 0x80000000U)4427{4428low &= 0x7FFFFFFFU, --high;4429if (high & 0x80000000U)4430low = high = 0U;4431}44324433min_f = f;4434}44354436return filter_data_select(ps, fd, min_f, distance, width);4437}4438}44394440debug(filters < PNG_FILTER_VALUE_LAST);4441return ps->filters = filters;4442# undef png_ptr4443}4444#else /* !SELECT_FILTER */4445/* Filter selection not being done, just call png_write_start_row: */4446# define select_filter(ps, rp, pp, bpp, width, start_of_pass)\4447png_write_start_row((ps), (start_of_pass), (pp) == NULL)4448#endif /* !SELECT_FILTER */44494450/* This is the common function to write multiple rows of PNG data. The data is4451* in the relevant PNG format but has had no filtering done.4452*/4453void /* PRIVATE */4454png_write_png_rows(png_structrp png_ptr, png_const_bytep *rows,4455png_uint_32 num_rows)4456{4457const png_zlib_statep ps = png_ptr->zlib_state;4458const unsigned int bpp = png_ptr->row_output_pixel_depth;4459# ifdef PNG_WRITE_FILTER_SUPPORTED4460png_const_bytep previous_row = ps->previous_write_row;4461# else /* !WRITE_FILTER */4462/* These are constant in the no-filer case: */4463const png_byte filter = PNG_FILTER_VALUE_NONE;4464const png_uint_32 max_pixels = ps->zlib_max_pixels;4465const png_uint_32 block_pixels = ps->zlib_max_aligned_pixels;4466# endif /* !WRITE_FILTER */4467/* Write the given rows handling the png_compress_IDAT argument limitations4468* (uInt) and any valid row width.4469*/4470png_uint_32 last_row_in_pass = 0U; /* Actual last, not last+1! */4471png_uint_32 pixels_in_pass = 0U;4472unsigned int first_row_in_pass = 0U; /* For do_interlace */4473unsigned int pixels_at_end = 0U; /* for a partial byte at the end */4474unsigned int base_info_flags = png_row_end;4475int pass = -1; /* Invalid: force calculation first time round */44764477debug(png_ptr->row_output_pixel_depth == PNG_PIXEL_DEPTH(*png_ptr));44784479while (num_rows-- > 0U)4480{4481if (png_ptr->pass != pass)4482{4483/* Recalcuate the row bytes and partial bits */4484pass = png_ptr->pass;4485pixels_in_pass = png_ptr->width;44864487if (png_ptr->interlaced == PNG_INTERLACE_NONE)4488{4489debug(pass == 0);4490last_row_in_pass = png_ptr->height - 1U;4491base_info_flags |= png_pass_last; /* there is only one */4492}44934494else4495{4496const png_uint_32 height = png_ptr->height;44974498last_row_in_pass = PNG_PASS_ROWS(height, pass);4499debug(pass >= 0 && pass < 7);45004501# ifdef PNG_WRITE_INTERLACING_SUPPORTED4502if (png_ptr->do_interlace)4503{4504/* libpng is doing the interlace handling, the row number is4505* actually the row in the image.4506*4507* This overflows when the PNG height is such that the are no4508* rows in this pass. This does not matter; because there are4509* no rows the value doesn't get used.4510*/4511last_row_in_pass =4512PNG_ROW_FROM_PASS_ROW(last_row_in_pass-1U, pass);4513first_row_in_pass = PNG_PASS_START_ROW(pass);4514}45154516else /* Application handles the interlace */4517# endif /* WRITE_INTERLACING */4518{4519/* The row does exist, so this works without checking the column4520* count.4521*/4522debug(last_row_in_pass > 0U);4523last_row_in_pass -= 1U;4524}45254526if (pass == PNG_LAST_PASS(pixels_in_pass/*PNG width*/, height))4527base_info_flags |= png_pass_last;45284529/* Finally, adjust pixels_in_pass for the interlacing (skip the4530* final pass; it is full width).4531*/4532if (pass < 6)4533pixels_in_pass = PNG_PASS_COLS(pixels_in_pass, pass);4534}45354536/* Mask out the bits in a partial byte. */4537pixels_at_end = pixels_in_pass & PNG_ADDOF(bpp);45384539# ifdef PNG_WRITE_FILTER_SUPPORTED4540/* Reset the previous_row pointer correctly; NULL at the start of4541* the pass. If row_number is not 0 then a previous write_rows was4542* interrupted in mid-pass and any required buffer should be in4543* previous_write_row (set in the initializer).4544*/4545if (png_ptr->row_number == first_row_in_pass)4546previous_row = NULL;4547# endif /* WRITE_FILTER */4548}45494550# ifdef PNG_WRITE_INTERLACING_SUPPORTED4551/* When libpng is handling the interlace we see rows that must be4552* skipped.4553*/4554if (!png_ptr->do_interlace ||4555PNG_ROW_IN_INTERLACE_PASS(png_ptr->row_number, pass))4556# endif /* WRITE_INTERLACING */4557{4558const unsigned int row_info_flags = base_info_flags |4559(png_ptr->row_number ==4560first_row_in_pass ? png_pass_first_row : 0) |4561(png_ptr->row_number == last_row_in_pass ? png_pass_last_row : 0);4562const int flush = row_flush(ps, row_info_flags);4563png_const_bytep row = *rows;4564png_uint_32 pixels_to_go = pixels_in_pass;4565# ifdef PNG_WRITE_FILTER_SUPPORTED4566/* The filter can change each time round. Call png_write_start_row4567* to resolve any changes. Note that when this function is used to4568* do filter selection from png_write_png_data on the first row4569* png_write_start_row will get called twice.4570*/4571const png_byte filter = select_filter(ps, row, previous_row, bpp,4572pixels_in_pass, png_ptr->row_number == first_row_in_pass);4573const png_uint_32 max_pixels = filter == PNG_FILTER_VALUE_NONE ?4574ps->zlib_max_pixels : ps->row_buffer_max_pixels;4575const png_uint_32 block_pixels = filter == PNG_FILTER_VALUE_NONE ?4576ps->zlib_max_aligned_pixels : ps->row_buffer_max_aligned_pixels;45774578/* The row handling uses png_compress_IDAT directly if there is no4579* filter to be applied, otherwise it uses filter_row.4580*/4581if (filter != PNG_FILTER_VALUE_NONE)4582{4583int start_of_row = 1;4584png_byte prev_pixels[4*2*2]; /* 2 pixels up to 4x2-bytes each */45854586memset(prev_pixels, 0U, sizeof prev_pixels);45874588while (pixels_to_go > max_pixels)4589{4590/* Write a block at once to maintain alignment */4591filter_row(png_ptr, previous_row, prev_pixels, row,4592bpp * block_pixels, bpp, filter, start_of_row,4593Z_NO_FLUSH);45944595if (previous_row != NULL)4596previous_row += (block_pixels * bpp) >> 3;45974598row += (block_pixels * bpp) >> 3;4599pixels_to_go -= block_pixels;4600start_of_row = 0;4601}46024603/* The filter code handles the partial byte at the end correctly,4604* so this is all that is required:4605*/4606if (pixels_to_go > 0)4607filter_row(png_ptr, previous_row, prev_pixels, row,4608bpp * pixels_to_go, bpp, filter, start_of_row, flush);4609}46104611else4612# endif /* WRITE_FILTER */46134614{4615/* The no-filter case. */4616const uInt block_bytes = (uInt)/*SAFE*/(4617bpp <= 8U ?4618block_pixels >> PNG_SHIFTOF(bpp) :4619block_pixels * (bpp >> 3));46204621/* png_write_start_IDAT guarantees this, but double check for4622* overflow above in debug:4623*/4624debug((block_bytes & (PNG_ROW_BUFFER_BYTE_ALIGN-1U)) == 0U);46254626/* The filter has to be written here: */4627png_compress_IDAT(png_ptr, &filter, 1U/*len*/, Z_NO_FLUSH);46284629/* Process blocks of pixels up to the limit. */4630while (pixels_to_go > max_pixels)4631{4632png_compress_IDAT(png_ptr, row, block_bytes, Z_NO_FLUSH);4633row += block_bytes;4634pixels_to_go -= block_pixels;4635}46364637/* Now compress the remainder; pixels_to_go <= max_pixels so it will4638* fit in a uInt.4639*/4640{4641const png_uint_32 remainder =4642bpp <= 8U4643? (pixels_to_go-pixels_at_end) >> PNG_SHIFTOF(bpp)4644: (pixels_to_go-pixels_at_end) * (bpp >> 3);46454646if (remainder > 0U)4647png_compress_IDAT(png_ptr, row, remainder,4648pixels_at_end > 0U ? Z_NO_FLUSH : flush);46494650else4651debug(pixels_at_end > 0U);46524653if (pixels_at_end > 0U)4654{4655/* There is a final partial byte. This is PNG format so the4656* left-most bits are the most significant.4657*/4658const png_byte last = PNG_BYTE(row[remainder] &4659~(0xFFU >> (pixels_at_end * bpp)));46604661png_compress_IDAT(png_ptr, &last, 1U, flush);4662}4663}4664}46654666png_write_end_row(png_ptr, flush);46674668# ifdef PNG_WRITE_FILTER_SUPPORTED4669previous_row = *rows;4670# endif /* WRITE_FILTER */4671# undef HANDLE4672} /* row in pass */46734674# ifdef PNG_WRITE_INTERLACING_SUPPORTED4675else /* row not in pass; just skip it */4676{4677if (++png_ptr->row_number >= png_ptr->height)4678{4679debug(png_ptr->row_number == png_ptr->height);46804681png_ptr->row_number = 0U;4682png_ptr->pass = 0x7U & (pass+1U);4683}4684}4685# endif /* WRITE_INTERLACING */46864687++rows;4688} /* while num_rows */46894690# ifdef PNG_WRITE_FILTER_SUPPORTED4691/* previous_row must be copied back unless we don't need it because the4692* next row is the first one in the pass (this relies on png_write_end_row4693* setting row_number to 0 at the end!)4694*/4695if (png_ptr->row_number != 0U && previous_row != NULL && SAVE_ROW(ps) &&4696ps->previous_write_row != previous_row/*all rows skipped*/)4697{4698# ifdef PNG_SELECT_FILTER_SUPPORTED4699/* We might be able to avoid any copy. */4700if (ps->current_write_row == previous_row)4701{4702png_bytep old = ps->previous_write_row;4703ps->previous_write_row = ps->current_write_row;4704ps->current_write_row = old; /* may be NULL */4705}47064707else4708# endif /* SELECT_FILTER */47094710if (ps->previous_write_row != NULL)4711memcpy(ps->previous_write_row, previous_row,4712png_calc_rowbytes(png_ptr, bpp, pixels_in_pass));47134714else4715ps->previous_write_row = allocate_row(png_ptr, previous_row,4716png_calc_rowbytes(png_ptr, bpp, pixels_in_pass));4717}4718# endif /* WRITE_FILTER */4719}47204721#ifdef PNG_WRITE_FILTER_SUPPORTED4722/* This filters the row, chooses which filter to use, if it has not already4723* been specified by the application, and then writes the row out with the4724* chosen filter.4725*/4726static void4727write_png_data(png_structrp png_ptr, png_const_bytep prev_row,4728png_bytep prev_pixels, png_const_bytep unfiltered_row, png_uint_32 x,4729unsigned int row_bits, unsigned int row_info_flags)4730/* This filters the row appropriately and returns an updated prev_row4731* (updated for 'x').4732*/4733{4734const png_zlib_statep ps = png_ptr->zlib_state;4735const unsigned int bpp = png_ptr->row_output_pixel_depth;4736const int flush = row_flush(ps, row_info_flags);4737const png_byte filter = ps->filters; /* just one */47384739/* These invariants are expected from the caller: */4740affirm(row_bits <= 8U*PNG_ROW_BUFFER_SIZE);4741debug(filter < PNG_FILTER_VALUE_LAST/*sic: last+1*/);47424743/* Now choose the correct filter implementation according to the number of4744* filters in the filters_to_try list. The prev_row parameter is made4745* NULL on the first row because it is uninitialized at that point.4746*/4747if (filter == PNG_FILTER_VALUE_NONE)4748write_unfiltered_rowbits(png_ptr, unfiltered_row, row_bits,4749x == 0 ? PNG_FILTER_VALUE_NONE : PNG_FILTER_VALUE_LAST, flush);47504751else4752filter_row(png_ptr,4753(row_info_flags & png_pass_first_row) ? NULL : prev_row,4754prev_pixels, unfiltered_row, row_bits, bpp, filter, x == 0, flush);47554756/* Handle end of row: */4757if ((row_info_flags & png_row_end) != 0)4758png_write_end_row(png_ptr, flush);4759}47604761void /* PRIVATE */4762png_write_png_data(png_structrp png_ptr, png_bytep prev_pixels,4763png_const_bytep unfiltered_row, png_uint_32 x,4764unsigned int width/*pixels*/, unsigned int row_info_flags)4765{4766const png_zlib_statep ps = png_ptr->zlib_state;47674768affirm(ps != NULL);47694770{4771const unsigned int bpp = png_ptr->row_output_pixel_depth;4772const unsigned int row_bits = width * bpp;4773png_bytep prev_row = ps->previous_write_row;47744775debug(bpp <= 64U && width <= 65535U &&4776width < 65535U/bpp); /* Expensive: only matters on 16-bit */47774778/* This is called once before starting a new row here, but below it is4779* only called once between starting a new list of rows.4780*/4781if (x == 0)4782png_write_start_row(ps, (row_info_flags & png_pass_first_row) != 0,4783prev_row == NULL);47844785/* If filter selection is required the filter will have at least one mask4786* bit set.4787*/4788# ifdef PNG_SELECT_FILTER_SUPPORTED4789if (ps->filters >= PNG_FILTER_NONE/*lowest mask bit*/)4790{4791/* If the entire row is passed in the input process it via4792* immediately, otherwise the row must be buffered for later4793* analysis.4794*/4795png_const_bytep row;47964797if (x > 0 || (row_info_flags & png_row_end) == 0)4798{4799/* The row must be saved for later. */4800png_bytep buffer = ps->current_write_row;48014802/* png_write_start row should always check this: */4803debug(ps->write_row_size > 0U);48044805if (buffer != NULL)4806memcpy(buffer + png_calc_rowbytes(png_ptr, bpp, x),4807unfiltered_row, (row_bits + 7U) >> 3);480848094810else if (x == 0U)4811ps->current_write_row = buffer = allocate_row(png_ptr,4812unfiltered_row, (row_bits + 7U) >> 3);48134814row = buffer;4815}48164817else4818row = unfiltered_row;48194820if (row != NULL) /* else out of memory */4821{4822/* At row end, process the save buffer. */4823if ((row_info_flags & png_row_end) != 0)4824png_write_png_rows(png_ptr, &row, 1U);48254826/* Early return to skip the single-filter code */4827return;4828}48294830/* Caching the row failed, so process the row using the lowest set4831* filter. The allocation error should only ever happen at the4832* start of the row. If this goes wrong the output will have been4833* damaged.4834*/4835affirm(x == 0U);4836}4837# endif /* SELECT_FILTER */48384839/* prev_row is either NULL or the position in the previous row buffer */4840if (prev_row != NULL && x > 0)4841prev_row += png_calc_rowbytes(png_ptr, bpp, x);48424843/* This is the single filter case (no selection): */4844write_png_data(png_ptr, prev_row, prev_pixels, unfiltered_row, x,4845row_bits, row_info_flags);48464847/* Copy the current row into the previous row buffer, if available, unless4848* this is the last row in the pass, when there is no point. Note that4849* write_previous_row may have garbage in a partial byte at the end as a4850* result of this memcpy.4851*/4852if (!(row_info_flags & png_pass_last_row) && SAVE_ROW(ps)) {4853if (prev_row != NULL)4854memcpy(prev_row, unfiltered_row, (row_bits + 7U) >> 3);48554856/* NOTE: if the application sets png_zlib_state::save_row in a callback4857* it isn't possible to do the save until the next row. allocate_row4858* handles OOM silently by turning off the save.4859*/4860else if (x == 0) /* can allocate the save buffer */4861ps->previous_write_row =4862allocate_row(png_ptr, unfiltered_row, (row_bits + 7U) >> 3);4863}4864}4865}4866#else /* !WRITE_FILTER */4867void /* PRIVATE */4868png_write_start_IDAT(png_structrp png_ptr)4869{4870png_zlib_statep ps = get_zlib_state(png_ptr);48714872/* Set up the IDAT compression state. Expect the state to have been released4873* by the previous owner, but it doesn't much matter if there was an error.4874* Note that the stream is not claimed yet.4875*/4876debug(png_ptr->zowner == 0U);48774878/* This sets the buffer limits and write_row_size, which is used below. */4879png_zlib_state_set_buffer_limits(png_ptr, ps);4880}48814882void /* PRIVATE */4883png_write_png_data(png_structrp png_ptr, png_bytep prev_pixels,4884png_const_bytep unfiltered_row, png_uint_32 x,4885unsigned int width/*pixels*/, unsigned int row_info_flags)4886{4887const unsigned int bpp = png_ptr->row_output_pixel_depth;4888int flush;4889png_uint_32 row_bits;48904891row_bits = width;4892row_bits *= bpp;4893/* These invariants are expected from the caller: */4894affirm(width < 65536U && bpp <= 64U && width < 65536U/bpp &&4895row_bits <= 8U*PNG_ROW_BUFFER_SIZE);48964897affirm(png_ptr->zlib_state != NULL);4898flush = row_flush(png_ptr->zlib_state, row_info_flags);48994900write_unfiltered_rowbits(png_ptr, unfiltered_row, row_bits,4901x == 0 ? PNG_FILTER_VALUE_NONE : PNG_FILTER_VALUE_LAST, flush);49024903PNG_UNUSED(prev_pixels)49044905/* Handle end of row: */4906if ((row_info_flags & png_row_end) != 0)4907png_write_end_row(png_ptr, flush);4908}4909#endif /* !WRITE_FILTER */49104911png_int_32 /* PRIVATE */4912png_write_setting(png_structrp png_ptr, png_uint_32 setting,4913png_uint_32 parameter, png_int_32 value)4914{4915/* Caller checks the arguments for basic validity */4916int only_get = (setting & PNG_SF_GET) != 0U;49174918setting &= ~PNG_SF_GET;49194920switch (setting)4921{4922/* Settings in png_struct: */4923case PNG_SW_IDAT_size:4924if (parameter > 0 && parameter <= PNG_UINT_31_MAX)4925{4926if (!only_get)4927png_ptr->IDAT_size = parameter;49284929return 0; /* set ok */4930}49314932else4933return PNG_EINVAL;49344935/* Settings in zlib_state: */4936case PNG_SW_COMPRESS_png_level:4937return compression_setting(png_ptr, parameter, png_level, value,4938only_get);49394940# ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED4941case PNG_SW_COMPRESS_zlib_level:4942return compression_setting(png_ptr, parameter, level, value,4943only_get);49444945case PNG_SW_COMPRESS_windowBits:4946return compression_setting(png_ptr, parameter, windowBits, value,4947only_get);49484949case PNG_SW_COMPRESS_memLevel:4950return compression_setting(png_ptr, parameter, memLevel, value,4951only_get);49524953case PNG_SW_COMPRESS_strategy:4954return compression_setting(png_ptr, parameter, strategy, value,4955only_get);49564957case PNG_SW_COMPRESS_method:4958if (value != 8) /* Only supported method */4959return PNG_EINVAL;4960return 8; /* old method */4961# endif /* WRITE_CUSTOMIZE_COMPRESSION */49624963# ifdef PNG_WRITE_FILTER_SUPPORTED4964case PNG_SW_COMPRESS_filters:4965/* The method must match that in the IHDR: */4966if (parameter == png_ptr->filter_method)4967{4968if (!only_get)4969return set_filter(get_zlib_state(png_ptr), value);49704971else if (png_ptr->zlib_state != NULL &&4972png_ptr->zlib_state->filter_mask != 0U/*unset*/)4973return png_ptr->zlib_state->filter_mask;49744975else4976return PNG_UNSET;4977}49784979else /* Invalid filter method */4980return PNG_EINVAL;49814982case PNG_SW_COMPRESS_row_buffers:4983/* New in 1.7.0: direct control of the buffering. */4984switch (parameter)4985{4986case 0:4987if (!only_get)4988get_zlib_state(png_ptr)->save_row = SAVE_ROW_OFF;4989return 0;49904991case 1:4992if (!only_get)4993get_zlib_state(png_ptr)->save_row = SAVE_ROW_ON;4994return 1;49954996default:4997return PNG_ENOSYS; /* no support for bigger values */4998}4999# endif /* WRITE_FILTER */50005001# ifdef PNG_WRITE_FLUSH_SUPPORTED5002case PNG_SW_FLUSH:5003/* Set the automatic flush interval or 0 to turn flushing off */5004if (!only_get)5005get_zlib_state(png_ptr)->flush_dist =5006value <= 0 ? 0xEFFFFFFFU : (png_uint_32)/*SAFE*/value;50075008return 0;5009# endif /* WRITE_FLUSH */50105011# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED5012case PNG_SRW_CHECK_FOR_INVALID_INDEX:5013/* The 'enabled' value is a FORTRAN style three-state: */5014if (value > 0)5015png_ptr->palette_index_check = PNG_PALETTE_CHECK_ON;50165017else if (value < 0)5018png_ptr->palette_index_check = PNG_PALETTE_CHECK_OFF;50195020else5021png_ptr->palette_index_check = PNG_PALETTE_CHECK_DEFAULT;50225023return 0;5024# endif /* WRITE_CHECK_FOR_INVALID_INDEX */50255026# ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED5027case PNG_SRW_ERROR_HANDLING:5028/* The parameter is a bit mask of what to set, the value is what to5029* set it to. PNG_IDAT_ERRORS is ignored on write.5030*/5031if (value >= PNG_IGNORE && value <= PNG_ERROR &&5032parameter <= PNG_ALL_ERRORS)5033{5034if ((parameter & PNG_BENIGN_ERRORS) != 0U)5035png_ptr->benign_error_action = value & 0x3U;50365037if ((parameter & PNG_APP_WARNINGS) != 0U)5038png_ptr->app_warning_action = value & 0x3U;50395040if ((parameter & PNG_APP_ERRORS) != 0U)5041png_ptr->app_error_action = value & 0x3U;50425043return 0;5044}50455046return PNG_EINVAL;5047# endif /* BENIGN_WRITE_ERRORS */50485049default:5050return PNG_ENOSYS; /* not supported (whatever it is) */5051}5052}5053#endif /* WRITE */505450555056