-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspng.c
4859 lines (3781 loc) · 138 KB
/
spng.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: (BSD-2-Clause AND libpng-2.0) */
#define SPNG__BUILD
#include "spng.h"
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#define ZLIB_CONST
#ifdef __FRAMAC__
#define SPNG_DISABLE_OPT
#include "tests/framac_stubs.h"
#else
#ifdef SPNG_USE_MINIZ
#include "miniz.h"
#else
#include <zlib.h>
#endif
#endif
#ifdef SPNG_MULTITHREADING
#include <pthread.h>
#endif
#define SPNG_READ_SIZE 8192
#define SPNG_TARGET_CLONES(x)
#ifndef SPNG_DISABLE_OPT
#if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)
#define SPNG_X86
#if defined(__x86_64__) || defined(_M_X64)
#define SPNG_X86_64
#endif
#elif defined(__aarch64__) || defined(_M_ARM64) || defined(__ARM_NEON)
/* #define SPNG_ARM */ /* buffer overflow for rgb8 images */
#define SPNG_DISABLE_OPT
#else
#warning "disabling SIMD optimizations for unknown target"
#define SPNG_DISABLE_OPT
#endif
#if defined(SPNG_X86_64) && defined(SPNG_ENABLE_TARGET_CLONES)
#undef SPNG_TARGET_CLONES
#define SPNG_TARGET_CLONES(x) __attribute__((target_clones(x)))
#else
#define SPNG_TARGET_CLONES(x)
#endif
#ifndef SPNG_DISABLE_OPT
static void defilter_sub3(size_t rowbytes, unsigned char *row);
static void defilter_sub4(size_t rowbytes, unsigned char *row);
static void defilter_avg3(size_t rowbytes, unsigned char *row, const unsigned char *prev);
static void defilter_avg4(size_t rowbytes, unsigned char *row, const unsigned char *prev);
static void defilter_paeth3(size_t rowbytes, unsigned char *row, const unsigned char *prev);
static void defilter_paeth4(size_t rowbytes, unsigned char *row, const unsigned char *prev);
#endif
#endif
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4244)
#endif
#if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || defined(__BIG_ENDIAN__)
#define SPNG_BIG_ENDIAN
#else
#define SPNG_LITTLE_ENDIAN
#endif
enum spng_state
{
SPNG_STATE_INVALID = 0,
SPNG_STATE_INIT = 1, /* No PNG buffer/stream is set */
SPNG_STATE_INPUT, /* Input PNG was set */
SPNG_STATE_IHDR, /* IHDR was read */
SPNG_STATE_FIRST_IDAT, /* Reached first IDAT */
SPNG_STATE_DECODE_INIT, /* Decoder is ready for progressive reads */
SPNG_STATE_EOI, /* Reached the last scanline/row */
SPNG_STATE_LAST_IDAT, /* Reached last IDAT, set at end of decode_image() */
SPNG_STATE_AFTER_IDAT, /* */
SPNG_STATE_IEND, /* Reached IEND */
};
#define SPNG_STR(x) _SPNG_STR(x)
#define _SPNG_STR(x) #x
#define SPNG_VERSION_STRING SPNG_STR(SPNG_VERSION_MAJOR) "." \
SPNG_STR(SPNG_VERSION_MINOR) "." \
SPNG_STR(SPNG_VERSION_PATCH)
#define SPNG_GET_CHUNK_BOILERPLATE(chunk) \
if(ctx == NULL || chunk == NULL) return 1; \
int ret = read_chunks(ctx, 0); \
if(ret) return ret;
#define SPNG_SET_CHUNK_BOILERPLATE(chunk) \
if(ctx == NULL || chunk == NULL) return 1; \
if(ctx->data == NULL) ctx->encode_only = 1; \
int ret = read_chunks(ctx, 0); \
if(ret) return ret;
struct spng_subimage
{
uint32_t width;
uint32_t height;
size_t out_width; /* byte width based on output format */
size_t scanline_width;
};
struct spng_plte_entry16
{
uint16_t red;
uint16_t green;
uint16_t blue;
uint16_t alpha;
};
struct spng_text2
{
int type;
char *keyword;
char *text;
size_t text_length;
uint8_t compression_flag; /* iTXt only */
char *language_tag; /* iTXt only */
char *translated_keyword; /* iTXt only */
};
struct decode_flags
{
unsigned apply_trns: 1;
unsigned apply_gamma: 1;
unsigned use_sbit: 1;
unsigned indexed: 1;
unsigned do_scaling: 1;
unsigned interlaced: 1;
unsigned same_layout: 1;
unsigned zerocopy: 1;
unsigned unpack: 1;
};
struct spng_chunk_bitfield
{
unsigned ihdr: 1;
unsigned plte: 1;
unsigned chrm: 1;
unsigned iccp: 1;
unsigned gama: 1;
unsigned sbit: 1;
unsigned srgb: 1;
unsigned text: 1;
unsigned bkgd: 1;
unsigned hist: 1;
unsigned trns: 1;
unsigned phys: 1;
unsigned splt: 1;
unsigned time: 1;
unsigned offs: 1;
unsigned exif: 1;
};
/* Packed sample iterator */
struct spng__iter
{
const uint8_t mask;
const unsigned initial_shift;
unsigned shift_amount, bit_depth;
const unsigned char *samples;
};
struct spng_ctx
{
size_t data_size;
size_t bytes_read;
unsigned char *stream_buf;
const unsigned char *data;
/* User-defined pointers for streaming */
spng_read_fn *read_fn;
void *read_user_ptr;
/* Used for buffer reads */
const unsigned char *png_buf; /* base pointer for the buffer */
size_t bytes_left;
size_t last_read_size;
/* These are updated by read_header()/read_chunk_bytes() */
struct spng_chunk current_chunk;
uint32_t cur_chunk_bytes_left;
uint32_t cur_actual_crc;
struct spng_alloc alloc;
int flags; /* context flags */
int fmt;
unsigned state: 4;
unsigned streaming: 1;
unsigned encode_only: 1;
unsigned strict : 1;
/* input file contains this chunk */
struct spng_chunk_bitfield file;
/* chunk was stored with spng_set_*() */
struct spng_chunk_bitfield user;
/* chunk was stored by reading or with spng_set_*() */
struct spng_chunk_bitfield stored;
struct spng_chunk first_idat, last_idat;
uint32_t max_width, max_height;
uint32_t max_chunk_size;
size_t chunk_cache_limit;
size_t chunk_cache_usage;
int crc_action_critical;
int crc_action_ancillary;
struct spng_ihdr ihdr;
struct spng_plte plte;
struct spng_chrm_int chrm_int;
struct spng_iccp iccp;
uint32_t gama;
struct spng_sbit sbit;
uint8_t srgb_rendering_intent;
uint32_t n_text;
struct spng_text2 *text_list;
struct spng_bkgd bkgd;
struct spng_hist hist;
struct spng_trns trns;
struct spng_phys phys;
uint32_t n_splt;
struct spng_splt *splt_list;
struct spng_time time;
struct spng_offs offs;
struct spng_exif exif;
struct spng_subimage subimage[7];
z_stream zstream;
unsigned char *scanline_buf, *prev_scanline_buf, *row_buf;
unsigned char *scanline, *prev_scanline, *row;
size_t total_out_size;
size_t out_width; /* total_out_size / ihdr.height */
unsigned channels;
unsigned bytes_per_pixel; /* input PNG */
unsigned pixel_size; /* output format */
int widest_pass;
int last_pass; /* last non-empty pass */
uint16_t *gamma_lut; /* points to either _lut8 or _lut16 */
uint16_t *gamma_lut16;
uint16_t gamma_lut8[256];
unsigned char trns_px[8];
struct spng_plte_entry16 decode_plte[256];
struct spng_sbit decode_sb;
struct decode_flags decode_flags;
struct spng_row_info row_info;
};
static const uint32_t png_u32max = 2147483647;
static const uint32_t adam7_x_start[7] = { 0, 4, 0, 2, 0, 1, 0 };
static const uint32_t adam7_y_start[7] = { 0, 0, 4, 0, 2, 0, 1 };
static const uint32_t adam7_x_delta[7] = { 8, 8, 4, 4, 2, 2, 1 };
static const uint32_t adam7_y_delta[7] = { 8, 8, 8, 4, 4, 2, 2 };
static const uint8_t png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
static const uint8_t type_ihdr[4] = { 73, 72, 68, 82 };
static const uint8_t type_plte[4] = { 80, 76, 84, 69 };
static const uint8_t type_idat[4] = { 73, 68, 65, 84 };
static const uint8_t type_iend[4] = { 73, 69, 78, 68 };
static const uint8_t type_trns[4] = { 116, 82, 78, 83 };
static const uint8_t type_chrm[4] = { 99, 72, 82, 77 };
static const uint8_t type_gama[4] = { 103, 65, 77, 65 };
static const uint8_t type_iccp[4] = { 105, 67, 67, 80 };
static const uint8_t type_sbit[4] = { 115, 66, 73, 84 };
static const uint8_t type_srgb[4] = { 115, 82, 71, 66 };
static const uint8_t type_text[4] = { 116, 69, 88, 116 };
static const uint8_t type_ztxt[4] = { 122, 84, 88, 116 };
static const uint8_t type_itxt[4] = { 105, 84, 88, 116 };
static const uint8_t type_bkgd[4] = { 98, 75, 71, 68 };
static const uint8_t type_hist[4] = { 104, 73, 83, 84 };
static const uint8_t type_phys[4] = { 112, 72, 89, 115 };
static const uint8_t type_splt[4] = { 115, 80, 76, 84 };
static const uint8_t type_time[4] = { 116, 73, 77, 69 };
static const uint8_t type_offs[4] = { 111, 70, 70, 115 };
static const uint8_t type_exif[4] = { 101, 88, 73, 102 };
static inline void *spng__malloc(spng_ctx *ctx, size_t size)
{
return ctx->alloc.malloc_fn(size);
}
static inline void *spng__calloc(spng_ctx *ctx, size_t nmemb, size_t size)
{
return ctx->alloc.calloc_fn(nmemb, size);
}
static inline void *spng__realloc(spng_ctx *ctx, void *ptr, size_t size)
{
return ctx->alloc.realloc_fn(ptr, size);
}
static inline void spng__free(spng_ctx *ctx, void *ptr)
{
ctx->alloc.free_fn(ptr);
}
#if defined(SPNG_USE_MINIZ)
static void *spng__zalloc(void *opaque, size_t items, size_t size)
#else
static void *spng__zalloc(void *opaque, uInt items, uInt size)
#endif
{
spng_ctx *ctx = opaque;
if(size > SIZE_MAX / items) return NULL;
size_t len = (size_t)items * size;
return spng__malloc(ctx, len);
}
static void spng__zfree(void *opqaue, void *ptr)
{
spng_ctx *ctx = opqaue;
spng__free(ctx, ptr);
}
static int spng__inflate_init(spng_ctx *ctx)
{
if(ctx->zstream.state) inflateEnd(&ctx->zstream);
ctx->zstream.zalloc = spng__zalloc;
ctx->zstream.zfree = spng__zfree;
ctx->zstream.opaque = ctx;
if(inflateInit(&ctx->zstream) != Z_OK) return SPNG_EZLIB;
#if ZLIB_VERNUM >= 0x1290 && !defined(SPNG_USE_MINIZ)
if(inflateValidate(&ctx->zstream, ctx->flags & SPNG_CTX_IGNORE_ADLER32)) return SPNG_EZLIB;
#else /* This requires zlib >= 1.2.11 */
#ifdef _MSC_VER
#pragma message ("inflateValidate() not available, SPNG_CTX_IGNORE_ADLER32 will be ignored")
#else
#warning "inflateValidate() not available, SPNG_CTX_IGNORE_ADLER32 will be ignored"
#endif
#endif
return 0;
}
static inline uint16_t read_u16(const void *_data)
{
const unsigned char *data = _data;
return (data[0] & 0xFFU) << 8 | (data[1] & 0xFFU);
}
static inline uint32_t read_u32(const void *_data)
{
const unsigned char *data = _data;
return (data[0] & 0xFFUL) << 24 | (data[1] & 0xFFUL) << 16 |
(data[2] & 0xFFUL) << 8 | (data[3] & 0xFFUL);
}
static inline int32_t read_s32(const void *_data)
{
const unsigned char *data = _data;
int32_t ret;
uint32_t val = (data[0] & 0xFFUL) << 24 | (data[1] & 0xFFUL) << 16 |
(data[2] & 0xFFUL) << 8 | (data[3] & 0xFFUL);
memcpy(&ret, &val, 4);
return ret;
}
/* Returns an iterator for 1,2,4,8-bit samples */
static struct spng__iter spng__iter_init(unsigned bit_depth, const unsigned char *samples)
{
struct spng__iter iter =
{
.mask = (uint16_t)(1 << bit_depth) - 1,
.shift_amount = 8 - bit_depth,
.initial_shift = 8 - bit_depth,
.bit_depth = bit_depth,
.samples = samples
};
return iter;
}
/* Returns the current sample unpacked, iterates to the next one */
static inline uint8_t get_sample(struct spng__iter *iter)
{
uint8_t x = (iter->samples[0] >> iter->shift_amount) & iter->mask;
iter->shift_amount -= iter->bit_depth;
if(iter->shift_amount > 7)
{
iter->shift_amount = iter->initial_shift;
iter->samples++;
}
return x;
}
static void u16_row_to_host(void *row, size_t size)
{
uint16_t *px = row;
size_t i, n = size / 2;
for(i=0; i < n; i++)
{
px[i] = read_u16(&px[i]);
}
}
static void rgb8_row_to_rgba8(const unsigned char *row, unsigned char *out, uint32_t n)
{
uint32_t i;
for(i=0; i < n; i++)
{
memcpy(out + i * 4, row + i * 3, 3);
out[i*4+3] = 255;
}
}
/* Calculate scanline width in bits, round up to the nearest byte */
static int calculate_scanline_width(struct spng_ctx *ctx, uint32_t width, size_t *scanline_width)
{
if(!width) return 1;
size_t res = ctx->channels * ctx->ihdr.bit_depth;
if(res > SIZE_MAX / width) return SPNG_EOVERFLOW;
res = res * width;
res += 15; /* Filter byte + 7 for rounding */
if(res < 15) return SPNG_EOVERFLOW;
res /= 8;
if(res > UINT32_MAX) return SPNG_EOVERFLOW;
*scanline_width = res;
return 0;
}
static int calculate_subimages(struct spng_ctx *ctx)
{
if(ctx == NULL) return 1;
struct spng_ihdr *ihdr = &ctx->ihdr;
struct spng_subimage *sub = ctx->subimage;
if(ihdr->interlace_method == 1)
{
sub[0].width = (ihdr->width + 7) >> 3;
sub[0].height = (ihdr->height + 7) >> 3;
sub[1].width = (ihdr->width + 3) >> 3;
sub[1].height = (ihdr->height + 7) >> 3;
sub[2].width = (ihdr->width + 3) >> 2;
sub[2].height = (ihdr->height + 3) >> 3;
sub[3].width = (ihdr->width + 1) >> 2;
sub[3].height = (ihdr->height + 3) >> 2;
sub[4].width = (ihdr->width + 1) >> 1;
sub[4].height = (ihdr->height + 1) >> 2;
sub[5].width = ihdr->width >> 1;
sub[5].height = (ihdr->height + 1) >> 1;
sub[6].width = ihdr->width;
sub[6].height = ihdr->height >> 1;
}
else
{
sub[0].width = ihdr->width;
sub[0].height = ihdr->height;
}
int i;
for(i=0; i < 7; i++)
{
if(sub[i].width == 0 || sub[i].height == 0) continue;
int ret = calculate_scanline_width(ctx, sub[i].width, &sub[i].scanline_width);
if(ret) return ret;
if(sub[ctx->widest_pass].scanline_width < sub[i].scanline_width) ctx->widest_pass = i;
ctx->last_pass = i;
}
return 0;
}
static int increase_cache_usage(spng_ctx *ctx, size_t bytes)
{
if(ctx == NULL || !bytes) return 1;
size_t new_usage = ctx->chunk_cache_usage + bytes;
/* Overflow, treat it as a normal error though */
if(new_usage < ctx->chunk_cache_usage) return 1;
if(new_usage > ctx->chunk_cache_limit) return 1;
ctx->chunk_cache_usage = new_usage;
return 0;
}
static int decrease_cache_usage(spng_ctx *ctx, size_t usage)
{
if(ctx == NULL || !usage) return 1;
if(usage > ctx->chunk_cache_usage) return 1;
ctx->chunk_cache_usage -= usage;
return 0;
}
static int is_critical_chunk(struct spng_chunk *chunk)
{
if(chunk == NULL) return 0;
if((chunk->type[0] & (1 << 5)) == 0) return 1;
return 0;
}
static inline int read_data(spng_ctx *ctx, size_t bytes)
{
if(ctx == NULL) return 1;
if(!bytes) return 0;
if(ctx->streaming && (bytes > SPNG_READ_SIZE)) return 1;
int ret;
ret = ctx->read_fn(ctx, ctx->read_user_ptr, ctx->stream_buf, bytes);
if(ret) return ret;
ctx->bytes_read += bytes;
if(ctx->bytes_read < bytes) return SPNG_EOVERFLOW;
return 0;
}
/* Read and check the current chunk's crc,
returns -SPNG_CRC_DISCARD if the chunk should be discarded */
static inline int read_and_check_crc(spng_ctx *ctx)
{
if(ctx == NULL) return 1;
int ret;
ret = read_data(ctx, 4);
if(ret) return ret;
ctx->current_chunk.crc = read_u32(ctx->data);
if(ctx->cur_actual_crc != ctx->current_chunk.crc)
{
if(is_critical_chunk(&ctx->current_chunk))
{
if(ctx->crc_action_critical == SPNG_CRC_USE) return 0;
}
else
{
if(ctx->crc_action_ancillary == SPNG_CRC_USE) return 0;
if(ctx->crc_action_ancillary == SPNG_CRC_DISCARD) return -SPNG_CRC_DISCARD;
}
return SPNG_ECHUNK_CRC;
}
return 0;
}
/* Read and validate the current chunk's crc and the next chunk header */
static inline int read_header(spng_ctx *ctx, int *discard)
{
if(ctx == NULL) return 1;
int ret;
struct spng_chunk chunk = { 0 };
ret = read_and_check_crc(ctx);
if(ret)
{
if(ret == -SPNG_CRC_DISCARD)
{
if(discard != NULL) *discard = 1;
}
else return ret;
}
ret = read_data(ctx, 8);
if(ret) return ret;
chunk.offset = ctx->bytes_read - 8;
chunk.length = read_u32(ctx->data);
memcpy(&chunk.type, ctx->data + 4, 4);
if(chunk.length > png_u32max) return SPNG_ECHUNK_SIZE;
ctx->cur_chunk_bytes_left = chunk.length;
ctx->cur_actual_crc = crc32(0, NULL, 0);
ctx->cur_actual_crc = crc32(ctx->cur_actual_crc, chunk.type, 4);
memcpy(&ctx->current_chunk, &chunk, sizeof(struct spng_chunk));
return 0;
}
/* Read chunk bytes and update crc */
static int read_chunk_bytes(spng_ctx *ctx, uint32_t bytes)
{
if(ctx == NULL) return 1;
if(!ctx->cur_chunk_bytes_left || !bytes) return 1;
if(bytes > ctx->cur_chunk_bytes_left) return 1; /* XXX: more specific error? */
int ret;
ret = read_data(ctx, bytes);
if(ret) return ret;
if(is_critical_chunk(&ctx->current_chunk) &&
ctx->crc_action_critical == SPNG_CRC_USE) goto skip_crc;
else if(ctx->crc_action_ancillary == SPNG_CRC_USE) goto skip_crc;
ctx->cur_actual_crc = crc32(ctx->cur_actual_crc, ctx->data, bytes);
skip_crc:
ctx->cur_chunk_bytes_left -= bytes;
return ret;
}
/* read_chunk_bytes() + read_data() with custom output buffer */
static int read_chunk_bytes2(spng_ctx *ctx, void *out, uint32_t bytes)
{
if(ctx == NULL) return 1;
if(!ctx->cur_chunk_bytes_left || !bytes) return 1;
if(bytes > ctx->cur_chunk_bytes_left) return 1; /* XXX: more specific error? */
int ret;
uint32_t len = bytes;
if(ctx->streaming && len > SPNG_READ_SIZE) len = SPNG_READ_SIZE;
while(bytes)
{
if(len > bytes) len = bytes;
ret = ctx->read_fn(ctx, ctx->read_user_ptr, out, len);
if(ret) return ret;
if(!ctx->streaming) memcpy(out, ctx->data, len);
ctx->bytes_read += len;
if(ctx->bytes_read < len) return SPNG_EOVERFLOW;
if(is_critical_chunk(&ctx->current_chunk) &&
ctx->crc_action_critical == SPNG_CRC_USE) goto skip_crc;
else if(ctx->crc_action_ancillary == SPNG_CRC_USE) goto skip_crc;
ctx->cur_actual_crc = crc32(ctx->cur_actual_crc, out, len);
skip_crc:
ctx->cur_chunk_bytes_left -= len;
out = (char*)out + len;
bytes -= len;
len = SPNG_READ_SIZE;
}
return 0;
}
static int discard_chunk_bytes(spng_ctx *ctx, uint32_t bytes)
{
if(ctx == NULL) return 1;
if(!bytes) return 0;
int ret;
if(ctx->streaming) /* Do small, consecutive reads */
{
while(bytes)
{
uint32_t len = SPNG_READ_SIZE;
if(len > bytes) len = bytes;
ret = read_chunk_bytes(ctx, len);
if(ret) return ret;
bytes -= len;
}
}
else
{
ret = read_chunk_bytes(ctx, bytes);
if(ret) return ret;
}
return 0;
}
/* Inflate a zlib stream starting with start_buf if non-NULL,
continuing from the datastream till an end marker,
allocating and writing the inflated stream to *out,
leaving "extra" bytes at the end, final buffer length is *len.
Takes into account the chunk size and cache limits.
*/
static int spng__inflate_stream(spng_ctx *ctx, char **out, size_t *len, size_t extra, const void *start_buf, size_t start_len)
{
int ret = spng__inflate_init(ctx);
if(ret) return ret;
size_t max = ctx->chunk_cache_limit - ctx->chunk_cache_usage;
if(ctx->max_chunk_size < max) max = ctx->max_chunk_size;
if(extra > max) return SPNG_EMEM;
max -= extra;
uint32_t read_size;
size_t size = 8 * 1024;
void *t, *buf = spng__malloc(ctx, size);
if(buf == NULL) return SPNG_EMEM;
z_stream *stream = &ctx->zstream;
if(start_buf != NULL && start_len)
{
stream->avail_in = start_len;
stream->next_in = start_buf;
}
else
{
stream->avail_in = 0;
stream->next_in = NULL;
}
stream->avail_out = size;
stream->next_out = buf;
while(ret != Z_STREAM_END)
{
ret = inflate(stream, 0);
if(ret == Z_OK) continue;
if(ret == Z_STREAM_END) break;
if(ret == Z_BUF_ERROR)
{
if(!stream->avail_out) /* Resize buffer */
{
/* overflow or reached chunk/cache limit */
if( (2 > SIZE_MAX / size) || (size > max / 2) ) goto mem;
size *= 2;
t = spng__realloc(ctx, buf, size);
if(t == NULL) goto mem;
buf = t;
stream->avail_out = size / 2;
stream->next_out = (unsigned char*)buf + size / 2;
}
if(!stream->avail_in) /* Read more chunk bytes */
{
read_size = ctx->cur_chunk_bytes_left;
if(ctx->streaming && read_size > SPNG_READ_SIZE) read_size = SPNG_READ_SIZE;
ret = read_chunk_bytes(ctx, read_size);
if(ret)
{
spng__free(ctx, buf);
return ret;
}
stream->avail_in = read_size;
stream->next_in = ctx->data;
}
}
else
{
spng__free(ctx, buf);
return SPNG_EZLIB;
}
}
size = stream->total_out;
if(!size)
{
spng__free(ctx, buf);
return SPNG_EZLIB;
}
size += extra;
if(size < extra) goto mem;
t = spng__realloc(ctx, buf, size);
if(t == NULL) goto mem;
buf = t;
increase_cache_usage(ctx, size);
*out = buf;
*len = size;
return 0;
mem:
spng__free(ctx, buf);
return SPNG_EMEM;
}
/* Read at least one byte from the IDAT stream */
static int read_idat_bytes(spng_ctx *ctx, uint32_t *bytes_read)
{
if(ctx == NULL || bytes_read == NULL) return 1;
if(memcmp(ctx->current_chunk.type, type_idat, 4)) return SPNG_EIDAT_TOO_SHORT;
int ret;
uint32_t len;
while(!ctx->cur_chunk_bytes_left)
{
ret = read_header(ctx, NULL);
if(ret) return ret;
if(memcmp(ctx->current_chunk.type, type_idat, 4)) return SPNG_EIDAT_TOO_SHORT;
}
if(ctx->streaming)
{/* TODO: estimate bytes to read for progressive reads */
len = SPNG_READ_SIZE;
if(len > ctx->cur_chunk_bytes_left) len = ctx->cur_chunk_bytes_left;
}
else len = ctx->current_chunk.length;
ret = read_chunk_bytes(ctx, len);
*bytes_read = len;
return ret;
}
static int read_scanline_bytes(spng_ctx *ctx, unsigned char *dest, size_t len)
{
if(ctx == NULL || dest == NULL) return 1;
int ret = Z_OK;
uint32_t bytes_read;
z_stream *zstream = &ctx->zstream;
zstream->avail_out = len;
zstream->next_out = dest;
while(zstream->avail_out != 0)
{
ret = inflate(&ctx->zstream, 0);
if(ret == Z_OK) continue;
if(ret == Z_STREAM_END) /* Reached an end-marker */
{
if(zstream->avail_out != 0) return SPNG_EIDAT_TOO_SHORT;
}
else if(ret == Z_BUF_ERROR) /* Read more IDAT bytes */
{
ret = read_idat_bytes(ctx, &bytes_read);
if(ret) return ret;
zstream->avail_in = bytes_read;
zstream->next_in = ctx->data;
}
else return SPNG_EIDAT_STREAM;
}
return 0;
}
static uint8_t paeth(uint8_t a, uint8_t b, uint8_t c)
{
int16_t p = (int16_t)a + (int16_t)b - (int16_t)c;
int16_t pa = abs(p - (int16_t)a);
int16_t pb = abs(p - (int16_t)b);
int16_t pc = abs(p - (int16_t)c);
if(pa <= pb && pa <= pc) return a;
else if(pb <= pc) return b;
return c;
}
SPNG_TARGET_CLONES("default,avx2")
static void defilter_up(size_t bytes, unsigned char *row, const unsigned char *prev)
{
size_t i;
for(i=0; i < bytes; i++)
{
row[i] += prev[i];
}
}
/* Defilter *scanline in-place.
*prev_scanline and *scanline should point to the first pixel,
scanline_width is the width of the scanline including the filter byte.
*/
static int defilter_scanline(const unsigned char *prev_scanline, unsigned char *scanline,
size_t scanline_width, unsigned bytes_per_pixel, unsigned filter)
{
if(prev_scanline == NULL || scanline == NULL || !scanline_width) return 1;
size_t i;
scanline_width--;
if(filter == 0) return 0;
#ifndef SPNG_DISABLE_OPT
if(filter == SPNG_FILTER_UP) goto no_opt;
if(bytes_per_pixel == 4)
{
if(filter == SPNG_FILTER_SUB)
defilter_sub4(scanline_width, scanline);
else if(filter == SPNG_FILTER_AVERAGE)
defilter_avg4(scanline_width, scanline, prev_scanline);
else if(filter == SPNG_FILTER_PAETH)
defilter_paeth4(scanline_width, scanline, prev_scanline);
else return SPNG_EFILTER;
return 0;
}
else if(bytes_per_pixel == 3)
{
if(filter == SPNG_FILTER_SUB)
defilter_sub3(scanline_width, scanline);
else if(filter == SPNG_FILTER_AVERAGE)
defilter_avg3(scanline_width, scanline, prev_scanline);
else if(filter == SPNG_FILTER_PAETH)
defilter_paeth3(scanline_width, scanline, prev_scanline);
else return SPNG_EFILTER;
return 0;
}
no_opt:
#endif
if(filter == SPNG_FILTER_UP)
{
defilter_up(scanline_width, scanline, prev_scanline);