-
Notifications
You must be signed in to change notification settings - Fork 270
/
cute_png.h
1850 lines (1566 loc) · 50.4 KB
/
cute_png.h
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
/*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
cute_png.h - v1.05
To create implementation (the function definitions)
#define CUTE_PNG_IMPLEMENTATION
in *one* C/CPP file (translation unit) that includes this file
SUMMARY:
This header wraps some very nice functions by Richard Mitton from his
tigr (Tiny Graphics) library, with some additional features and small
bug-fixes.
Revision history:
1.00 (12/23/2016) initial release
1.01 (03/08/2017) tRNS chunk support for paletted images
1.02 (10/23/2017) support for explicitly loading paletted png images
1.03 (11/12/2017) construct atlas in memory
1.04 (08/23/2018) various bug fixes for filter and word decoder
added `cp_load_blank`
1.05 (11/10/2022) added `cp_save_png_to_memory`
EXAMPLES:
Loading a PNG from disk, then freeing it
cp_image_t img = cp_load_png("images/pic.png");
...
free(img.pix);
CUTE_PNG_MEMSET(&img, 0, sizeof(img));
Loading a PNG from memory, then freeing it
cp_image_t img = cp_load_png_mem(memory, sizeof(memory));
...
free(img.pix);
CUTE_PNG_MEMSET(&img, 0, sizeof(img));
Saving a PNG to disk
cp_save_png("images/example.png", &img);
// img is just a raw RGBA buffer, and can come from anywhere,
// not only from cp_load*** functions
Creating a texture atlas in memory
int w = 1024;
int h = 1024;
cp_atlas_image_t* imgs_out = (cp_atlas_image_t*)malloc(sizeof(cp_atlas_image_t) * my_png_count);
cp_image_t atlas_img = cp_make_atlas(w, int h, my_png_array, my_png_count, imgs_out);
// just pass an array of pointers to images along with the image count. Make sure to also
// provide an array of `cp_atlas_image_t` for `cp_make_atlas` to output important UV info for the
// images that fit into the atlas.
Using the default atlas saver
int errors = cp_default_save_atlas("atlas.png", "atlas.txt", atlas_img, atlas_imgs, img_count, names_of_all_images ? names_of_all_images : 0);
if (errors) { ... }
// Atlas info (like uv coordinates) are in "atlas.txt", and the image was writen to "atlas.png".
// atlas_imgs was an array of `cp_atlas_image_t` from the `cp_make_atlas` function.
Inflating a DEFLATE block (decompressing memory stored in DEFLATE format)
cp_inflate(in, in_bytes, out, out_bytes);
// this function requires knowledge of the un-compressed size
// does *not* do any internal realloc! Will return errors if an
// attempt to overwrite the out buffer is made
CUSTOMIZATION
There are various macros in this header you can customize by defining them before
including cute_png.h. Simply define one to override the default behavior.
CUTE_PNG_ALLOCA
CUTE_PNG_ALLOC
CUTE_PNG_FREE
CUTE_PNG_CALLOC
CUTE_PNG_REALLOC
CUTE_PNG_MEMCPY
CUTE_PNG_MEMCMP
CUTE_PNG_MEMSET
CUTE_PNG_ASSERT
CUTE_PNG_FPRINTF
CUTE_PNG_SEEK_SET
CUTE_PNG_SEEK_END
CUTE_PNG_FILE
CUTE_PNG_FOPEN
CUTE_PNG_FSEEK
CUTE_PNG_FREAD
CUTE_PNG_FTELL
CUTE_PNG_FWRITE
CUTE_PNG_FCLOSE
CUTE_PNG_FERROR
CUTE_PNG_ATLAS_MUST_FIT
CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV
CUTE_PNG_ATLAS_EMPTY_COLOR
*/
/*
Contributors:
Zachary Carter 1.01 - bug catch for tRNS chunk in paletted images
Dennis Korpel 1.03 - fix some pointer/memory related bugs
Dennis Korpel 1.04 - fix for filter on first row of pixels
*/
#if !defined(CUTE_PNG_H)
#ifdef _WIN32
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#endif
#ifndef CUTE_PNG_ATLAS_MUST_FIT
#define CUTE_PNG_ATLAS_MUST_FIT 1 // returns error from cp_make_atlas if *any* input image does not fit
#endif // CUTE_PNG_ATLAS_MUST_FIT
#ifndef CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV
#define CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV 1 // flips output uv coordinate's y. Can be useful to "flip image on load"
#endif // CUTE_PNG_ATLAS_FLIP_Y_AXIS_FOR_UV
#ifndef CUTE_PNG_ATLAS_EMPTY_COLOR
#define CUTE_PNG_ATLAS_EMPTY_COLOR 0x000000FF // the fill color for empty areas in a texture atlas (RGBA)
#endif // CUTE_PNG_ATLAS_EMPTY_COLOR
#include <stdint.h>
#include <limits.h>
typedef struct cp_pixel_t cp_pixel_t;
typedef struct cp_image_t cp_image_t;
typedef struct cp_indexed_image_t cp_indexed_image_t;
typedef struct cp_atlas_image_t cp_atlas_image_t;
// Read this in the event of errors from any function
extern const char* cp_error_reason;
// return 1 for success, 0 for failures
int cp_inflate(void* in, int in_bytes, void* out, int out_bytes);
int cp_save_png(const char* file_name, const cp_image_t* img);
typedef struct cp_saved_png_t
{
int size; // Size of the `data` buffer.
void* data; // Pointer to the saved png in memory.
// NULL if something went wrong.
// Call CUTE_PNG_FREE on `data` when done.
} cp_saved_png_t;
// Saves a png file to memory.
// Call CUTE_PNG_FREE on .data when done.
cp_saved_png_t cp_save_png_to_memory(const cp_image_t* img);
// Constructs an atlas image in-memory. The atlas pixels are stored in the returned image. free the pixels
// when done with them. The user must provide an array of cp_atlas_image_t for the `imgs` param. `imgs` holds
// information about uv coordinates for an associated image in the `pngs` array. Output image has NULL
// pixels buffer in the event of errors.
cp_image_t cp_make_atlas(int atlasWidth, int atlasHeight, const cp_image_t* pngs, int png_count, cp_atlas_image_t* imgs_out);
// A decent "default" function, ready to use out-of-the-box. Saves out an easy to parse text formatted info file
// along with an atlas image. `names` param can be optionally NULL.
int cp_default_save_atlas(const char* out_path_image, const char* out_path_atlas_txt, const cp_image_t* atlas, const cp_atlas_image_t* imgs, int img_count, const char** names);
// these two functions return cp_image_t::pix as 0 in event of errors
// call free on cp_image_t::pix when done, or call cp_free_png
cp_image_t cp_load_png(const char *file_name);
cp_image_t cp_load_png_mem(const void *png_data, int png_length);
cp_image_t cp_load_blank(int w, int h); // Alloc's pixels, but `pix` memory is uninitialized.
void cp_free_png(cp_image_t* img);
void cp_flip_image_horizontal(cp_image_t* img);
// Reads the w/h of the png without doing any other decompression or parsing.
void cp_load_png_wh(const void* png_data, int png_length, int* w, int* h);
// loads indexed (paletted) pngs, but does not depalette the image into RGBA pixels
// these two functions return cp_indexed_image_t::pix as 0 in event of errors
// call free on cp_indexed_image_t::pix when done, or call cp_free_indexed_png
cp_indexed_image_t cp_load_indexed_png(const char* file_name);
cp_indexed_image_t cp_load_indexed_png_mem(const void *png_data, int png_length);
void cp_free_indexed_png(cp_indexed_image_t* img);
// converts paletted image into a standard RGBA image
// call free on cp_image_t::pix when done
cp_image_t cp_depallete_indexed_image(cp_indexed_image_t* img);
// Pre-process the pixels to transform the image data to a premultiplied alpha format.
// Resource: http://www.essentialmath.com/GDC2015/VanVerth_Jim_DoingMathwRGB.pdf
void cp_premultiply(cp_image_t* img);
struct cp_pixel_t
{
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
struct cp_image_t
{
int w;
int h;
cp_pixel_t* pix;
};
struct cp_indexed_image_t
{
int w;
int h;
uint8_t* pix;
uint8_t palette_len;
cp_pixel_t palette[256];
};
struct cp_atlas_image_t
{
int img_index; // index into the `imgs` array
int w, h; // pixel w/h of original image
float minx, miny; // u coordinate
float maxx, maxy; // v coordinate
int fit; // non-zero if image fit and was placed into the atlas
};
#define CUTE_PNG_H
#endif
#ifdef CUTE_PNG_IMPLEMENTATION
#ifndef CUTE_PNG_IMPLEMENTATION_ONCE
#define CUTE_PNG_IMPLEMENTATION_ONCE
#if !defined(CUTE_PNG_ALLOCA)
#define CUTE_PNG_ALLOCA alloca
#ifdef _WIN32
#include <malloc.h>
#elif defined(__linux__)
#include <alloca.h>
#endif
#endif
#if !defined(CUTE_PNG_ALLOC)
#include <stdlib.h>
#define CUTE_PNG_ALLOC malloc
#endif
#if !defined(CUTE_PNG_FREE)
#include <stdlib.h>
#define CUTE_PNG_FREE free
#endif
#if !defined(CUTE_PNG_CALLOC)
#include <stdlib.h>
#define CUTE_PNG_CALLOC calloc
#endif
#if !defined(CUTE_PNG_REALLOC)
#include <stdlib.h>
#define CUTE_PNG_REALLOC realloc
#endif
#if !defined(CUTE_PNG_MEMCPY)
#include <string.h>
#define CUTE_PNG_MEMCPY memcpy
#endif
#if !defined(CUTE_PNG_MEMCMP)
#include <string.h>
#define CUTE_PNG_MEMCMP memcmp
#endif
#if !defined(CUTE_PNG_MEMSET)
#include <string.h>
#define CUTE_PNG_MEMSET memset
#endif
#if !defined(CUTE_PNG_ASSERT)
#include <assert.h>
#define CUTE_PNG_ASSERT assert
#endif
#if !defined(CUTE_PNG_FPRINTF)
#include <stdio.h>
#define CUTE_PNG_FPRINTF fprintf
#endif
#if !defined(CUTE_PNG_SEEK_SET)
#include <stdio.h>
#define CUTE_PNG_SEEK_SET SEEK_SET
#endif
#if !defined(CUTE_PNG_SEEK_END)
#include <stdio.h>
#define CUTE_PNG_SEEK_END SEEK_END
#endif
#if !defined(CUTE_PNG_FILE)
#include <stdio.h>
#define CUTE_PNG_FILE FILE
#endif
#if !defined(CUTE_PNG_FOPEN)
#include <stdio.h>
#define CUTE_PNG_FOPEN fopen
#endif
#if !defined(CUTE_PNG_FSEEK)
#include <stdio.h>
#define CUTE_PNG_FSEEK fseek
#endif
#if !defined(CUTE_PNG_FREAD)
#include <stdio.h>
#define CUTE_PNG_FREAD fread
#endif
#if !defined(CUTE_PNG_FTELL)
#include <stdio.h>
#define CUTE_PNG_FTELL ftell
#endif
#if !defined(CUTE_PNG_FWRITE)
#include <stdio.h>
#define CUTE_PNG_FWRITE fwrite
#endif
#if !defined(CUTE_PNG_FCLOSE)
#include <stdio.h>
#define CUTE_PNG_FCLOSE fclose
#endif
#if !defined(CUTE_PNG_FERROR)
#include <stdio.h>
#define CUTE_PNG_FERROR ferror
#endif
static cp_pixel_t cp_make_pixel_a(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
cp_pixel_t p;
p.r = r; p.g = g; p.b = b; p.a = a;
return p;
}
static cp_pixel_t cp_make_pixel(uint8_t r, uint8_t g, uint8_t b)
{
cp_pixel_t p;
p.r = r; p.g = g; p.b = b; p.a = 0xFF;
return p;
}
const char* cp_error_reason;
#define CUTE_PNG_FAIL() do { goto cp_err; } while (0)
#define CUTE_PNG_CHECK(X, Y) do { if (!(X)) { cp_error_reason = Y; CUTE_PNG_FAIL(); } } while (0)
#define CUTE_PNG_CALL(X) do { if (!(X)) goto cp_err; } while (0)
#define CUTE_PNG_LOOKUP_BITS 9
#define CUTE_PNG_LOOKUP_COUNT (1 << CUTE_PNG_LOOKUP_BITS)
#define CUTE_PNG_LOOKUP_MASK (CUTE_PNG_LOOKUP_COUNT - 1)
#define CUTE_PNG_DEFLATE_MAX_BITLEN 15
// DEFLATE tables from RFC 1951
uint8_t cp_fixed_table[288 + 32] = {
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
}; // 3.2.6
uint8_t cp_permutation_order[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; // 3.2.7
uint8_t cp_len_extra_bits[29 + 2] = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0, 0,0 }; // 3.2.5
uint32_t cp_len_base[29 + 2] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 0,0 }; // 3.2.5
uint8_t cp_dist_extra_bits[30 + 2] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13, 0,0 }; // 3.2.5
uint32_t cp_dist_base[30 + 2] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 0,0 }; // 3.2.5
typedef struct cp_state_t
{
uint64_t bits;
int count;
uint32_t* words;
int word_count;
int word_index;
int bits_left;
int final_word_available;
uint32_t final_word;
char* out;
char* out_end;
char* begin;
uint16_t lookup[CUTE_PNG_LOOKUP_COUNT];
uint32_t lit[288];
uint32_t dst[32];
uint32_t len[19];
uint32_t nlit;
uint32_t ndst;
uint32_t nlen;
} cp_state_t;
static int cp_would_overflow(cp_state_t* s, int num_bits)
{
return (s->bits_left + s->count) - num_bits < 0;
}
static char* cp_ptr(cp_state_t* s)
{
CUTE_PNG_ASSERT(!(s->bits_left & 7));
return (char*)(s->words + s->word_index) - (s->count / 8);
}
static uint64_t cp_peak_bits(cp_state_t* s, int num_bits_to_read)
{
if (s->count < num_bits_to_read)
{
if (s->word_index < s->word_count)
{
uint32_t word = s->words[s->word_index++];
s->bits |= (uint64_t)word << s->count;
s->count += 32;
CUTE_PNG_ASSERT(s->word_index <= s->word_count);
}
else if (s->final_word_available)
{
uint32_t word = s->final_word;
s->bits |= (uint64_t)word << s->count;
s->count += s->bits_left;
s->final_word_available = 0;
}
}
return s->bits;
}
static uint32_t cp_consume_bits(cp_state_t* s, int num_bits_to_read)
{
CUTE_PNG_ASSERT(s->count >= num_bits_to_read);
uint32_t bits = s->bits & (((uint64_t)1 << num_bits_to_read) - 1);
s->bits >>= num_bits_to_read;
s->count -= num_bits_to_read;
s->bits_left -= num_bits_to_read;
return bits;
}
static uint32_t cp_read_bits(cp_state_t* s, int num_bits_to_read)
{
CUTE_PNG_ASSERT(num_bits_to_read <= 32);
CUTE_PNG_ASSERT(num_bits_to_read >= 0);
CUTE_PNG_ASSERT(s->bits_left > 0);
CUTE_PNG_ASSERT(s->count <= 64);
CUTE_PNG_ASSERT(!cp_would_overflow(s, num_bits_to_read));
cp_peak_bits(s, num_bits_to_read);
uint32_t bits = cp_consume_bits(s, num_bits_to_read);
return bits;
}
static char* cp_read_file_to_memory(const char* path, int* size)
{
char* data = 0;
CUTE_PNG_FILE* fp = CUTE_PNG_FOPEN(path, "rb");
int sizeNum = 0;
if (fp)
{
CUTE_PNG_FSEEK(fp, 0, CUTE_PNG_SEEK_END);
sizeNum = CUTE_PNG_FTELL(fp);
CUTE_PNG_FSEEK(fp, 0, CUTE_PNG_SEEK_SET);
data = (char*)CUTE_PNG_ALLOC(sizeNum + 1);
CUTE_PNG_FREAD(data, sizeNum, 1, fp);
data[sizeNum] = 0;
CUTE_PNG_FCLOSE(fp);
}
if (size) *size = sizeNum;
return data;
}
static uint32_t cp_rev16(uint32_t a)
{
a = ((a & 0xAAAA) >> 1) | ((a & 0x5555) << 1);
a = ((a & 0xCCCC) >> 2) | ((a & 0x3333) << 2);
a = ((a & 0xF0F0) >> 4) | ((a & 0x0F0F) << 4);
a = ((a & 0xFF00) >> 8) | ((a & 0x00FF) << 8);
return a;
}
// RFC 1951 section 3.2.2
static int cp_build(cp_state_t* s, uint32_t* tree, uint8_t* lens, int sym_count)
{
int n, codes[16], first[16], counts[16] = { 0 };
// Frequency count
for (n = 0; n < sym_count; n++) counts[lens[n]]++;
// Distribute codes
counts[0] = codes[0] = first[0] = 0;
for (n = 1; n <= 15; ++n)
{
codes[n] = (codes[n - 1] + counts[n - 1]) << 1;
first[n] = first[n - 1] + counts[n - 1];
}
if (s) CUTE_PNG_MEMSET(s->lookup, 0, sizeof(s->lookup));
for (int i = 0; i < sym_count; ++i)
{
int len = lens[i];
if (len != 0)
{
CUTE_PNG_ASSERT(len < 16);
uint32_t code = codes[len]++;
uint32_t slot = first[len]++;
tree[slot] = (code << (32 - len)) | (i << 4) | len;
if (s && len <= CUTE_PNG_LOOKUP_BITS)
{
int j = cp_rev16(code) >> (16 - len);
while (j < (1 << CUTE_PNG_LOOKUP_BITS))
{
s->lookup[j] = (uint16_t)((len << CUTE_PNG_LOOKUP_BITS) | i);
j += (1 << len);
}
}
}
}
int max_index = first[15];
return max_index;
}
static int cp_stored(cp_state_t* s)
{
char* p;
// 3.2.3
// skip any remaining bits in current partially processed byte
cp_read_bits(s, s->count & 7);
// 3.2.4
// read LEN and NLEN, should complement each other
uint16_t LEN = (uint16_t)cp_read_bits(s, 16);
uint16_t NLEN = (uint16_t)cp_read_bits(s, 16);
CUTE_PNG_CHECK(LEN == (uint16_t)(~NLEN), "Failed to find LEN and NLEN as complements within stored (uncompressed) stream.");
CUTE_PNG_CHECK(s->bits_left / 8 <= (int)LEN, "Stored block extends beyond end of input stream.");
p = cp_ptr(s);
CUTE_PNG_MEMCPY(s->out, p, LEN);
s->out += LEN;
return 1;
cp_err:
return 0;
}
// 3.2.6
static int cp_fixed(cp_state_t* s)
{
s->nlit = cp_build(s, s->lit, cp_fixed_table, 288);
s->ndst = cp_build(0, s->dst, cp_fixed_table + 288, 32);
return 1;
}
static int cp_decode(cp_state_t* s, uint32_t* tree, int hi)
{
uint64_t bits = cp_peak_bits(s, 16);
uint32_t search = (cp_rev16((uint32_t)bits) << 16) | 0xFFFF;
int lo = 0;
while (lo < hi)
{
int guess = (lo + hi) >> 1;
if (search < tree[guess]) hi = guess;
else lo = guess + 1;
}
uint32_t key = tree[lo - 1];
uint32_t len = (32 - (key & 0xF));
CUTE_PNG_ASSERT((search >> len) == (key >> len));
int code = cp_consume_bits(s, key & 0xF);
(void)code;
return (key >> 4) & 0xFFF;
}
// 3.2.7
static int cp_dynamic(cp_state_t* s)
{
uint8_t lenlens[19] = { 0 };
int nlit = 257 + cp_read_bits(s, 5);
int ndst = 1 + cp_read_bits(s, 5);
int nlen = 4 + cp_read_bits(s, 4);
for (int i = 0 ; i < nlen; ++i)
lenlens[cp_permutation_order[i]] = (uint8_t)cp_read_bits(s, 3);
// Build the tree for decoding code lengths
s->nlen = cp_build(0, s->len, lenlens, 19);
uint8_t lens[288 + 32];
for (int n = 0; n < nlit + ndst;)
{
int sym = cp_decode(s, s->len, s->nlen);
switch (sym)
{
case 16: for (int i = 3 + cp_read_bits(s, 2); i; --i, ++n) lens[n] = lens[n - 1]; break;
case 17: for (int i = 3 + cp_read_bits(s, 3); i; --i, ++n) lens[n] = 0; break;
case 18: for (int i = 11 + cp_read_bits(s, 7); i; --i, ++n) lens[n] = 0; break;
default: lens[n++] = (uint8_t)sym; break;
}
}
s->nlit = cp_build(s, s->lit, lens, nlit);
s->ndst = cp_build(0, s->dst, lens + nlit, ndst);
return 1;
}
// 3.2.3
static int cp_block(cp_state_t* s)
{
while (1)
{
int symbol = cp_decode(s, s->lit, s->nlit);
if (symbol < 256)
{
CUTE_PNG_CHECK(s->out + 1 <= s->out_end, "Attempted to overwrite out buffer while outputting a symbol.");
*s->out = (char)symbol;
s->out += 1;
}
else if (symbol > 256)
{
symbol -= 257;
int length = cp_read_bits(s, cp_len_extra_bits[symbol]) + cp_len_base[symbol];
int distance_symbol = cp_decode(s, s->dst, s->ndst);
int backwards_distance = cp_read_bits(s, cp_dist_extra_bits[distance_symbol]) + cp_dist_base[distance_symbol];
CUTE_PNG_CHECK(s->out - backwards_distance >= s->begin, "Attempted to write before out buffer (invalid backwards distance).");
CUTE_PNG_CHECK(s->out + length <= s->out_end, "Attempted to overwrite out buffer while outputting a string.");
char* src = s->out - backwards_distance;
char* dst = s->out;
s->out += length;
switch (backwards_distance)
{
case 1: // very common in images
CUTE_PNG_MEMSET(dst, *src, length);
break;
default: while (length--) *dst++ = *src++;
}
}
else break;
}
return 1;
cp_err:
return 0;
}
// 3.2.3
int cp_inflate(void* in, int in_bytes, void* out, int out_bytes)
{
cp_state_t* s = (cp_state_t*)CUTE_PNG_CALLOC(1, sizeof(cp_state_t));
s->bits = 0;
s->count = 0;
s->word_index = 0;
s->bits_left = in_bytes * 8;
// s->words is the in-pointer rounded up to a multiple of 4
int first_bytes = (int) ((( (size_t) in + 3) & ~3) - (size_t) in);
s->words = (uint32_t*)((char*)in + first_bytes);
s->word_count = (in_bytes - first_bytes) / 4;
int last_bytes = ((in_bytes - first_bytes) & 3);
for (int i = 0; i < first_bytes; ++i)
s->bits |= (uint64_t)(((uint8_t*)in)[i]) << (i * 8);
s->final_word_available = last_bytes ? 1 : 0;
s->final_word = 0;
for(int i = 0; i < last_bytes; i++)
s->final_word |= ((uint8_t*)in)[in_bytes - last_bytes+i] << (i * 8);
s->count = first_bytes * 8;
s->out = (char*)out;
s->out_end = s->out + out_bytes;
s->begin = (char*)out;
int count = 0;
int bfinal;
do
{
bfinal = cp_read_bits(s, 1);
int btype = cp_read_bits(s, 2);
switch (btype)
{
case 0: CUTE_PNG_CALL(cp_stored(s)); break;
case 1: cp_fixed(s); CUTE_PNG_CALL(cp_block(s)); break;
case 2: cp_dynamic(s); CUTE_PNG_CALL(cp_block(s)); break;
case 3: CUTE_PNG_CHECK(0, "Detected unknown block type within input stream.");
}
++count;
}
while (!bfinal);
CUTE_PNG_FREE(s);
return 1;
cp_err:
CUTE_PNG_FREE(s);
return 0;
}
static uint8_t cp_paeth(uint8_t a, uint8_t b, uint8_t c)
{
int p = a + b - c;
int pa = abs(p - a);
int pb = abs(p - b);
int pc = abs(p - c);
return (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c;
}
typedef struct cp_save_png_data_t
{
uint32_t crc;
uint32_t adler;
uint32_t bits;
uint32_t prev;
uint32_t runlen;
int buflen;
int bufcap;
char* buffer;
} cp_save_png_data_t;
uint32_t CP_CRC_TABLE[] = {
0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
};
static void cp_put8(cp_save_png_data_t* s, uint32_t a)
{
if (s->buflen >= s->bufcap)
{
s->bufcap *= 2;
s->buffer = (char*)CUTE_PNG_REALLOC(s->buffer, s->bufcap);
}
s->buffer[s->buflen++] = a;
s->crc = (s->crc >> 4) ^ CP_CRC_TABLE[(s->crc & 15) ^ (a & 15)];
s->crc = (s->crc >> 4) ^ CP_CRC_TABLE[(s->crc & 15) ^ (a >> 4)];
}
static void cp_update_adler(cp_save_png_data_t* s, uint32_t v)
{
uint32_t s1 = s->adler & 0xFFFF;
uint32_t s2 = (s->adler >> 16) & 0xFFFF;
s1 = (s1 + v) % 65521;
s2 = (s2 + s1) % 65521;
s->adler = (s2 << 16) + s1;
}
static void cp_put32(cp_save_png_data_t* s, uint32_t v)
{
cp_put8(s, (v >> 24) & 0xFF);
cp_put8(s, (v >> 16) & 0xFF);
cp_put8(s, (v >> 8) & 0xFF);
cp_put8(s, v & 0xFF);
}
static void cp_put_bits(cp_save_png_data_t* s, uint32_t data, uint32_t bitcount)
{
while (bitcount--)
{
uint32_t prev = s->bits;
s->bits = (s->bits >> 1) | ((data & 1) << 7);
data >>= 1;
if (prev & 1)
{
cp_put8(s, s->bits);
s->bits = 0x80;
}
}
}
static void cp_put_bitsr(cp_save_png_data_t* s, uint32_t data, uint32_t bitcount)
{
while (bitcount--)
cp_put_bits(s, data >> bitcount, 1);
}
static void cp_begin_chunk(cp_save_png_data_t* s, const char* id, uint32_t len)
{
cp_put32(s, len);
s->crc = 0xFFFFFFFF;
cp_put8(s, (unsigned char)id[0]);
cp_put8(s, (unsigned char)id[1]);
cp_put8(s, (unsigned char)id[2]);
cp_put8(s, (unsigned char)id[3]);
}
static void cp_encode_literal(cp_save_png_data_t* s, uint32_t v)
{
// Encode a literal/length using the built-in tables.
// Could do better with a custom table but whatever.
if (v < 144) cp_put_bitsr(s, 0x030 + v - 0, 8);
else if (v < 256) cp_put_bitsr(s, 0x190 + v - 144, 9);
else if (v < 280) cp_put_bitsr(s, 0x000 + v - 256, 7);
else cp_put_bitsr(s, 0x0c0 + v - 280, 8);
}
static void cp_encode_len(cp_save_png_data_t* s, uint32_t code, uint32_t bits, uint32_t len)
{
cp_encode_literal(s, code + (len >> bits));
cp_put_bits(s, len, bits);
cp_put_bits(s, 0, 5);
}
static void cp_end_run(cp_save_png_data_t* s)
{
s->runlen--;
cp_encode_literal(s, s->prev);
if (s->runlen >= 67) cp_encode_len(s, 277, 4, s->runlen - 67);
else if (s->runlen >= 35) cp_encode_len(s, 273, 3, s->runlen - 35);
else if (s->runlen >= 19) cp_encode_len(s, 269, 2, s->runlen - 19);
else if (s->runlen >= 11) cp_encode_len(s, 265, 1, s->runlen - 11);
else if (s->runlen >= 3) cp_encode_len(s, 257, 0, s->runlen - 3);
else while (s->runlen--) cp_encode_literal(s, s->prev);
}
static void cp_encode_byte(cp_save_png_data_t *s, uint8_t v)
{
cp_update_adler(s, v);
// Simple RLE compression. We could do better by doing a search
// to find matches, but this works pretty well TBH.
if (s->prev == v && s->runlen < 115) s->runlen++;
else
{
if (s->runlen) cp_end_run(s);
s->prev = v;
s->runlen = 1;
}
}
static void cp_save_header(cp_save_png_data_t* s, cp_image_t* img)
{
const unsigned char* hdr = (const unsigned char*)"\211PNG\r\n\032\n";
for (int i = 0; i < 8; ++i) {
cp_put8(s, *hdr++);
}
cp_begin_chunk(s, "IHDR", 13);
cp_put32(s, img->w);
cp_put32(s, img->h);
cp_put8(s, 8); // bit depth
cp_put8(s, 6); // RGBA
cp_put8(s, 0); // compression (deflate)
cp_put8(s, 0); // filter (standard)
cp_put8(s, 0); // interlace off
cp_put32(s, ~s->crc);
}
static void cp_save_data(cp_save_png_data_t* s, cp_image_t* img, long dataPos, long* dataSize)
{
cp_begin_chunk(s, "IDAT", 0);
cp_put8(s, 0x08); // zlib compression method
cp_put8(s, 0x1D); // zlib compression flags
cp_put_bits(s, 3, 3); // zlib last block + fixed dictionary
for (int y = 0; y < img->h; ++y)
{
cp_pixel_t *row = &img->pix[y * img->w];
cp_pixel_t prev = cp_make_pixel_a(0, 0, 0, 0);
cp_encode_byte(s, 1); // sub filter
for (int x = 0; x < img->w; ++x)
{
cp_encode_byte(s, row[x].r - prev.r);
cp_encode_byte(s, row[x].g - prev.g);
cp_encode_byte(s, row[x].b - prev.b);
cp_encode_byte(s, row[x].a - prev.a);
prev = row[x];
}
}
cp_end_run(s);
cp_encode_literal(s, 256); // terminator
while (s->bits != 0x80) cp_put_bits(s, 0, 1);
cp_put32(s, s->adler);
*dataSize = (s->buflen - dataPos) - 8;
cp_put32(s, ~s->crc);
}
cp_saved_png_t cp_save_png_to_memory(const cp_image_t* img)
{
cp_saved_png_t result = { 0 };
cp_save_png_data_t s = { 0 };
long dataPos, dataSize, fileSize;
if (!img) return result;
s.adler = 1;
s.bits = 0x80;
s.prev = 0xFFFF;
s.bufcap = 1024;
s.buffer = (char*)CUTE_PNG_ALLOC(1024);
cp_save_header(&s, (cp_image_t*)img);
dataPos = s.buflen;
cp_save_data(&s, (cp_image_t*)img, dataPos, &dataSize);
// End chunk.
cp_begin_chunk(&s, "IEND", 0);
cp_put32(&s, ~s.crc);
// Write back payload size.
fileSize = s.buflen;
s.buflen = dataPos;
cp_put32(&s, dataSize);
result.size = fileSize;
result.data = s.buffer;
return result;
}
int cp_save_png(const char* file_name, const cp_image_t* img)
{
cp_saved_png_t s;
long err;
CUTE_PNG_FILE* fp = CUTE_PNG_FOPEN(file_name, "wb");
if (!fp) return 1;
s = cp_save_png_to_memory(img);
CUTE_PNG_FWRITE(s.data, s.size, 1, fp);
err = CUTE_PNG_FERROR(fp);
CUTE_PNG_FCLOSE(fp);
CUTE_PNG_FREE(s.data);
return !err;
}
typedef struct cp_raw_png_t
{
const uint8_t* p;
const uint8_t* end;
} cp_raw_png_t;
static uint32_t cp_make32(const uint8_t* s)
{
return (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
}
static const uint8_t* cp_chunk(cp_raw_png_t* png, const char* chunk, uint32_t minlen)
{
uint32_t len = cp_make32(png->p);
const uint8_t* start = png->p;
if (!CUTE_PNG_MEMCMP(start + 4, chunk, 4) && len >= minlen)
{
int offset = len + 12;
if (png->p + offset <= png->end)
{
png->p += offset;
return start + 8;
}
}
return 0;
}
static const uint8_t* cp_find(cp_raw_png_t* png, const char* chunk, uint32_t minlen)
{
const uint8_t *start;
while (png->p < png->end)
{
uint32_t len = cp_make32(png->p);
start = png->p;
png->p += len + 12;
if (!CUTE_PNG_MEMCMP(start+4, chunk, 4) && len >= minlen && png->p <= png->end)
return start + 8;
}
return 0;
}
static int cp_unfilter(int w, int h, int bpp, uint8_t* raw)
{
int len = w * bpp;
uint8_t *prev;
int x;
if (h > 0)
{
#define FILTER_LOOP_FIRST(A) for (x = bpp; x < len; x++) raw[x] += A; break
switch (*raw++)
{
case 0: break;
case 1: FILTER_LOOP_FIRST(raw[x - bpp]);
case 2: break;
case 3: FILTER_LOOP_FIRST(raw[x - bpp] / 2);