CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/ext/libpng17/pngwutil.c
Views: 1401
1
#ifdef _MSC_VER
2
#pragma warning (disable:4018)
3
#pragma warning (disable:4028)
4
#pragma warning (disable:4146)
5
#pragma warning (disable:4334)
6
#endif
7
8
/* pngwutil.c - utilities to write a PNG file
9
*
10
* Last changed in libpng 1.7.0 [(PENDING RELEASE)]
11
* Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
12
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
13
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
14
*
15
* This code is released under the libpng license.
16
* For conditions of distribution and use, see the disclaimer
17
* and license in png.h
18
*/
19
20
#include "pngpriv.h"
21
#define PNG_SRC_FILE PNG_SRC_FILE_pngwutil
22
23
#ifdef PNG_WRITE_SUPPORTED
24
25
#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
26
/* Place a 32-bit number into a buffer in PNG byte order. We work
27
* with unsigned numbers for convenience, although one supported
28
* ancillary chunk uses signed (two's complement) numbers.
29
*/
30
void PNGAPI
31
png_save_uint_32(png_bytep buf, png_uint_32 i)
32
{
33
buf[0] = PNG_BYTE(i >> 24);
34
buf[1] = PNG_BYTE(i >> 16);
35
buf[2] = PNG_BYTE(i >> 8);
36
buf[3] = PNG_BYTE(i);
37
}
38
39
/* Place a 16-bit number into a buffer in PNG byte order.
40
* The parameter is declared unsigned int, not png_uint_16,
41
* just to avoid potential problems on pre-ANSI C compilers.
42
*/
43
void PNGAPI
44
png_save_uint_16(png_bytep buf, unsigned int i)
45
{
46
buf[0] = PNG_BYTE(i >> 8);
47
buf[1] = PNG_BYTE(i);
48
}
49
#endif /* WRITE_INT_FUNCTIONS */
50
51
/* Simple function to write the signature. If we have already written
52
* the magic bytes of the signature, or more likely, the PNG stream is
53
* being embedded into another stream and doesn't need its own signature,
54
* we should call png_set_sig_bytes() to tell libpng how many of the
55
* bytes have already been written.
56
*/
57
void PNGAPI
58
png_write_sig(png_structrp png_ptr)
59
{
60
png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
61
62
#ifdef PNG_IO_STATE_SUPPORTED
63
/* Inform the I/O callback that the signature is being written */
64
png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
65
#endif
66
67
/* Write the rest of the 8 byte signature */
68
png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
69
(png_size_t)(8 - png_ptr->sig_bytes));
70
71
if (png_ptr->sig_bytes < 3)
72
png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
73
}
74
75
/* Write the start of a PNG chunk. The type is the chunk type.
76
* The total_length is the sum of the lengths of all the data you will be
77
* passing in png_write_chunk_data().
78
*/
79
static void
80
png_write_chunk_header(png_structrp png_ptr, png_uint_32 chunk_name,
81
png_uint_32 length)
82
{
83
png_byte buf[8];
84
85
#if defined(PNG_DEBUG) && (PNG_DEBUG > 0)
86
PNG_CSTRING_FROM_CHUNK(buf, chunk_name);
87
png_debug2(0, "Writing %s chunk, length = %lu", buf, (unsigned long)length);
88
#endif
89
90
if (png_ptr == NULL)
91
return;
92
93
#ifdef PNG_IO_STATE_SUPPORTED
94
/* Inform the I/O callback that the chunk header is being written.
95
* PNG_IO_CHUNK_HDR requires a single I/O call.
96
*/
97
png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;
98
#endif
99
100
/* Write the length and the chunk name */
101
png_save_uint_32(buf, length);
102
png_save_uint_32(buf + 4, chunk_name);
103
png_write_data(png_ptr, buf, 8);
104
105
/* Put the chunk name into png_ptr->chunk_name */
106
png_ptr->chunk_name = chunk_name;
107
108
/* Reset the crc and run it over the chunk name */
109
png_reset_crc(png_ptr, buf+4);
110
111
#ifdef PNG_IO_STATE_SUPPORTED
112
/* Inform the I/O callback that chunk data will (possibly) be written.
113
* PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.
114
*/
115
png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;
116
#endif
117
}
118
119
void PNGAPI
120
png_write_chunk_start(png_structrp png_ptr, png_const_bytep chunk_string,
121
png_uint_32 length)
122
{
123
png_write_chunk_header(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), length);
124
}
125
126
/* Write the data of a PNG chunk started with png_write_chunk_header().
127
* Note that multiple calls to this function are allowed, and that the
128
* sum of the lengths from these calls *must* add up to the total_length
129
* given to png_write_chunk_header().
130
*/
131
void PNGAPI
132
png_write_chunk_data(png_structrp png_ptr, png_const_voidp data,
133
png_size_t length)
134
{
135
/* Write the data, and run the CRC over it */
136
if (png_ptr == NULL)
137
return;
138
139
if (data != NULL && length > 0)
140
{
141
png_write_data(png_ptr, data, length);
142
143
/* Update the CRC after writing the data,
144
* in case the user I/O routine alters it.
145
*/
146
png_calculate_crc(png_ptr, data, length);
147
}
148
}
149
150
/* Finish a chunk started with png_write_chunk_header(). */
151
void PNGAPI
152
png_write_chunk_end(png_structrp png_ptr)
153
{
154
png_byte buf[4];
155
156
if (png_ptr == NULL) return;
157
158
#ifdef PNG_IO_STATE_SUPPORTED
159
/* Inform the I/O callback that the chunk CRC is being written.
160
* PNG_IO_CHUNK_CRC requires a single I/O function call.
161
*/
162
png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;
163
#endif
164
165
/* Write the crc in a single operation */
166
png_save_uint_32(buf, png_ptr->crc);
167
168
png_write_data(png_ptr, buf, (png_size_t)4);
169
}
170
171
/* Write a PNG chunk all at once. The type is an array of ASCII characters
172
* representing the chunk name. The array must be at least 4 bytes in
173
* length, and does not need to be null terminated. To be safe, pass the
174
* pre-defined chunk names here, and if you need a new one, define it
175
* where the others are defined. The length is the length of the data.
176
* All the data must be present. If that is not possible, use the
177
* png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
178
* functions instead.
179
*/
180
static void
181
png_write_complete_chunk(png_structrp png_ptr, png_uint_32 chunk_name,
182
png_const_voidp data, png_size_t length)
183
{
184
if (png_ptr == NULL)
185
return;
186
187
/* On 64 bit architectures 'length' may not fit in a png_uint_32. */
188
if (length > PNG_UINT_31_MAX)
189
png_error(png_ptr, "length exceeds PNG maximum");
190
191
png_write_chunk_header(png_ptr, chunk_name, (png_uint_32)/*SAFE*/length);
192
png_write_chunk_data(png_ptr, data, length);
193
png_write_chunk_end(png_ptr);
194
}
195
196
/* This is the API that calls the internal function above. */
197
void PNGAPI
198
png_write_chunk(png_structrp png_ptr, png_const_bytep chunk_string,
199
png_const_voidp data, png_size_t length)
200
{
201
png_write_complete_chunk(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), data,
202
length);
203
}
204
205
static png_alloc_size_t
206
png_write_row_buffer_size(png_const_structrp png_ptr)
207
/* Returns the width of the widest pass in the first row of an interlaced
208
* image. Passes in the first row are: 0.5.3.5.1.5.3.5, so the widest row is
209
* normally the one from pass 5. The only exception is if the image is only
210
* one pixel wide, so:
211
*/
212
#define PNG_FIRST_ROW_MAX_WIDTH(w) (w > 1U ? PNG_PASS_COLS(w, 5U) : 1U)
213
214
/* For interlaced images the count of pixels is rounded up to a the number of
215
* pixels in the first pass (numbered 0). This ensures that passes before
216
* the last can be packed in the buffer without overflow.
217
*/
218
{
219
png_alloc_size_t w;
220
221
/* If the image is interlaced adjust 'w' for the interlacing: */
222
if (png_ptr->interlaced != PNG_INTERLACE_NONE)
223
{
224
/* Take advantage of the fact that 1-row interlaced PNGs require half the
225
* normal row width:
226
*/
227
if (png_ptr->height == 1U) /* no pass 6 */
228
w = PNG_FIRST_ROW_MAX_WIDTH(png_ptr->width);
229
230
/* Otherwise round up to a multiple of 8. This may waste a few (less
231
* than 8) bytes for PNGs with a height less than 57 but this hardly
232
* matters.
233
*/
234
else
235
w = (png_ptr->width + 7U) & ~7U;
236
}
237
238
else
239
w = png_ptr->width;
240
241
/* The rounding above may leave 'w' exactly 2^31 */
242
debug(w <= 0x80000000U);
243
244
switch (png_ptr->row_output_pixel_depth)
245
{
246
/* This would happen if the function is called before png_write_IHDR. */
247
default: NOT_REACHED; return 0;
248
249
case 1: w = (w+7) >> 3; break;
250
case 2: w = (w+3) >> 2; break;
251
case 4: w = (w+1) >> 1; break;
252
case 8: break;
253
case 16: w <<= 1; break; /* overflow: w is set to 0, which is OK */
254
255
/* For the remaining cases the answer is w*bytes; where bytes is 3,4,6
256
* or 8. This may overflow 32 bits. There is no way to compute the
257
* result on an arbitrary platform, so test the maximum of a (size_t)
258
* against w for each possible byte depth:
259
*/
260
# define CASE(b)\
261
case b*8:\
262
if (w <= (PNG_SIZE_MAX/b)/*compile-time constant*/)\
263
return w * b;\
264
return 0;
265
266
CASE(3)
267
CASE(4)
268
CASE(6)
269
CASE(8)
270
271
# undef CASE
272
}
273
274
/* This is the low bit depth case. The following can never be false on
275
* systems with a 32-bit or greater size_t:
276
*/
277
if (w <= PNG_SIZE_MAX)
278
return w;
279
280
return 0U;
281
}
282
283
/* Release memory used by the deflate mechanism */
284
static void
285
png_deflateEnd(png_const_structrp png_ptr, z_stream *zs, int check)
286
{
287
if (zs->state != NULL)
288
{
289
int ret = deflateEnd(zs);
290
291
/* Z_DATA_ERROR means there was pending output. */
292
if ((ret != Z_OK && (check || ret != Z_DATA_ERROR)) || zs->state != NULL)
293
{
294
png_zstream_error(zs, ret);
295
296
if (check)
297
png_error(png_ptr, zs->msg);
298
299
else
300
png_warning(png_ptr, zs->msg);
301
302
zs->state = NULL;
303
}
304
}
305
}
306
307
/* 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 in
308
* the event of a write error (previous implementations just leaked memory.)
309
*
310
* From 1.7.0 the size is fixed to the same as the (uncompressed) row buffer
311
* size. This avoids allocating a large chunk of memory when compressing small
312
* images. This type is also opaque outside this file.
313
*/
314
typedef struct png_compression_buffer
315
{
316
struct png_compression_buffer *next;
317
png_byte output[PNG_ROW_BUFFER_SIZE];
318
} png_compression_buffer, *png_compression_bufferp;
319
320
/* png_compression_buffer methods */
321
/* Deleting a compression buffer deletes the whole list: */
322
static void
323
png_free_compression_buffer(png_const_structrp png_ptr,
324
png_compression_bufferp *listp)
325
{
326
png_compression_bufferp list = *listp;
327
328
if (list != NULL)
329
{
330
*listp = NULL;
331
332
do
333
{
334
png_compression_bufferp next = list->next;
335
336
png_free(png_ptr, list);
337
list = next;
338
}
339
while (list != NULL);
340
}
341
}
342
343
/* Return the next compression buffer in the list, allocating it if necessary.
344
* The caller must update 'end' if required; this just moves down the list.
345
*/
346
static png_compression_bufferp
347
png_get_compression_buffer(png_const_structrp png_ptr,
348
png_compression_bufferp *end)
349
{
350
png_compression_bufferp next = *end;
351
352
if (next == NULL)
353
{
354
next = png_voidcast(png_compression_bufferp, png_malloc_base(png_ptr,
355
sizeof *next));
356
357
/* Check for OOM: this is a recoverable error for non-critical chunks, let
358
* the caller decide what to do rather than issuing a png_error here.
359
*/
360
if (next != NULL)
361
{
362
next->next = NULL; /* initialize the buffer */
363
*end = next;
364
}
365
}
366
367
return next; /* may still be NULL on OOM */
368
}
369
370
/* This structure is used to hold all the data for zlib compression of a single
371
* stream of data. It may be re-used, it stores the compressed data internally
372
* and can handle arbitrary input and output.
373
*
374
* 'list' is the output data contained in compression buffers, 'end' points to
375
* list at the start and is advanced down the compression buffer list (extending
376
* it as required) as the data is written. If 'end' points into a compression
377
* buffer (does not point to 'list') that is the buffer in use in
378
* z_stream::{next,avail}_out.
379
*
380
* Compression may be performed in multiple steps, '*end' always points to the
381
* compression buffer *after* the one that is in use, so 'end' is pointing
382
* *into* the one in use.
383
*
384
* end(on entry) .... end ....... end(on exit)
385
* | | |
386
* | | |
387
* V +----V-----+ +-----V----+ +----------+
388
* list ---> | next --+--> | next --+--> | next |
389
* | output[] | | output[] | | output[] |
390
* +----------+ +----------+ +----------+
391
* [in use] [unused]
392
*
393
* These invariants should always hold:
394
*
395
* 1) If zs.state is NULL decompression is not in progress, list may be non-NULL
396
* but end could be anything;
397
*
398
* 2) Otherwise if zs.next_out is NULL list will be NULL and end will point at
399
* list, len, overflow and start will be 0;
400
*
401
* 3) Otherwise list is non-NULL and end points at the 'next' element of an
402
* in-use compression buffer. zs.next_out points into the 'output' element
403
* of the same buffer. {overflow, len} is the amount of compressed data, len
404
* being the low 31 bits, overflow being the higher bits. start is used for
405
* writing and is the index of the first byte in list->output to write,
406
* {overflow, len} does not include start.
407
*/
408
typedef struct
409
{
410
z_stream zs; /* zlib compression data */
411
png_compression_bufferp list; /* Head of the buffer list */
412
png_compression_bufferp *end; /* Pointer to last 'next' pointer */
413
png_uint_32 len; /* Bottom 31 bits of data length */
414
unsigned int overflow; /* Top bits of data length */
415
unsigned int start; /* Start of data in first block */
416
} png_zlib_compress, *png_zlib_compressp;
417
418
/* png_zlib_compress methods */
419
/* Initialize the compress structure. The z_stream itself is not initialized,
420
* however the the 'user' fields are set, including {next,avail}_{in,out}. The
421
* initialization does not change 'list', however it does set 'end' to point to
422
* it, effectively truncating the list.
423
*/
424
static void
425
png_zlib_compress_init(png_structrp png_ptr, png_zlib_compressp pz)
426
{
427
/* png_zlib_compress z_stream: */
428
pz->zs.zalloc = png_zalloc;
429
pz->zs.zfree = png_zfree;
430
/* NOTE: this does not destroy 'restrict' because in all the functions herein
431
* *png_ptr is only ever accessed via *either* pz->zs.opaque *or* a passed in
432
* png_ptr.
433
*/
434
pz->zs.opaque = png_ptr;
435
436
pz->zs.next_in = NULL;
437
pz->zs.avail_in = 0U;
438
pz->zs.total_in = 0U;
439
440
pz->zs.next_out = NULL;
441
pz->zs.avail_out = 0U;
442
pz->zs.total_out = 0U;
443
444
pz->zs.msg = PNGZ_MSG_CAST("zlib success"); /* safety */
445
446
/* pz->list preserved */
447
pz->end = &pz->list;
448
pz->len = 0U;
449
pz->overflow = 0U;
450
pz->start = 0U;
451
}
452
453
/* Return the png_ptr: this is defined here for all the remaining
454
* png_zlib_compress methods because they are only ever called with zs
455
* initialized.
456
*/
457
#define png_ptr png_voidcast(png_const_structrp, pz->zs.opaque)
458
459
#if PNG_RELEASE_BUILD
460
# define png_zlib_compress_validate(pz, in_use) ((void)0)
461
#else /* !RELEASE_BUILD */
462
static void
463
png_zlib_compress_validate(png_zlib_compressp pz, int in_use)
464
{
465
const uInt o_size = sizeof pz->list->output;
466
467
affirm(pz->end != NULL && (in_use || (pz->zs.next_in == NULL &&
468
pz->zs.avail_in == 0U && *pz->end == NULL)));
469
470
if (pz->overflow == 0U && pz->len == 0U && pz->start == 0U) /* empty */
471
{
472
affirm((pz->end == &pz->list && pz->zs.next_out == NULL
473
&& pz->zs.avail_out == 0U) ||
474
(pz->list != NULL && pz->end == &pz->list->next &&
475
pz->zs.next_out == pz->list->output &&
476
pz->zs.avail_out == o_size));
477
}
478
479
else /* not empty */
480
{
481
png_compression_bufferp *ep = &pz->list, list;
482
png_uint_32 o, l;
483
484
affirm(*ep != NULL && pz->zs.next_out != NULL);
485
486
/* Check the list length: */
487
o = pz->overflow;
488
l = pz->len;
489
affirm((l & 0x80000000U) == 0U && (o & 0x80000000U) == 0U);
490
491
do
492
{
493
list = *ep;
494
l -= o_size;
495
if (l & 0x80000000U) --o, l &= 0x7FFFFFFFU;
496
ep = &list->next;
497
}
498
while (ep != pz->end);
499
500
l += pz->start;
501
l += pz->zs.avail_out;
502
if (l & 0x80000000U) ++o, l &= 0x7FFFFFFFU;
503
504
affirm(o == 0U && l == 0U && pz->zs.next_out >= list->output &&
505
pz->zs.next_out + pz->zs.avail_out == list->output + o_size);
506
}
507
}
508
#endif /* !RELEASE_BUILD */
509
510
/* Destroy one zlib compress structure. */
511
static void
512
png_zlib_compress_destroy(png_zlib_compressp pz, int check)
513
{
514
/* If the 'opaque' pointer is NULL this png_zlib_compress was never
515
* initialized, so do nothing.
516
*/
517
if (png_ptr != NULL)
518
{
519
if (pz->zs.state != NULL)
520
{
521
if (check)
522
png_zlib_compress_validate(pz, 0/*in_use*/);
523
524
png_deflateEnd(png_ptr, &pz->zs, check);
525
}
526
527
pz->end = &pz->list; /* safety */
528
png_free_compression_buffer(png_ptr, &pz->list);
529
}
530
}
531
532
/* Ensure that space is available for output, returns the amount of space
533
* available, 0 on OOM. This updates pz->zs.avail_out (etc) as required.
534
*/
535
static uInt
536
png_zlib_compress_avail_out(png_zlib_compressp pz)
537
{
538
uInt avail_out = pz->zs.avail_out;
539
540
png_zlib_compress_validate(pz, 1/*in_use*/);
541
542
if (avail_out == 0U)
543
{
544
png_compression_bufferp next;
545
546
affirm(pz->end == &pz->list || (pz->end != NULL && pz->list != NULL));
547
next = png_get_compression_buffer(png_ptr, pz->end);
548
549
if (next != NULL)
550
{
551
pz->zs.next_out = next->output;
552
pz->zs.avail_out = avail_out = sizeof next->output;
553
pz->end = &next->next;
554
}
555
556
/* else return 0: OOM */
557
}
558
559
else
560
affirm(pz->end != NULL && pz->list != NULL);
561
562
return avail_out;
563
}
564
565
/* Compress the given data given an initialized png_zlib_compress structure.
566
* This may be called multiple times, interleaved with writes as required.
567
*
568
* The input data is passed in in pz->zs.next_in, however the length of the data
569
* is in 'input_len' (to avoid the zlib uInt limit) and pz->zs.avail_in is
570
* overwritten (and left at 0).
571
*
572
* The output information is used and the amount of compressed data is added on
573
* to pz->{overflow,len}.
574
*
575
* If 'limit' is a limit on the amount of data to add to the output (not the
576
* total amount). The function will retun Z_BUF_ERROR if the limit is reached
577
* and the function will never produce more (additional) compressed data than
578
* the limit.
579
*
580
* All of zstream::next_in[input] is consumed if a success code is returned
581
* (Z_OK or Z_STREAM_END if flush is Z_FINISH), otherwise next_in may be used to
582
* determine how much was compressed.
583
*
584
* pz->overflow is not checked for overflow, so if 'limit' is not set overflow
585
* is possible. The caller must guard against this when supplying a limit of 0.
586
*/
587
static int
588
png_compress(
589
png_zlib_compressp pz,
590
png_alloc_size_t input_len, /* Length of data to be compressed */
591
png_uint_32 limit, /* Limit on amount of compressed data made */
592
int flush) /* Flush parameter at end of input */
593
{
594
const int unlimited = (limit == 0U);
595
596
/* Sanity checking: */
597
affirm(pz->zs.state != NULL &&
598
(pz->zs.next_out == NULL
599
? pz->end == &pz->list && pz->len == 0U && pz->overflow == 0U
600
: pz->list != NULL && pz->end != NULL));
601
implies(pz->zs.next_out == NULL, pz->zs.avail_out == 0);
602
603
for (;;)
604
{
605
uInt extra;
606
607
/* OUTPUT: make sure some space is available: */
608
if (png_zlib_compress_avail_out(pz) == 0U)
609
return Z_MEM_ERROR;
610
611
/* INPUT: limit the deflate call input to ZLIB_IO_MAX: */
612
/* Adjust the input counters: */
613
{
614
uInt avail_in = ZLIB_IO_MAX;
615
616
if (avail_in > input_len)
617
avail_in = (uInt)/*SAFE*/input_len;
618
619
input_len -= avail_in;
620
pz->zs.avail_in = avail_in;
621
}
622
623
if (!unlimited && pz->zs.avail_out > limit)
624
{
625
extra = (uInt)/*SAFE*/(pz->zs.avail_out - limit); /* unused bytes */
626
pz->zs.avail_out = (uInt)/*SAFE*/limit;
627
limit = 0U;
628
}
629
630
else
631
{
632
extra = 0U;
633
limit -= pz->zs.avail_out; /* limit >= 0U */
634
}
635
636
pz->len += pz->zs.avail_out; /* maximum that can be produced */
637
638
/* Compress the data */
639
{
640
int ret = deflate(&pz->zs, input_len > 0U ? Z_NO_FLUSH : flush);
641
642
/* Claw back input data that was not consumed (because avail_in is
643
* reset above every time round the loop) and correct the output
644
* length.
645
*/
646
input_len += pz->zs.avail_in;
647
pz->zs.avail_in = 0; /* safety */
648
pz->len -= pz->zs.avail_out;
649
650
if (pz->len & 0x80000000U)
651
++pz->overflow, pz->len &= 0x7FFFFFFFU;
652
653
limit += pz->zs.avail_out;
654
pz->zs.avail_out += extra;
655
656
/* Check the error code: */
657
switch (ret)
658
{
659
case Z_OK:
660
if (pz->zs.avail_out > extra)
661
{
662
/* zlib had output space, so all the input should have been
663
* consumed:
664
*/
665
affirm(input_len == 0U /* else unexpected stop */ &&
666
flush != Z_FINISH/* ret != Z_STREAM_END */);
667
return Z_OK;
668
}
669
670
else
671
{
672
/* zlib ran out of output space, produce some more. If the
673
* limit is 0 at this point, however, no more space is
674
* available.
675
*/
676
if (unlimited || limit > 0U)
677
break; /* Allocate more output */
678
679
/* No more output space available, but the input may have all
680
* been consumed.
681
*/
682
if (input_len == 0U && flush != Z_FINISH)
683
return Z_OK;
684
685
/* Input all consumed, but insufficient space to flush the
686
* output; this is the Z_BUF_ERROR case.
687
*/
688
return Z_BUF_ERROR;
689
}
690
691
case Z_STREAM_END:
692
affirm(input_len == 0U && flush == Z_FINISH);
693
return Z_STREAM_END;
694
695
case Z_BUF_ERROR:
696
/* This means that we are flushing all the output; expect
697
* avail_out and input_len to be 0.
698
*
699
* NOTE: if png_compress is called with input_len 0 and flush set
700
* to Z_NO_FLUSH this affirm will fire because zlib will have no
701
* work to do.
702
*/
703
affirm(input_len == 0U && pz->zs.avail_out == extra);
704
/* Allocate another buffer */
705
break;
706
707
default:
708
/* An error */
709
return ret;
710
}
711
}
712
}
713
}
714
715
#undef png_ptr /* remove definition using a png_zlib_compressp */
716
717
/* All the compression state is held here, it is allocated when required. This
718
* ensures that the read code doesn't carry the overhead of the much less
719
* frequently used write stuff.
720
*
721
* TODO: make png_create_write_struct allocate this stuff after the main
722
* png_struct.
723
*/
724
struct filter_selector; /* Used only for filter selection */
725
726
typedef struct png_zlib_state
727
{
728
png_zlib_compress s; /* Primary compression state */
729
png_compression_bufferp stash; /* Unused compression buffers */
730
731
# define ps_png_ptr(ps) png_upcast(png_const_structrp, (ps)->s.zs.opaque)
732
/* A png_ptr, used below in functions that only have a png_zlib_state.
733
* NOTE: the png_zlib_compress must have been initialized!
734
*/
735
736
png_uint_32 zlib_max_pixels;
737
/* Maximum number of pixels that zlib can handle at once; the lesser of
738
* the PNG maximum and the maximum that will fit in (uInt)-1 bytes. This
739
* number of pixels may not be byte aligned.
740
*/
741
png_uint_32 zlib_max_aligned_pixels;
742
/* The maximum number of pixels that zlib can handle while maintaining a
743
* buffer byte alignment of PNG_ROW_BUFFER_BYTE_ALIGN; <= the previous
744
* value.
745
*/
746
747
png_alloc_size_t write_row_size;
748
/* Size of the PNG row (without the filter byte) in bytes or 0 if it is
749
* too large to be cached.
750
*/
751
752
# ifdef PNG_WRITE_FILTER_SUPPORTED
753
/* During write libpng needs the previous row when writing a new row with
754
* up, avg or paeth and one or more image rows when performing filter
755
* selection. So if performing filter selection typically two or more
756
* rows are required while if no filter selection is to be done only the
757
* previous row pointer is required.
758
*/
759
png_bytep previous_write_row; /* Last row written, if any */
760
# ifdef PNG_SELECT_FILTER_SUPPORTED
761
png_bytep current_write_row; /* Row being written */
762
struct filter_selector *selector; /* Data for filter selection */
763
png_uint_32 filter_select_window;
764
/* The number of bytes of uncompressed PNG data which are assumed to
765
* be relevant when doing filter selection. Limited to 8453377
766
* (about 2^23); the maximum number of bytes that can be encoded in
767
* the largest deflate window.
768
*/
769
# define PNG_FILTER_SELECT_WINDOW_MAX 8453377U
770
png_byte filter_select_threshold;
771
/* If the number of distinct codes seen in the PNG data are below
772
* this threshold the PNG data will not be filtered (if the 'none'
773
* filter is allowed). If this is still true and a particular
774
* filter does not add new codes that filter will be used.
775
*/
776
png_byte filter_select_threshold2;
777
/* If the number of distinct codes that result by using a particular
778
* filter is below this second threshold that filter will be used.
779
* (When multiple filters pass this criterion the lowest numbered
780
* one producing the lowest number of new codes will be
781
* chosen.)
782
*/
783
# endif /* SELECT_FILTER */
784
785
unsigned int row_buffer_max_pixels;
786
/* The maximum number of pixels that can fit in PNG_ROW_BUFFER_SIZE
787
* bytes; not necessary a whole number of bytes.
788
*/
789
unsigned int row_buffer_max_aligned_pixels;
790
/* The maximum number of pixels that can fit in PNG_ROW_BUFFER_SIZE
791
* bytes while maintaining PNG_ROW_BUFFER_BYTE_ALIGN alignment.
792
*/
793
794
unsigned int filter_mask :8; /* mask of filters to consider on NEXT row */
795
# define PREVIOUS_ROW_FILTERS\
796
(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)
797
unsigned int filters :8; /* Filters for current row */
798
unsigned int save_row :2; /* As below: */
799
# define SAVE_ROW_UNSET 0U
800
# define SAVE_ROW_OFF 1U /* Previous-row filters will be ignored */
801
# define SAVE_ROW_DEFAULT 2U /* Default to save rows set by libpng */
802
# define SAVE_ROW_ON 3U /* Force rows to be saved */
803
# define SAVE_ROW(ps) ((ps)->save_row >= SAVE_ROW_DEFAULT)
804
# endif /* WRITE_FILTER */
805
806
/* Compression settings: see below for how these are encoded. */
807
png_uint_32 pz_IDAT; /* Settings for the image */
808
png_uint_32 pz_iCCP; /* Settings for iCCP chunks */
809
png_uint_32 pz_text; /* Settings for text chunks */
810
png_uint_32 pz_current; /* Last set settings */
811
812
# ifdef PNG_WRITE_FLUSH_SUPPORTED
813
png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
814
png_uint_32 flush_rows; /* number of rows written since last flush */
815
# endif /* WRITE_FLUSH */
816
} png_zlib_state;
817
818
/* Create the zlib state: */
819
static void
820
png_create_zlib_state(png_structrp png_ptr)
821
{
822
png_zlib_statep ps = png_voidcast(png_zlib_state*,
823
png_malloc(png_ptr, sizeof *ps));
824
825
/* Clear to NULL/0: */
826
memset(ps, 0, sizeof *ps);
827
828
debug(png_ptr->zlib_state == NULL);
829
png_ptr->zlib_state = ps;
830
png_zlib_compress_init(png_ptr, &ps->s);
831
832
# ifdef PNG_WRITE_FILTER_SUPPORTED
833
ps->previous_write_row = NULL;
834
# ifdef PNG_SELECT_FILTER_SUPPORTED
835
ps->current_write_row = NULL;
836
ps->selector = NULL;
837
# endif /* SELECT_FILTER */
838
# endif /* WRITE_FILTER */
839
# ifdef PNG_WRITE_FLUSH_SUPPORTED
840
/* Set this to prevent flushing by making it larger than the number
841
* of rows in the largest interlaced PNG; PNG_UINT_31_MAX times
842
* (1/8+1/8+1/8+1/4+1/4+1/2+1/2); 1.875, or 15/8
843
*/
844
ps->flush_dist = 0xEFFFFFFFU;
845
# endif /* WRITE_FLUSH */
846
}
847
848
static void
849
png_zlib_state_set_buffer_limits(png_const_structrp png_ptr, png_zlib_statep ps)
850
/* Delayed initialization of the zlib state maxima; this is not done above in
851
* case the zlib_state is created before the IHDR has been written, which
852
* would lead to the various png_struct fields used below being
853
* uninitialized.
854
*/
855
{
856
/* Initialization of the buffer size constants. */
857
const unsigned int bpp = PNG_PIXEL_DEPTH(*png_ptr);
858
const unsigned int byte_pp = bpp >> 3; /* May be 0 */
859
const unsigned int pixel_block =
860
/* Number of pixels required to maintain PNG_ROW_BUFFER_BYTE_ALIGN
861
* alignment. For multi-byte pixels use the first set bit to determine
862
* if the pixels have a greater alignment already.
863
*/
864
bpp < 8U ?
865
PNG_ROW_BUFFER_BYTE_ALIGN * (8U/bpp) :
866
PNG_ROW_BUFFER_BYTE_ALIGN <= (byte_pp & -byte_pp) ?
867
1U :
868
PNG_ROW_BUFFER_BYTE_ALIGN / (byte_pp & -byte_pp);
869
870
/* pixel_block must always be a power of two: */
871
debug(bpp > 0 && pixel_block > 0 &&
872
(pixel_block & -pixel_block) == pixel_block &&
873
((8U*PNG_ROW_BUFFER_BYTE_ALIGN-1U) & (pixel_block*bpp)) == 0U);
874
875
/* Zlib maxima */
876
{
877
png_uint_32 max = (uInt)-1; /* max bytes */
878
879
if (bpp <= 8U)
880
{
881
/* Maximum number of bytes PNG can generate in the lower bit depth
882
* cases:
883
*/
884
png_uint_32 png_max =
885
(0x7FFFFFFF + PNG_ADDOF(bpp)) >> PNG_SHIFTOF(bpp);
886
887
if (png_max < max)
888
max = 0x7FFFFFFF;
889
}
890
891
else /* bpp > 8U */
892
{
893
max /= byte_pp;
894
if (max > 0x7FFFFFFF)
895
max = 0x7FFFFFFF;
896
}
897
898
/* So this is the maximum number of pixels regardless of alignment: */
899
ps->zlib_max_pixels = max;
900
901
/* For byte alignment the value has to be a multiple of pixel_block and
902
* that is a power of 2, so:
903
*/
904
ps->zlib_max_aligned_pixels = max & ~(pixel_block-1U);
905
}
906
907
# ifdef PNG_WRITE_FILTER_SUPPORTED
908
/* PNG_ROW_BUFFER maxima; this is easier because PNG_ROW_BUFFER_SIZE is
909
* limited so that the number of bits fits in any ANSI-C (unsigned int).
910
*/
911
{
912
const unsigned int max = (8U * PNG_ROW_BUFFER_SIZE) / bpp;
913
914
ps->row_buffer_max_pixels = max;
915
ps->row_buffer_max_aligned_pixels = max & ~(pixel_block-1U);
916
}
917
# endif /* WRITE_FILTER */
918
919
/* NOTE: this will be 0 for very long rows on 32-bit or less systems */
920
ps->write_row_size = png_write_row_buffer_size(png_ptr);
921
}
922
923
static png_zlib_statep
924
get_zlib_state(png_structrp png_ptr)
925
{
926
if (png_ptr->zlib_state == NULL)
927
png_create_zlib_state(png_ptr);
928
929
return png_ptr->zlib_state;
930
}
931
932
/* Internal API to clean up all the deflate related stuff, including the buffer
933
* lists.
934
*/
935
static void /* PRIVATE */
936
png_deflate_release(png_structrp png_ptr, png_zlib_statep ps, int check)
937
{
938
# ifdef PNG_WRITE_FILTER_SUPPORTED
939
/* Free any mode-specific data that is owned here: */
940
if (ps->previous_write_row != NULL)
941
{
942
png_bytep p = ps->previous_write_row;
943
ps->previous_write_row = NULL;
944
png_free(png_ptr, p);
945
}
946
947
# ifdef PNG_SELECT_FILTER_SUPPORTED
948
if (ps->current_write_row != NULL)
949
{
950
png_bytep p = ps->current_write_row;
951
ps->current_write_row = NULL;
952
png_free(png_ptr, p);
953
}
954
955
if (ps->selector != NULL)
956
{
957
struct filter_selector *s = ps->selector;
958
ps->selector = NULL;
959
png_free(png_ptr, s);
960
}
961
# endif /* SELECT_FILTER */
962
# endif /* WRITE_FILTER */
963
964
/* The main z_stream opaque pointer needs to remain set to png_ptr; it is
965
* only set once.
966
*/
967
png_zlib_compress_destroy(&ps->s, check);
968
png_free_compression_buffer(png_ptr, &ps->stash);
969
}
970
971
void /* PRIVATE */
972
png_deflate_destroy(png_structrp png_ptr)
973
{
974
png_zlib_statep ps = png_ptr->zlib_state;
975
976
if (ps != NULL)
977
{
978
png_deflate_release(png_ptr, ps, 0/*check*/);
979
png_ptr->zlib_state = NULL;
980
png_free(png_ptr, ps);
981
}
982
}
983
984
/* Compression settings.
985
*
986
* These are stored packed into a png_uint_32 to make comparison with the
987
* current setting quick. The packing method uses four bits for each setting
988
* and reserves '0' for unset.
989
*
990
* ps_<setting>_base: The lowest valid value (encoded as 1).
991
* ps_<setting>_max: The highest valid value.
992
* ps_<setting>_pos: The position in the range 0..3 (shift of 0..12).
993
*
994
* The low 16 bits are the zlib compression parameters:
995
*/
996
#define pz_level_base (-1)
997
#define pz_level_max 9
998
#define pz_level_pos 0
999
#define pz_windowBits_base 8
1000
#define pz_windowBits_max 15
1001
#define pz_windowBits_pos 1
1002
#define pz_memLevel_base 1
1003
#define pz_memLevel_max 9
1004
#define pz_memLevel_pos 2
1005
#define pz_strategy_base 0
1006
#define pz_strategy_max 4
1007
#define pz_strategy_pos 3
1008
#define pz_zlib_bits 0xFFFFU
1009
/* Anything below this is not used directly by zlib: */
1010
#define pz_png_level_base 0
1011
#define pz_png_level_max 6
1012
#define pz_png_level_pos 4
1013
1014
#define pz_offset(name) (pz_ ## name ## _base - 1)
1015
/* setting_value == pz_offset(setting)+encoded_value */
1016
#define pz_min(name) pz_ ## name ## _base
1017
#define pz_max(name) pz_ ## name ## _max
1018
#define pz_shift(name) (4 * pz_ ## name ## _pos)
1019
1020
#define pz_bits(name,x) ((int)(((x)>>pz_shift(name))&0xF))
1021
/* the encoded value, or 0 if unset */
1022
1023
/* Enquiries: */
1024
#define pz_isset(name,x) (pz_bits(name,x) != 0)
1025
#define pz_value(name,x) (pz_bits(name,x)+pz_offset(name))
1026
1027
/* Assignments: */
1028
#define pz_clear(name,x) ((x)&~((png_uint_32)0xFU<<pz_shift(name)))
1029
#define pz_encode(name,v) ((png_uint_32)((v)-pz_offset(name))<<pz_shift(name))
1030
#define pz_change(name,x,v) (pz_clear(name,x) | pz_encode(name, v))
1031
1032
/* Direct use/modification: */
1033
#define pz_var(ps, type) ((ps)->pz_ ## type)
1034
#define pz_get(ps, type, name, def)\
1035
(pz_isset(name, pz_var(ps, type)) ? pz_value(name, pz_var(ps, type)) : (def))
1036
/* pz_assign checks for out-of-range values and clears the setting if these are
1037
* given. No warning or error is generated.
1038
*/
1039
#define pz_assign(ps, type, name, value)\
1040
(pz_var(ps, type) = pz_clear(name, pz_var(ps, type)) |\
1041
((value) >= pz_min(name) && (value) <= pz_max(name) ?\
1042
pz_encode(name, value) : 0))
1043
1044
static png_int_32
1045
pz_compression_setting(png_structrp png_ptr, png_uint_32 owner,
1046
int min, int max, int shift, png_int_32 value, int only_get, int unset)
1047
/* This is a support function for png_write_setting below. */
1048
{
1049
png_zlib_statep ps;
1050
png_uint_32p psettings;
1051
1052
/* The value is only required for a 'set', eliminate out-of-range values
1053
* first:
1054
*/
1055
if (!only_get && (value < min || value > max))
1056
return PNG_EDOM;
1057
1058
/* If setting a value make sure the state exists: */
1059
if (!only_get)
1060
ps = get_zlib_state(png_ptr);
1061
1062
else if (owner != 0U) /* ps may be NULL */
1063
ps = png_ptr->zlib_state;
1064
1065
else /* get and owner is 0U */
1066
return 0; /* supported */
1067
1068
psettings = NULL;
1069
switch (owner)
1070
{
1071
png_int_32 res;
1072
1073
case png_IDAT:
1074
if (ps != NULL) psettings = &ps->pz_IDAT;
1075
break;
1076
1077
case png_iCCP:
1078
if (ps != NULL) psettings = &ps->pz_iCCP;
1079
break;
1080
1081
case 0U:
1082
/* All the settings. At this point the 'get' case has returned 0
1083
* above, the value has been checked and the paramter is 0, therefore
1084
* valid. Each of the following calls should succeed and it would be
1085
* reasonable to eliminate the PNG_FAILED tests in a world where
1086
* software engineers never made mistakes.
1087
*/
1088
res = pz_compression_setting(png_ptr, png_IDAT, min, max, shift,
1089
value, 0/*set*/, 1/*iff unset*/);
1090
1091
if (PNG_FAILED(res))
1092
return res;
1093
1094
res = pz_compression_setting(png_ptr, png_iCCP, min, max, shift,
1095
value, 0/*set*/, 1/*iff unset*/);
1096
1097
if (PNG_FAILED(res))
1098
return res;
1099
1100
/* The text settings are changed regardless of the customize support
1101
* because if WRITE_CUSTOMIZE_ZTXT_COMPRESSION is not supported the old
1102
* behavior was to use the WRITE_CUSTOMIZE_COMPRESSION setting.
1103
*
1104
* However, when we get png_zTXt directly (from png_write_setting) and
1105
* the support is not compiled in return PNG_ENOSYS.
1106
*/
1107
unset = 1; /* i.e. only if not already set */
1108
1109
# ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1110
case png_zTXt:
1111
case png_iTXt:
1112
# endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
1113
if (ps != NULL) psettings = &ps->pz_text;
1114
break;
1115
1116
default:
1117
/* Return PNG_ENOSYS, not PNG_EINVAL, to support future addition of new
1118
* compressed chunks and the fact that zTXt and iTXt customization can
1119
* be disabled.
1120
*/
1121
return PNG_ENOSYS;
1122
}
1123
1124
if (psettings == NULL)
1125
return PNG_UNSET; /* valid setting that is not set */
1126
1127
{
1128
png_uint_32 settings = *psettings;
1129
png_uint_32 mask = 0xFU << shift;
1130
1131
/* Do not set it if 'only_get' was passed in or if 'unset' is true and the
1132
* setting is not currently set:
1133
*/
1134
if (!only_get && ((settings & mask) == 0U || !unset))
1135
*psettings = (settings & ~mask) +
1136
((png_uint_32)/*SAFE*/(value-min+1) << shift);
1137
1138
settings &= mask;
1139
1140
if (settings == 0U)
1141
return PNG_UNSET;
1142
1143
else
1144
return (int)/*SAFE*/((settings >> shift)-1U) + min;
1145
}
1146
}
1147
1148
#define compression_setting(pp, owner, setting, value, get)\
1149
pz_compression_setting(pp, owner, pz_min(setting), pz_max(setting),\
1150
pz_shift(setting), value, get, 0/*always*/)
1151
1152
/* There is (as of zlib 1.2.8) a bug in the implementation of compression with a
1153
* window size of 256 which zlib works round by resetting windowBits from 8 to 9
1154
* whenever deflateInit2 is called with that value. Fix this up here.
1155
*/
1156
static void
1157
fix_cinfo(png_zlib_statep ps, png_bytep data, png_alloc_size_t data_size)
1158
{
1159
/* Do this if the CINFO field is '1', meaning windowBits of 9. The first
1160
* byte of the stream is the CMF value, CINFO is in the upper four bits.
1161
*
1162
* If zlib didn't futz with the value then it should match the value in
1163
* pz_current; check this is debug. (See below for why this works in the
1164
* pz_default_settings call.)
1165
*/
1166
# define png_ptr png_voidcast(png_const_structrp, ps->s.zs.opaque)
1167
if (data[0] == 0x18U &&
1168
pz_get(ps, current, windowBits, 0) == 8 /* i.e. it was requested */)
1169
{
1170
/* Double check this here; the fixup only works if the data was 256 bytes
1171
* or shorter *or* the window is never used. For safety repeat the checks
1172
* done in pz_default_settings; technically we should be able to just skip
1173
* this test.
1174
*
1175
* TODO: set a 'fixup' flag in zlib_state to make this quicker?
1176
*/
1177
if (data_size <= 256U ||
1178
pz_get(ps, current, strategy, Z_RLE) == Z_HUFFMAN_ONLY ||
1179
pz_get(ps, current, level, 1) == Z_NO_COMPRESSION)
1180
{
1181
unsigned int d1;
1182
1183
data[0] = 0x08U;
1184
/* The header checksum must be fixed too. The FCHECK (low 5 bits) make
1185
* CMF.FLG a multiple of 31:
1186
*/
1187
d1 = data[1] & 0xE0U; /* top three bits */
1188
d1 += 31U - (0x0800U + d1) % 31U;
1189
data[1] = PNG_BYTE(d1);
1190
}
1191
1192
else /* pz_default_settings is expected to guarantee the above */
1193
NOT_REACHED;
1194
}
1195
1196
else if (data_size > 0U)
1197
{
1198
/* Prior to 1.7.0 libpng would shrink the windowBits even if the
1199
* application requested a particular value, so:
1200
*/
1201
unsigned int z_cinfo = data[0] >> 4;
1202
unsigned int half_z_window_size = 1U << (z_cinfo + 7);
1203
1204
if (data_size <= half_z_window_size && z_cinfo > 0)
1205
{
1206
unsigned int tmp;
1207
1208
do
1209
{
1210
half_z_window_size >>= 1;
1211
--z_cinfo;
1212
}
1213
while (z_cinfo > 0 && data_size <= half_z_window_size);
1214
1215
data[0] = PNG_BYTE((z_cinfo << 4) + 0x8U);
1216
tmp = data[1] & 0xE0U; /* top three bits */
1217
tmp += 31U - ((data[0] << 8) + tmp) % 31U;
1218
data[1] = PNG_BYTE(tmp);
1219
}
1220
}
1221
1222
else
1223
NOT_REACHED; /* invalid data size (0) */
1224
# undef png_ptr
1225
}
1226
1227
static png_uint_32
1228
pz_default_settings(png_uint_32 settings, const png_uint_32 owner,
1229
const png_alloc_size_t data_size, const unsigned int filters/*for IDAT*/)
1230
{
1231
int png_level, strategy, zlib_level, windowBits;
1232
1233
/* The png 'level' parameter controls the defaults below. It uses the same
1234
* numbering scheme as the Zlib compression level except that -1 invokes the
1235
* set of options and, in some cases, libpng behavior of libpng 1.6 and
1236
* earlier.
1237
*
1238
* In the comments below reference is made to the differences beteen the
1239
* legacy compression sizes from libpng 1.6 and earlier and the result of
1240
* using the various options. These are quoted as an overall size change in
1241
* the compression of 147323 PNG test files. The set of test files is
1242
* slightly restricted because pre-1.7 versions of png_read_png leave random
1243
* bits into the final byte of a row which ends with a partial byte. This
1244
* affects the compression unpredictably so such files were omitted from the
1245
* measurements.
1246
*/
1247
if (!pz_isset(png_level, settings))
1248
{
1249
png_level = PNG_DEFAULT_COMPRESSION_LEVEL;
1250
settings |= pz_encode(png_level, png_level);
1251
}
1252
1253
else
1254
png_level = pz_value(png_level, settings);
1255
1256
/* First default the strategy. At lower data sizes other strategies do as
1257
* well as the zlib default compression strategy but they never seem to
1258
* improve on it with the 1.7 filtering.
1259
*/
1260
if (!pz_isset(strategy, settings))
1261
{
1262
switch (png_level)
1263
{
1264
case PNG_COMPRESSION_COMPAT: /* Legacy setting */
1265
/* The pre-1.7 code used Z_FILTERED normally but uses
1266
* Z_DEFAULT_STRATEGY for palette or low-bit-depth images.
1267
*
1268
* In fact Z_DEFAULT_STRATEGY works best for filtered images as
1269
* well, however the change in results is small:
1270
*
1271
* Z_DEFAULT_STRATEGY: -0.1%
1272
* Z_FILTERED: +0.1%
1273
*
1274
* NOTE: this happened even if WRITE_FILTER was *not* supported.
1275
*/
1276
if (owner != png_IDAT || filters == PNG_FILTER_NONE)
1277
strategy = Z_DEFAULT_STRATEGY;
1278
1279
else
1280
strategy = Z_FILTERED;
1281
break;
1282
1283
case PNG_COMPRESSION_HIGH_SPEED:
1284
/* RLE is as fast as HUFFMAN_ONLY and can reduce size a lot in a few
1285
* cases.
1286
*/
1287
strategy = Z_RLE;
1288
break;
1289
1290
default: /* For GCC */
1291
case PNG_COMPRESSION_LOW:
1292
case PNG_COMPRESSION_MEDIUM:
1293
/* Z_FILTERED is almost as good as the default and can be
1294
* significantly faster. It biases the algorithm towards smaller
1295
* byte values.
1296
*
1297
* Using Z_DEFAULT_STRATEGY here, rather than Z_FILTERED, benefits
1298
* smaller 8 and 16-bit gray and larger 8 and 16-bit RGB images,
1299
* however the overall gain is only 0.1% because it is offset by
1300
* losses in larger 8-bit gray and alpha images. It is extremely
1301
* difficult to deduce a pattern other than biases in the test set
1302
* of images.
1303
*
1304
* Looking at the pattern of behavior with the 1.6 filter selection
1305
* algorithm (none of palette or low-bit-depth, else all) produces
1306
* results as follows:
1307
*/
1308
if (owner == png_IDAT)
1309
{
1310
if (filters == PNG_FILTER_NONE)
1311
strategy = Z_DEFAULT_STRATEGY;
1312
1313
else
1314
strategy = Z_FILTERED;
1315
}
1316
1317
else if (owner == png_iCCP)
1318
strategy = Z_DEFAULT_STRATEGY;
1319
1320
/* TODO: investigate this, the observed behavior is suspicious: */
1321
else /* text chunk */
1322
strategy = Z_FILTERED; /* Always better for some reason */
1323
break;
1324
1325
case PNG_COMPRESSION_LOW_MEMORY:
1326
/* Reduce memory at all costs, speed doesn't matter. */
1327
case PNG_COMPRESSION_HIGH_READ_SPEED:
1328
case PNG_COMPRESSION_HIGH:
1329
if (owner == png_IDAT || owner == png_iCCP)
1330
strategy = Z_DEFAULT_STRATEGY;
1331
1332
else
1333
strategy = Z_FILTERED;
1334
break;
1335
}
1336
1337
settings |= pz_encode(strategy, strategy);
1338
}
1339
1340
else
1341
strategy = pz_value(strategy, settings);
1342
1343
/* Next the zlib level; this just defaults to the png level, except that for
1344
* Huffman or RLE encoding the level setting for Zlib doesn't matter.
1345
*/
1346
if (!pz_isset(level, settings))
1347
{
1348
switch (strategy)
1349
{
1350
case Z_HUFFMAN_ONLY:
1351
case Z_RLE:
1352
/* The 'level' doesn't make any significant difference to the
1353
* compression with these strategies; in a test set of about 3GByte
1354
* of PNG files the total compressed size changed under 20 bytes
1355
* with libpng 1.6!
1356
*/
1357
zlib_level = 1;
1358
break;
1359
1360
default: /* Z_FIXED, Z_FILTERED, Z_DEFAULT_STRATEGY */
1361
/* Everything that uses the window seems to show rapidly diminishing
1362
* returns above level 6 (at least with libpng 1.6).
1363
* Z_DEFAULT_COMPRESSION is, in fact, level 6 so Mark seems to
1364
* concur. With libpng 1.6 the following results were obtained
1365
* using the full test set of files (including those with a partial
1366
* byte at the end of the row) and just varying the zlib level:
1367
*
1368
* LEVEL SIZE(bytes) CHANGE TIME(s) CHANGE METRIC
1369
* 9 2550246600 -1.19% 1972 +227% -77%
1370
* 8 2556675866 -0.94% 1215 +101% -59%
1371
* 7 2572685552 -0.32% 679 +12% -15%
1372
* 6 2581196708 0% 604 0% 0%
1373
* 5 2602831249 +0.84% 414 -30% +87%
1374
* 4 2625206800 +1.71% 358 -40% +153%
1375
* 3 2674752349 +3.62% 298 -50% +303%
1376
* 2 2716261483 +5.23% 262 -56% +537%
1377
* 1 2749875805 +6.53% 251 -57% +662%
1378
* 0 7174488347 202 -66%
1379
*
1380
* The CHANGE columns express the change in compressed size
1381
* (positive is an increase; a decrease in compression) and time
1382
* (positive is an increase; an increase in time) relative to level
1383
* 6. The METRIC column is a measure of the compression-per-second
1384
* relative to level 6; positive is an increase in
1385
* compression-per-second.
1386
*
1387
* The metric is derived by assuming the difference in time between
1388
* level 0 (which does no compression) and the level being
1389
* considered is spent doing the compression. (Reasonable, since
1390
* only the level changed). Just the inverse of the product of the
1391
* size and the time difference is a measure of compression per
1392
* second. It can be seen that time dominates the metric;
1393
* compression only varies slightly (under 8%) across the level
1394
* range.
1395
*/
1396
switch (png_level)
1397
{
1398
case PNG_COMPRESSION_COMPAT:
1399
zlib_level = Z_DEFAULT_COMPRESSION; /* NOTE: -1 */
1400
break;
1401
1402
case PNG_COMPRESSION_HIGH_SPEED:
1403
zlib_level = 1;
1404
break;
1405
1406
default: /* For GCC */
1407
case PNG_COMPRESSION_LOW:
1408
zlib_level = 3;
1409
break;
1410
1411
case PNG_COMPRESSION_MEDIUM:
1412
zlib_level = 6; /* Old default! */
1413
break;
1414
1415
case PNG_COMPRESSION_LOW_MEMORY:
1416
case PNG_COMPRESSION_HIGH_READ_SPEED:
1417
case PNG_COMPRESSION_HIGH:
1418
zlib_level = 9;
1419
break;
1420
}
1421
break;
1422
}
1423
1424
settings |= pz_encode(level, zlib_level);
1425
}
1426
1427
else
1428
zlib_level = pz_value(level, settings);
1429
1430
/* Now default windowBits. This is probably the most important of the
1431
* settings because it is pretty much the only one that affects decode
1432
* performance. The smaller the better:
1433
*/
1434
if (!pz_isset(windowBits, settings))
1435
{
1436
if (png_level == PNG_COMPRESSION_COMPAT/* Legacy */)
1437
{
1438
/* This is the libpng16 calculation (it is wrong; a misunderstanding of
1439
* what zlib actually requires!)
1440
*
1441
* Using the code below with the legacy choice of Z_FILTERED or
1442
* Z_DEFAULT_STRATEGY increases the size of the test files by only
1443
* 0.04%, however the settings below considerably reduce the windowBits
1444
* used potentially benefitting read code a lot.
1445
*
1446
* NOTE: the algorithm below was determined by experiment and
1447
* observation with the same set of test files; there is some
1448
* considerable possibility that a different set might show different
1449
* results. Obtaining large, representative, test sets is both a
1450
* considerable amount of work and very error prone. [JB 20160518]
1451
*/
1452
windowBits = 15;
1453
1454
if (data_size <= 16384U)
1455
{
1456
unsigned int half_window_size = 1U << (windowBits-1);
1457
1458
while (data_size + 262U <= half_window_size)
1459
{
1460
half_window_size >>= 1;
1461
--windowBits;
1462
}
1463
}
1464
}
1465
1466
/* The window size affects the memory used on both read and write but also
1467
* the time on write (but not normally read). Handle the low memory
1468
* requirement first:
1469
*/
1470
else if (zlib_level == Z_NO_COMPRESSION ||
1471
png_level == PNG_COMPRESSION_LOW_MEMORY)
1472
windowBits = 8;
1473
1474
/* If the strategy has been set to something that doesn't benefit from
1475
* higher windowBits values take advantage of this. Note that pz_value
1476
* returns an invalid value if pz_isset is false.
1477
*
1478
* The only png_level that affects this decision is HIGH_SPEED, because
1479
* a smaller windowBits should speed up the search, however the code above
1480
* chose zlib_level based on this so ignore that consideration and just
1481
* use zlib_level below.
1482
*/
1483
else switch (strategy)
1484
{
1485
png_alloc_size_t test_size;
1486
1487
case Z_HUFFMAN_ONLY:
1488
/* Use the minimum; the window doesn't get used */
1489
windowBits = 8;
1490
break;
1491
1492
case Z_RLE:
1493
/* The longest length code is 258 bytes, the shortest string that
1494
* can achieve this is 259 bytes long; 259 copies of the same byte
1495
* which can be encoded as a code for the byte value then a string
1496
* of length 258 starting at the first byte. So if the data is
1497
* longer than 256 bytes use '9' for the windowBits, otherwise use
1498
* 8:
1499
*/
1500
if (data_size <= 256U)
1501
windowBits = 8;
1502
1503
else
1504
windowBits = 9;
1505
break;
1506
1507
/* By experiment using about 150,000 files the optimal windowBits
1508
* value across a range of files is somewhat less than implied by
1509
* the data size and depends on the zlib level and the strategy
1510
* used, the following values were determined by experiment using
1511
* those files:
1512
*/
1513
case Z_FILTERED:
1514
/* The Z_FILTERED case changes suddenly at (zlib) level 4 to
1515
* benefit from looking at all the data:
1516
*/
1517
if (zlib_level < 4 && zlib_level != Z_DEFAULT_COMPRESSION/*-1: 6*/)
1518
test_size = data_size / 8U;
1519
1520
else
1521
test_size = data_size;
1522
1523
goto check_test_size;
1524
1525
case Z_FIXED:
1526
/* With the fixed Huffman tables better compression only ever comes
1527
* from looking for matches, so, logically:
1528
*/
1529
test_size = data_size;
1530
goto check_test_size;
1531
1532
default:
1533
/* The default algorithm always does better with a window smaller
1534
* than all the data and shows jumps at level 4 and level 8. The
1535
* net effect with the test set of images is a very minor overall
1536
* improvement compared to the pre-1.7 calculation (data size +
1537
* 262). The benefit is less than 0.01%, however smaller window
1538
* sizes reduce the memory zlib has to allocate in the decoder.
1539
*/
1540
switch (zlib_level)
1541
{
1542
case 1: case 2: case 3:
1543
test_size = data_size / 8U;
1544
break;
1545
1546
default: /* -1(Z_DEFAULT_COMPRESSION) == 6, 4..7 */
1547
/* This includes, implicitly, ZLIB_NO_COMPRESSION, but that
1548
* was eliminated in the 'if' above.
1549
*/
1550
test_size = data_size / 4U;
1551
break;
1552
1553
case 8: case 9:
1554
test_size = data_size / 3U;
1555
break;
1556
}
1557
1558
goto check_test_size;
1559
1560
check_test_size:
1561
/* Find the smallest window that covers 'test_size' bytes, subject
1562
* to the constraint that if the actual data size is more than 256
1563
* bytes the minimum windowBits that can be supported is 9:
1564
*/
1565
if (data_size <= 256U)
1566
windowBits = 8;
1567
1568
else
1569
windowBits = 9;
1570
1571
while (windowBits < 15 && (1U << windowBits) < test_size)
1572
++windowBits;
1573
1574
break;
1575
}
1576
1577
settings |= pz_encode(windowBits, windowBits);
1578
}
1579
1580
else
1581
windowBits = pz_value(windowBits, settings);
1582
1583
/* zlib has a problem with 256 byte windows; 512 is used instead.
1584
* We can't work round this if the data size is more than 256 bytes and
1585
* the strategy actually uses the window (everything except huffman-only)
1586
* so fix the problem here.
1587
*/
1588
if (windowBits == 8 && data_size > 256U && strategy != Z_HUFFMAN_ONLY &&
1589
zlib_level != Z_NO_COMPRESSION)
1590
settings = pz_change(windowBits, settings, 9);
1591
1592
/* For memLevel this just increases the memory used but can help with the
1593
* Huffman code generation even to level 9 (the maximum), so just set the
1594
* max. This affects memory used, not (apparently) compression speed so
1595
* the only relevant png_level is LOW_MEMORY.
1596
*
1597
* The legacy setting is '8'; this is the level that Zlib defaults to because
1598
* 16-bit iAPX86 systems could not handle '9'. Because MAX_MEM_LEVEL is used
1599
* below this does not matter; zconf.h selects 8 or 9 as appropriate.
1600
*
1601
* In fact using '9' with the legacy settings increases the size of the test
1602
* set minutely; +0.007%. This is hardly significant; 0.007% of the test
1603
* images equals 10 images. (Nevertheless it is interesting, just as the
1604
* observation that decreasing windowBits can result in smaller compressed
1605
* sizes is interesting.)
1606
*/
1607
if (!pz_isset(memLevel, settings))
1608
{
1609
int memLevel;
1610
1611
switch (png_level)
1612
{
1613
case PNG_COMPRESSION_COMPAT:
1614
memLevel = 8;
1615
break;
1616
1617
case PNG_COMPRESSION_LOW_MEMORY:
1618
memLevel = 1;
1619
break;
1620
1621
default:
1622
memLevel = MAX_MEM_LEVEL/*from zconf.h*/;
1623
break;
1624
}
1625
1626
settings |= pz_encode(memLevel, memLevel);
1627
}
1628
1629
return settings;
1630
}
1631
1632
/* This is used below to find the size of an image to pass to png_deflate_claim.
1633
* It returns 0 for images whose size would overflow a 32-bit integer or have
1634
* rows which cannot be allocated.
1635
*/
1636
static png_alloc_size_t
1637
png_image_size(png_const_structrp png_ptr)
1638
{
1639
/* The size returned here is limited to PNG_SIZE_MAX, if the size would
1640
* exceed that (or is close to exceeding that) 0 is returned. See below for
1641
* a variant that limits the size of 0xFFFFFFFFU.
1642
*/
1643
const png_alloc_size_t rowbytes = png_ptr->zlib_state->write_row_size;
1644
1645
/* NON-INTERLACED: (1+rowbytes) * h
1646
* INTERLACED: Each pixel is transmitted exactly once, so the size is
1647
* (rowbytes * h) + the count of filter bytes. Each complete
1648
* block of 8 image rows generates at most 15 output rows
1649
* (less for narrow images), so the filter byte count is
1650
* at most (15*h/8)+14. Because the original rows are split
1651
* extra byte passing may be introduced. Account for this by
1652
* allowing an extra 1 byte per output row; that's two bytes
1653
* including the filer byte.
1654
*
1655
* So:
1656
* NON-INTERLACED: (rowbytes * h) + h
1657
* INTERLACED: < (rowbytes * h) + 2*(15 * h/8) + 2*15
1658
*
1659
* Hence:
1660
*/
1661
if (rowbytes != 0)
1662
{
1663
const png_uint_32 h = png_ptr->height;
1664
1665
if (png_ptr->interlaced == PNG_INTERLACE_NONE)
1666
{
1667
const png_alloc_size_t limit = PNG_SIZE_MAX / h;
1668
1669
/* On 16-bit systems the above might be 0, so: */
1670
if (rowbytes </*allow 1 for filter byte*/ limit)
1671
return (rowbytes+1U) * h;
1672
}
1673
1674
else /* INTERLACED */
1675
{
1676
const png_uint_32 w = png_ptr->width;
1677
1678
/* Interlacing makes the image larger because of the replication of
1679
* both the filter byte and the padding to a byte boundary.
1680
*/
1681
png_alloc_size_t cb_base;
1682
int pass;
1683
1684
for (cb_base=0, pass=0; pass<PNG_INTERLACE_ADAM7_PASSES; ++pass)
1685
{
1686
const png_uint_32 pass_w = PNG_PASS_COLS(w, pass);
1687
1688
if (pass_w > 0)
1689
{
1690
const png_uint_32 pass_h = PNG_PASS_ROWS(h, pass);
1691
1692
if (pass_h > 0)
1693
{
1694
/* This is the number of bytes available for each row of this
1695
* pass:
1696
*/
1697
const png_alloc_size_t limit = (PNG_SIZE_MAX - cb_base)/pass_h;
1698
/* This cannot overflow because if it did rowbytes would
1699
* have been 0 above.
1700
*/
1701
const png_alloc_size_t pass_bytes =
1702
PNG_ROWBYTES(png_ptr->row_output_pixel_depth, pass_w);
1703
1704
if (pass_bytes </*allow 1 for filter byte*/ limit)
1705
cb_base += (pass_bytes+1U) * pass_h;
1706
1707
else
1708
return 0U; /* insufficient address space left */
1709
}
1710
}
1711
}
1712
1713
return cb_base;
1714
}
1715
}
1716
1717
/* Failure case: */
1718
return 0U;
1719
}
1720
1721
/* Initialize the compressor for the appropriate type of compression. */
1722
static png_zlib_statep
1723
png_deflate_claim(png_structrp png_ptr, png_uint_32 owner,
1724
png_alloc_size_t data_size)
1725
{
1726
png_zlib_statep ps = get_zlib_state(png_ptr);
1727
1728
affirm(png_ptr->zowner == 0);
1729
1730
{
1731
int ret; /* zlib return code */
1732
unsigned int filters = 0U;
1733
png_uint_32 settings;
1734
1735
switch (owner)
1736
{
1737
case png_IDAT:
1738
debug(data_size == 0U);
1739
data_size = png_image_size(png_ptr);
1740
1741
if (data_size == 0U)
1742
data_size = PNG_SIZE_MAX;
1743
1744
settings = ps->pz_IDAT;
1745
# ifdef PNG_WRITE_FILTER_SUPPORTED
1746
filters = ps->filter_mask;
1747
debug(filters != 0U);
1748
# else /* !WRITE_FILTER */
1749
filters = PNG_FILTER_NONE;
1750
# endif /* !WRITE_FILTER */
1751
break;
1752
1753
case png_iCCP:
1754
settings = ps->pz_iCCP;
1755
break;
1756
1757
default: /* text chunk */
1758
settings = ps->pz_text;
1759
break;
1760
}
1761
1762
settings = pz_default_settings(settings, owner, data_size, filters);
1763
1764
/* Check against the previous initialized values, if any. The relevant
1765
* settings are in the low 16 bits.
1766
*/
1767
if (ps->s.zs.state != NULL &&
1768
((settings ^ ps->pz_current) & pz_zlib_bits) != 0U)
1769
png_deflateEnd(png_ptr, &ps->s.zs, 0/*check*/);
1770
1771
/* For safety clear out the input and output pointers (currently zlib
1772
* doesn't use them on Init, but it might in the future).
1773
*/
1774
ps->s.zs.next_in = NULL;
1775
ps->s.zs.avail_in = 0;
1776
ps->s.zs.next_out = NULL;
1777
ps->s.zs.avail_out = 0;
1778
1779
/* The length fields must be cleared too and the lists reset: */
1780
ps->s.overflow = ps->s.len = ps->s.start = 0U;
1781
1782
if (ps->s.list != NULL) /* error in prior chunk writing */
1783
{
1784
debug(ps->stash == NULL);
1785
ps->stash = ps->s.list;
1786
ps->s.list = NULL;
1787
}
1788
1789
ps->s.end = &ps->s.list;
1790
1791
/* Now initialize if required, setting the new parameters, otherwise just
1792
* do a simple reset to the previous parameters.
1793
*/
1794
if (ps->s.zs.state != NULL)
1795
ret = deflateReset(&ps->s.zs);
1796
1797
else
1798
ret = deflateInit2(&ps->s.zs, pz_value(level, settings), Z_DEFLATED,
1799
pz_value(windowBits, settings), pz_value(memLevel, settings),
1800
pz_value(strategy, settings));
1801
1802
ps->pz_current = settings;
1803
1804
/* The return code is from either deflateReset or deflateInit2; they have
1805
* pretty much the same set of error codes.
1806
*/
1807
if (ret == Z_OK && ps->s.zs.state != NULL)
1808
png_ptr->zowner = owner;
1809
1810
else
1811
{
1812
png_zstream_error(&ps->s.zs, ret);
1813
png_error(png_ptr, ps->s.zs.msg);
1814
}
1815
}
1816
1817
return ps;
1818
}
1819
1820
#ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED /* includes iCCP */
1821
/* Compress the block of data at the end of a chunk. This claims and releases
1822
* png_struct::z_stream. It returns the amount of data in the chunk list or
1823
* zero on error (a zlib stream always contains some bytes!)
1824
*
1825
* prefix_len is the amount of (uncompressed) data before the start of the
1826
* compressed data. The routine will return 0 if the total of the compressed
1827
* data and the prefix exceeds PNG_UINT_MAX_31.
1828
*
1829
* NOTE: this function may not return; it only returns 0 if
1830
* png_chunk_report(PNG_CHUNK_WRITE_ERROR) returns (not the default).
1831
*/
1832
static int /* success */
1833
png_compress_chunk_data(png_structrp png_ptr, png_uint_32 chunk_name,
1834
png_uint_32 prefix_len, png_const_voidp input, png_alloc_size_t input_len)
1835
{
1836
/* To find the length of the output it is necessary to first compress the
1837
* input. The result is buffered rather than using the two-pass algorithm
1838
* that is used on the inflate side; deflate is assumed to be slower and a
1839
* PNG writer is assumed to have more memory available than a PNG reader.
1840
*
1841
* IMPLEMENTATION NOTE: the zlib API deflateBound() can be used to find an
1842
* upper limit on the output size, but it is always bigger than the input
1843
* size so it is likely to be more efficient to use this linked-list
1844
* approach.
1845
*/
1846
png_zlib_statep ps = png_deflate_claim(png_ptr, chunk_name, input_len);
1847
1848
affirm(ps != NULL);
1849
1850
/* The data compression function always returns so that we can clean up. */
1851
ps->s.zs.next_in = PNGZ_INPUT_CAST(png_voidcast(const Bytef*, input));
1852
1853
/* Use the stash, if available: */
1854
debug(ps->s.list == NULL);
1855
ps->s.list = ps->stash;
1856
ps->stash = NULL;
1857
1858
{
1859
int ret = png_compress(&ps->s, input_len, PNG_UINT_31_MAX-prefix_len,
1860
Z_FINISH);
1861
1862
ps->s.zs.next_out = NULL; /* safety */
1863
ps->s.zs.avail_out = 0;
1864
ps->s.zs.next_in = NULL;
1865
ps->s.zs.avail_in = 0;
1866
png_ptr->zowner = 0; /* release png_ptr::zstream */
1867
1868
/* Since Z_FINISH was passed as the flush parameter any result other than
1869
* Z_STREAM_END is an error. In any case in the event of an error free
1870
* the whole compression state; the only expected error is Z_MEM_ERROR.
1871
*/
1872
if (ret != Z_STREAM_END)
1873
{
1874
png_zlib_compress_destroy(&ps->s, 0/*check*/);
1875
1876
/* This is not very likely given the PNG_UINT_31_MAX limit above, but
1877
* if code is added to limit the size of the chunks produced it can
1878
* start to happen.
1879
*/
1880
if (ret == Z_BUF_ERROR)
1881
ps->s.zs.msg = PNGZ_MSG_CAST("compressed chunk too long");
1882
1883
else
1884
png_zstream_error(&ps->s.zs, ret);
1885
1886
png_chunk_report(png_ptr, ps->s.zs.msg, PNG_CHUNK_WRITE_ERROR);
1887
return 0;
1888
}
1889
}
1890
1891
/* png_compress is meant to guarantee this on a successful return: */
1892
affirm(ps->s.overflow == 0U && ps->s.len <= PNG_UINT_31_MAX - prefix_len);
1893
1894
/* Correct the zlib CINFO field: */
1895
if (ps->s.len >= 2U)
1896
fix_cinfo(ps, ps->s.list->output, input_len);
1897
1898
return 1;
1899
}
1900
1901
/* Return the length of the compressed data; this is effectively a debug
1902
* function to catch inconsistencies caused by internal errors. It will
1903
* disappear in a release build.
1904
*/
1905
#if PNG_RELEASE_BUILD
1906
# define png_length_compressed_chunk_data(pp, p) ((pp)->zlib_state->s.len)
1907
#else /* !RELEASE_BUILD */
1908
static png_uint_32
1909
png_length_compressed_chunk_data(png_structrp png_ptr, png_uint_32 p)
1910
{
1911
png_zlib_statep ps = png_ptr->zlib_state;
1912
1913
debug(ps != NULL && ps->s.overflow == 0U && ps->s.len <= PNG_UINT_31_MAX-p);
1914
return ps->s.len;
1915
}
1916
#endif /* !RELEASE_BUILD */
1917
1918
/* Write all the data produced by the above function; the caller must write the
1919
* prefix and chunk header.
1920
*/
1921
static void
1922
png_write_compressed_chunk_data(png_structrp png_ptr)
1923
{
1924
png_zlib_statep ps = png_ptr->zlib_state;
1925
png_compression_bufferp next;
1926
png_uint_32 output_len;
1927
1928
affirm(ps != NULL && ps->s.overflow == 0U);
1929
next = ps->s.list;
1930
1931
for (output_len = ps->s.len; output_len > 0U; next = next->next)
1932
{
1933
png_uint_32 size = PNG_ROW_BUFFER_SIZE;
1934
1935
/* If this affirm fails there is a bug in the calculation of
1936
* output_length above, or in the buffer_limit code in png_compress.
1937
*/
1938
affirm(next != NULL && output_len > 0U);
1939
1940
if (size > output_len)
1941
size = output_len;
1942
1943
png_write_chunk_data(png_ptr, next->output, size);
1944
1945
output_len -= size;
1946
}
1947
1948
/* Release the list back to the stash. */
1949
debug(ps->stash == NULL);
1950
ps->stash = ps->s.list;
1951
ps->s.list = NULL;
1952
ps->s.end = &ps->s.list;
1953
}
1954
#endif /* WRITE_COMPRESSED_TEXT */
1955
1956
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
1957
defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
1958
/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
1959
* and if invalid, correct the keyword rather than discarding the entire
1960
* chunk. The PNG 1.0 specification requires keywords 1-79 characters in
1961
* length, forbids leading or trailing whitespace, multiple internal spaces,
1962
* and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
1963
*
1964
* The 'new_key' buffer must be at least 80 characters in size (for the keyword
1965
* plus a trailing '\0'). If this routine returns 0 then there was no keyword,
1966
* or a valid one could not be generated, and the caller must CHUNK_WRITE_ERROR.
1967
*/
1968
static unsigned int
1969
png_check_keyword(png_structrp png_ptr, png_const_charp key, png_bytep new_key)
1970
{
1971
png_const_charp orig_key = key;
1972
unsigned int key_len = 0;
1973
int bad_character = 0;
1974
int space = 1;
1975
1976
png_debug(1, "in png_check_keyword");
1977
1978
if (key == NULL)
1979
{
1980
*new_key = 0;
1981
return 0;
1982
}
1983
1984
while (*key && key_len < 79)
1985
{
1986
png_byte ch = (png_byte)(0xff & *key++);
1987
1988
if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/))
1989
*new_key++ = ch, ++key_len, space = 0;
1990
1991
else if (space == 0)
1992
{
1993
/* A space or an invalid character when one wasn't seen immediately
1994
* before; output just a space.
1995
*/
1996
*new_key++ = 32, ++key_len, space = 1;
1997
1998
/* If the character was not a space then it is invalid. */
1999
if (ch != 32)
2000
bad_character = ch;
2001
}
2002
2003
else if (bad_character == 0)
2004
bad_character = ch; /* just skip it, record the first error */
2005
}
2006
2007
if (key_len > 0 && space != 0) /* trailing space */
2008
{
2009
--key_len, --new_key;
2010
if (bad_character == 0)
2011
bad_character = 32;
2012
}
2013
2014
/* Terminate the keyword */
2015
*new_key = 0;
2016
2017
if (key_len == 0)
2018
return 0;
2019
2020
#ifdef PNG_WARNINGS_SUPPORTED
2021
/* Try to only output one warning per keyword: */
2022
if (*key != 0) /* keyword too long */
2023
png_app_warning(png_ptr, "keyword truncated");
2024
2025
else if (bad_character != 0)
2026
{
2027
PNG_WARNING_PARAMETERS(p)
2028
2029
png_warning_parameter(p, 1, orig_key);
2030
png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_02x, bad_character);
2031
2032
png_formatted_warning(png_ptr, p, "keyword \"@1\": bad character '0x@2'");
2033
}
2034
#endif /* WARNINGS */
2035
2036
return key_len;
2037
}
2038
#endif /* WRITE_TEXT || WRITE_pCAL || WRITE_iCCP || WRITE_sPLT */
2039
2040
/* Write the IHDR chunk, and update the png_struct with the necessary
2041
* information. Note that the rest of this code depends upon this
2042
* information being correct.
2043
*/
2044
void /* PRIVATE */
2045
png_write_IHDR(png_structrp png_ptr, png_uint_32 width, png_uint_32 height,
2046
int bit_depth, int color_type, int compression_type, int filter_method,
2047
int interlace_type)
2048
{
2049
png_byte buf[13]; /* Buffer to store the IHDR info */
2050
2051
png_debug(1, "in png_write_IHDR");
2052
2053
/* Check that we have valid input data from the application info */
2054
switch (color_type)
2055
{
2056
case PNG_COLOR_TYPE_GRAY:
2057
switch (bit_depth)
2058
{
2059
case 1:
2060
case 2:
2061
case 4:
2062
case 8:
2063
#ifdef PNG_WRITE_16BIT_SUPPORTED
2064
case 16:
2065
#endif
2066
break;
2067
2068
default:
2069
png_error(png_ptr, "Invalid bit depth for grayscale image");
2070
}
2071
break;
2072
2073
case PNG_COLOR_TYPE_RGB:
2074
#ifdef PNG_WRITE_16BIT_SUPPORTED
2075
if (bit_depth != 8 && bit_depth != 16)
2076
#else
2077
if (bit_depth != 8)
2078
#endif
2079
png_error(png_ptr, "Invalid bit depth for RGB image");
2080
2081
break;
2082
2083
case PNG_COLOR_TYPE_PALETTE:
2084
switch (bit_depth)
2085
{
2086
case 1:
2087
case 2:
2088
case 4:
2089
case 8:
2090
break;
2091
2092
default:
2093
png_error(png_ptr, "Invalid bit depth for paletted image");
2094
}
2095
break;
2096
2097
case PNG_COLOR_TYPE_GRAY_ALPHA:
2098
if (bit_depth != 8 && bit_depth != 16)
2099
png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
2100
2101
break;
2102
2103
case PNG_COLOR_TYPE_RGB_ALPHA:
2104
#ifdef PNG_WRITE_16BIT_SUPPORTED
2105
if (bit_depth != 8 && bit_depth != 16)
2106
#else
2107
if (bit_depth != 8)
2108
#endif
2109
png_error(png_ptr, "Invalid bit depth for RGBA image");
2110
2111
break;
2112
2113
default:
2114
png_error(png_ptr, "Invalid image color type specified");
2115
}
2116
2117
if (compression_type != PNG_COMPRESSION_TYPE_BASE)
2118
{
2119
png_app_error(png_ptr, "Invalid compression type specified");
2120
compression_type = PNG_COMPRESSION_TYPE_BASE;
2121
}
2122
2123
/* Write filter_method 64 (intrapixel differencing) only if
2124
* 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
2125
* 2. Libpng did not write a PNG signature (this filter_method is only
2126
* used in PNG datastreams that are embedded in MNG datastreams) and
2127
* 3. The application called png_permit_mng_features with a mask that
2128
* included PNG_FLAG_MNG_FILTER_64 and
2129
* 4. The filter_method is 64 and
2130
* 5. The color_type is RGB or RGBA
2131
*/
2132
if (
2133
# ifdef PNG_MNG_FEATURES_SUPPORTED
2134
!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
2135
((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
2136
(color_type == PNG_COLOR_TYPE_RGB ||
2137
color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
2138
(filter_method == PNG_INTRAPIXEL_DIFFERENCING)) &&
2139
# endif /* MNG_FEATURES */
2140
filter_method != PNG_FILTER_TYPE_BASE)
2141
{
2142
png_app_error(png_ptr, "Invalid filter type specified");
2143
filter_method = PNG_FILTER_TYPE_BASE;
2144
}
2145
2146
if (interlace_type != PNG_INTERLACE_NONE &&
2147
interlace_type != PNG_INTERLACE_ADAM7)
2148
{
2149
png_app_error(png_ptr, "Invalid interlace type specified");
2150
interlace_type = PNG_INTERLACE_ADAM7;
2151
}
2152
2153
/* Save the relevant information */
2154
png_ptr->bit_depth = png_check_byte(png_ptr, bit_depth);
2155
png_ptr->color_type = png_check_byte(png_ptr, color_type);
2156
png_ptr->interlaced = png_check_byte(png_ptr, interlace_type);
2157
png_ptr->filter_method = png_check_byte(png_ptr, filter_method);
2158
png_ptr->width = width;
2159
png_ptr->height = height;
2160
2161
/* Pack the header information into the buffer */
2162
png_save_uint_32(buf, width);
2163
png_save_uint_32(buf + 4, height);
2164
buf[8] = png_check_byte(png_ptr, bit_depth);
2165
buf[9] = png_check_byte(png_ptr, color_type);
2166
buf[10] = png_check_byte(png_ptr, compression_type);
2167
buf[11] = png_check_byte(png_ptr, filter_method);
2168
buf[12] = png_check_byte(png_ptr, interlace_type);
2169
2170
/* Write the chunk */
2171
png_write_complete_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
2172
png_ptr->mode |= PNG_HAVE_IHDR;
2173
}
2174
2175
/* Write the palette. We are careful not to trust png_color to be in the
2176
* correct order for PNG, so people can redefine it to any convenient
2177
* structure.
2178
*/
2179
void /* PRIVATE */
2180
png_write_PLTE(png_structrp png_ptr, png_const_colorp palette,
2181
unsigned int num_pal)
2182
{
2183
png_uint_32 max_palette_length, i;
2184
png_const_colorp pal_ptr;
2185
png_byte buf[3];
2186
2187
png_debug(1, "in png_write_PLTE");
2188
2189
max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
2190
(1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
2191
2192
if ((
2193
# ifdef PNG_MNG_FEATURES_SUPPORTED
2194
(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 &&
2195
# endif /* MNG_FEATURES */
2196
num_pal == 0) || num_pal > max_palette_length)
2197
{
2198
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
2199
{
2200
png_error(png_ptr, "Invalid number of colors in palette");
2201
}
2202
2203
else
2204
{
2205
png_warning(png_ptr, "Invalid number of colors in palette");
2206
return;
2207
}
2208
}
2209
2210
if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
2211
{
2212
png_warning(png_ptr,
2213
"Ignoring request to write a PLTE chunk in grayscale PNG");
2214
2215
return;
2216
}
2217
2218
png_ptr->num_palette = png_check_bits(png_ptr, num_pal, 9);
2219
png_debug1(3, "num_palette = %d", png_ptr->num_palette);
2220
2221
png_write_chunk_header(png_ptr, png_PLTE, num_pal * 3U);
2222
2223
for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
2224
{
2225
buf[0] = pal_ptr->red;
2226
buf[1] = pal_ptr->green;
2227
buf[2] = pal_ptr->blue;
2228
png_write_chunk_data(png_ptr, buf, 3U);
2229
}
2230
2231
png_write_chunk_end(png_ptr);
2232
png_ptr->mode |= PNG_HAVE_PLTE;
2233
}
2234
2235
/* Write an IEND chunk */
2236
void /* PRIVATE */
2237
png_write_IEND(png_structrp png_ptr)
2238
{
2239
png_debug(1, "in png_write_IEND");
2240
2241
png_write_complete_chunk(png_ptr, png_IEND, NULL, (png_size_t)0);
2242
png_ptr->mode |= PNG_HAVE_IEND;
2243
}
2244
2245
#if defined(PNG_WRITE_gAMA_SUPPORTED) || defined(PNG_WRITE_cHRM_SUPPORTED)
2246
static int
2247
png_save_int_31(png_structrp png_ptr, png_bytep buf, png_int_32 i)
2248
/* Save a signed value as a PNG unsigned value; the argument is required to
2249
* be in the range 0..0x7FFFFFFFU. If not a *warning* is produced and false
2250
* is returned. Because this is only called from png_write_cHRM_fixed and
2251
* png_write_gAMA_fixed below this is safe (we don't need either chunk,
2252
* particularly if the value is bogus.)
2253
*
2254
* The warning is png_app_error; it may return if the app tells it to but the
2255
* app can have it error out. JB 20150821: I believe the checking in png.c
2256
* actually makes this error impossible, but this is safe.
2257
*/
2258
{
2259
#ifndef __COVERITY__
2260
if (i >= 0 && i <= 0x7FFFFFFF)
2261
#else
2262
/* Supress bogus Coverity complaint */
2263
if (i >= 0)
2264
#endif
2265
{
2266
png_save_uint_32(buf, (png_uint_32)/*SAFE*/i);
2267
return 1;
2268
}
2269
2270
else
2271
{
2272
png_chunk_report(png_ptr, "negative value in cHRM or gAMA",
2273
PNG_CHUNK_WRITE_ERROR);
2274
return 0;
2275
}
2276
}
2277
#endif /* WRITE_gAMA || WRITE_cHRM */
2278
2279
#ifdef PNG_WRITE_gAMA_SUPPORTED
2280
/* Write a gAMA chunk */
2281
void /* PRIVATE */
2282
png_write_gAMA_fixed(png_structrp png_ptr, png_fixed_point file_gamma)
2283
{
2284
png_byte buf[4];
2285
2286
png_debug(1, "in png_write_gAMA");
2287
2288
/* file_gamma is saved in 1/100,000ths */
2289
if (png_save_int_31(png_ptr, buf, file_gamma))
2290
png_write_complete_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
2291
}
2292
#endif
2293
2294
#ifdef PNG_WRITE_sRGB_SUPPORTED
2295
/* Write a sRGB chunk */
2296
void /* PRIVATE */
2297
png_write_sRGB(png_structrp png_ptr, int srgb_intent)
2298
{
2299
png_byte buf[1];
2300
2301
png_debug(1, "in png_write_sRGB");
2302
2303
if (srgb_intent >= PNG_sRGB_INTENT_LAST)
2304
png_chunk_report(png_ptr, "Invalid sRGB rendering intent specified",
2305
PNG_CHUNK_WRITE_ERROR);
2306
2307
buf[0] = png_check_byte(png_ptr, srgb_intent);
2308
png_write_complete_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
2309
}
2310
#endif
2311
2312
#ifdef PNG_WRITE_iCCP_SUPPORTED
2313
/* Write an iCCP chunk */
2314
void /* PRIVATE */
2315
png_write_iCCP(png_structrp png_ptr, png_const_charp name,
2316
png_const_voidp profile)
2317
{
2318
png_uint_32 name_len;
2319
png_uint_32 profile_len;
2320
png_byte new_name[81]; /* 1 byte for the compression byte */
2321
2322
png_debug(1, "in png_write_iCCP");
2323
2324
affirm(profile != NULL);
2325
2326
profile_len = png_get_uint_32(profile);
2327
name_len = png_check_keyword(png_ptr, name, new_name);
2328
2329
if (name_len == 0)
2330
{
2331
png_chunk_report(png_ptr, "iCCP: invalid keyword", PNG_CHUNK_WRITE_ERROR);
2332
return;
2333
}
2334
2335
++name_len; /* trailing '\0' */
2336
new_name[name_len++] = PNG_COMPRESSION_TYPE_BASE;
2337
2338
if (png_compress_chunk_data(png_ptr, png_iCCP, name_len, profile,
2339
profile_len))
2340
{
2341
png_write_chunk_header(png_ptr, png_iCCP,
2342
name_len+png_length_compressed_chunk_data(png_ptr, name_len));
2343
png_write_chunk_data(png_ptr, new_name, name_len);
2344
png_write_compressed_chunk_data(png_ptr);
2345
png_write_chunk_end(png_ptr);
2346
}
2347
}
2348
#endif
2349
2350
#ifdef PNG_WRITE_sPLT_SUPPORTED
2351
/* Write a sPLT chunk */
2352
void /* PRIVATE */
2353
png_write_sPLT(png_structrp png_ptr, png_const_sPLT_tp spalette)
2354
{
2355
png_uint_32 name_len;
2356
png_byte new_name[80];
2357
png_byte entrybuf[10];
2358
png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
2359
png_size_t palette_size = entry_size * spalette->nentries;
2360
png_sPLT_entryp ep;
2361
2362
png_debug(1, "in png_write_sPLT");
2363
2364
name_len = png_check_keyword(png_ptr, spalette->name, new_name);
2365
2366
if (name_len == 0)
2367
png_error(png_ptr, "sPLT: invalid keyword");
2368
2369
/* Make sure we include the NULL after the name */
2370
png_write_chunk_header(png_ptr, png_sPLT,
2371
(png_uint_32)(name_len + 2 + palette_size));
2372
2373
png_write_chunk_data(png_ptr, new_name, name_len + 1);
2374
2375
png_write_chunk_data(png_ptr, &spalette->depth, 1);
2376
2377
/* Loop through each palette entry, writing appropriately */
2378
for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
2379
{
2380
if (spalette->depth == 8)
2381
{
2382
entrybuf[0] = png_check_byte(png_ptr, ep->red);
2383
entrybuf[1] = png_check_byte(png_ptr, ep->green);
2384
entrybuf[2] = png_check_byte(png_ptr, ep->blue);
2385
entrybuf[3] = png_check_byte(png_ptr, ep->alpha);
2386
png_save_uint_16(entrybuf + 4, ep->frequency);
2387
}
2388
2389
else
2390
{
2391
png_save_uint_16(entrybuf + 0, ep->red);
2392
png_save_uint_16(entrybuf + 2, ep->green);
2393
png_save_uint_16(entrybuf + 4, ep->blue);
2394
png_save_uint_16(entrybuf + 6, ep->alpha);
2395
png_save_uint_16(entrybuf + 8, ep->frequency);
2396
}
2397
2398
png_write_chunk_data(png_ptr, entrybuf, entry_size);
2399
}
2400
2401
png_write_chunk_end(png_ptr);
2402
}
2403
#endif
2404
2405
#ifdef PNG_WRITE_sBIT_SUPPORTED
2406
/* Write the sBIT chunk */
2407
void /* PRIVATE */
2408
png_write_sBIT(png_structrp png_ptr, png_const_color_8p sbit, int color_type)
2409
{
2410
png_byte buf[4];
2411
png_size_t size;
2412
2413
png_debug(1, "in png_write_sBIT");
2414
2415
/* Make sure we don't depend upon the order of PNG_COLOR_8 */
2416
if ((color_type & PNG_COLOR_MASK_COLOR) != 0)
2417
{
2418
unsigned int maxbits;
2419
2420
maxbits = color_type==PNG_COLOR_TYPE_PALETTE ? 8 : png_ptr->bit_depth;
2421
2422
if (sbit->red == 0 || sbit->red > maxbits ||
2423
sbit->green == 0 || sbit->green > maxbits ||
2424
sbit->blue == 0 || sbit->blue > maxbits)
2425
{
2426
png_app_error(png_ptr, "Invalid sBIT depth specified");
2427
return;
2428
}
2429
2430
buf[0] = sbit->red;
2431
buf[1] = sbit->green;
2432
buf[2] = sbit->blue;
2433
size = 3;
2434
}
2435
2436
else
2437
{
2438
if (sbit->gray == 0 || sbit->gray > png_ptr->bit_depth)
2439
{
2440
png_app_error(png_ptr, "Invalid sBIT depth specified");
2441
return;
2442
}
2443
2444
buf[0] = sbit->gray;
2445
size = 1;
2446
}
2447
2448
if ((color_type & PNG_COLOR_MASK_ALPHA) != 0)
2449
{
2450
if (sbit->alpha == 0 || sbit->alpha > png_ptr->bit_depth)
2451
{
2452
png_app_error(png_ptr, "Invalid sBIT depth specified");
2453
return;
2454
}
2455
2456
buf[size++] = sbit->alpha;
2457
}
2458
2459
png_write_complete_chunk(png_ptr, png_sBIT, buf, size);
2460
}
2461
#endif
2462
2463
#ifdef PNG_WRITE_cHRM_SUPPORTED
2464
/* Write the cHRM chunk */
2465
void /* PRIVATE */
2466
png_write_cHRM_fixed(png_structrp png_ptr, const png_xy *xy)
2467
{
2468
png_byte buf[32];
2469
2470
png_debug(1, "in png_write_cHRM");
2471
2472
/* Each value is saved in 1/100,000ths */
2473
if (png_save_int_31(png_ptr, buf, xy->whitex) &&
2474
png_save_int_31(png_ptr, buf + 4, xy->whitey) &&
2475
png_save_int_31(png_ptr, buf + 8, xy->redx) &&
2476
png_save_int_31(png_ptr, buf + 12, xy->redy) &&
2477
png_save_int_31(png_ptr, buf + 16, xy->greenx) &&
2478
png_save_int_31(png_ptr, buf + 20, xy->greeny) &&
2479
png_save_int_31(png_ptr, buf + 24, xy->bluex) &&
2480
png_save_int_31(png_ptr, buf + 28, xy->bluey))
2481
png_write_complete_chunk(png_ptr, png_cHRM, buf, 32);
2482
}
2483
#endif
2484
2485
#ifdef PNG_WRITE_tRNS_SUPPORTED
2486
/* Write the tRNS chunk */
2487
void /* PRIVATE */
2488
png_write_tRNS(png_structrp png_ptr, png_const_bytep trans_alpha,
2489
png_const_color_16p tran, int num_trans, int color_type)
2490
{
2491
png_byte buf[6];
2492
2493
png_debug(1, "in png_write_tRNS");
2494
2495
if (color_type == PNG_COLOR_TYPE_PALETTE)
2496
{
2497
affirm(num_trans > 0 && num_trans <= PNG_MAX_PALETTE_LENGTH);
2498
{
2499
# ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
2500
union
2501
{
2502
png_uint_32 u32[1];
2503
png_byte b8[PNG_MAX_PALETTE_LENGTH];
2504
} inverted_alpha;
2505
2506
/* Invert the alpha channel (in tRNS) if required */
2507
if (png_ptr->write_invert_alpha)
2508
{
2509
int i;
2510
2511
memcpy(inverted_alpha.b8, trans_alpha, num_trans);
2512
2513
for (i=0; 4*i<num_trans; ++i)
2514
inverted_alpha.u32[i] = ~inverted_alpha.u32[i];
2515
2516
trans_alpha = inverted_alpha.b8;
2517
}
2518
# endif /* WRITE_INVERT_ALPHA */
2519
2520
png_write_complete_chunk(png_ptr, png_tRNS, trans_alpha, num_trans);
2521
}
2522
}
2523
2524
else if (color_type == PNG_COLOR_TYPE_GRAY)
2525
{
2526
/* One 16 bit value */
2527
affirm(tran->gray < (1 << png_ptr->bit_depth));
2528
png_save_uint_16(buf, tran->gray);
2529
png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
2530
}
2531
2532
else if (color_type == PNG_COLOR_TYPE_RGB)
2533
{
2534
/* Three 16 bit values */
2535
png_save_uint_16(buf, tran->red);
2536
png_save_uint_16(buf + 2, tran->green);
2537
png_save_uint_16(buf + 4, tran->blue);
2538
affirm(png_ptr->bit_depth == 8 || (buf[0] | buf[2] | buf[4]) == 0);
2539
png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
2540
}
2541
2542
else /* Already checked in png_set_tRNS */
2543
impossible("invalid tRNS");
2544
}
2545
#endif
2546
2547
#ifdef PNG_WRITE_bKGD_SUPPORTED
2548
/* Write the background chunk */
2549
void /* PRIVATE */
2550
png_write_bKGD(png_structrp png_ptr, png_const_color_16p back, int color_type)
2551
{
2552
png_byte buf[6];
2553
2554
png_debug(1, "in png_write_bKGD");
2555
2556
if (color_type == PNG_COLOR_TYPE_PALETTE)
2557
{
2558
if (
2559
# ifdef PNG_MNG_FEATURES_SUPPORTED
2560
(png_ptr->num_palette != 0 ||
2561
(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0) &&
2562
# endif /* MNG_FEATURES */
2563
back->index >= png_ptr->num_palette)
2564
{
2565
png_app_error(png_ptr, "Invalid background palette index");
2566
return;
2567
}
2568
2569
buf[0] = back->index;
2570
png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
2571
}
2572
2573
else if ((color_type & PNG_COLOR_MASK_COLOR) != 0)
2574
{
2575
png_save_uint_16(buf, back->red);
2576
png_save_uint_16(buf + 2, back->green);
2577
png_save_uint_16(buf + 4, back->blue);
2578
#ifdef PNG_WRITE_16BIT_SUPPORTED
2579
if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]) != 0)
2580
#else
2581
if ((buf[0] | buf[2] | buf[4]) != 0)
2582
#endif
2583
{
2584
png_app_error(png_ptr,
2585
"Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
2586
2587
return;
2588
}
2589
2590
png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
2591
}
2592
2593
else
2594
{
2595
if (back->gray >= (1 << png_ptr->bit_depth))
2596
{
2597
png_app_error(png_ptr,
2598
"Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
2599
2600
return;
2601
}
2602
2603
png_save_uint_16(buf, back->gray);
2604
png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
2605
}
2606
}
2607
#endif
2608
2609
#ifdef PNG_WRITE_hIST_SUPPORTED
2610
/* Write the histogram */
2611
void /* PRIVATE */
2612
png_write_hIST(png_structrp png_ptr, png_const_uint_16p hist, int num_hist)
2613
{
2614
int i;
2615
png_byte buf[3];
2616
2617
png_debug(1, "in png_write_hIST");
2618
2619
if (num_hist > (int)png_ptr->num_palette)
2620
{
2621
png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
2622
png_ptr->num_palette);
2623
2624
png_warning(png_ptr, "Invalid number of histogram entries specified");
2625
return;
2626
}
2627
2628
png_write_chunk_header(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
2629
2630
for (i = 0; i < num_hist; i++)
2631
{
2632
png_save_uint_16(buf, hist[i]);
2633
png_write_chunk_data(png_ptr, buf, (png_size_t)2);
2634
}
2635
2636
png_write_chunk_end(png_ptr);
2637
}
2638
#endif
2639
2640
#ifdef PNG_WRITE_tEXt_SUPPORTED
2641
/* Write a tEXt chunk */
2642
void /* PRIVATE */
2643
png_write_tEXt(png_structrp png_ptr, png_const_charp key, png_const_charp text,
2644
png_size_t text_len)
2645
{
2646
unsigned int key_len;
2647
png_byte new_key[80];
2648
2649
png_debug(1, "in png_write_tEXt");
2650
2651
key_len = png_check_keyword(png_ptr, key, new_key);
2652
2653
if (key_len == 0)
2654
{
2655
png_chunk_report(png_ptr, "tEXt: invalid keyword", PNG_CHUNK_WRITE_ERROR);
2656
return;
2657
}
2658
2659
if (text == NULL || *text == '\0')
2660
text_len = 0;
2661
2662
else
2663
text_len = strlen(text);
2664
2665
if (text_len > PNG_UINT_31_MAX - (key_len+1))
2666
{
2667
png_chunk_report(png_ptr, "tEXt: text too long", PNG_CHUNK_WRITE_ERROR);
2668
return;
2669
}
2670
2671
/* Make sure we include the 0 after the key */
2672
png_write_chunk_header(png_ptr, png_tEXt,
2673
(png_uint_32)/*checked above*/(key_len + text_len + 1));
2674
/*
2675
* We leave it to the application to meet PNG-1.0 requirements on the
2676
* contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
2677
* any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
2678
* The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
2679
*/
2680
png_write_chunk_data(png_ptr, new_key, key_len + 1);
2681
2682
if (text_len != 0)
2683
png_write_chunk_data(png_ptr, (png_const_bytep)text, text_len);
2684
2685
png_write_chunk_end(png_ptr);
2686
}
2687
#endif
2688
2689
#ifdef PNG_WRITE_zTXt_SUPPORTED
2690
/* Write a compressed text chunk */
2691
void /* PRIVATE */
2692
png_write_zTXt(png_structrp png_ptr, png_const_charp key, png_const_charp text,
2693
int compression)
2694
{
2695
unsigned int key_len;
2696
png_byte new_key[81];
2697
2698
png_debug(1, "in png_write_zTXt");
2699
2700
if (compression != PNG_TEXT_COMPRESSION_zTXt)
2701
png_app_warning(png_ptr, "zTXt: invalid compression type ignored");
2702
2703
key_len = png_check_keyword(png_ptr, key, new_key);
2704
2705
if (key_len == 0)
2706
{
2707
png_chunk_report(png_ptr, "zTXt: invalid keyword", PNG_CHUNK_WRITE_ERROR);
2708
return;
2709
}
2710
2711
/* Add the compression method and 1 for the keyword separator. */
2712
++key_len;
2713
new_key[key_len++] = PNG_COMPRESSION_TYPE_BASE;
2714
2715
if (png_compress_chunk_data(png_ptr, png_zTXt, key_len, text, strlen(text)))
2716
{
2717
png_write_chunk_header(png_ptr, png_zTXt,
2718
key_len+png_length_compressed_chunk_data(png_ptr, key_len));
2719
png_write_chunk_data(png_ptr, new_key, key_len);
2720
png_write_compressed_chunk_data(png_ptr);
2721
png_write_chunk_end(png_ptr);
2722
}
2723
2724
/* else chunk report already issued and ignored */
2725
}
2726
#endif
2727
2728
#ifdef PNG_WRITE_iTXt_SUPPORTED
2729
/* Write an iTXt chunk */
2730
void /* PRIVATE */
2731
png_write_iTXt(png_structrp png_ptr, int compression, png_const_charp key,
2732
png_const_charp lang, png_const_charp lang_key, png_const_charp text)
2733
{
2734
png_uint_32 key_len, prefix_len, data_len;
2735
png_size_t lang_len, lang_key_len, text_len;
2736
png_byte new_key[82]; /* 80 bytes for the key, 2 byte compression info */
2737
2738
png_debug(1, "in png_write_iTXt");
2739
2740
key_len = png_check_keyword(png_ptr, key, new_key);
2741
2742
if (key_len == 0)
2743
{
2744
png_chunk_report(png_ptr, "iTXt: invalid keyword", PNG_CHUNK_WRITE_ERROR);
2745
return;
2746
}
2747
2748
debug(new_key[key_len] == 0);
2749
++key_len; /* terminating 0 added by png_check_keyword */
2750
2751
/* Set the compression flag */
2752
switch (compression)
2753
{
2754
case PNG_ITXT_COMPRESSION_NONE:
2755
case PNG_TEXT_COMPRESSION_NONE:
2756
compression = new_key[key_len++] = 0; /* no compression */
2757
break;
2758
2759
case PNG_TEXT_COMPRESSION_zTXt:
2760
case PNG_ITXT_COMPRESSION_zTXt:
2761
compression = new_key[key_len++] = 1; /* compressed */
2762
break;
2763
2764
default:
2765
png_chunk_report(png_ptr, "iTXt: invalid compression",
2766
PNG_CHUNK_WRITE_ERROR);
2767
return;
2768
}
2769
2770
new_key[key_len++] = PNG_COMPRESSION_TYPE_BASE;
2771
2772
/* We leave it to the application to meet PNG-1.0 requirements on the
2773
* contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
2774
* any non-Latin-1 characters except for NEWLINE (yes, this is really weird
2775
* in an 'international' text string. ISO PNG, however, specifies that the
2776
* text is UTF-8 and this *IS NOT YET CHECKED*, so invalid sequences may be
2777
* present.
2778
*
2779
* The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
2780
*
2781
* TODO: validate the language tag correctly (see the spec.)
2782
*/
2783
if (lang == NULL) lang = ""; /* empty language is valid */
2784
lang_len = strlen(lang)+1U;
2785
if (lang_key == NULL) lang_key = ""; /* may be empty */
2786
lang_key_len = strlen(lang_key)+1U;
2787
if (text == NULL) text = ""; /* may be empty */
2788
2789
if (lang_len > PNG_UINT_31_MAX-key_len ||
2790
lang_key_len > PNG_UINT_31_MAX-key_len-lang_len)
2791
{
2792
png_chunk_report(png_ptr, "iTXt: prefix too long", PNG_CHUNK_WRITE_ERROR);
2793
return;
2794
}
2795
2796
prefix_len = (png_uint_32)/*SAFE*/(key_len+lang_len+lang_key_len);
2797
text_len = strlen(text); /* no trailing '\0' */
2798
2799
if (compression != 0)
2800
{
2801
if (png_compress_chunk_data(png_ptr, png_iTXt, prefix_len, text,
2802
text_len))
2803
data_len = png_length_compressed_chunk_data(png_ptr, prefix_len);
2804
2805
else
2806
return; /* chunk report already issued and ignored */
2807
}
2808
2809
else
2810
{
2811
if (text_len > PNG_UINT_31_MAX-prefix_len)
2812
{
2813
png_chunk_report(png_ptr, "iTXt: text too long",
2814
PNG_CHUNK_WRITE_ERROR);
2815
return;
2816
}
2817
2818
data_len = (png_uint_32)/*SAFE*/text_len;
2819
}
2820
2821
png_write_chunk_header(png_ptr, png_iTXt, prefix_len+data_len);
2822
png_write_chunk_data(png_ptr, new_key, key_len);
2823
png_write_chunk_data(png_ptr, lang, lang_len);
2824
png_write_chunk_data(png_ptr, lang_key, lang_key_len);
2825
2826
if (compression != 0)
2827
png_write_compressed_chunk_data(png_ptr);
2828
2829
else
2830
png_write_chunk_data(png_ptr, text, data_len);
2831
2832
png_write_chunk_end(png_ptr);
2833
}
2834
#endif /* WRITE_iTXt */
2835
2836
#if defined(PNG_WRITE_oFFs_SUPPORTED) ||\
2837
defined(PNG_WRITE_pCAL_SUPPORTED)
2838
/* PNG signed integers are saved in 32-bit 2's complement format. ANSI C-90
2839
* defines a cast of a signed integer to an unsigned integer either to preserve
2840
* the value, if it is positive, or to calculate:
2841
*
2842
* (UNSIGNED_MAX+1) + integer
2843
*
2844
* Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the
2845
* negative integral value is added the result will be an unsigned value
2846
* correspnding to the 2's complement representation.
2847
*/
2848
static int
2849
save_int_32(png_structrp png_ptr, png_bytep buf, png_int_32 j)
2850
{
2851
png_uint_32 i = 0xFFFFFFFFU & (png_uint_32)/*SAFE & CORRECT*/j;
2852
2853
if (i != 0x80000000U/*value not permitted*/)
2854
{
2855
png_save_uint_32(buf, i);
2856
return 1;
2857
}
2858
2859
else
2860
{
2861
png_chunk_report(png_ptr, "invalid value in oFFS or pCAL",
2862
PNG_CHUNK_WRITE_ERROR);
2863
return 0;
2864
}
2865
}
2866
#endif /* WRITE_oFFs || WRITE_pCAL */
2867
2868
#ifdef PNG_WRITE_oFFs_SUPPORTED
2869
/* Write the oFFs chunk */
2870
void /* PRIVATE */
2871
png_write_oFFs(png_structrp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
2872
int unit_type)
2873
{
2874
png_byte buf[9];
2875
2876
png_debug(1, "in png_write_oFFs");
2877
2878
if (unit_type >= PNG_OFFSET_LAST)
2879
png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
2880
2881
if (save_int_32(png_ptr, buf, x_offset) &&
2882
save_int_32(png_ptr, buf + 4, y_offset))
2883
{
2884
/* unit type is 0 or 1, this has been checked already so the following
2885
* is safe:
2886
*/
2887
buf[8] = unit_type != 0;
2888
png_write_complete_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
2889
}
2890
}
2891
#endif /* WRITE_oFFs */
2892
2893
#ifdef PNG_WRITE_pCAL_SUPPORTED
2894
/* Write the pCAL chunk (described in the PNG extensions document) */
2895
void /* PRIVATE */
2896
png_write_pCAL(png_structrp png_ptr, png_charp purpose, png_int_32 X0,
2897
png_int_32 X1, int type, int nparams, png_const_charp units,
2898
png_charpp params)
2899
{
2900
png_uint_32 purpose_len;
2901
size_t units_len;
2902
png_byte buf[10];
2903
png_byte new_purpose[80];
2904
2905
png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
2906
2907
if (type >= PNG_EQUATION_LAST)
2908
png_error(png_ptr, "Unrecognized equation type for pCAL chunk");
2909
2910
purpose_len = png_check_keyword(png_ptr, purpose, new_purpose);
2911
2912
if (purpose_len == 0)
2913
png_error(png_ptr, "pCAL: invalid keyword");
2914
2915
++purpose_len; /* terminator */
2916
2917
png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
2918
units_len = strlen(units) + (nparams == 0 ? 0 : 1);
2919
png_debug1(3, "pCAL units length = %d", (int)units_len);
2920
2921
if (save_int_32(png_ptr, buf, X0) &&
2922
save_int_32(png_ptr, buf + 4, X1))
2923
{
2924
png_size_tp params_len = png_voidcast(png_size_tp,
2925
png_malloc(png_ptr, nparams * sizeof (png_size_t)));
2926
int i;
2927
size_t total_len = purpose_len + units_len + 10;
2928
2929
/* Find the length of each parameter, making sure we don't count the
2930
* null terminator for the last parameter.
2931
*/
2932
for (i = 0; i < nparams; i++)
2933
{
2934
params_len[i] = strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
2935
png_debug2(3, "pCAL parameter %d length = %lu", i,
2936
(unsigned long)params_len[i]);
2937
total_len += params_len[i];
2938
}
2939
2940
png_debug1(3, "pCAL total length = %d", (int)total_len);
2941
png_write_chunk_header(png_ptr, png_pCAL, (png_uint_32)total_len);
2942
png_write_chunk_data(png_ptr, new_purpose, purpose_len);
2943
buf[8] = png_check_byte(png_ptr, type);
2944
buf[9] = png_check_byte(png_ptr, nparams);
2945
png_write_chunk_data(png_ptr, buf, (png_size_t)10);
2946
png_write_chunk_data(png_ptr, (png_const_bytep)units,
2947
(png_size_t)units_len);
2948
2949
for (i = 0; i < nparams; i++)
2950
png_write_chunk_data(png_ptr, (png_const_bytep)params[i],
2951
params_len[i]);
2952
2953
png_free(png_ptr, params_len);
2954
png_write_chunk_end(png_ptr);
2955
}
2956
}
2957
#endif /* WRITE_pCAL */
2958
2959
#ifdef PNG_WRITE_sCAL_SUPPORTED
2960
/* Write the sCAL chunk */
2961
void /* PRIVATE */
2962
png_write_sCAL_s(png_structrp png_ptr, int unit, png_const_charp width,
2963
png_const_charp height)
2964
{
2965
png_byte buf[64];
2966
png_size_t wlen, hlen, total_len;
2967
2968
png_debug(1, "in png_write_sCAL_s");
2969
2970
wlen = strlen(width);
2971
hlen = strlen(height);
2972
total_len = wlen + hlen + 2;
2973
2974
if (total_len > 64)
2975
{
2976
png_warning(png_ptr, "Can't write sCAL (buffer too small)");
2977
return;
2978
}
2979
2980
buf[0] = png_check_byte(png_ptr, unit);
2981
memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */
2982
memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */
2983
2984
png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
2985
png_write_complete_chunk(png_ptr, png_sCAL, buf, total_len);
2986
}
2987
#endif
2988
2989
#ifdef PNG_WRITE_pHYs_SUPPORTED
2990
/* Write the pHYs chunk */
2991
void /* PRIVATE */
2992
png_write_pHYs(png_structrp png_ptr, png_uint_32 x_pixels_per_unit,
2993
png_uint_32 y_pixels_per_unit,
2994
int unit_type)
2995
{
2996
png_byte buf[9];
2997
2998
png_debug(1, "in png_write_pHYs");
2999
3000
if (unit_type >= PNG_RESOLUTION_LAST)
3001
png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
3002
3003
png_save_uint_32(buf, x_pixels_per_unit);
3004
png_save_uint_32(buf + 4, y_pixels_per_unit);
3005
buf[8] = png_check_byte(png_ptr, unit_type);
3006
3007
png_write_complete_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
3008
}
3009
#endif
3010
3011
#ifdef PNG_WRITE_tIME_SUPPORTED
3012
/* Write the tIME chunk. Use either png_convert_from_struct_tm()
3013
* or png_convert_from_time_t(), or fill in the structure yourself.
3014
*/
3015
void /* PRIVATE */
3016
png_write_tIME(png_structrp png_ptr, png_const_timep mod_time)
3017
{
3018
png_byte buf[7];
3019
3020
png_debug(1, "in png_write_tIME");
3021
3022
if (mod_time->month > 12 || mod_time->month < 1 ||
3023
mod_time->day > 31 || mod_time->day < 1 ||
3024
mod_time->hour > 23 || mod_time->second > 60)
3025
{
3026
png_warning(png_ptr, "Invalid time specified for tIME chunk");
3027
return;
3028
}
3029
3030
png_save_uint_16(buf, mod_time->year);
3031
buf[2] = mod_time->month;
3032
buf[3] = mod_time->day;
3033
buf[4] = mod_time->hour;
3034
buf[5] = mod_time->minute;
3035
buf[6] = mod_time->second;
3036
3037
png_write_complete_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
3038
}
3039
#endif
3040
3041
static void
3042
png_end_IDAT(png_structrp png_ptr)
3043
{
3044
png_zlib_statep ps = png_ptr->zlib_state;
3045
3046
png_ptr->zowner = 0U; /* release the stream */
3047
3048
if (ps != NULL)
3049
png_deflate_release(png_ptr, ps, 1/*check*/);
3050
}
3051
3052
static void
3053
png_write_IDAT(png_structrp png_ptr, int flush)
3054
{
3055
png_zlib_statep ps = png_ptr->zlib_state;
3056
png_uint_32 IDAT_size;
3057
3058
/* Check for a correctly initialized list, the requirement that the end
3059
* pointer is NULL means that the end of the list can be easily detected.
3060
*/
3061
affirm(ps != NULL && ps->s.end != NULL && *ps->s.end == NULL);
3062
png_zlib_compress_validate(&png_ptr->zlib_state->s, 0/*in_use*/);
3063
3064
IDAT_size = png_ptr->IDAT_size;
3065
if (IDAT_size == 0U)
3066
{
3067
switch (pz_get(ps, IDAT, png_level, PNG_DEFAULT_COMPRESSION_LEVEL))
3068
{
3069
case PNG_COMPRESSION_COMPAT: /* Legacy */
3070
IDAT_size = 8192U;
3071
break;
3072
3073
case PNG_COMPRESSION_LOW_MEMORY:
3074
case PNG_COMPRESSION_HIGH_SPEED:
3075
case PNG_COMPRESSION_LOW:
3076
/* png_compress uses PNG_ROW_BUFFER_SIZE buffers for the compressed
3077
* data. Optimize to allocate only one of these:
3078
*/
3079
IDAT_size = PNG_ROW_BUFFER_SIZE;
3080
break;
3081
3082
default:
3083
case PNG_COMPRESSION_MEDIUM:
3084
IDAT_size = PNG_ZBUF_SIZE;
3085
break;
3086
3087
case PNG_COMPRESSION_HIGH_READ_SPEED:
3088
/* Assume the reader reads partial IDAT chunks (pretty much a
3089
* requirement given that some PNG encoders produce just one IDAT)
3090
*/
3091
case PNG_COMPRESSION_HIGH:
3092
/* This doesn't control the amount of memory allocated unless the
3093
* PNG IDAT data really is this big.
3094
*
3095
* TODO: review handling out-of-memory from png_compress() by
3096
* flushing an IDAT.
3097
*/
3098
IDAT_size = PNG_UINT_31_MAX;
3099
break;
3100
}
3101
}
3102
3103
/* Write IDAT chunks while either 'flush' is true or there are at
3104
* least png_ptr->IDAT_size bytes available to be written.
3105
*/
3106
for (;;)
3107
{
3108
png_uint_32 len = IDAT_size;
3109
3110
if (ps->s.overflow == 0U)
3111
{
3112
png_uint_32 avail = ps->s.len;
3113
3114
if (avail < len)
3115
{
3116
/* When end_of_image is true everything gets written, otherwise
3117
* there must be at least IDAT_size bytes available.
3118
*/
3119
if (!flush)
3120
return;
3121
3122
if (avail == 0U)
3123
break;
3124
3125
len = avail;
3126
}
3127
}
3128
3129
png_write_chunk_header(png_ptr, png_IDAT, len);
3130
3131
/* Write bytes from the buffer list, adjusting {overflow,len} as they are
3132
* written.
3133
*/
3134
do
3135
{
3136
png_compression_bufferp next = ps->s.list;
3137
unsigned int avail = sizeof next->output;
3138
unsigned int start = ps->s.start;
3139
unsigned int written;
3140
3141
affirm(next != NULL);
3142
3143
if (next->next == NULL) /* end of list */
3144
{
3145
/* The z_stream should always be pointing into this output buffer,
3146
* the buffer may not be full:
3147
*/
3148
debug(ps->s.zs.next_out + ps->s.zs.avail_out ==
3149
next->output + sizeof next->output);
3150
avail -= ps->s.zs.avail_out;
3151
}
3152
3153
else /* not end of list */
3154
debug((ps->s.zs.next_out < next->output ||
3155
ps->s.zs.next_out > next->output + sizeof next->output) &&
3156
(ps->s.overflow > 0 ||
3157
ps->s.start + ps->s.len >= sizeof next->output));
3158
3159
/* First, if this is the very first IDAT (PNG_HAVE_IDAT not set)
3160
* fix the Zlib CINFO field if required:
3161
*/
3162
if ((png_ptr->mode & PNG_HAVE_IDAT) == 0U &&
3163
avail >= start+2U /* enough for the zlib header */)
3164
{
3165
debug(start == 0U);
3166
fix_cinfo(ps, next->output+start, png_image_size(png_ptr));
3167
}
3168
3169
else /* always expect to see at least 2 bytes: */
3170
debug((png_ptr->mode & PNG_HAVE_IDAT) != 0U);
3171
3172
/* Set this now to prevent the above happening again second time round
3173
* the loop:
3174
*/
3175
png_ptr->mode |= PNG_HAVE_IDAT;
3176
3177
if (avail <= start+len)
3178
{
3179
/* Write all of this buffer: */
3180
affirm(avail > start); /* else overflow on the subtract */
3181
written = avail-start;
3182
png_write_chunk_data(png_ptr, next->output+start, written);
3183
3184
/* At the end there are no buffers in the list but the z_stream
3185
* still points into the old (just released) buffer. This can
3186
* happen when the old buffer is not full if the compressed bytes
3187
* exactly match the IDAT length; it should always happen when
3188
* end_of_image is set.
3189
*/
3190
ps->s.list = next->next;
3191
3192
if (next->next == NULL)
3193
{
3194
debug(avail == start+len);
3195
ps->s.end = &ps->s.list;
3196
ps->s.zs.next_out = NULL;
3197
ps->s.zs.avail_out = 0U;
3198
}
3199
3200
next->next = ps->stash;
3201
ps->stash = next;
3202
ps->s.start = 0U;
3203
}
3204
3205
else /* write only part of this buffer */
3206
{
3207
written = len;
3208
png_write_chunk_data(png_ptr, next->output+start, written);
3209
ps->s.start = (unsigned int)/*SAFE*/(start + written);
3210
}
3211
3212
/* 'written' bytes were written: */
3213
len -= written;
3214
3215
if (written <= ps->s.len)
3216
ps->s.len -= written;
3217
3218
else
3219
{
3220
affirm(ps->s.overflow > 0U);
3221
--ps->s.overflow;
3222
ps->s.len += 0x80000000U - written;
3223
UNTESTED
3224
}
3225
}
3226
while (len > 0U);
3227
3228
png_write_chunk_end(png_ptr);
3229
}
3230
3231
/* avail == 0 && flush */
3232
png_end_IDAT(png_ptr);
3233
png_ptr->mode |= PNG_AFTER_IDAT;
3234
}
3235
3236
/* This is is a convenience wrapper to handle IDAT compression; it takes a
3237
* pointer to the input data and places no limit on the size of the output but
3238
* is otherwise the same as png_compress(). It also handles the use of the
3239
* stash (only used for IDAT compression.)
3240
*/
3241
static int
3242
png_compress_IDAT_data(png_structrp png_ptr, png_zlib_statep ps,
3243
png_zlib_compressp pz, png_const_voidp input, uInt input_len, int flush)
3244
{
3245
/* Delay initialize the z_stream. */
3246
if (png_ptr->zowner != png_IDAT)
3247
png_deflate_claim(png_ptr, png_IDAT, 0U);
3248
3249
affirm(png_ptr->zowner == png_IDAT && pz->end != NULL && *pz->end == NULL);
3250
3251
/* z_stream::{next,avail}_out are set by png_compress to point into the
3252
* buffer list. next_in must be set here, avail_in comes from the input_len
3253
* parameter:
3254
*/
3255
pz->zs.next_in = PNGZ_INPUT_CAST(png_voidcast(const Bytef*, input));
3256
*pz->end = ps->stash; /* May be NULL */
3257
ps->stash = NULL;
3258
3259
/* zlib buffers the output, the maximum amount of compressed data that can be
3260
* produced here is governed by the amount of buffering.
3261
*/
3262
{
3263
int ret = png_compress(pz, input_len, 0U/*unlimited*/, flush);
3264
3265
affirm(pz->end != NULL && ps->stash == NULL);
3266
ps->stash = *pz->end; /* May be NULL */
3267
*pz->end = NULL;
3268
3269
/* Z_FINISH should give Z_STREAM_END, everything else should give Z_OK, in
3270
* either case all the input should have been consumed:
3271
*/
3272
implies(ret == Z_OK || ret == Z_FINISH, pz->zs.avail_in == 0U &&
3273
(ret == Z_STREAM_END) == (flush == Z_FINISH));
3274
pz->zs.next_in = NULL;
3275
pz->zs.avail_in = 0U; /* safety */
3276
png_zlib_compress_validate(pz, 0/*in_use*/);
3277
3278
return ret;
3279
}
3280
}
3281
3282
/* Compress some image data using the main png_zlib_compress. Write the result
3283
* out if there is sufficient data.
3284
*/
3285
static void
3286
png_compress_IDAT(png_structrp png_ptr, png_const_voidp input, uInt input_len,
3287
int flush)
3288
{
3289
png_zlib_statep ps = png_ptr->zlib_state;
3290
int ret = png_compress_IDAT_data(png_ptr, ps, &ps->s, input, input_len,
3291
flush);
3292
3293
/* Check the return code. */
3294
if (ret == Z_OK || ret == Z_STREAM_END)
3295
png_write_IDAT(png_ptr, flush == Z_FINISH);
3296
3297
else /* ret != Z_OK && ret != Z_STREAM_END */
3298
{
3299
/* This is an error condition. It is fatal. */
3300
png_end_IDAT(png_ptr);
3301
png_zstream_error(&ps->s.zs, ret);
3302
png_error(png_ptr, ps->s.zs.msg);
3303
}
3304
}
3305
3306
/* This is called at the end of every row to handle the required callbacks and
3307
* advance png_struct::row_number and png_struct::pass.
3308
*/
3309
static void
3310
png_write_end_row(png_structrp png_ptr, int flush)
3311
{
3312
png_uint_32 row_number = png_ptr->row_number;
3313
unsigned int pass = png_ptr->pass;
3314
3315
debug(pass < 7U);
3316
implies(flush == Z_FINISH, png_ptr->zowner == 0U);
3317
3318
/* API NOTE: the write callback is made before any changes to the row number
3319
* or pass however, in 1.7.0, the zlib stream can be closed before the
3320
* callback is made (this is new). The application flush function happens
3321
* afterward as was the case before. In 1.7.0 this is solely determined by
3322
* the order of the code that follows.
3323
*/
3324
if (png_ptr->write_row_fn != NULL)
3325
png_ptr->write_row_fn(png_ptr, row_number, pass);
3326
3327
# ifdef PNG_WRITE_FLUSH_SUPPORTED
3328
if (flush == Z_SYNC_FLUSH)
3329
{
3330
if (png_ptr->output_flush_fn != NULL)
3331
png_ptr->output_flush_fn(png_ptr);
3332
png_ptr->zlib_state->flush_rows = 0U;
3333
}
3334
# else /* !WRITE_FLUSH */
3335
PNG_UNUSED(flush)
3336
# endif /* !WRITE_FLUSH */
3337
3338
/* Finally advance to the next row/pass: */
3339
if (png_ptr->interlaced == PNG_INTERLACE_NONE)
3340
{
3341
debug(row_number < png_ptr->height);
3342
3343
if (++row_number == png_ptr->height) /* last row */
3344
{
3345
row_number = 0U;
3346
debug(flush == Z_FINISH);
3347
png_ptr->pass = 7U;
3348
}
3349
}
3350
3351
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
3352
else /* interlaced */ if (png_ptr->do_interlace)
3353
{
3354
/* This gets called only for rows that are processed; i.e. rows that
3355
* are in the pass of a pass which is itself in the output.
3356
*/
3357
debug(row_number < png_ptr->height &&
3358
PNG_PASS_IN_IMAGE(png_ptr->width, png_ptr->height, pass) &&
3359
pass <= PNG_LAST_PASS(png_ptr->width, png_ptr->height) &&
3360
PNG_ROW_IN_INTERLACE_PASS(row_number, pass));
3361
3362
/* NOTE: the last row of the original image may not be in the pass, in
3363
* this case the code which skipped the row must do the increment
3364
* below! See 'interlace_row' in pngwrite.c and the code in
3365
* png_write_png_rows below.
3366
*
3367
* In that case an earlier row will be the last one in the pass (if the
3368
* pass is in the output), check this here:
3369
*/
3370
implies(pass == PNG_LAST_PASS(png_ptr->width, png_ptr->height) &&
3371
PNG_LAST_PASS_ROW(row_number, pass, png_ptr->height),
3372
flush == Z_FINISH);
3373
3374
if (++row_number == png_ptr->height) /* last row */
3375
{
3376
row_number = 0U;
3377
png_ptr->pass = 0x7U & ++pass;
3378
}
3379
}
3380
# endif /* WRITE_INTERLACING */
3381
3382
else /* application does interlace */
3383
{
3384
implies(png_ptr->height == 1U, pass != 6U);
3385
debug(PNG_PASS_IN_IMAGE(png_ptr->width, png_ptr->height, pass) &&
3386
row_number < PNG_PASS_ROWS(png_ptr->height, pass));
3387
3388
if (++row_number == PNG_PASS_ROWS(png_ptr->height, pass))
3389
{
3390
/* last row in this pass, next one may be empty. */
3391
row_number = 0U;
3392
3393
do
3394
++pass;
3395
while (pass < 7U &&
3396
!PNG_PASS_IN_IMAGE(png_ptr->width, png_ptr->height, pass));
3397
3398
implies(png_ptr->height == 1U, pass != 6U);
3399
implies(pass == 7U, flush == Z_FINISH);
3400
png_ptr->pass = 0x7U & pass;
3401
}
3402
}
3403
3404
png_ptr->row_number = row_number;
3405
}
3406
3407
#ifdef PNG_WRITE_FLUSH_SUPPORTED
3408
/* Flush the current output buffers now */
3409
void PNGAPI
3410
png_write_flush(png_structrp png_ptr)
3411
{
3412
png_debug(1, "in png_write_flush");
3413
3414
/* Force a flush at the end of the current row by setting 'flush_rows' to the
3415
* maximum:
3416
*/
3417
if (png_ptr != NULL && png_ptr->zlib_state != NULL)
3418
png_ptr->zlib_state->flush_rows = 0xEFFFFFFF;
3419
}
3420
3421
/* Return the correct flush to use */
3422
static int
3423
row_flush(png_zlib_statep ps, unsigned int row_info_flags)
3424
{
3425
if (PNG_IDAT_END(row_info_flags))
3426
return Z_FINISH;
3427
3428
else if ((row_info_flags & png_row_end) != 0 &&
3429
++ps->flush_rows >= ps->flush_dist)
3430
return Z_SYNC_FLUSH;
3431
3432
else
3433
return Z_NO_FLUSH;
3434
}
3435
#else /* !WRITE_FLUSH */
3436
# define row_flush(ps, ri) (PNG_IDAT_END(ri) ? Z_FINISH : Z_NO_FLUSH)
3437
#endif /* !WRITE_FLUSH */
3438
3439
static void
3440
write_filtered_row(png_structrp png_ptr, png_const_voidp filtered_row,
3441
unsigned int row_bytes, unsigned int filter /*if at start of row*/,
3442
int flush)
3443
{
3444
/* This handles writing a row that has been filtered, or did not need to be
3445
* filtered. If the data row has a partial pixel it must have been handled
3446
* correctly in the caller; filters generate a full 8 bits even if the pixel
3447
* only has one significant bit!
3448
*/
3449
debug(row_bytes > 0);
3450
affirm(row_bytes <= ZLIB_IO_MAX); /* I.e. it fits in a uInt */
3451
3452
if (filter < PNG_FILTER_VALUE_LAST) /* start of row */
3453
{
3454
png_byte buffer[1];
3455
3456
buffer[0] = PNG_BYTE(filter);
3457
png_compress_IDAT(png_ptr, buffer, 1U/*len*/, Z_NO_FLUSH);
3458
}
3459
3460
png_compress_IDAT(png_ptr, filtered_row, row_bytes, flush);
3461
}
3462
3463
static void
3464
write_unfiltered_rowbits(png_structrp png_ptr, png_const_bytep filtered_row,
3465
unsigned int row_bits, png_byte filter /*if at start of row*/,
3466
int flush)
3467
{
3468
/* Same as above, but it correctly clears the unused bits in a partial
3469
* byte.
3470
*/
3471
const png_uint_32 row_bytes = row_bits >> 3;
3472
3473
debug(filter == PNG_FILTER_VALUE_NONE || filter == PNG_FILTER_VALUE_LAST);
3474
3475
if (row_bytes > 0U)
3476
{
3477
row_bits -= row_bytes << 3;
3478
write_filtered_row(png_ptr, filtered_row, row_bytes, filter,
3479
row_bits == 0U ? flush : Z_NO_FLUSH);
3480
filter = PNG_FILTER_VALUE_LAST; /* written */
3481
}
3482
3483
/* Handle a partial byte. */
3484
if (row_bits > 0U)
3485
{
3486
png_byte buffer[1];
3487
3488
buffer[0] = PNG_BYTE(filtered_row[row_bytes] & ~(0xFFU >> row_bits));
3489
write_filtered_row(png_ptr, buffer, 1U, filter, flush);
3490
}
3491
}
3492
3493
#ifdef PNG_WRITE_FILTER_SUPPORTED
3494
static void
3495
filter_block_singlebyte(unsigned int row_bytes, png_bytep sub_row,
3496
png_bytep up_row, png_bytep avg_row, png_bytep paeth_row,
3497
png_const_bytep row, png_const_bytep prev_row, png_bytep prev_pixels)
3498
{
3499
/* Calculate rows for all four filters where the input has one byte per pixel
3500
* (more accurately per filter-unit).
3501
*/
3502
png_byte a = prev_pixels[0];
3503
png_byte c = prev_pixels[1];
3504
3505
while (row_bytes-- > 0U)
3506
{
3507
const png_byte x = *row++;
3508
const png_byte b = prev_row == NULL ? 0U : *prev_row++;
3509
3510
/* Calculate each filtered byte in turn: */
3511
if (sub_row != NULL) *sub_row++ = 0xFFU & (x - a);
3512
if (up_row != NULL) *up_row++ = 0xFFU & (x - b);
3513
if (avg_row != NULL) *avg_row++ = 0xFFU & (x - (a+b)/2U);
3514
3515
/* Paeth is a little more difficult: */
3516
if (paeth_row != NULL)
3517
{
3518
int pa = b-c; /* a+b-c - a */
3519
int pb = a-c; /* a+b-c - b */
3520
int pc = pa+pb; /* a+b-c - c = b-c + a-c */
3521
png_byte p = a;
3522
3523
pa = abs(pa);
3524
pb = abs(pb);
3525
if (pa > pb) pa = pb, p = b;
3526
if (pa > abs(pc)) p = c;
3527
3528
*paeth_row++ = 0xFFU & (x - p);
3529
}
3530
3531
/* And set a and c for the next pixel: */
3532
a = x;
3533
c = b;
3534
}
3535
3536
/* Store a and c for the next block: */
3537
prev_pixels[0] = a;
3538
prev_pixels[1] = c;
3539
}
3540
3541
static void
3542
filter_block_multibyte(unsigned int row_bytes,
3543
const unsigned int bpp, png_bytep sub_row, png_bytep up_row,
3544
png_bytep avg_row, png_bytep paeth_row, png_const_bytep row,
3545
png_const_bytep prev_row, png_bytep prev_pixels)
3546
{
3547
/* Calculate rows for all four filters, the input is a block of bytes such
3548
* that row_bytes is a multiple of bpp. bpp can be 2, 3, 4, 6 or 8.
3549
* prev_pixels will be updated to the last pixels processed.
3550
*/
3551
while (row_bytes >= bpp)
3552
{
3553
unsigned int i;
3554
3555
for (i=0; i<bpp; ++i)
3556
{
3557
const png_byte a = prev_pixels[i];
3558
const png_byte c = prev_pixels[i+bpp];
3559
const png_byte b = prev_row == NULL ? 0U : *prev_row++;
3560
const png_byte x = *row++;
3561
3562
/* Save for the next pixel: */
3563
prev_pixels[i] = x;
3564
prev_pixels[i+bpp] = b;
3565
3566
/* Calculate each filtered byte in turn: */
3567
if (sub_row != NULL) *sub_row++ = 0xFFU & (x - a);
3568
if (up_row != NULL) *up_row++ = 0xFFU & (x - b);
3569
if (avg_row != NULL) *avg_row++ = 0xFFU & (x - (a+b)/2U);
3570
3571
/* Paeth is a little more difficult: */
3572
if (paeth_row != NULL)
3573
{
3574
int pa = b-c; /* a+b-c - a */
3575
int pb = a-c; /* a+b-c - b */
3576
int pc = pa+pb; /* a+b-c - c = b-c + a-c */
3577
png_byte p = a;
3578
3579
pa = abs(pa);
3580
pb = abs(pb);
3581
if (pa > pb) pa = pb, p = b;
3582
if (pa > abs(pc)) p = c;
3583
3584
*paeth_row++ = 0xFFU & (x - p);
3585
}
3586
}
3587
3588
row_bytes -= i;
3589
}
3590
}
3591
3592
static void
3593
filter_block(png_const_bytep prev_row, png_bytep prev_pixels,
3594
png_const_bytep unfiltered_row, unsigned int row_bits,
3595
const unsigned int bpp, png_bytep sub_row, png_bytep up_row,
3596
png_bytep avg_row, png_bytep paeth_row)
3597
{
3598
const unsigned int row_bytes = row_bits >> 3; /* complete bytes */
3599
3600
if (bpp <= 8U)
3601
{
3602
/* There may be a partial byte at the end. */
3603
if (row_bytes > 0)
3604
filter_block_singlebyte(row_bytes, sub_row, up_row, avg_row, paeth_row,
3605
unfiltered_row, prev_row, prev_pixels);
3606
3607
/* The partial byte must be handled correctly here; both the previous row
3608
* value and the current value need to have non-present bits cleared.
3609
*/
3610
if ((row_bits & 7U) != 0)
3611
{
3612
const png_byte mask = PNG_BYTE(~(0xFFU >> (row_bits & 7U)));
3613
png_byte buffer[2];
3614
3615
buffer[0] = unfiltered_row[row_bytes] & mask;
3616
3617
if (prev_row != NULL)
3618
buffer[1U] = prev_row[row_bytes] & mask;
3619
3620
else
3621
buffer[1U] = 0U;
3622
3623
filter_block_singlebyte(1U,
3624
sub_row == NULL ? NULL : sub_row+row_bytes,
3625
up_row == NULL ? NULL : up_row+row_bytes,
3626
avg_row == NULL ? NULL : avg_row+row_bytes,
3627
paeth_row == NULL ? NULL : paeth_row+row_bytes,
3628
buffer, buffer+1U, prev_pixels);
3629
}
3630
}
3631
3632
else
3633
filter_block_multibyte(row_bytes, bpp >> 3,
3634
sub_row, up_row, avg_row, paeth_row,
3635
unfiltered_row, prev_row, prev_pixels);
3636
}
3637
3638
static void
3639
filter_row(png_structrp png_ptr, png_const_bytep prev_row,
3640
png_bytep prev_pixels, png_const_bytep unfiltered_row,
3641
unsigned int row_bits, unsigned int bpp, unsigned int filter,
3642
int start_of_row, int flush)
3643
{
3644
/* filters_to_try identifies a single filter and it is not PNG_FILTER_NONE.
3645
*/
3646
png_byte filtered_row[PNG_ROW_BUFFER_SIZE];
3647
3648
affirm((row_bits+7U) >> 3 <= PNG_ROW_BUFFER_SIZE &&
3649
filter >= PNG_FILTER_VALUE_SUB && filter <= PNG_FILTER_VALUE_PAETH);
3650
debug((row_bits % bpp) == 0U);
3651
3652
filter_block(prev_row, prev_pixels, unfiltered_row, row_bits, bpp,
3653
filter == PNG_FILTER_VALUE_SUB ? filtered_row : NULL,
3654
filter == PNG_FILTER_VALUE_UP ? filtered_row : NULL,
3655
filter == PNG_FILTER_VALUE_AVG ? filtered_row : NULL,
3656
filter == PNG_FILTER_VALUE_PAETH ? filtered_row : NULL);
3657
3658
write_filtered_row(png_ptr, filtered_row, (row_bits+7U)>>3,
3659
start_of_row ? filter : PNG_FILTER_VALUE_LAST, flush);
3660
}
3661
3662
/* Allow the application to select one or more row filters to use. */
3663
static png_int_32
3664
set_filter(png_zlib_statep ps, unsigned int filtersIn)
3665
{
3666
/* Notice that PNG_NO_FILTERS is 0 and passes this test; this is OK because
3667
* filters then gets set to PNG_FILTER_NONE, as is required.
3668
*
3669
* The argument to this routine is actually an (int), but conversion to
3670
* (unsigned int) is safe because it leaves the top bits set which results in
3671
* PNG_EDOM below.
3672
*/
3673
if (filtersIn < PNG_FILTER_NONE)
3674
filtersIn = PNG_FILTER_MASK(filtersIn);
3675
3676
/* PNG_ALL_FILTERS is a constant, unfortunately it is nominally signed, for
3677
* historical reasons, hence the PNG_BIC_MASK here.
3678
*/
3679
if ((filtersIn & PNG_BIC_MASK(PNG_ALL_FILTERS)) == 0U)
3680
{
3681
# ifndef PNG_SELECT_FILTER_SUPPORTED
3682
filtersIn &= -filtersIn; /* Use lowest set bit */
3683
# endif /* !SELECT_FILTER */
3684
3685
return ps->filter_mask = filtersIn & PNG_ALL_FILTERS;
3686
}
3687
3688
else /* Out-of-range filtersIn: */
3689
return PNG_EDOM;
3690
}
3691
#endif /* WRITE_FILTER */
3692
3693
#ifdef PNG_WRITE_FILTER_SUPPORTED
3694
void /* PRIVATE */
3695
png_write_start_IDAT(png_structrp png_ptr)
3696
{
3697
png_zlib_statep ps = get_zlib_state(png_ptr);
3698
3699
/* Set up the IDAT compression state. Expect the state to have been released
3700
* by the previous owner, but it doesn't much matter if there was an error.
3701
* Note that the stream is not claimed yet.
3702
*/
3703
debug(png_ptr->zowner == 0U);
3704
3705
/* This sets the buffer limits and write_row_size, which is used below. */
3706
png_zlib_state_set_buffer_limits(png_ptr, ps);
3707
3708
if (ps->filter_mask == 0)
3709
{
3710
# ifdef PNG_SELECT_FILTER_SUPPORTED
3711
/* Now default the filter mask if it hasn't been set already: */
3712
int png_level =
3713
pz_get(ps, IDAT, png_level, PNG_DEFAULT_COMPRESSION_LEVEL);
3714
3715
/* If the bit depth is less than 8, so pixels are not byte aligned, PNG
3716
* filtering hardly ever helps because there is no correlation between
3717
* the bytes on which the filter works and the actual pixel values.
3718
* Note that GIF is a whole lot better at this because it uses LZW to
3719
* compress a bit-stream, not a byte stream as in the deflate
3720
* implementation of LZ77.
3721
*
3722
* If the row size is less than 256 bytes filter selection algorithms
3723
* are flakey because the restricted range of codes in each row can
3724
* lead to poor selection of filters, particularly if the bytes in the
3725
* image are themselves limited. (This happens when a low bit-depth
3726
* image is encoded with 8-bit channels.)
3727
*
3728
* By experiment with the test set of images the breakpoint between
3729
* not filtering and filtering based on which gives best compression by
3730
* row size is as follows:
3731
*
3732
* NONE FAST ALL
3733
* PAL <=anything [even 8-bit palette images larger if filtered]
3734
* G<8 <=anything [low bit depth gray images]
3735
* G8 <=16 [+~1%] >16
3736
* G16 <=128 [+~1%] >128
3737
* GA8 <=64 [+~1%] >64
3738
* GA16 <=anything [always better without filtering!]
3739
* RGB8 <=32 [+0-2%(1)] >32
3740
* RGB16 <=1024 [+~1%] >1024
3741
* RGBA8 <=64 [+~~1%] >64
3742
* RGBA16 <=128 {+~0.5%] >128
3743
*
3744
* (1) The largest 24-bit RGB image (RGB8) faired better, by 1.3%,
3745
* with 'fast' filters. This is assumed to be random.
3746
*
3747
* Aggregated across all color types and bit depths the breakpoint for
3748
* filtering is >16 bytes, but the size increase only exceeds 0.5% for
3749
* images with rows between 64 and 128 bytes, hence the choices below.
3750
*
3751
* Across all the test images that change (not including selecting just
3752
* the 'fast' filters by default) does not change the compressed size
3753
* significantly (+0.06% across the whole test set), however it does
3754
* substantially increase the number of images without filtering.
3755
*
3756
* Using just none and sub filters results in overall compressed sizes
3757
* somewhere around the geometric mean of no filtering and 'fast'.
3758
*
3759
* The image size also plays a part. Filtering is not an advantage for
3760
* images of size <= 512 bytes. This is also reflected below.
3761
*
3762
* NOTE: the libpng 1.6 (and earlier) algorithm seems to work
3763
* because it biases the byte codes in the output towards 0 and 255.
3764
* Zlib doesn't care what the codes are, but Huffman encoding always
3765
* benefits from a biased distribution and the filters themselves were
3766
* designed to produce values in this range.
3767
*
3768
* In a raw comparison with the legacy code selection of specific sets
3769
* of filters always increased the compressed size of the test set, as
3770
* follows:
3771
*
3772
* PNG_ALL_FILTERS: +0.26%
3773
* PNG_FAST_FILTERS: +1.9%
3774
* NONE+SUB: +5.8%
3775
* PNG_NO_FILTERS: +14%
3776
*
3777
* This mainly proves that a static selection of filters (without
3778
* considering the PNG format) is always worse than the legacy
3779
* algorithm below.
3780
*
3781
* NOTE: ps->filter_mask must be set to a mask value, not a simple
3782
* PNG_FILTER_VALUE_ number.
3783
*/
3784
if (ps->write_row_size == 0U /* row cannot be buffered */)
3785
ps->filter_mask = PNG_FILTER_NONE;
3786
3787
else if (png_level == PNG_COMPRESSION_COMPAT/* Legacy */)
3788
{
3789
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3790
png_ptr->bit_depth < 8U)
3791
ps->filter_mask = PNG_FILTER_NONE;
3792
3793
else
3794
ps->filter_mask = PNG_ALL_FILTERS;
3795
}
3796
3797
/* NOTE: overall with the following size tests (row and image size) the
3798
* test set of images end up 0.06% larger, however some color types are
3799
* smaller and some larger; the differences are minute. If the test is
3800
* <=128 (which means <=129 bytes per row with the filter byte) the
3801
* resultant inclusion of 32x32 RGBA images results in significantly
3802
* increased compressed size.
3803
*
3804
* The test on png_level captures the following settings:
3805
*
3806
* PNG_COMPRESSION_LOW_MEMORY
3807
* PNG_COMPRESSION_HIGH_SPEED
3808
* PNG_COMPRESSION_HIGH_READ_SPEED
3809
*
3810
* NOTE: this relies on the exact values in png.h!
3811
*/
3812
else if (png_level <= PNG_COMPRESSION_HIGH_READ_SPEED
3813
|| png_ptr->color_type == PNG_COLOR_TYPE_PALETTE
3814
|| png_ptr->bit_depth < 8U
3815
|| ps->write_row_size/*does not include filter*/ < 128U
3816
|| png_image_size(png_ptr) <= 512U)
3817
ps->filter_mask = PNG_FILTER_NONE;
3818
3819
/* ELSE: there are at least 128 bytes in every row and the pixels
3820
* are multiples of a byte.
3821
*/
3822
else switch (png_level)
3823
{
3824
default: /* For GCC */
3825
case PNG_COMPRESSION_LOW:
3826
ps->filter_mask = PNG_FILTER_NONE+PNG_FILTER_SUB;
3827
break;
3828
3829
case PNG_COMPRESSION_MEDIUM:
3830
ps->filter_mask = PNG_FAST_FILTERS;
3831
break;
3832
3833
case PNG_COMPRESSION_HIGH:
3834
ps->filter_mask = PNG_ALL_FILTERS;
3835
break;
3836
}
3837
# else /* !SELECT_FILTER */
3838
ps->filter_mask = PNG_FILTER_NONE;
3839
# endif /* !SELECT_FILTER */
3840
}
3841
}
3842
3843
static png_byte
3844
png_write_start_row(png_zlib_statep ps, int start_of_pass, int no_previous_row)
3845
/* Called at the start of a row to set up anything required for filter
3846
* handling in the row. Sets png_zlib_state::filters to a single filter.
3847
*/
3848
{
3849
unsigned int mask = ps->filter_mask;
3850
3851
/* If we see a previous-row filter in mask and png_zlib_state::save_row is
3852
* still unset set it. This means that the first time a previous-row filter
3853
* is seen row-saving gets turned on.
3854
*/
3855
if (ps->save_row == SAVE_ROW_UNSET && (mask & PREVIOUS_ROW_FILTERS) != 0U)
3856
ps->save_row = SAVE_ROW_DEFAULT;
3857
3858
if ((no_previous_row /* row not stored */ && !start_of_pass) ||
3859
ps->save_row == SAVE_ROW_OFF /* disabled by app */ ||
3860
ps->write_row_size == 0U /* row too large to buffer */)
3861
mask &= PNG_BIC_MASK(PREVIOUS_ROW_FILTERS);
3862
3863
/* On the first row of a pass Paeth is equivalent to sub and up is equivalent
3864
* to none, so try to simplify the mask in in this case.
3865
*/
3866
else if (start_of_pass) {
3867
# define MATCH(flags) ((mask & (flags)) == (flags))
3868
if (MATCH(PNG_FILTER_NONE|PNG_FILTER_UP))
3869
mask &= PNG_BIC_MASK(PNG_FILTER_UP);
3870
3871
if (MATCH(PNG_FILTER_SUB|PNG_FILTER_PAETH))
3872
mask &= PNG_BIC_MASK(PNG_FILTER_PAETH);
3873
# undef MATCH
3874
}
3875
3876
# ifdef PNG_SELECT_FILTER_SUPPORTED
3877
if ((mask & (mask-1U)) == 0U /* single bit set */ ||
3878
ps->write_row_size == 0U /* row cannot be buffered */)
3879
# endif /* SELECT_FILTER */
3880
/* Convert the lowest set bit into the corresponding value. If no bits
3881
* are set select NONE. After this switch statement the value of
3882
* ps->filters is guaranteed to just be a single filter.
3883
*/
3884
switch (mask & -mask)
3885
{
3886
default: mask = PNG_FILTER_VALUE_NONE; break;
3887
case PNG_FILTER_SUB: mask = PNG_FILTER_VALUE_SUB; break;
3888
case PNG_FILTER_UP: mask = PNG_FILTER_VALUE_UP; break;
3889
case PNG_FILTER_AVG: mask = PNG_FILTER_VALUE_AVG; break;
3890
case PNG_FILTER_PAETH: mask = PNG_FILTER_VALUE_PAETH; break;
3891
}
3892
3893
return ps->filters = PNG_BYTE(mask);
3894
}
3895
3896
static png_bytep
3897
allocate_row(png_structrp png_ptr, png_const_bytep data, png_alloc_size_t size)
3898
/* Utility to allocate and save some row bytes. If the result is NULL the
3899
* allocation failed and the png_zlib_struct will have been updated to
3900
* prevent further allocation attempts.
3901
*/
3902
{
3903
const png_zlib_statep ps = png_ptr->zlib_state;
3904
png_bytep buffer;
3905
3906
debug(ps->write_row_size > 0U);
3907
3908
/* OOM is handled silently, as is the case where the row is too large to
3909
* buffer.
3910
*/
3911
buffer = png_voidcast(png_bytep,
3912
png_malloc_base(png_ptr, ps->write_row_size));
3913
3914
/* Setting write_row_size to 0 switches on the code for handling a row that
3915
* is too large to buffer. This will kick in next time round, i.e. on the
3916
* next row.
3917
*/
3918
if (buffer == NULL)
3919
ps->write_row_size = 0U;
3920
3921
else
3922
memcpy(buffer, data, size);
3923
3924
return buffer;
3925
}
3926
#endif /* WRITE_FILTER */
3927
3928
#ifdef PNG_SELECT_FILTER_SUPPORTED
3929
/* Bit set operations. Not in ANSI C-90 but commonly available in highly
3930
* optimized versions, hence the ifndef. These operations just work on bitsets
3931
* of size 256. The second argument (the code index) may be evaluated multiple
3932
* times.
3933
*/
3934
#ifndef PNG_CODE_SET /* Can be set in pngpriv.h */
3935
typedef png_uint_32 png_codeset[8];
3936
# define PNG_CODE_MASK(i) (((png_uint_32)1U) << ((i) & 0x1FU))
3937
# define PNG_CODE_IS_SET(c,i) (((c)[(i) >> 5] & PNG_CODE_MASK(i)))
3938
# define PNG_CODE_SET(c,i) (((c)[(i) >> 5] |= PNG_CODE_MASK(i)))
3939
# define PNG_CODE_CLEAR(c,i) (((c)[(i) >> 5] &= ~PNG_CODE_MASK(i)))
3940
#endif /* !PNG_CODE_SET */
3941
3942
typedef struct filter_selector
3943
{
3944
/* Persistent filter selection information (stored across row boundaries).
3945
* A code is not considered if it last occured more than 'window' bytes ago.
3946
* The deflate algorithm means that 'window' cannot exceed 8453377, however
3947
* practical versions may be far less. When 'distance' reaches 'window' any
3948
* code where:
3949
*
3950
* distance - code_distance[code] > window
3951
*
3952
* at the end of a row 'code' is removed from codeset. Otherwise
3953
* (rearranging the above):
3954
*
3955
* distance - window <= code_distance[code]
3956
*
3957
* and so the distances of the still active codes can be reduced:
3958
*
3959
* code_distance[code] -= distance-window
3960
* distance = window
3961
*
3962
* This prevents any wrap of 'distance' on a row which is shorter than
3963
* 2^32-window.
3964
*
3965
* However when then row is 2^32-window or more bytes long (the row can be up
3966
* to just under 2^34 bytes long) this algorithm doesn't work; 'distance'
3967
* will overflow in the middle of the row and all codes are relevant. This
3968
* is handled below simply by reseting the set of present codes at the start
3969
* of the row and ignoring the overflow.
3970
*/
3971
unsigned int code_count; /* Number of distinct codes seen */
3972
int png_level; /* Cached compression level */
3973
png_uint_32 filter_select_max_width;
3974
/* The maximum number of pixels which can be fitted in the window without
3975
* filling the entire window (i.e. the maximum number that can be fitted
3976
* in (window-1) bytes).
3977
*/
3978
png_uint_32 sum_bias[PNG_FILTER_VALUE_LAST];
3979
/* For each filter a measure of its cost in the filter sum calculation.
3980
* This allows filter selection based on the sum-of-absolute-dfferences
3981
* method to be biased to favour particular filters. There was no such
3982
* bias before 1.7 and the filter byte was ignored.
3983
*/
3984
png_uint_32 distance; /* Distance from beginning */
3985
png_codeset codeset; /* Set of seen codes */
3986
png_uint_32 code_distance[256]; /* Distance at last occurence */
3987
} filter_selector;
3988
3989
static const filter_selector *
3990
png_start_filter_select(png_zlib_statep ps, unsigned int bpp)
3991
{
3992
# define png_ptr ps_png_ptr(ps)
3993
filter_selector *fs = ps->selector;
3994
3995
if (fs == NULL)
3996
{
3997
fs = png_voidcast(filter_selector*, png_malloc_base(png_ptr, sizeof *fs));
3998
3999
if (fs != NULL)
4000
{
4001
png_uint_32 window = ps->filter_select_window;
4002
fs->png_level = pz_get(ps, IDAT, png_level,
4003
PNG_DEFAULT_COMPRESSION_LEVEL);
4004
4005
/* Delay initialize this here: */
4006
if (window < 3U || window > PNG_FILTER_SELECT_WINDOW_MAX)
4007
ps->filter_select_window = window = PNG_FILTER_SELECT_WINDOW_MAX;
4008
4009
fs->code_count = 0;
4010
4011
switch (fs->png_level)
4012
{
4013
default:
4014
/* TODO: investigate other settings */
4015
{
4016
unsigned int f;
4017
4018
for (f=0; f<PNG_FILTER_VALUE_LAST; ++f)
4019
fs->sum_bias[f] = f;
4020
}
4021
ps->filter_select_threshold = 64U; /* 6bit RGB */
4022
ps->filter_select_threshold2 = 50U; /* TODO: experiment! */
4023
break;
4024
4025
case PNG_COMPRESSION_COMPAT: /* Legacy */
4026
memset(fs->sum_bias, 0U, sizeof fs->sum_bias);
4027
ps->filter_select_threshold = 1U; /* disabled */
4028
ps->filter_select_threshold2 = 1U;
4029
break;
4030
}
4031
4032
/* This is the maximum row width, in pixels, of a row which fits and
4033
* leaves 1 byte free in the window. For any bigger row filter
4034
* selection ignores the previous rows.
4035
*/
4036
fs->filter_select_max_width = ((window-2U/*filter+last byte*/)*8U)/bpp;
4037
fs->distance = 0U;
4038
memset(fs->codeset, 0U, sizeof fs->codeset);
4039
/* fs->code_distance is left uninitialized because fs->codeset says
4040
* whether or not each entry has been initialized.
4041
*/
4042
ps->selector = fs;
4043
}
4044
4045
else
4046
ps->write_row_size = 0U; /* OOM */
4047
}
4048
# undef png_ptr
4049
4050
return fs;
4051
}
4052
4053
typedef struct
4054
{
4055
/* Per-filter data. This remains separate from the above until the filter
4056
* selection has been made. It reflects the above however the codeset only
4057
* records codes present in this row.
4058
*
4059
* The 'sum' fields are the sum of the absolute deviation of each code from
4060
* 0, the algorithm from 1.6 and earlier. In other words:
4061
*
4062
* if (code >= 128)
4063
* sum += code;
4064
* else
4065
* sum += 256-code;
4066
*/
4067
unsigned int code_count; /* Number of distinct codes seen in row */
4068
unsigned int new_code_count; /* Number of new codes seen in row */
4069
png_uint_32 sum_low; /* Low 31 bits of code sum */
4070
png_uint_32 sum_high; /* High 32 bits of code sum */
4071
png_codeset codeset; /* Set of codes seen in this row */
4072
png_uint_32 code_distance[256]; /* Distance at last occurence in this row */
4073
} filter_data;
4074
4075
static void
4076
filter_data_init(filter_data *fd, png_uint_32 distance, unsigned int filter,
4077
unsigned int code_is_set, png_uint_32 bias)
4078
{
4079
fd->code_count = 1U;
4080
fd->new_code_count = !code_is_set;
4081
fd->sum_low = bias;
4082
fd->sum_high = 0U;
4083
memset(&fd->codeset, 0U, sizeof fd->codeset);
4084
PNG_CODE_SET(fd->codeset, filter);
4085
fd->code_distance[filter] = distance;
4086
}
4087
4088
static void
4089
add_code(const filter_selector *fs, filter_data *fd, png_uint_32 distance,
4090
unsigned int code)
4091
{
4092
if (!PNG_CODE_IS_SET(fd->codeset, code))
4093
{
4094
PNG_CODE_SET(fd->codeset, code);
4095
++(fd->code_count);
4096
fd->code_distance[code] = distance;
4097
if (!PNG_CODE_IS_SET(fs->codeset, code))
4098
++(fd->new_code_count);
4099
}
4100
4101
{
4102
png_uint_32 low = fd->sum_low;
4103
4104
if (code <= 128U)
4105
low += code;
4106
4107
else
4108
low += 256U-code;
4109
4110
/* Handle overflow into the top bit: */
4111
if (low & 0x80000000U)
4112
fd->sum_low = low & 0x7FFFFFFFU, ++fd->sum_high;
4113
4114
else
4115
fd->sum_low = low;
4116
}
4117
}
4118
4119
static png_byte
4120
filter_data_select(png_zlib_statep ps, filter_data fd[PNG_FILTER_VALUE_LAST],
4121
unsigned int filter, png_uint_32 distance, png_uint_32 w)
4122
{
4123
# define png_ptr ps_png_ptr(ps)
4124
/* Choose how to do this depending on the row and window size. */
4125
filter_selector *fs = ps->selector;
4126
png_uint_32 window = ps->filter_select_window;
4127
4128
affirm(fs != NULL);
4129
4130
/* Check the width against the maximum number of pixels that can fit in a
4131
* window without filling it:
4132
*/
4133
if (w > fs->filter_select_max_width)
4134
{
4135
/* The cache is not used */
4136
fs->distance = 0U; /* for next row */
4137
fs->code_count = 0U;
4138
memset(fs->codeset, 0U, sizeof fs->codeset);
4139
}
4140
4141
else
4142
{
4143
/* Merge the two code sets, discounting codes that last occurred before
4144
* the start of the window.
4145
*/
4146
png_uint_32 adjust, code_count;
4147
unsigned int code;
4148
4149
/* filter_selector::distance is the distance of the first byte in the row
4150
* (the filter byte), but 'distance' can wrap on long rows. The above
4151
* test is meant to exclude the wrap case by excluding any case where the
4152
* row has as many bytes as the window, so:
4153
*/
4154
affirm(distance > fs->distance && distance - fs->distance < window);
4155
4156
/* Set 'adjust' to the current distance of the start of the window. I.e:
4157
*
4158
* +---------------+--------+
4159
* | before window | window | future data
4160
* +---------------+--------+
4161
* A A
4162
* | |
4163
* adjust + + distance
4164
*
4165
* If the window isn't full yet 'adjust' will be zero, otherwise all the
4166
* distances will be reduced by 'adjust' so that the first byte of the
4167
* window has distance 0.
4168
*/
4169
if (distance > window)
4170
adjust = distance-window;
4171
4172
else
4173
adjust = 0;
4174
4175
4176
/* This may be decreased below if some old codes only occured before the
4177
* start of the window.
4178
*/
4179
code_count = fs->code_count + fd->new_code_count;
4180
4181
for (code=0U; code<256U; ++code)
4182
{
4183
if (PNG_CODE_IS_SET(fd[filter].codeset, code))
4184
{
4185
PNG_CODE_SET(fs->codeset, code);
4186
debug(fd[filter].code_distance[code] >= adjust);
4187
fs->code_distance[code] = fd[filter].code_distance[code] - adjust;
4188
}
4189
4190
else if (PNG_CODE_IS_SET(fs->codeset, code) && adjust > 0)
4191
{
4192
/* The code did not occur in this row, the old distance may now be
4193
* outside the window (because adjust is non-zero).
4194
*/
4195
const png_uint_32 d = fs->code_distance[code];
4196
4197
if (d >= adjust)
4198
fs->code_distance[code] = d-adjust;
4199
4200
else
4201
PNG_CODE_CLEAR(fs->codeset, code), --code_count;
4202
}
4203
}
4204
4205
fs->code_count = code_count;
4206
fs->distance = distance - adjust; /* I.e. either distance or window! */
4207
}
4208
4209
return ps->filters = PNG_BYTE(filter);
4210
# undef png_ptr
4211
}
4212
4213
static png_byte
4214
select_filter(png_zlib_statep ps, png_const_bytep row,
4215
png_const_bytep prev, unsigned int bpp, png_uint_32 width, int start_of_pass)
4216
/* Select a filter from the list provided by png_write_start_row. */
4217
{
4218
png_byte filters = png_write_start_row(ps, start_of_pass, prev == NULL);
4219
4220
# define png_ptr ps_png_ptr(ps)
4221
if (filters >= PNG_FILTER_NONE) /* multiple filters to test */
4222
{
4223
const png_uint_32 max_pixels = ps->row_buffer_max_pixels;
4224
const png_uint_32 block_pixels = ps->row_buffer_max_aligned_pixels;
4225
const filter_selector *fs = ps->selector;
4226
png_uint_32 pixels_to_go = width;
4227
png_uint_32 distance;
4228
unsigned int bits_at_end = 0U;
4229
png_byte prev_pixels[4*2*2]; /* 2 pixels up to 4x2-bytes each */
4230
filter_data fd[PNG_FILTER_VALUE_LAST];
4231
4232
debug((filters & (filters-1)) != 0U); /* Expect more than one bit! */
4233
4234
if (fs == NULL)
4235
{
4236
/* Delay initialize with a quiet OOM handler */
4237
fs = png_start_filter_select(ps, bpp);
4238
if (fs == NULL)
4239
{
4240
ps->filters = PNG_FILTER_VALUE_NONE;
4241
return PNG_FILTER_VALUE_NONE;
4242
}
4243
}
4244
4245
/* If PNG_FILTER_NONE is in the list check it first. */
4246
if (filters & PNG_FILTER_NONE)
4247
{
4248
png_const_bytep rp = row;
4249
png_uint_32 w = width;
4250
4251
distance = fs->distance;
4252
filter_data_init(fd+PNG_FILTER_VALUE_NONE, distance++,
4253
PNG_FILTER_VALUE_NONE,
4254
PNG_CODE_IS_SET(fs->codeset, PNG_FILTER_VALUE_NONE),
4255
fs->sum_bias[PNG_FILTER_VALUE_NONE]);
4256
4257
if (bpp >= 8) /* complete bytes */
4258
{
4259
const unsigned int bytes = bpp/8U;
4260
4261
while (w > 0)
4262
{
4263
unsigned int b;
4264
for (b=0; b<bytes; ++b)
4265
add_code(fs, fd+PNG_FILTER_VALUE_NONE, distance++, *rp++);
4266
--w;
4267
}
4268
}
4269
4270
else /* multiple pixels per byte */
4271
{
4272
const unsigned int ppb = 8U/bpp;
4273
4274
debug(ppb * bpp == 8U); /* Expect bpp to be a power of 2 */
4275
4276
while (w >= ppb)
4277
{
4278
add_code(fs, fd+PNG_FILTER_VALUE_NONE, distance++, *rp++);
4279
w -= ppb;
4280
}
4281
4282
if (w > 0) /* partial byte at end */
4283
add_code(fs, fd+PNG_FILTER_VALUE_NONE, distance++,
4284
*rp & (0xFFU >> (w*bpp) /* zero unused bits */));
4285
}
4286
4287
/* For PNG data with a small number of codes it is worth skipping the
4288
* filtering because it almost always increases the code count
4289
* significantly. This is controlled by
4290
* png_zlib_state::filter_select_threshold and causes an early return
4291
* here.
4292
*/
4293
if (fd[PNG_FILTER_VALUE_NONE].new_code_count +
4294
fs->code_count < ps->filter_select_threshold)
4295
return filter_data_select(ps, fd, PNG_FILTER_VALUE_NONE, distance,
4296
width);
4297
} /* PNG_FILTER_NONE */
4298
4299
memset(prev_pixels, 0U, sizeof prev_pixels);
4300
distance = fs->distance;
4301
4302
{
4303
unsigned int i;
4304
4305
for (i=PNG_FILTER_VALUE_NONE+1U; i<PNG_FILTER_VALUE_LAST; ++i)
4306
if (PNG_FILTER_MASK(i) & filters)
4307
filter_data_init(fd+i, distance, i,
4308
PNG_CODE_IS_SET(fs->codeset, i), fs->sum_bias[i]);
4309
}
4310
4311
++distance;
4312
4313
while (pixels_to_go || bits_at_end)
4314
{
4315
unsigned int bits, i;
4316
union
4317
{
4318
PNG_ROW_BUFFER_ALIGN_TYPE force_buffer_alignment;
4319
png_byte row[4][PNG_ROW_BUFFER_SIZE];
4320
} filtered;
4321
union
4322
{
4323
PNG_ROW_BUFFER_ALIGN_TYPE force_buffer_alignment;
4324
png_byte byte;
4325
} last;
4326
4327
if (pixels_to_go)
4328
{
4329
if (pixels_to_go > max_pixels)
4330
{
4331
/* Maintain alignment by consuming on block_pixels at once */
4332
bits = block_pixels * bpp;
4333
pixels_to_go -= block_pixels; /* May be 0 */
4334
}
4335
4336
else
4337
{
4338
bits = pixels_to_go * bpp;
4339
bits_at_end = bits & 0x7U;
4340
bits -= bits_at_end;
4341
pixels_to_go = 0U; /* +bits_at_end */
4342
}
4343
}
4344
4345
else /* incomplete byte at the end of the pixel */
4346
{
4347
/* Make sure the unused bits are cleared (to zero, although this is
4348
* an arbitrary choice):
4349
*/
4350
last.byte = PNG_BYTE(*row & ~(0xFFU >> bits_at_end));
4351
row = &last.byte;
4352
bits = bits_at_end;
4353
bits_at_end = 0U;
4354
}
4355
4356
filter_block(prev, prev_pixels, row, bits, bpp,
4357
filtered.row[0/*sub*/], filtered.row[1/*up*/],
4358
filtered.row[2/*avg*/], filtered.row[3/*Paeth*/]);
4359
4360
/* A block of (bits+7)/8 bytes is now available to process. */
4361
for (i=0; 8U*i < bits; ++i, ++distance)
4362
{
4363
unsigned int f;
4364
4365
for (f=PNG_FILTER_VALUE_NONE+1U; f<PNG_FILTER_VALUE_LAST; ++f)
4366
if (PNG_FILTER_MASK(f) & filters)
4367
add_code(fs, fd+f, distance, filtered.row[f-1U][i]);
4368
}
4369
4370
if (prev != NULL)
4371
prev += bits >> 3;
4372
4373
row += bits >> 3;
4374
}
4375
4376
/* Now look at the candidate filters, including 'none' and select the
4377
* best. We know that 'none' increases the code count beyond the
4378
* threshold, so if the old code count is below the threshold and there is
4379
* a filter which does not increase the code count select it; doing so
4380
* should do no harm to the overall compression.
4381
*/
4382
if (fs->code_count < ps->filter_select_threshold)
4383
{
4384
unsigned int f, min_new_count = 257U, min_f = PNG_FILTER_VALUE_NONE;
4385
4386
for (f=PNG_FILTER_VALUE_NONE+1U; f<PNG_FILTER_VALUE_LAST; ++f)
4387
if ((PNG_FILTER_MASK(f) & filters) != 0)
4388
{
4389
unsigned int new_code_count = fd[f].new_code_count;
4390
4391
if (new_code_count == 0U)
4392
return filter_data_select(ps, fd, f, distance, width);
4393
4394
else if (new_code_count < min_new_count)
4395
min_new_count = new_code_count, min_f = f;
4396
}
4397
4398
/* Use the second threshold to decide whether to select the best filter
4399
* on this basis alone:
4400
*/
4401
if (min_f != PNG_FILTER_VALUE_NONE &&
4402
fs->code_count + min_new_count < ps->filter_select_threshold2)
4403
return filter_data_select(ps, fd, min_f, distance, width);
4404
}
4405
4406
/* Now fall back to the libpng 1.6 and earlier algorithm. This favours
4407
* the filter which produces least deviation in the codes from 0. When
4408
* this works it does so by reducing the distribution of code values. The
4409
* filters implicitly encode the difference between a predictor based on
4410
* adjacent values, the assumption is that this will result in values
4411
* close to 0.
4412
*/
4413
{
4414
png_uint_32 high = -1;
4415
png_uint_32 low = -1;
4416
unsigned int min_f = 0 /*unset, but safe*/;
4417
unsigned int f;
4418
4419
for (f=PNG_FILTER_VALUE_NONE; f<PNG_FILTER_VALUE_LAST; ++f)
4420
if ((PNG_FILTER_MASK(f) & filters) != 0 &&
4421
(fd[f].sum_high < high ||
4422
(fd[f].sum_high == high && fd[f].sum_low < low)))
4423
{
4424
high = fd[f].sum_high;
4425
low = fd[f].sum_low;
4426
4427
if (low & 0x80000000U)
4428
{
4429
low &= 0x7FFFFFFFU, --high;
4430
if (high & 0x80000000U)
4431
low = high = 0U;
4432
}
4433
4434
min_f = f;
4435
}
4436
4437
return filter_data_select(ps, fd, min_f, distance, width);
4438
}
4439
}
4440
4441
debug(filters < PNG_FILTER_VALUE_LAST);
4442
return ps->filters = filters;
4443
# undef png_ptr
4444
}
4445
#else /* !SELECT_FILTER */
4446
/* Filter selection not being done, just call png_write_start_row: */
4447
# define select_filter(ps, rp, pp, bpp, width, start_of_pass)\
4448
png_write_start_row((ps), (start_of_pass), (pp) == NULL)
4449
#endif /* !SELECT_FILTER */
4450
4451
/* This is the common function to write multiple rows of PNG data. The data is
4452
* in the relevant PNG format but has had no filtering done.
4453
*/
4454
void /* PRIVATE */
4455
png_write_png_rows(png_structrp png_ptr, png_const_bytep *rows,
4456
png_uint_32 num_rows)
4457
{
4458
const png_zlib_statep ps = png_ptr->zlib_state;
4459
const unsigned int bpp = png_ptr->row_output_pixel_depth;
4460
# ifdef PNG_WRITE_FILTER_SUPPORTED
4461
png_const_bytep previous_row = ps->previous_write_row;
4462
# else /* !WRITE_FILTER */
4463
/* These are constant in the no-filer case: */
4464
const png_byte filter = PNG_FILTER_VALUE_NONE;
4465
const png_uint_32 max_pixels = ps->zlib_max_pixels;
4466
const png_uint_32 block_pixels = ps->zlib_max_aligned_pixels;
4467
# endif /* !WRITE_FILTER */
4468
/* Write the given rows handling the png_compress_IDAT argument limitations
4469
* (uInt) and any valid row width.
4470
*/
4471
png_uint_32 last_row_in_pass = 0U; /* Actual last, not last+1! */
4472
png_uint_32 pixels_in_pass = 0U;
4473
unsigned int first_row_in_pass = 0U; /* For do_interlace */
4474
unsigned int pixels_at_end = 0U; /* for a partial byte at the end */
4475
unsigned int base_info_flags = png_row_end;
4476
int pass = -1; /* Invalid: force calculation first time round */
4477
4478
debug(png_ptr->row_output_pixel_depth == PNG_PIXEL_DEPTH(*png_ptr));
4479
4480
while (num_rows-- > 0U)
4481
{
4482
if (png_ptr->pass != pass)
4483
{
4484
/* Recalcuate the row bytes and partial bits */
4485
pass = png_ptr->pass;
4486
pixels_in_pass = png_ptr->width;
4487
4488
if (png_ptr->interlaced == PNG_INTERLACE_NONE)
4489
{
4490
debug(pass == 0);
4491
last_row_in_pass = png_ptr->height - 1U;
4492
base_info_flags |= png_pass_last; /* there is only one */
4493
}
4494
4495
else
4496
{
4497
const png_uint_32 height = png_ptr->height;
4498
4499
last_row_in_pass = PNG_PASS_ROWS(height, pass);
4500
debug(pass >= 0 && pass < 7);
4501
4502
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
4503
if (png_ptr->do_interlace)
4504
{
4505
/* libpng is doing the interlace handling, the row number is
4506
* actually the row in the image.
4507
*
4508
* This overflows when the PNG height is such that the are no
4509
* rows in this pass. This does not matter; because there are
4510
* no rows the value doesn't get used.
4511
*/
4512
last_row_in_pass =
4513
PNG_ROW_FROM_PASS_ROW(last_row_in_pass-1U, pass);
4514
first_row_in_pass = PNG_PASS_START_ROW(pass);
4515
}
4516
4517
else /* Application handles the interlace */
4518
# endif /* WRITE_INTERLACING */
4519
{
4520
/* The row does exist, so this works without checking the column
4521
* count.
4522
*/
4523
debug(last_row_in_pass > 0U);
4524
last_row_in_pass -= 1U;
4525
}
4526
4527
if (pass == PNG_LAST_PASS(pixels_in_pass/*PNG width*/, height))
4528
base_info_flags |= png_pass_last;
4529
4530
/* Finally, adjust pixels_in_pass for the interlacing (skip the
4531
* final pass; it is full width).
4532
*/
4533
if (pass < 6)
4534
pixels_in_pass = PNG_PASS_COLS(pixels_in_pass, pass);
4535
}
4536
4537
/* Mask out the bits in a partial byte. */
4538
pixels_at_end = pixels_in_pass & PNG_ADDOF(bpp);
4539
4540
# ifdef PNG_WRITE_FILTER_SUPPORTED
4541
/* Reset the previous_row pointer correctly; NULL at the start of
4542
* the pass. If row_number is not 0 then a previous write_rows was
4543
* interrupted in mid-pass and any required buffer should be in
4544
* previous_write_row (set in the initializer).
4545
*/
4546
if (png_ptr->row_number == first_row_in_pass)
4547
previous_row = NULL;
4548
# endif /* WRITE_FILTER */
4549
}
4550
4551
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
4552
/* When libpng is handling the interlace we see rows that must be
4553
* skipped.
4554
*/
4555
if (!png_ptr->do_interlace ||
4556
PNG_ROW_IN_INTERLACE_PASS(png_ptr->row_number, pass))
4557
# endif /* WRITE_INTERLACING */
4558
{
4559
const unsigned int row_info_flags = base_info_flags |
4560
(png_ptr->row_number ==
4561
first_row_in_pass ? png_pass_first_row : 0) |
4562
(png_ptr->row_number == last_row_in_pass ? png_pass_last_row : 0);
4563
const int flush = row_flush(ps, row_info_flags);
4564
png_const_bytep row = *rows;
4565
png_uint_32 pixels_to_go = pixels_in_pass;
4566
# ifdef PNG_WRITE_FILTER_SUPPORTED
4567
/* The filter can change each time round. Call png_write_start_row
4568
* to resolve any changes. Note that when this function is used to
4569
* do filter selection from png_write_png_data on the first row
4570
* png_write_start_row will get called twice.
4571
*/
4572
const png_byte filter = select_filter(ps, row, previous_row, bpp,
4573
pixels_in_pass, png_ptr->row_number == first_row_in_pass);
4574
const png_uint_32 max_pixels = filter == PNG_FILTER_VALUE_NONE ?
4575
ps->zlib_max_pixels : ps->row_buffer_max_pixels;
4576
const png_uint_32 block_pixels = filter == PNG_FILTER_VALUE_NONE ?
4577
ps->zlib_max_aligned_pixels : ps->row_buffer_max_aligned_pixels;
4578
4579
/* The row handling uses png_compress_IDAT directly if there is no
4580
* filter to be applied, otherwise it uses filter_row.
4581
*/
4582
if (filter != PNG_FILTER_VALUE_NONE)
4583
{
4584
int start_of_row = 1;
4585
png_byte prev_pixels[4*2*2]; /* 2 pixels up to 4x2-bytes each */
4586
4587
memset(prev_pixels, 0U, sizeof prev_pixels);
4588
4589
while (pixels_to_go > max_pixels)
4590
{
4591
/* Write a block at once to maintain alignment */
4592
filter_row(png_ptr, previous_row, prev_pixels, row,
4593
bpp * block_pixels, bpp, filter, start_of_row,
4594
Z_NO_FLUSH);
4595
4596
if (previous_row != NULL)
4597
previous_row += (block_pixels * bpp) >> 3;
4598
4599
row += (block_pixels * bpp) >> 3;
4600
pixels_to_go -= block_pixels;
4601
start_of_row = 0;
4602
}
4603
4604
/* The filter code handles the partial byte at the end correctly,
4605
* so this is all that is required:
4606
*/
4607
if (pixels_to_go > 0)
4608
filter_row(png_ptr, previous_row, prev_pixels, row,
4609
bpp * pixels_to_go, bpp, filter, start_of_row, flush);
4610
}
4611
4612
else
4613
# endif /* WRITE_FILTER */
4614
4615
{
4616
/* The no-filter case. */
4617
const uInt block_bytes = (uInt)/*SAFE*/(
4618
bpp <= 8U ?
4619
block_pixels >> PNG_SHIFTOF(bpp) :
4620
block_pixels * (bpp >> 3));
4621
4622
/* png_write_start_IDAT guarantees this, but double check for
4623
* overflow above in debug:
4624
*/
4625
debug((block_bytes & (PNG_ROW_BUFFER_BYTE_ALIGN-1U)) == 0U);
4626
4627
/* The filter has to be written here: */
4628
png_compress_IDAT(png_ptr, &filter, 1U/*len*/, Z_NO_FLUSH);
4629
4630
/* Process blocks of pixels up to the limit. */
4631
while (pixels_to_go > max_pixels)
4632
{
4633
png_compress_IDAT(png_ptr, row, block_bytes, Z_NO_FLUSH);
4634
row += block_bytes;
4635
pixels_to_go -= block_pixels;
4636
}
4637
4638
/* Now compress the remainder; pixels_to_go <= max_pixels so it will
4639
* fit in a uInt.
4640
*/
4641
{
4642
const png_uint_32 remainder =
4643
bpp <= 8U
4644
? (pixels_to_go-pixels_at_end) >> PNG_SHIFTOF(bpp)
4645
: (pixels_to_go-pixels_at_end) * (bpp >> 3);
4646
4647
if (remainder > 0U)
4648
png_compress_IDAT(png_ptr, row, remainder,
4649
pixels_at_end > 0U ? Z_NO_FLUSH : flush);
4650
4651
else
4652
debug(pixels_at_end > 0U);
4653
4654
if (pixels_at_end > 0U)
4655
{
4656
/* There is a final partial byte. This is PNG format so the
4657
* left-most bits are the most significant.
4658
*/
4659
const png_byte last = PNG_BYTE(row[remainder] &
4660
~(0xFFU >> (pixels_at_end * bpp)));
4661
4662
png_compress_IDAT(png_ptr, &last, 1U, flush);
4663
}
4664
}
4665
}
4666
4667
png_write_end_row(png_ptr, flush);
4668
4669
# ifdef PNG_WRITE_FILTER_SUPPORTED
4670
previous_row = *rows;
4671
# endif /* WRITE_FILTER */
4672
# undef HANDLE
4673
} /* row in pass */
4674
4675
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
4676
else /* row not in pass; just skip it */
4677
{
4678
if (++png_ptr->row_number >= png_ptr->height)
4679
{
4680
debug(png_ptr->row_number == png_ptr->height);
4681
4682
png_ptr->row_number = 0U;
4683
png_ptr->pass = 0x7U & (pass+1U);
4684
}
4685
}
4686
# endif /* WRITE_INTERLACING */
4687
4688
++rows;
4689
} /* while num_rows */
4690
4691
# ifdef PNG_WRITE_FILTER_SUPPORTED
4692
/* previous_row must be copied back unless we don't need it because the
4693
* next row is the first one in the pass (this relies on png_write_end_row
4694
* setting row_number to 0 at the end!)
4695
*/
4696
if (png_ptr->row_number != 0U && previous_row != NULL && SAVE_ROW(ps) &&
4697
ps->previous_write_row != previous_row/*all rows skipped*/)
4698
{
4699
# ifdef PNG_SELECT_FILTER_SUPPORTED
4700
/* We might be able to avoid any copy. */
4701
if (ps->current_write_row == previous_row)
4702
{
4703
png_bytep old = ps->previous_write_row;
4704
ps->previous_write_row = ps->current_write_row;
4705
ps->current_write_row = old; /* may be NULL */
4706
}
4707
4708
else
4709
# endif /* SELECT_FILTER */
4710
4711
if (ps->previous_write_row != NULL)
4712
memcpy(ps->previous_write_row, previous_row,
4713
png_calc_rowbytes(png_ptr, bpp, pixels_in_pass));
4714
4715
else
4716
ps->previous_write_row = allocate_row(png_ptr, previous_row,
4717
png_calc_rowbytes(png_ptr, bpp, pixels_in_pass));
4718
}
4719
# endif /* WRITE_FILTER */
4720
}
4721
4722
#ifdef PNG_WRITE_FILTER_SUPPORTED
4723
/* This filters the row, chooses which filter to use, if it has not already
4724
* been specified by the application, and then writes the row out with the
4725
* chosen filter.
4726
*/
4727
static void
4728
write_png_data(png_structrp png_ptr, png_const_bytep prev_row,
4729
png_bytep prev_pixels, png_const_bytep unfiltered_row, png_uint_32 x,
4730
unsigned int row_bits, unsigned int row_info_flags)
4731
/* This filters the row appropriately and returns an updated prev_row
4732
* (updated for 'x').
4733
*/
4734
{
4735
const png_zlib_statep ps = png_ptr->zlib_state;
4736
const unsigned int bpp = png_ptr->row_output_pixel_depth;
4737
const int flush = row_flush(ps, row_info_flags);
4738
const png_byte filter = ps->filters; /* just one */
4739
4740
/* These invariants are expected from the caller: */
4741
affirm(row_bits <= 8U*PNG_ROW_BUFFER_SIZE);
4742
debug(filter < PNG_FILTER_VALUE_LAST/*sic: last+1*/);
4743
4744
/* Now choose the correct filter implementation according to the number of
4745
* filters in the filters_to_try list. The prev_row parameter is made
4746
* NULL on the first row because it is uninitialized at that point.
4747
*/
4748
if (filter == PNG_FILTER_VALUE_NONE)
4749
write_unfiltered_rowbits(png_ptr, unfiltered_row, row_bits,
4750
x == 0 ? PNG_FILTER_VALUE_NONE : PNG_FILTER_VALUE_LAST, flush);
4751
4752
else
4753
filter_row(png_ptr,
4754
(row_info_flags & png_pass_first_row) ? NULL : prev_row,
4755
prev_pixels, unfiltered_row, row_bits, bpp, filter, x == 0, flush);
4756
4757
/* Handle end of row: */
4758
if ((row_info_flags & png_row_end) != 0)
4759
png_write_end_row(png_ptr, flush);
4760
}
4761
4762
void /* PRIVATE */
4763
png_write_png_data(png_structrp png_ptr, png_bytep prev_pixels,
4764
png_const_bytep unfiltered_row, png_uint_32 x,
4765
unsigned int width/*pixels*/, unsigned int row_info_flags)
4766
{
4767
const png_zlib_statep ps = png_ptr->zlib_state;
4768
4769
affirm(ps != NULL);
4770
4771
{
4772
const unsigned int bpp = png_ptr->row_output_pixel_depth;
4773
const unsigned int row_bits = width * bpp;
4774
png_bytep prev_row = ps->previous_write_row;
4775
4776
debug(bpp <= 64U && width <= 65535U &&
4777
width < 65535U/bpp); /* Expensive: only matters on 16-bit */
4778
4779
/* This is called once before starting a new row here, but below it is
4780
* only called once between starting a new list of rows.
4781
*/
4782
if (x == 0)
4783
png_write_start_row(ps, (row_info_flags & png_pass_first_row) != 0,
4784
prev_row == NULL);
4785
4786
/* If filter selection is required the filter will have at least one mask
4787
* bit set.
4788
*/
4789
# ifdef PNG_SELECT_FILTER_SUPPORTED
4790
if (ps->filters >= PNG_FILTER_NONE/*lowest mask bit*/)
4791
{
4792
/* If the entire row is passed in the input process it via
4793
* immediately, otherwise the row must be buffered for later
4794
* analysis.
4795
*/
4796
png_const_bytep row;
4797
4798
if (x > 0 || (row_info_flags & png_row_end) == 0)
4799
{
4800
/* The row must be saved for later. */
4801
png_bytep buffer = ps->current_write_row;
4802
4803
/* png_write_start row should always check this: */
4804
debug(ps->write_row_size > 0U);
4805
4806
if (buffer != NULL)
4807
memcpy(buffer + png_calc_rowbytes(png_ptr, bpp, x),
4808
unfiltered_row, (row_bits + 7U) >> 3);
4809
4810
4811
else if (x == 0U)
4812
ps->current_write_row = buffer = allocate_row(png_ptr,
4813
unfiltered_row, (row_bits + 7U) >> 3);
4814
4815
row = buffer;
4816
}
4817
4818
else
4819
row = unfiltered_row;
4820
4821
if (row != NULL) /* else out of memory */
4822
{
4823
/* At row end, process the save buffer. */
4824
if ((row_info_flags & png_row_end) != 0)
4825
png_write_png_rows(png_ptr, &row, 1U);
4826
4827
/* Early return to skip the single-filter code */
4828
return;
4829
}
4830
4831
/* Caching the row failed, so process the row using the lowest set
4832
* filter. The allocation error should only ever happen at the
4833
* start of the row. If this goes wrong the output will have been
4834
* damaged.
4835
*/
4836
affirm(x == 0U);
4837
}
4838
# endif /* SELECT_FILTER */
4839
4840
/* prev_row is either NULL or the position in the previous row buffer */
4841
if (prev_row != NULL && x > 0)
4842
prev_row += png_calc_rowbytes(png_ptr, bpp, x);
4843
4844
/* This is the single filter case (no selection): */
4845
write_png_data(png_ptr, prev_row, prev_pixels, unfiltered_row, x,
4846
row_bits, row_info_flags);
4847
4848
/* Copy the current row into the previous row buffer, if available, unless
4849
* this is the last row in the pass, when there is no point. Note that
4850
* write_previous_row may have garbage in a partial byte at the end as a
4851
* result of this memcpy.
4852
*/
4853
if (!(row_info_flags & png_pass_last_row) && SAVE_ROW(ps)) {
4854
if (prev_row != NULL)
4855
memcpy(prev_row, unfiltered_row, (row_bits + 7U) >> 3);
4856
4857
/* NOTE: if the application sets png_zlib_state::save_row in a callback
4858
* it isn't possible to do the save until the next row. allocate_row
4859
* handles OOM silently by turning off the save.
4860
*/
4861
else if (x == 0) /* can allocate the save buffer */
4862
ps->previous_write_row =
4863
allocate_row(png_ptr, unfiltered_row, (row_bits + 7U) >> 3);
4864
}
4865
}
4866
}
4867
#else /* !WRITE_FILTER */
4868
void /* PRIVATE */
4869
png_write_start_IDAT(png_structrp png_ptr)
4870
{
4871
png_zlib_statep ps = get_zlib_state(png_ptr);
4872
4873
/* Set up the IDAT compression state. Expect the state to have been released
4874
* by the previous owner, but it doesn't much matter if there was an error.
4875
* Note that the stream is not claimed yet.
4876
*/
4877
debug(png_ptr->zowner == 0U);
4878
4879
/* This sets the buffer limits and write_row_size, which is used below. */
4880
png_zlib_state_set_buffer_limits(png_ptr, ps);
4881
}
4882
4883
void /* PRIVATE */
4884
png_write_png_data(png_structrp png_ptr, png_bytep prev_pixels,
4885
png_const_bytep unfiltered_row, png_uint_32 x,
4886
unsigned int width/*pixels*/, unsigned int row_info_flags)
4887
{
4888
const unsigned int bpp = png_ptr->row_output_pixel_depth;
4889
int flush;
4890
png_uint_32 row_bits;
4891
4892
row_bits = width;
4893
row_bits *= bpp;
4894
/* These invariants are expected from the caller: */
4895
affirm(width < 65536U && bpp <= 64U && width < 65536U/bpp &&
4896
row_bits <= 8U*PNG_ROW_BUFFER_SIZE);
4897
4898
affirm(png_ptr->zlib_state != NULL);
4899
flush = row_flush(png_ptr->zlib_state, row_info_flags);
4900
4901
write_unfiltered_rowbits(png_ptr, unfiltered_row, row_bits,
4902
x == 0 ? PNG_FILTER_VALUE_NONE : PNG_FILTER_VALUE_LAST, flush);
4903
4904
PNG_UNUSED(prev_pixels)
4905
4906
/* Handle end of row: */
4907
if ((row_info_flags & png_row_end) != 0)
4908
png_write_end_row(png_ptr, flush);
4909
}
4910
#endif /* !WRITE_FILTER */
4911
4912
png_int_32 /* PRIVATE */
4913
png_write_setting(png_structrp png_ptr, png_uint_32 setting,
4914
png_uint_32 parameter, png_int_32 value)
4915
{
4916
/* Caller checks the arguments for basic validity */
4917
int only_get = (setting & PNG_SF_GET) != 0U;
4918
4919
setting &= ~PNG_SF_GET;
4920
4921
switch (setting)
4922
{
4923
/* Settings in png_struct: */
4924
case PNG_SW_IDAT_size:
4925
if (parameter > 0 && parameter <= PNG_UINT_31_MAX)
4926
{
4927
if (!only_get)
4928
png_ptr->IDAT_size = parameter;
4929
4930
return 0; /* set ok */
4931
}
4932
4933
else
4934
return PNG_EINVAL;
4935
4936
/* Settings in zlib_state: */
4937
case PNG_SW_COMPRESS_png_level:
4938
return compression_setting(png_ptr, parameter, png_level, value,
4939
only_get);
4940
4941
# ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
4942
case PNG_SW_COMPRESS_zlib_level:
4943
return compression_setting(png_ptr, parameter, level, value,
4944
only_get);
4945
4946
case PNG_SW_COMPRESS_windowBits:
4947
return compression_setting(png_ptr, parameter, windowBits, value,
4948
only_get);
4949
4950
case PNG_SW_COMPRESS_memLevel:
4951
return compression_setting(png_ptr, parameter, memLevel, value,
4952
only_get);
4953
4954
case PNG_SW_COMPRESS_strategy:
4955
return compression_setting(png_ptr, parameter, strategy, value,
4956
only_get);
4957
4958
case PNG_SW_COMPRESS_method:
4959
if (value != 8) /* Only supported method */
4960
return PNG_EINVAL;
4961
return 8; /* old method */
4962
# endif /* WRITE_CUSTOMIZE_COMPRESSION */
4963
4964
# ifdef PNG_WRITE_FILTER_SUPPORTED
4965
case PNG_SW_COMPRESS_filters:
4966
/* The method must match that in the IHDR: */
4967
if (parameter == png_ptr->filter_method)
4968
{
4969
if (!only_get)
4970
return set_filter(get_zlib_state(png_ptr), value);
4971
4972
else if (png_ptr->zlib_state != NULL &&
4973
png_ptr->zlib_state->filter_mask != 0U/*unset*/)
4974
return png_ptr->zlib_state->filter_mask;
4975
4976
else
4977
return PNG_UNSET;
4978
}
4979
4980
else /* Invalid filter method */
4981
return PNG_EINVAL;
4982
4983
case PNG_SW_COMPRESS_row_buffers:
4984
/* New in 1.7.0: direct control of the buffering. */
4985
switch (parameter)
4986
{
4987
case 0:
4988
if (!only_get)
4989
get_zlib_state(png_ptr)->save_row = SAVE_ROW_OFF;
4990
return 0;
4991
4992
case 1:
4993
if (!only_get)
4994
get_zlib_state(png_ptr)->save_row = SAVE_ROW_ON;
4995
return 1;
4996
4997
default:
4998
return PNG_ENOSYS; /* no support for bigger values */
4999
}
5000
# endif /* WRITE_FILTER */
5001
5002
# ifdef PNG_WRITE_FLUSH_SUPPORTED
5003
case PNG_SW_FLUSH:
5004
/* Set the automatic flush interval or 0 to turn flushing off */
5005
if (!only_get)
5006
get_zlib_state(png_ptr)->flush_dist =
5007
value <= 0 ? 0xEFFFFFFFU : (png_uint_32)/*SAFE*/value;
5008
5009
return 0;
5010
# endif /* WRITE_FLUSH */
5011
5012
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
5013
case PNG_SRW_CHECK_FOR_INVALID_INDEX:
5014
/* The 'enabled' value is a FORTRAN style three-state: */
5015
if (value > 0)
5016
png_ptr->palette_index_check = PNG_PALETTE_CHECK_ON;
5017
5018
else if (value < 0)
5019
png_ptr->palette_index_check = PNG_PALETTE_CHECK_OFF;
5020
5021
else
5022
png_ptr->palette_index_check = PNG_PALETTE_CHECK_DEFAULT;
5023
5024
return 0;
5025
# endif /* WRITE_CHECK_FOR_INVALID_INDEX */
5026
5027
# ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
5028
case PNG_SRW_ERROR_HANDLING:
5029
/* The parameter is a bit mask of what to set, the value is what to
5030
* set it to. PNG_IDAT_ERRORS is ignored on write.
5031
*/
5032
if (value >= PNG_IGNORE && value <= PNG_ERROR &&
5033
parameter <= PNG_ALL_ERRORS)
5034
{
5035
if ((parameter & PNG_BENIGN_ERRORS) != 0U)
5036
png_ptr->benign_error_action = value & 0x3U;
5037
5038
if ((parameter & PNG_APP_WARNINGS) != 0U)
5039
png_ptr->app_warning_action = value & 0x3U;
5040
5041
if ((parameter & PNG_APP_ERRORS) != 0U)
5042
png_ptr->app_error_action = value & 0x3U;
5043
5044
return 0;
5045
}
5046
5047
return PNG_EINVAL;
5048
# endif /* BENIGN_WRITE_ERRORS */
5049
5050
default:
5051
return PNG_ENOSYS; /* not supported (whatever it is) */
5052
}
5053
}
5054
#endif /* WRITE */
5055
5056