-
Notifications
You must be signed in to change notification settings - Fork 14
/
ok_png.c
1922 lines (1747 loc) · 69 KB
/
ok_png.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
/*
ok-file-formats
https://github.com/brackeen/ok-file-formats
Copyright (c) 2014-2020 David Brackeen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "ok_png.h"
#include <stdlib.h>
#include <string.h>
#if __STDC_VERSION__ >= 199901L
#define RESTRICT restrict
#else
#define RESTRICT
#endif
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
#define OK_SIZE_MAX (~(size_t)0)
#define PNG_TYPE(a, b, c, d) ((a << 24) | (b << 16) | (c << 8) | d)
static const uint32_t OK_PNG_CHUNK_IHDR = PNG_TYPE('I', 'H', 'D', 'R');
static const uint32_t OK_PNG_CHUNK_PLTE = PNG_TYPE('P', 'L', 'T', 'E');
static const uint32_t OK_PNG_CHUNK_TRNS = PNG_TYPE('t', 'R', 'N', 'S');
static const uint32_t OK_PNG_CHUNK_IDAT = PNG_TYPE('I', 'D', 'A', 'T');
static const uint32_t OK_PNG_CHUNK_IEND = PNG_TYPE('I', 'E', 'N', 'D');
static const uint32_t OK_PNG_CHUNK_CGBI = PNG_TYPE('C', 'g', 'B', 'I');
static const uint8_t OK_PNG_COLOR_TYPE_GRAYSCALE = 0;
static const uint8_t OK_PNG_COLOR_TYPE_RGB = 2;
static const uint8_t OK_PNG_COLOR_TYPE_PALETTE = 3;
static const uint8_t OK_PNG_COLOR_TYPE_GRAYSCALE_WITH_ALPHA = 4;
static const uint8_t OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA = 6;
static const uint8_t OK_PNG_SAMPLES_PER_PIXEL[] = {1, 0, 3, 1, 2, 0, 4};
#ifndef OK_NO_DEFAULT_ALLOCATOR
static void *ok_stdlib_alloc(void *user_data, size_t size) {
(void)user_data;
return malloc(size);
}
static void ok_stdlib_free(void *user_data, void *memory) {
(void)user_data;
free(memory);
}
const ok_png_allocator OK_PNG_DEFAULT_ALLOCATOR = {
.alloc = ok_stdlib_alloc,
.free = ok_stdlib_free,
.image_alloc = NULL
};
#endif
typedef enum {
OK_PNG_FILTER_NONE = 0,
OK_PNG_FILTER_SUB,
OK_PNG_FILTER_UP,
OK_PNG_FILTER_AVG,
OK_PNG_FILTER_PAETH,
OK_PNG_NUM_FILTERS
} ok_png_filter_type;
typedef struct {
// Image
ok_png *png;
// Allocator
ok_png_allocator allocator;
void *allocator_user_data;
// Input
ok_png_input input;
void *input_user_data;
// Decode options
ok_png_decode_flags decode_flags;
// Decoding
ok_inflater *inflater;
size_t inflater_bytes_read;
uint8_t *inflate_buffer;
uint8_t *curr_scanline;
uint8_t *prev_scanline;
uint32_t scanline;
uint8_t interlace_pass; // 0 for uninitialized, 1 for non-interlaced, 1..7 for interlaced
bool ready_for_next_interlace_pass;
uint8_t *temp_data_row;
bool decoding_completed;
// PNG data
uint8_t bit_depth;
uint8_t color_type;
uint8_t interlace_method;
uint8_t palette[256 * 4];
uint32_t palette_length;
uint16_t single_transparent_color_key[3];
bool has_single_transparent_color;
bool is_ios_format;
} ok_png_decoder;
#define ok_alloc(decoder, size) (decoder)->allocator.alloc((decoder)->allocator_user_data, (size))
#define ok_png_error(png, error_code, message) ok_png_set_error((png), (error_code))
static void ok_png_set_error(ok_png *png, ok_png_error error_code) {
if (png) {
png->width = 0;
png->height = 0;
png->error_code = error_code;
}
}
static bool ok_read(ok_png_decoder *decoder, uint8_t *buffer, size_t length) {
if (decoder->input.read(decoder->input_user_data, buffer, length) == length) {
return true;
} else {
ok_png_error(decoder->png, OK_PNG_ERROR_IO, "Read error: error calling input function.");
return false;
}
}
static bool ok_seek(ok_png_decoder *decoder, long length) {
if (decoder->input.seek(decoder->input_user_data, length)) {
return true;
} else {
ok_png_error(decoder->png, OK_PNG_ERROR_IO, "Seek error: error calling input function.");
return false;
}
}
#ifndef OK_NO_STDIO
static size_t ok_file_read(void *user_data, uint8_t *buffer, size_t length) {
return fread(buffer, 1, length, (FILE *)user_data);
}
static bool ok_file_seek(void *user_data, long count) {
return fseek((FILE *)user_data, count, SEEK_CUR) == 0;
}
static const ok_png_input OK_PNG_FILE_INPUT = {
.read = ok_file_read,
.seek = ok_file_seek,
};
#endif
static void ok_png_decode(ok_png *png, ok_png_decode_flags decode_flags,
ok_png_input input, void *input_user_data,
ok_png_allocator allocator, void *allocator_user_data);
// Public API
#if !defined(OK_NO_STDIO) && !defined(OK_NO_DEFAULT_ALLOCATOR)
ok_png ok_png_read(FILE *file, ok_png_decode_flags decode_flags) {
return ok_png_read_with_allocator(file, decode_flags, OK_PNG_DEFAULT_ALLOCATOR, NULL);
}
#endif
#if !defined(OK_NO_STDIO)
ok_png ok_png_read_with_allocator(FILE *file, ok_png_decode_flags decode_flags,
ok_png_allocator allocator, void *allocator_user_data) {
ok_png png = { 0 };
if (file) {
ok_png_decode(&png, decode_flags, OK_PNG_FILE_INPUT, file, allocator, allocator_user_data);
} else {
ok_png_error(&png, OK_PNG_ERROR_API, "File not found");
}
return png;
}
#endif
ok_png ok_png_read_from_input(ok_png_decode_flags decode_flags,
ok_png_input input_callbacks, void *input_callbacks_user_data,
ok_png_allocator allocator, void *allocator_user_data) {
ok_png png = { 0 };
ok_png_decode(&png, decode_flags, input_callbacks, input_callbacks_user_data,
allocator, allocator_user_data);
return png;
}
// Main read functions
static inline uint16_t readBE16(const uint8_t *data) {
return (uint16_t)((data[0] << 8) | data[1]);
}
static inline uint32_t readBE32(const uint8_t *data) {
return (((uint32_t)data[0] << 24) |
((uint32_t)data[1] << 16) |
((uint32_t)data[2] << 8) |
((uint32_t)data[3] << 0));
}
static inline void ok_png_premultiply(uint8_t *dst) {
const uint8_t a = dst[3];
if (a == 0) {
dst[0] = 0;
dst[1] = 0;
dst[2] = 0;
} else if (a < 255) {
dst[0] = (a * dst[0] + 127) / 255;
dst[1] = (a * dst[1] + 127) / 255;
dst[2] = (a * dst[2] + 127) / 255;
}
}
static inline void ok_png_unpremultiply(uint8_t *dst) {
const uint8_t a = dst[3];
if (a > 0 && a < 255) {
dst[0] = 255 * dst[0] / a;
dst[1] = 255 * dst[1] / a;
dst[2] = 255 * dst[2] / a;
}
}
static bool ok_png_read_header(ok_png_decoder *decoder, uint32_t chunk_length) {
ok_png *png = decoder->png;
if (chunk_length != 13) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Invalid IHDR chunk length");
return false;
}
uint8_t chunk_data[13];
if (!ok_read(decoder, chunk_data, sizeof(chunk_data))) {
return false;
}
png->width = readBE32(chunk_data);
png->height = readBE32(chunk_data + 4);
png->bpp = 4; // Always decoding to 32-bit color
decoder->bit_depth = chunk_data[8];
decoder->color_type = chunk_data[9];
uint8_t compression_method = chunk_data[10];
uint8_t filter_method = chunk_data[11];
decoder->interlace_method = chunk_data[12];
uint64_t stride = (uint64_t)png->width * png->bpp;
if (compression_method != 0) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Invalid compression method");
return false;
} else if (filter_method != 0) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Invalid filter method");
return false;
} else if (decoder->interlace_method != 0 && decoder->interlace_method != 1) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Invalid interlace method");
return false;
} else if (stride > UINT32_MAX) {
ok_png_error(png, OK_PNG_ERROR_UNSUPPORTED, "Width too large");
return false;
}
const int c = decoder->color_type;
const int b = decoder->bit_depth;
const bool valid =
(c == OK_PNG_COLOR_TYPE_GRAYSCALE && (b == 1 || b == 2 || b == 4 || b == 8 || b == 16)) ||
(c == OK_PNG_COLOR_TYPE_RGB && (b == 8 || b == 16)) ||
(c == OK_PNG_COLOR_TYPE_PALETTE && (b == 1 || b == 2 || b == 4 || b == 8)) ||
(c == OK_PNG_COLOR_TYPE_GRAYSCALE_WITH_ALPHA && (b == 8 || b == 16)) ||
(c == OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA && (b == 8 || b == 16));
if (!valid) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Invalid combination of color type and bit depth");
return false;
}
png->stride = (uint32_t)stride;
png->has_alpha = (c == OK_PNG_COLOR_TYPE_GRAYSCALE_WITH_ALPHA ||
c == OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA);
decoder->interlace_pass = 0;
decoder->ready_for_next_interlace_pass = true;
return true;
}
static bool ok_png_read_palette(ok_png_decoder *decoder, uint32_t chunk_length) {
ok_png *png = decoder->png;
decoder->palette_length = chunk_length / 3;
if (decoder->palette_length > 256 || decoder->palette_length * 3 != chunk_length) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Invalid palette chunk length");
return false;
}
const bool src_is_bgr = decoder->is_ios_format;
const bool dst_is_bgr = (decoder->decode_flags & OK_PNG_COLOR_FORMAT_BGRA) != 0;
const bool should_byteswap = src_is_bgr != dst_is_bgr;
uint8_t *dst = decoder->palette;
uint8_t buffer[256 * 3];
if (!ok_read(decoder, buffer, 3 * decoder->palette_length)) {
return false;
}
uint8_t *in = buffer;
if (should_byteswap) {
for (uint32_t i = 0; i < decoder->palette_length; i++, in += 3, dst += 4) {
dst[0] = in[2];
dst[1] = in[1];
dst[2] = in[0];
dst[3] = 0xff;
}
} else {
for (uint32_t i = 0; i < decoder->palette_length; i++, in += 3, dst += 4) {
dst[0] = in[0];
dst[1] = in[1];
dst[2] = in[2];
dst[3] = 0xff;
}
}
return true;
}
static bool ok_png_read_transparency(ok_png_decoder *decoder, uint32_t chunk_length) {
ok_png *png = decoder->png;
png->has_alpha = true;
if (decoder->color_type == OK_PNG_COLOR_TYPE_PALETTE) {
if (chunk_length > decoder->palette_length || chunk_length > 256) {
ok_png_error(png, OK_PNG_ERROR_INVALID,
"Invalid transparency length for palette color type");
return false;
}
const bool should_premultiply = (decoder->decode_flags & OK_PNG_PREMULTIPLIED_ALPHA) != 0;
uint8_t *dst = decoder->palette;
uint8_t buffer[256];
if (!ok_read(decoder, buffer, chunk_length)) {
return false;
}
for (uint32_t i = 0; i < chunk_length; i++) {
dst[3] = buffer[i];
if (should_premultiply) {
ok_png_premultiply(dst);
}
dst += 4;
}
return true;
} else if (decoder->color_type == OK_PNG_COLOR_TYPE_GRAYSCALE) {
if (chunk_length != 2) {
ok_png_error(png, OK_PNG_ERROR_INVALID,
"Invalid transparency length for grayscale color type");
return false;
} else {
uint8_t buffer[2];
if (!ok_read(decoder, buffer, sizeof(buffer))) {
return false;
}
const uint16_t v = readBE16(buffer);
decoder->single_transparent_color_key[0] = v;
decoder->single_transparent_color_key[1] = v;
decoder->single_transparent_color_key[2] = v;
decoder->has_single_transparent_color = true;
return true;
}
} else if (decoder->color_type == OK_PNG_COLOR_TYPE_RGB) {
if (chunk_length != 6) {
ok_png_error(png, OK_PNG_ERROR_INVALID,
"Invalid transparency length for truecolor color type");
return false;
} else {
uint8_t buffer[6];
if (!ok_read(decoder, buffer, sizeof(buffer))) {
return false;
}
decoder->single_transparent_color_key[0] = readBE16(buffer + 0);
decoder->single_transparent_color_key[1] = readBE16(buffer + 2);
decoder->single_transparent_color_key[2] = readBE16(buffer + 4);
decoder->has_single_transparent_color = true;
return true;
}
} else {
ok_png_error(png, OK_PNG_ERROR_INVALID,
"Invalid transparency for color type");
return false;
}
}
static inline int ok_png_paeth_predictor(int a, int b, int c) {
int p = a + b - c;
int pa = abs(p - a);
int pb = abs(p - b);
int pc = abs(p - c);
if (pa <= pb && pa <= pc) {
return a;
} else if (pb <= pc) {
return b;
} else {
return c;
}
}
static void ok_png_decode_filter(uint8_t * RESTRICT curr, const uint8_t * RESTRICT prev,
size_t length, int filter, uint8_t bpp) {
switch (filter) {
case OK_PNG_FILTER_NONE:
// Do nothing
break;
case OK_PNG_FILTER_SUB: {
// Input = Sub
// Raw(x) = Sub(x) + Raw(x-bpp)
// For all x < 0, assume Raw(x) = 0.
for (size_t i = bpp; i < length; i++) {
curr[i] = curr[i] + curr[i - bpp];
}
break;
}
case OK_PNG_FILTER_UP: {
// Input = Up
// Raw(x) = Up(x) + Prior(x)
for (size_t i = 0; i < length; i++) {
curr[i] = curr[i] + prev[i];
}
break;
}
case OK_PNG_FILTER_AVG: {
// Input = Average
// Raw(x) = Average(x) + floor((Raw(x-bpp)+Prior(x))/2)
for (size_t i = 0; i < bpp; i++) {
curr[i] = curr[i] + (prev[i] >> 1);
}
for (size_t j = bpp; j < length; j++) {
curr[j] = curr[j] + ((curr[j - bpp] + prev[j]) >> 1);
}
break;
}
case OK_PNG_FILTER_PAETH: {
// Input = Paeth
// Raw(x) = Paeth(x) + PaethPredictor(Raw(x-bpp), Prior(x), Prior(x-bpp))
for (size_t i = 0; i < bpp; i++) {
curr[i] += prev[i];
}
for (size_t j = bpp; j < length; j++) {
curr[j] += ok_png_paeth_predictor(curr[j - bpp], prev[j], prev[j - bpp]);
}
break;
}
}
}
static void ok_png_transform_scanline(ok_png_decoder *decoder, const uint8_t *src, uint32_t width) {
ok_png *png = decoder->png;
const bool dst_flip_y = (decoder->decode_flags & OK_PNG_FLIP_Y) != 0;
uint8_t *dst_start;
uint8_t *dst_end;
if (decoder->interlace_method == 0) {
const uint32_t dst_y =
(dst_flip_y ? (png->height - decoder->scanline - 1) : decoder->scanline);
dst_start = png->data + (dst_y * png->stride);
} else if (decoder->interlace_pass == 7) {
const uint32_t t_scanline = decoder->scanline * 2 + 1;
const uint32_t dst_y = dst_flip_y ? (png->height - t_scanline - 1) : t_scanline;
dst_start = png->data + (dst_y * png->stride);
} else {
dst_start = decoder->temp_data_row;
}
dst_end = dst_start + width * png->bpp;
const int c = decoder->color_type;
const int d = decoder->bit_depth;
const bool t = decoder->has_single_transparent_color;
const bool has_full_alpha = (c == OK_PNG_COLOR_TYPE_GRAYSCALE_WITH_ALPHA ||
c == OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA);
const bool src_is_premultiplied = decoder->is_ios_format;
const bool dst_is_premultiplied = (decoder->decode_flags & OK_PNG_PREMULTIPLIED_ALPHA) != 0;
const bool src_is_bgr = decoder->is_ios_format;
const bool dst_is_bgr = (decoder->decode_flags & OK_PNG_COLOR_FORMAT_BGRA) != 0;
bool should_byteswap = ((c == OK_PNG_COLOR_TYPE_RGB || c == OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA) &&
src_is_bgr != dst_is_bgr);
// Simple transforms
if (c == OK_PNG_COLOR_TYPE_GRAYSCALE && d == 8 && !t) {
uint8_t *dst = dst_start;
while (dst < dst_end) {
uint8_t v = *src++;
*dst++ = v;
*dst++ = v;
*dst++ = v;
*dst++ = 0xff;
}
} else if (c == OK_PNG_COLOR_TYPE_PALETTE && d == 8) {
uint8_t *dst = dst_start;
const uint8_t *palette = decoder->palette;
while (dst < dst_end) {
memcpy(dst, palette + *src * 4, 4);
dst += 4;
src++;
}
} else if (c == OK_PNG_COLOR_TYPE_RGB && d == 8 && !t) {
if (should_byteswap) {
uint8_t *dst = dst_start;
while (dst < dst_end) {
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
dst[3] = 0xff;
src += 3;
dst += 4;
}
should_byteswap = false;
} else {
uint8_t *dst = dst_start;
while (dst < dst_end) {
memcpy(dst, src, 3);
dst[3] = 0xff;
src += 3;
dst += 4;
}
}
} else if (c == OK_PNG_COLOR_TYPE_GRAYSCALE_WITH_ALPHA && d == 8) {
uint8_t *dst = dst_start;
while (dst < dst_end) {
uint8_t v = *src++;
uint8_t a = *src++;
*dst++ = v;
*dst++ = v;
*dst++ = v;
*dst++ = a;
}
} else if (c == OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA && d == 8) {
memcpy(dst_start, src, width * 4);
} else {
// Complex transforms: 1-, 2-, 4- and 16-bit, and 8-bit with single-color transparency.
const uint8_t *palette = decoder->palette;
const int bitmask = (1 << d) - 1;
int bit = 8 - d;
uint16_t tr = decoder->single_transparent_color_key[0];
uint16_t tg = decoder->single_transparent_color_key[1];
uint16_t tb = decoder->single_transparent_color_key[2];
if (d <= 8) {
tr = (uint16_t)((tr & bitmask) * (255 / bitmask));
tg = (uint16_t)((tg & bitmask) * (255 / bitmask));
tb = (uint16_t)((tb & bitmask) * (255 / bitmask));
}
uint8_t *dst = dst_start;
while (dst < dst_end) {
uint16_t r = 0;
uint16_t g = 0;
uint16_t b = 0;
uint16_t a = 0xffff;
if (d < 8) {
if (bit < 0) {
bit = 8 - d;
src++;
}
int v = (*src >> bit) & bitmask;
if (c == OK_PNG_COLOR_TYPE_GRAYSCALE) {
r = g = b = (uint16_t)(v * (255 / bitmask));
} else {
const uint8_t *psrc = palette + (v * 4);
r = *psrc++;
g = *psrc++;
b = *psrc++;
a = *psrc++;
}
bit -= d;
} else if (d == 8) {
if (c == OK_PNG_COLOR_TYPE_GRAYSCALE) {
r = g = b = *src++;
} else if (c == OK_PNG_COLOR_TYPE_PALETTE) {
const uint8_t *psrc = palette + (*src++ * 4);
r = *psrc++;
g = *psrc++;
b = *psrc++;
a = *psrc++;
} else if (c == OK_PNG_COLOR_TYPE_GRAYSCALE_WITH_ALPHA) {
r = g = b = *src++;
a = *src++;
} else if (c == OK_PNG_COLOR_TYPE_RGB) {
r = *src++;
g = *src++;
b = *src++;
} else if (c == OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA) {
r = *src++;
g = *src++;
b = *src++;
a = *src++;
}
} else if (d == 16) {
if (c == OK_PNG_COLOR_TYPE_GRAYSCALE) {
r = g = b = readBE16(src);
src += 2;
} else if (c == OK_PNG_COLOR_TYPE_GRAYSCALE_WITH_ALPHA) {
r = g = b = readBE16(src);
a = readBE16(src + 2);
src += 4;
} else if (c == OK_PNG_COLOR_TYPE_RGB) {
r = readBE16(src);
g = readBE16(src + 2);
b = readBE16(src + 4);
src += 6;
} else if (c == OK_PNG_COLOR_TYPE_RGB_WITH_ALPHA) {
r = readBE16(src);
g = readBE16(src + 2);
b = readBE16(src + 4);
a = readBE16(src + 6);
src += 8;
}
}
if (t && r == tr && g == tg && b == tb) {
a = 0;
if (dst_is_premultiplied) {
r = b = g = 0;
}
}
if (d == 16) {
// This is libpng's formula for scaling 16-bit to 8-bit
r = (r * 255 + 32895) >> 16;
g = (g * 255 + 32895) >> 16;
b = (b * 255 + 32895) >> 16;
a = (a * 255 + 32895) >> 16;
}
if (should_byteswap) {
*dst++ = (uint8_t)b;
*dst++ = (uint8_t)g;
*dst++ = (uint8_t)r;
*dst++ = (uint8_t)a;
} else {
*dst++ = (uint8_t)r;
*dst++ = (uint8_t)g;
*dst++ = (uint8_t)b;
*dst++ = (uint8_t)a;
}
}
should_byteswap = false;
}
// Color format convert: Premultiply, un-premultiply, and swap if needed
if (should_byteswap) {
if (has_full_alpha && src_is_premultiplied && !dst_is_premultiplied) {
// Convert from BGRA_PRE to RGBA
for (uint8_t *dst = dst_start; dst < dst_end; dst += 4) {
const uint8_t v = dst[0];
dst[0] = dst[2];
dst[2] = v;
ok_png_unpremultiply(dst);
}
} else if (has_full_alpha && !src_is_premultiplied && dst_is_premultiplied) {
// Convert from BGRA to RGBA_PRE
for (uint8_t *dst = dst_start; dst < dst_end; dst += 4) {
const uint8_t v = dst[0];
dst[0] = dst[2];
dst[2] = v;
ok_png_premultiply(dst);
}
} else {
// Convert from BGRA to RGBA (or BGRA_PRE to RGBA_PRE)
for (uint8_t *dst = dst_start; dst < dst_end; dst += 4) {
const uint8_t v = dst[0];
dst[0] = dst[2];
dst[2] = v;
}
}
} else if (has_full_alpha) {
if (src_is_premultiplied && !dst_is_premultiplied) {
// Convert from RGBA_PRE to RGBA
for (uint8_t *dst = dst_start; dst < dst_end; dst += 4) {
ok_png_unpremultiply(dst);
}
} else if (!src_is_premultiplied && dst_is_premultiplied) {
// Convert from RGBA to RGBA_PRE
for (uint8_t *dst = dst_start; dst < dst_end; dst += 4) {
ok_png_premultiply(dst);
}
} else {
// Do nothing: Already in correct format, RGBA or RGBA_PRE
}
}
// If interlaced, copy from the temp buffer
if (decoder->interlace_method == 1 && decoder->interlace_pass < 7) {
const int i = decoder->interlace_pass;
const uint32_t s = decoder->scanline;
// 1 2 3 4 5 6 7
static const uint32_t dst_x[] = {0, 0, 4, 0, 2, 0, 1, 0 };
static const uint32_t dst_dx[] = {0, 8, 8, 4, 4, 2, 2, 1 };
const uint32_t dst_y[] = {0, s*8, s*8, 4+s*8, s*4, 2+s*4, s*2, 1+s*2 };
uint32_t x = dst_x[i];
uint32_t y = dst_y[i];
uint32_t dx = 4 * dst_dx[i];
if (dst_flip_y) {
y = (png->height - y - 1);
}
src = dst_start;
uint8_t *src_end = dst_end;
uint8_t *dst = png->data + (y * png->stride) + (x * 4);
while (src < src_end) {
memcpy(dst, src, 4);
dst += dx;
src += 4;
}
}
}
static uint32_t ok_png_get_width_for_pass(const ok_png_decoder *decoder) {
const uint32_t w = decoder->png->width;
if (decoder->interlace_method == 0) {
return w;
}
switch (decoder->interlace_pass) {
case 1: return (w + 7) / 8;
case 2: return (w + 3) / 8;
case 3: return (w + 3) / 4;
case 4: return (w + 1) / 4;
case 5: return (w + 1) / 2;
case 6: return w / 2;
case 7: return w;
default: return 0;
}
}
static uint32_t ok_png_get_height_for_pass(const ok_png_decoder *decoder) {
const uint32_t h = decoder->png->height;
if (decoder->interlace_method == 0) {
return h;
}
switch (decoder->interlace_pass) {
case 1: return (h + 7) / 8;
case 2: return (h + 7) / 8;
case 3: return (h + 3) / 8;
case 4: return (h + 3) / 4;
case 5: return (h + 1) / 4;
case 6: return (h + 1) / 2;
case 7: return h / 2;
default: return 0;
}
}
static bool ok_png_read_data(ok_png_decoder *decoder, uint32_t bytes_remaining) {
ok_png *png = decoder->png;
size_t inflate_buffer_size = 64 * 1024;
size_t num_passes = decoder->interlace_method == 0 ? 1 : 7;
uint8_t bits_per_pixel = decoder->bit_depth * OK_PNG_SAMPLES_PER_PIXEL[decoder->color_type];
uint8_t bytes_per_pixel = (bits_per_pixel + 7) / 8;
uint64_t max_bytes_per_scanline = 1 + ((uint64_t)png->width * bits_per_pixel + 7) / 8;
size_t platform_max_bytes_per_scanline = (size_t)max_bytes_per_scanline;
// Create buffers
if (!png->data) {
if (decoder->allocator.image_alloc) {
decoder->allocator.image_alloc(decoder->allocator_user_data,
png->width, png->height, png->bpp,
&png->data, &png->stride);
} else {
uint64_t size = (uint64_t)png->stride * png->height;
size_t platform_size = (size_t)size;
if (platform_size == size) {
png->data = ok_alloc(decoder, platform_size);
}
}
if (!png->data) {
ok_png_error(png, OK_PNG_ERROR_ALLOCATION, "Couldn't allocate memory for image");
return false;
}
if (png->stride < png->width * png->bpp) {
ok_png_error(png, OK_PNG_ERROR_API, "Invalid stride");
return false;
}
}
if (!decoder->prev_scanline) {
if (max_bytes_per_scanline == platform_max_bytes_per_scanline) {
decoder->prev_scanline = ok_alloc(decoder, platform_max_bytes_per_scanline);
}
}
if (!decoder->curr_scanline) {
if (max_bytes_per_scanline == platform_max_bytes_per_scanline) {
decoder->curr_scanline = ok_alloc(decoder, platform_max_bytes_per_scanline);
}
}
if (!decoder->inflate_buffer) {
decoder->inflate_buffer = ok_alloc(decoder, inflate_buffer_size);
}
if (decoder->interlace_method == 1 && !decoder->temp_data_row) {
decoder->temp_data_row = ok_alloc(decoder, png->width * png->bpp);
}
if (!decoder->curr_scanline || !decoder->prev_scanline || !decoder->inflate_buffer ||
(decoder->interlace_method == 1 && !decoder->temp_data_row)) {
ok_png_error(png, OK_PNG_ERROR_ALLOCATION, "Couldn't allocate buffers");
return false;
}
// Setup inflater
if (!decoder->inflater) {
decoder->inflater = ok_inflater_init(decoder->is_ios_format,
decoder->allocator, decoder->allocator_user_data);
if (!decoder->inflater) {
ok_png_error(png, OK_PNG_ERROR_ALLOCATION, "Couldn't init inflater");
return false;
}
}
// Sanity check - this happened with one file in the PNG suite
if (decoder->decoding_completed) {
if (bytes_remaining > 0) {
return ok_seek(decoder, (long)bytes_remaining);
} else {
return true;
}
}
// Read data
uint32_t curr_width = ok_png_get_width_for_pass(decoder);
uint32_t curr_height = ok_png_get_height_for_pass(decoder);
size_t curr_bytes_per_scanline = (size_t)(1 + ((uint64_t)curr_width * bits_per_pixel + 7) / 8);
while (true) {
// Setup pass
while (decoder->ready_for_next_interlace_pass) {
decoder->ready_for_next_interlace_pass = false;
decoder->scanline = 0;
decoder->interlace_pass++;
if (decoder->interlace_pass == num_passes + 1) {
// Done decoding - skip any remaining chunk data
decoder->decoding_completed = true;
if (bytes_remaining > 0) {
return ok_seek(decoder, (long)bytes_remaining);
} else {
return true;
}
}
curr_width = ok_png_get_width_for_pass(decoder);
curr_height = ok_png_get_height_for_pass(decoder);
curr_bytes_per_scanline = (size_t)(1 + ((uint64_t)curr_width * bits_per_pixel + 7) / 8);
if (curr_width == 0 || curr_height == 0) {
// No data for this pass - happens if width or height <= 4
decoder->ready_for_next_interlace_pass = true;
} else {
memset(decoder->curr_scanline, 0, curr_bytes_per_scanline);
memset(decoder->prev_scanline, 0, curr_bytes_per_scanline);
decoder->inflater_bytes_read = 0;
}
}
// Read compressed data
if (ok_inflater_needs_input(decoder->inflater)) {
if (bytes_remaining == 0) {
// Need more data, but there is no remaining data in this chunk.
// There may be another IDAT chunk.
return true;
}
const size_t len = min(inflate_buffer_size, bytes_remaining);
if (!ok_read(decoder, decoder->inflate_buffer, len)) {
return false;
}
bytes_remaining -= len;
ok_inflater_set_input(decoder->inflater, decoder->inflate_buffer, len);
}
// Decompress data
size_t len = ok_inflater_inflate(decoder->inflater,
decoder->curr_scanline + decoder->inflater_bytes_read,
curr_bytes_per_scanline - decoder->inflater_bytes_read);
if (len == OK_SIZE_MAX) {
ok_png_error(png, OK_PNG_ERROR_INFLATER, "Inflater error");
return false;
}
decoder->inflater_bytes_read += len;
if (decoder->inflater_bytes_read == curr_bytes_per_scanline) {
// Apply filter
const int filter = decoder->curr_scanline[0];
if (filter > 0 && filter < OK_PNG_NUM_FILTERS) {
ok_png_decode_filter(decoder->curr_scanline + 1, decoder->prev_scanline + 1,
curr_bytes_per_scanline - 1, filter, bytes_per_pixel);
} else if (filter != 0) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Invalid filter type");
return false;
}
// Transform
ok_png_transform_scanline(decoder, decoder->curr_scanline + 1, curr_width);
// Setup for next scanline or pass
decoder->scanline++;
if (decoder->scanline == curr_height) {
decoder->ready_for_next_interlace_pass = true;
} else {
uint8_t *temp = decoder->curr_scanline;
decoder->curr_scanline = decoder->prev_scanline;
decoder->prev_scanline = temp;
decoder->inflater_bytes_read = 0;
}
}
}
}
static void ok_png_decode2(ok_png_decoder *decoder) {
ok_png *png = decoder->png;
uint8_t png_header[8];
if (!ok_read(decoder, png_header, sizeof(png_header))) {
return;
}
uint8_t png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
if (memcmp(png_header, png_signature, 8) != 0) {
ok_png_error(decoder->png, OK_PNG_ERROR_INVALID, "Invalid signature (not a PNG file)");
return;
}
// When info_only is true, we only care about the IHDR chunk and whether or not
// the tRNS chunk exists.
bool info_only = (decoder->decode_flags & OK_PNG_INFO_ONLY) != 0;
bool hdr_found = false;
bool end_found = false;
while (!end_found) {
uint8_t chunk_header[8];
uint8_t chunk_footer[4];
if (!ok_read(decoder, chunk_header, sizeof(chunk_header))) {
return;
}
const uint32_t chunk_length = readBE32(chunk_header);
const uint32_t chunk_type = readBE32(chunk_header + 4);
bool success = false;
if (!hdr_found && chunk_type != OK_PNG_CHUNK_CGBI && chunk_type != OK_PNG_CHUNK_IHDR) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "IHDR chunk must appear first");
return;
}
if (chunk_type == OK_PNG_CHUNK_IHDR) {
if (hdr_found) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Multiple IHDR chunks not allowed");
return;
}
hdr_found = true;
success = ok_png_read_header(decoder, chunk_length);
if (success && info_only) {
// If the png has alpha, then we have all the info we need.
// Otherwise, continue scanning to see if the tRNS chunk exists.
if (png->has_alpha) {
return;
}
}
} else if (chunk_type == OK_PNG_CHUNK_CGBI) {
success = ok_seek(decoder, (long)chunk_length);
decoder->is_ios_format = true;
} else if (chunk_type == OK_PNG_CHUNK_PLTE && !info_only) {
success = ok_png_read_palette(decoder, chunk_length);
} else if (chunk_type == OK_PNG_CHUNK_TRNS) {
if (info_only) {
// No need to parse this chunk, we have all the info we need.
png->has_alpha = true;
return;
} else {
success = ok_png_read_transparency(decoder, chunk_length);
}
} else if (chunk_type == OK_PNG_CHUNK_IDAT) {
if (info_only) {
// Both IHDR and tRNS must come before IDAT, so we have all the info we need.
return;
}
success = ok_png_read_data(decoder, chunk_length);
} else if (chunk_type == OK_PNG_CHUNK_IEND) {
success = ok_seek(decoder, (long)chunk_length);
end_found = true;
} else {
// Ignore this chunk
success = ok_seek(decoder, (long)chunk_length);
}
if (!success) {
return;
}
// Read the footer (CRC) and ignore it
if (!ok_read(decoder, chunk_footer, sizeof(chunk_footer))) {
return;
}
}
// Sanity check
if (!decoder->decoding_completed) {
ok_png_error(png, OK_PNG_ERROR_INVALID, "Missing imaga data");
}
}
void ok_png_decode(ok_png *png, ok_png_decode_flags decode_flags,