-
Notifications
You must be signed in to change notification settings - Fork 6
/
spng.c
6996 lines (5474 loc) · 195 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
/* Not build options, edit at your own risk! */
#define SPNG_READ_SIZE (8192)
#define SPNG_WRITE_SIZE SPNG_READ_SIZE
#define SPNG_MAX_CHUNK_COUNT (1000)
#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 /* NOTE: only arm64 builds are tested! */
#else
#pragma message "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);
#if defined(SPNG_ARM)
static uint32_t expand_palette_rgba8_neon(unsigned char *row, const unsigned char *scanline, const unsigned char *plte, uint32_t width);
static uint32_t expand_palette_rgb8_neon(unsigned char *row, const unsigned char *scanline, const unsigned char *plte, uint32_t width);
#endif
#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, /* Decoder input PNG was set */
SPNG_STATE_OUTPUT = SPNG_STATE_INPUT, /* Encoder output was set */
SPNG_STATE_IHDR, /* IHDR was read/written */
SPNG_STATE_FIRST_IDAT, /* Encoded up to / reached first IDAT */
SPNG_STATE_DECODE_INIT, /* Decoder is ready for progressive reads */
SPNG_STATE_ENCODE_INIT = SPNG_STATE_DECODE_INIT,
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 */
};
enum spng__internal
{
SPNG__IO_SIGNAL = 1 << 9,
SPNG__CTX_FLAGS_ALL = (SPNG_CTX_IGNORE_ADLER32 | SPNG_CTX_ENCODER)
};
#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) return 1; \
int ret = read_chunks(ctx, 0); \
if(ret) return ret; \
if(!ctx->stored.chunk) return SPNG_ECHUNKAVAIL; \
if(chunk == NULL) return 1
#define SPNG_SET_CHUNK_BOILERPLATE(chunk) \
if(ctx == NULL || chunk == NULL) return 1; \
if(ctx->data == NULL && !ctx->encode_only) return SPNG_ENOSRC; \
int ret = read_chunks(ctx, 0); \
if(ret) return ret
/* Determine if the spng_option can be overriden/optimized */
#define spng__optimize(option) (ctx->optimize_option & (1 << option))
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_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 */
size_t cache_usage;
char user_keyword_storage[80];
};
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 encode_flags
{
unsigned interlace: 1;
unsigned same_layout: 1;
unsigned to_bigendian: 1;
unsigned progressive: 1;
unsigned finalize: 1;
enum spng_filter_choice filter_choice;
};
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;
unsigned unknown: 1;
};
/* Packed sample iterator */
struct spng__iter
{
const uint8_t mask;
unsigned shift_amount;
const unsigned initial_shift, bit_depth;
const unsigned char *samples;
};
union spng__decode_plte
{
struct spng_plte_entry rgba[256];
unsigned char rgb[256 * 3];
unsigned char raw[256 * 4];
uint32_t align_this;
};
struct spng__zlib_options
{
int compression_level;
int window_bits;
int mem_level;
int strategy;
int data_type;
};
typedef void spng__undo(spng_ctx *ctx);
struct spng_ctx
{
size_t data_size;
size_t bytes_read;
size_t stream_buf_size;
unsigned char *stream_buf;
const unsigned char *data;
/* User-defined pointers for streaming */
spng_read_fn *read_fn;
spng_write_fn *write_fn;
void *stream_user_ptr;
/* Used for buffer reads */
const unsigned char *png_base;
size_t bytes_left;
size_t last_read_size;
/* Used for encoding */
int user_owns_out_png;
unsigned char *out_png;
unsigned char *write_ptr;
size_t out_png_size;
size_t bytes_encoded;
/* These are updated by read/write_header()/read_chunk_bytes() */
struct spng_chunk current_chunk;
uint32_t cur_chunk_bytes_left;
uint32_t cur_actual_crc;
struct spng_alloc alloc;
enum spng_ctx_flags flags;
enum spng_format fmt;
enum spng_state state;
unsigned streaming: 1;
unsigned internal_buffer: 1; /* encoding to internal buffer */
unsigned inflate: 1;
unsigned deflate: 1;
unsigned encode_only: 1;
unsigned strict: 1;
unsigned discard: 1;
unsigned skip_crc: 1;
unsigned keep_unknown: 1;
unsigned prev_was_idat: 1;
struct spng__zlib_options image_options;
struct spng__zlib_options text_options;
spng__undo *undo;
/* 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;
/* used to reset the above in case of an error */
struct spng_chunk_bitfield prev_stored;
struct spng_chunk first_idat, last_idat;
uint32_t max_width, max_height;
size_t max_chunk_size;
size_t chunk_cache_limit;
size_t chunk_cache_usage;
uint32_t chunk_count_limit;
uint32_t chunk_count_total;
int crc_action_critical;
int crc_action_ancillary;
uint32_t optimize_option;
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;
uint32_t n_chunks;
struct spng_unknown_chunk *chunk_list;
struct spng_subimage subimage[7];
z_stream zstream;
unsigned char *scanline_buf, *prev_scanline_buf, *row_buf, *filtered_scanline_buf;
unsigned char *scanline, *prev_scanline, *row, *filtered_scanline;
/* based on fmt */
size_t image_size; /* may be zero */
size_t image_width;
unsigned bytes_per_pixel; /* derived from ihdr */
unsigned pixel_size; /* derived from spng_format+ihdr */
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];
union spng__decode_plte decode_plte;
struct spng_sbit decode_sb;
struct decode_flags decode_flags;
struct spng_row_info row_info;
struct encode_flags encode_flags;
};
static const uint32_t spng_u32max = INT32_MAX;
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 spng_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 inline uint16_t read_u16(const void *src)
{
const unsigned char *data = src;
return (data[0] & 0xFFU) << 8 | (data[1] & 0xFFU);
}
static inline uint32_t read_u32(const void *src)
{
const unsigned char *data = src;
return (data[0] & 0xFFUL) << 24 | (data[1] & 0xFFUL) << 16 |
(data[2] & 0xFFUL) << 8 | (data[3] & 0xFFUL);
}
static inline int32_t read_s32(const void *src)
{
int32_t ret = (int32_t)read_u32(src);
return ret;
}
static inline void write_u16(void *dest, uint16_t x)
{
unsigned char *data = dest;
data[0] = x >> 8;
data[1] = x & 0xFF;
}
static inline void write_u32(void *dest, uint32_t x)
{
unsigned char *data = dest;
data[0] = (x >> 24);
data[1] = (x >> 16) & 0xFF;
data[2] = (x >> 8) & 0xFF;
data[3] = x & 0xFF;
}
static inline void write_s32(void *dest, int32_t x)
{
uint32_t n = x;
write_u32(dest, n);
}
/* 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 = (uint32_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 u16_row_to_bigendian(void *row, size_t size)
{
uint16_t *px = (uint16_t*)row;
size_t i, n = size / 2;
for(i=0; i < n; i++)
{
write_u16(&px[i], 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;
}
}
static unsigned num_channels(const struct spng_ihdr *ihdr)
{
switch(ihdr->color_type)
{
case SPNG_COLOR_TYPE_TRUECOLOR: return 3;
case SPNG_COLOR_TYPE_GRAYSCALE_ALPHA: return 2;
case SPNG_COLOR_TYPE_TRUECOLOR_ALPHA: return 4;
case SPNG_COLOR_TYPE_GRAYSCALE:
case SPNG_COLOR_TYPE_INDEXED:
return 1;
default: return 0;
}
}
/* Calculate scanline width in bits, round up to the nearest byte */
static int calculate_scanline_width(const struct spng_ihdr *ihdr, uint32_t width, size_t *scanline_width)
{
if(ihdr == NULL || !width) return SPNG_EINTERNAL;
size_t res = num_channels(ihdr) * 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 SPNG_EINTERNAL;
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(ihdr, 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 check_decode_fmt(const struct spng_ihdr *ihdr, const int fmt)
{
switch(fmt)
{
case SPNG_FMT_RGBA8:
case SPNG_FMT_RGBA16:
case SPNG_FMT_RGB8:
case SPNG_FMT_PNG:
case SPNG_FMT_RAW:
return 0;
case SPNG_FMT_G8:
case SPNG_FMT_GA8:
if(ihdr->color_type == SPNG_COLOR_TYPE_GRAYSCALE && ihdr->bit_depth <= 8) return 0;
else return SPNG_EFMT;
case SPNG_FMT_GA16:
if(ihdr->color_type == SPNG_COLOR_TYPE_GRAYSCALE && ihdr->bit_depth == 16) return 0;
else return SPNG_EFMT;
default: return SPNG_EFMT;
}
}
static int calculate_image_width(const struct spng_ihdr *ihdr, int fmt, size_t *len)
{
if(ihdr == NULL || len == NULL) return SPNG_EINTERNAL;
size_t res = ihdr->width;
unsigned bytes_per_pixel;
switch(fmt)
{
case SPNG_FMT_RGBA8:
case SPNG_FMT_GA16:
bytes_per_pixel = 4;
break;
case SPNG_FMT_RGBA16:
bytes_per_pixel = 8;
break;
case SPNG_FMT_RGB8:
bytes_per_pixel = 3;
break;
case SPNG_FMT_PNG:
case SPNG_FMT_RAW:
{
int ret = calculate_scanline_width(ihdr, ihdr->width, &res);
if(ret) return ret;
res -= 1; /* exclude filter byte */
bytes_per_pixel = 1;
break;
}
case SPNG_FMT_G8:
bytes_per_pixel = 1;
break;
case SPNG_FMT_GA8:
bytes_per_pixel = 2;
break;
default: return SPNG_EINTERNAL;
}
if(res > SIZE_MAX / bytes_per_pixel) return SPNG_EOVERFLOW;
res = res * bytes_per_pixel;
*len = res;
return 0;
}
static int calculate_image_size(const struct spng_ihdr *ihdr, int fmt, size_t *len)
{
if(ihdr == NULL || len == NULL) return SPNG_EINTERNAL;
size_t res = 0;
int ret = calculate_image_width(ihdr, fmt, &res);
if(ret) return ret;
if(res > SIZE_MAX / ihdr->height) return SPNG_EOVERFLOW;
res = res * ihdr->height;
*len = res;
return 0;
}
static int increase_cache_usage(spng_ctx *ctx, size_t bytes, int new_chunk)
{
if(ctx == NULL || !bytes) return SPNG_EINTERNAL;
if(new_chunk)
{
ctx->chunk_count_total++;
if(ctx->chunk_count_total < 1) return SPNG_EOVERFLOW;
if(ctx->chunk_count_total > ctx->chunk_count_limit) return SPNG_ECHUNK_LIMITS;
}
size_t new_usage = ctx->chunk_cache_usage + bytes;
if(new_usage < ctx->chunk_cache_usage) return SPNG_EOVERFLOW;
if(new_usage > ctx->chunk_cache_limit) return SPNG_ECHUNK_LIMITS;
ctx->chunk_cache_usage = new_usage;
return 0;
}
static int decrease_cache_usage(spng_ctx *ctx, size_t usage)
{
if(ctx == NULL || !usage) return SPNG_EINTERNAL;
if(usage > ctx->chunk_cache_usage) return SPNG_EINTERNAL;
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 int decode_err(spng_ctx *ctx, int err)
{
ctx->state = SPNG_STATE_INVALID;
return err;
}
static int encode_err(spng_ctx *ctx, int err)
{
ctx->state = SPNG_STATE_INVALID;
return err;
}
static inline int read_data(spng_ctx *ctx, size_t bytes)
{
if(ctx == NULL) return SPNG_EINTERNAL;
if(!bytes) return 0;
if(ctx->streaming && (bytes > SPNG_READ_SIZE)) return SPNG_EINTERNAL;
int ret = ctx->read_fn(ctx, ctx->stream_user_ptr, ctx->stream_buf, bytes);
if(ret)
{
if(ret > 0 || ret < SPNG_IO_ERROR) ret = SPNG_IO_ERROR;
return ret;
}
ctx->bytes_read += bytes;
if(ctx->bytes_read < bytes) return SPNG_EOVERFLOW;
return 0;
}
/* Ensure there is enough space for encoding starting at ctx->write_ptr */
static int require_bytes(spng_ctx *ctx, size_t bytes)
{
if(ctx == NULL) return SPNG_EINTERNAL;
if(ctx->streaming)
{
if(bytes > ctx->stream_buf_size)
{
size_t new_size = ctx->stream_buf_size;
/* Start at default IDAT size + header + crc */
if(new_size < (SPNG_WRITE_SIZE + 12)) new_size = SPNG_WRITE_SIZE + 12;
if(new_size < bytes) new_size = bytes;
void *temp = spng__realloc(ctx, ctx->stream_buf, new_size);
if(temp == NULL) return encode_err(ctx, SPNG_EMEM);
ctx->stream_buf = temp;
ctx->stream_buf_size = bytes;
ctx->write_ptr = ctx->stream_buf;
}
return 0;
}
if(!ctx->internal_buffer) return SPNG_ENODST;
size_t required = ctx->bytes_encoded + bytes;
if(required < bytes) return SPNG_EOVERFLOW;
if(required > ctx->out_png_size)
{
size_t new_size = ctx->out_png_size;
/* Start with a size that doesn't require a realloc() 100% of the time */
if(new_size < (SPNG_WRITE_SIZE * 2)) new_size = SPNG_WRITE_SIZE * 2;
/* Prefer the next power of two over the requested size */
while(new_size < required)
{
if(new_size / SIZE_MAX > 2) return encode_err(ctx, SPNG_EOVERFLOW);
new_size *= 2;
}
void *temp = spng__realloc(ctx, ctx->out_png, new_size);
if(temp == NULL) return encode_err(ctx, SPNG_EMEM);
ctx->out_png = temp;
ctx->out_png_size = new_size;
ctx->write_ptr = ctx->out_png + ctx->bytes_encoded;
}
return 0;
}
static int write_data(spng_ctx *ctx, const void *data, size_t bytes)
{
if(ctx == NULL) return SPNG_EINTERNAL;
if(!bytes) return 0;
if(ctx->streaming)
{
if(bytes > SPNG_WRITE_SIZE) return SPNG_EINTERNAL;
int ret = ctx->write_fn(ctx, ctx->stream_user_ptr, (void*)data, bytes);
if(ret)
{
if(ret > 0 || ret < SPNG_IO_ERROR) ret = SPNG_IO_ERROR;
return encode_err(ctx, ret);
}
}
else
{
int ret = require_bytes(ctx, bytes);
if(ret) return encode_err(ctx, ret);
memcpy(ctx->write_ptr, data, bytes);
ctx->write_ptr += bytes;
}
ctx->bytes_encoded += bytes;
if(ctx->bytes_encoded < bytes) return SPNG_EOVERFLOW;
return 0;
}
static int write_header(spng_ctx *ctx, const uint8_t chunk_type[4], size_t chunk_length, unsigned char **data)
{
if(ctx == NULL || chunk_type == NULL) return SPNG_EINTERNAL;
if(chunk_length > spng_u32max) return SPNG_EINTERNAL;
size_t total = chunk_length + 12;
int ret = require_bytes(ctx, total);
if(ret) return ret;
uint32_t crc = crc32(0, NULL, 0);
ctx->current_chunk.crc = crc32(crc, chunk_type, 4);
memcpy(&ctx->current_chunk.type, chunk_type, 4);
ctx->current_chunk.length = (uint32_t)chunk_length;
if(!data) return SPNG_EINTERNAL;
if(ctx->streaming) *data = ctx->stream_buf + 8;
else *data = ctx->write_ptr + 8;
return 0;
}
static int trim_chunk(spng_ctx *ctx, uint32_t length)
{
if(length > spng_u32max) return SPNG_EINTERNAL;
if(length > ctx->current_chunk.length) return SPNG_EINTERNAL;
ctx->current_chunk.length = length;
return 0;
}
static int finish_chunk(spng_ctx *ctx)
{
if(ctx == NULL) return SPNG_EINTERNAL;
struct spng_chunk *chunk = &ctx->current_chunk;
unsigned char *header;
unsigned char *chunk_data;
if(ctx->streaming)
{
chunk_data = ctx->stream_buf + 8;
header = ctx->stream_buf;
}
else
{
chunk_data = ctx->write_ptr + 8;
header = ctx->write_ptr;
}
write_u32(header, chunk->length);
memcpy(header + 4, chunk->type, 4);
chunk->crc = crc32(chunk->crc, chunk_data, chunk->length);
write_u32(chunk_data + chunk->length, chunk->crc);
if(ctx->streaming)
{
const unsigned char *ptr = ctx->stream_buf;
uint32_t bytes_left = chunk->length + 12;
uint32_t len = 0;
while(bytes_left)
{
ptr += len;
len = SPNG_WRITE_SIZE;
if(len > bytes_left) len = bytes_left;
int ret = write_data(ctx, ptr, len);
if(ret) return ret;
bytes_left -= len;
}
}
else
{
ctx->bytes_encoded += chunk->length;
if(ctx->bytes_encoded < chunk->length) return SPNG_EOVERFLOW;
ctx->bytes_encoded += 12;
if(ctx->bytes_encoded < 12) return SPNG_EOVERFLOW;
ctx->write_ptr += chunk->length + 12;
}
return 0;
}
static int write_chunk(spng_ctx *ctx, const uint8_t type[4], const void *data, size_t length)
{
if(ctx == NULL || type == NULL) return SPNG_EINTERNAL;
if(length && data == NULL) return SPNG_EINTERNAL;
unsigned char *write_ptr;
int ret = write_header(ctx, type, length, &write_ptr);
if(ret) return ret;
if(length) memcpy(write_ptr, data, length);
return finish_chunk(ctx);
}
static int write_iend(spng_ctx *ctx)
{
unsigned char iend_chunk[12] = { 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130 };
return write_data(ctx, iend_chunk, 12);
}