-
Notifications
You must be signed in to change notification settings - Fork 1
/
lodepng.cpp
5992 lines (5171 loc) · 236 KB
/
lodepng.cpp
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
/*
LodePNG version 20190210
Copyright (c) 2005-2019 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
The manual and changelog are in the header file "lodepng.h"
Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
*/
#include "lodepng.h"
#include <limits.h> /* LONG_MAX */
#include <stdio.h> /* file handling */
#include <stdlib.h> /* allocations */
#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
#endif /*_MSC_VER */
const char* LODEPNG_VERSION_STRING = "20190210";
/*
This source file is built up in the following large parts. The code sections
with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
-Tools for C and common code for PNG and Zlib
-C Code for Zlib (huffman, deflate, ...)
-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
-The C++ wrapper around all of the above
*/
/*The malloc, realloc and free functions defined here with "lodepng_" in front
of the name, so that you can easily change them to others related to your
platform if needed. Everything else in the code calls these. Pass
-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
define them in your own project's source files without needing to change
lodepng source code. Don't forget to remove "static" if you copypaste them
from here.*/
#ifdef LODEPNG_COMPILE_ALLOCATORS
static void* lodepng_malloc(size_t size) {
#ifdef LODEPNG_MAX_ALLOC
if(size > LODEPNG_MAX_ALLOC) return 0;
#endif
return malloc(size);
}
static void* lodepng_realloc(void* ptr, size_t new_size) {
#ifdef LODEPNG_MAX_ALLOC
if(new_size > LODEPNG_MAX_ALLOC) return 0;
#endif
return realloc(ptr, new_size);
}
static void lodepng_free(void* ptr) {
free(ptr);
}
#else /*LODEPNG_COMPILE_ALLOCATORS*/
void* lodepng_malloc(size_t size);
void* lodepng_realloc(void* ptr, size_t new_size);
void lodepng_free(void* ptr);
#endif /*LODEPNG_COMPILE_ALLOCATORS*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // Tools for C, and common code for PNG and Zlib. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))
/*
Often in case of an error a value is assigned to a variable and then it breaks
out of a loop (to go to the cleanup phase of a function). This macro does that.
It makes the error handling code shorter and more readable.
Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
*/
#define CERROR_BREAK(errorvar, code){\
errorvar = code;\
break;\
}
/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
#define ERROR_BREAK(code) CERROR_BREAK(error, code)
/*Set error var to the error code, and return it.*/
#define CERROR_RETURN_ERROR(errorvar, code){\
errorvar = code;\
return code;\
}
/*Try the code, if it returns error, also return the error.*/
#define CERROR_TRY_RETURN(call){\
unsigned error = call;\
if(error) return error;\
}
/*Set error var to the error code, and return from the void function.*/
#define CERROR_RETURN(errorvar, code){\
errorvar = code;\
return;\
}
/*
About uivector, ucvector and string:
-All of them wrap dynamic arrays or text strings in a similar way.
-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
-They're not used in the interface, only internally in this file as static functions.
-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
*/
#ifdef LODEPNG_COMPILE_ZLIB
/*dynamic vector of unsigned ints*/
typedef struct uivector {
unsigned* data;
size_t size; /*size in number of unsigned longs*/
size_t allocsize; /*allocated size in bytes*/
} uivector;
static void uivector_cleanup(void* p) {
((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
lodepng_free(((uivector*)p)->data);
((uivector*)p)->data = NULL;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_reserve(uivector* p, size_t allocsize) {
if(allocsize > p->allocsize) {
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
void* data = lodepng_realloc(p->data, newsize);
if(data) {
p->allocsize = newsize;
p->data = (unsigned*)data;
}
else return 0; /*error: not enough memory*/
}
return 1;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_resize(uivector* p, size_t size) {
if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
p->size = size;
return 1; /*success*/
}
/*resize and give all new elements the value*/
static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) {
size_t oldsize = p->size, i;
if(!uivector_resize(p, size)) return 0;
for(i = oldsize; i < size; ++i) p->data[i] = value;
return 1;
}
static void uivector_init(uivector* p) {
p->data = NULL;
p->size = p->allocsize = 0;
}
#ifdef LODEPNG_COMPILE_ENCODER
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_push_back(uivector* p, unsigned c) {
if(!uivector_resize(p, p->size + 1)) return 0;
p->data[p->size - 1] = c;
return 1;
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
/* /////////////////////////////////////////////////////////////////////////// */
/*dynamic vector of unsigned chars*/
typedef struct ucvector {
unsigned char* data;
size_t size; /*used size*/
size_t allocsize; /*allocated size*/
} ucvector;
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned ucvector_reserve(ucvector* p, size_t allocsize) {
if(allocsize > p->allocsize) {
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
void* data = lodepng_realloc(p->data, newsize);
if(data) {
p->allocsize = newsize;
p->data = (unsigned char*)data;
}
else return 0; /*error: not enough memory*/
}
return 1;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned ucvector_resize(ucvector* p, size_t size) {
if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0;
p->size = size;
return 1; /*success*/
}
#ifdef LODEPNG_COMPILE_PNG
static void ucvector_cleanup(void* p) {
((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
lodepng_free(((ucvector*)p)->data);
((ucvector*)p)->data = NULL;
}
static void ucvector_init(ucvector* p) {
p->data = NULL;
p->size = p->allocsize = 0;
}
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ZLIB
/*you can both convert from vector to buffer&size and vica versa. If you use
init_buffer to take over a buffer and size, it is not needed to use cleanup*/
static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) {
p->data = buffer;
p->allocsize = p->size = size;
}
#endif /*LODEPNG_COMPILE_ZLIB*/
#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned ucvector_push_back(ucvector* p, unsigned char c) {
if(!ucvector_resize(p, p->size + 1)) return 0;
p->data[p->size - 1] = c;
return 1;
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_PNG
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*free string pointer and set it to NULL*/
static void string_cleanup(char** out) {
lodepng_free(*out);
*out = NULL;
}
/* dynamically allocates a new string with a copy of the null terminated input text */
static char* alloc_string(const char* in) {
size_t insize = strlen(in);
char* out = (char*)lodepng_malloc(insize + 1);
if(out) {
size_t i;
for(i = 0; i != insize; ++i) {
out[i] = in[i];
}
out[i] = 0;
}
return out;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
#endif /*LODEPNG_COMPILE_PNG*/
/* ////////////////////////////////////////////////////////////////////////// */
unsigned lodepng_read32bitInt(const unsigned char* buffer) {
return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]);
}
#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
/*buffer must have at least 4 allocated bytes available*/
static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) {
buffer[0] = (unsigned char)((value >> 24) & 0xff);
buffer[1] = (unsigned char)((value >> 16) & 0xff);
buffer[2] = (unsigned char)((value >> 8) & 0xff);
buffer[3] = (unsigned char)((value ) & 0xff);
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
#ifdef LODEPNG_COMPILE_ENCODER
static void lodepng_add32bitInt(ucvector* buffer, unsigned value) {
ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/
lodepng_set32bitInt(&buffer->data[buffer->size - 4], value);
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / File IO / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_DISK
/* returns negative value on error. This should be pure C compatible, so no fstat. */
static long lodepng_filesize(const char* filename) {
FILE* file;
long size;
file = fopen(filename, "rb");
if(!file) return -1;
if(fseek(file, 0, SEEK_END) != 0) {
fclose(file);
return -1;
}
size = ftell(file);
/* It may give LONG_MAX as directory size, this is invalid for us. */
if(size == LONG_MAX) size = -1;
fclose(file);
return size;
}
/* load file into buffer that already has the correct allocated size. Returns error code.*/
static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) {
FILE* file;
size_t readsize;
file = fopen(filename, "rb");
if(!file) return 78;
readsize = fread(out, 1, size, file);
fclose(file);
if (readsize != size) return 78;
return 0;
}
unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) {
long size = lodepng_filesize(filename);
if (size < 0) return 78;
*outsize = (size_t)size;
*out = (unsigned char*)lodepng_malloc((size_t)size);
if(!(*out) && size > 0) return 83; /*the above malloc failed*/
return lodepng_buffer_file(*out, (size_t)size, filename);
}
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) {
FILE* file;
file = fopen(filename, "wb" );
if(!file) return 79;
fwrite(buffer, 1, buffersize, file);
fclose(file);
return 0;
}
#endif /*LODEPNG_COMPILE_DISK*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // End of common code and tools. Begin of Zlib related code. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_ENCODER
/*TODO: this ignores potential out of memory errors*/
#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit){\
/*add a new byte at the end*/\
if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\
/*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\
(bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\
++(*bitpointer);\
}
static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) {
size_t i;
for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1));
}
static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) {
size_t i;
for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DECODER
#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) {
unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream));
++(*bitpointer);
return result;
}
static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) {
unsigned result = 0, i;
for(i = 0; i != nbits; ++i) {
result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
++(*bitpointer);
}
return result;
}
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / Deflate - Huffman / */
/* ////////////////////////////////////////////////////////////////////////// */
#define FIRST_LENGTH_CODE_INDEX 257
#define LAST_LENGTH_CODE_INDEX 285
/*256 literals, the end code, some length codes, and 2 unused codes*/
#define NUM_DEFLATE_CODE_SYMBOLS 288
/*the distance codes have their own symbols, 30 used, 2 unused*/
#define NUM_DISTANCE_SYMBOLS 32
/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
#define NUM_CODE_LENGTH_CODES 19
/*the base lengths represented by codes 257-285*/
static const unsigned LENGTHBASE[29]
= {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};
/*the extra bits used by codes 257-285 (added to base length)*/
static const unsigned LENGTHEXTRA[29]
= {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};
/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
static const unsigned DISTANCEBASE[30]
= {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};
/*the extra bits of backwards distances (added to base)*/
static const unsigned DISTANCEEXTRA[30]
= {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};
/*the order in which "code length alphabet code lengths" are stored, out of this
the huffman tree of the dynamic huffman tree lengths is generated*/
static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
= {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
/* ////////////////////////////////////////////////////////////////////////// */
/*
Huffman tree struct, containing multiple representations of the tree
*/
typedef struct HuffmanTree {
unsigned* tree2d;
unsigned* tree1d;
unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
unsigned maxbitlen; /*maximum number of bits a single code can get*/
unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
} HuffmanTree;
/*function used for debug purposes to draw the tree in ascii art with C++*/
/*
static void HuffmanTree_draw(HuffmanTree* tree) {
std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
for(size_t i = 0; i != tree->tree1d.size; ++i) {
if(tree->lengths.data[i])
std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
}
std::cout << std::endl;
}*/
static void HuffmanTree_init(HuffmanTree* tree) {
tree->tree2d = 0;
tree->tree1d = 0;
tree->lengths = 0;
}
static void HuffmanTree_cleanup(HuffmanTree* tree) {
lodepng_free(tree->tree2d);
lodepng_free(tree->tree1d);
lodepng_free(tree->lengths);
}
/*the tree representation used by the decoder. return value is error*/
static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) {
unsigned nodefilled = 0; /*up to which node it is filled*/
unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
unsigned n, i;
tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned));
if(!tree->tree2d) return 83; /*alloc fail*/
/*
convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
uninited, a value >= numcodes is an address to another bit, a value < numcodes
is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
many columns as codes - 1.
A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
Here, the internal nodes are stored (what their 0 and 1 option point to).
There is only memory for such good tree currently, if there are more nodes
(due to too long length codes), error 55 will happen
*/
for(n = 0; n < tree->numcodes * 2; ++n) {
tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
}
for(n = 0; n < tree->numcodes; ++n) /*the codes*/ {
for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ {
unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
/*oversubscribed, see comment in lodepng_error_text*/
if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55;
if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ {
if(i + 1 == tree->lengths[n]) /*last bit*/ {
tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
treepos = 0;
} else {
/*put address of the next step in here, first that address has to be found of course
(it's just nodefilled + 1)...*/
++nodefilled;
/*addresses encoded with numcodes added to it*/
tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
treepos = nodefilled;
}
}
else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
}
}
for(n = 0; n < tree->numcodes * 2; ++n) {
if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
}
return 0;
}
/*
Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
numcodes, lengths and maxbitlen must already be filled in correctly. return
value is error.
*/
static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) {
uivector blcount;
uivector nextcode;
unsigned error = 0;
unsigned bits, n;
uivector_init(&blcount);
uivector_init(&nextcode);
tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
if(!tree->tree1d) error = 83; /*alloc fail*/
if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
|| !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
error = 83; /*alloc fail*/
if(!error) {
/*step 1: count number of instances of each code length*/
for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]];
/*step 2: generate the nextcode values*/
for(bits = 1; bits <= tree->maxbitlen; ++bits) {
nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1;
}
/*step 3: generate all the codes*/
for(n = 0; n != tree->numcodes; ++n) {
if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
}
}
uivector_cleanup(&blcount);
uivector_cleanup(&nextcode);
if(!error) return HuffmanTree_make2DTree(tree);
else return error;
}
/*
given the code lengths (as stored in the PNG file), generate the tree as defined
by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
return value is error.
*/
static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
size_t numcodes, unsigned maxbitlen) {
unsigned i;
tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->maxbitlen = maxbitlen;
return HuffmanTree_makeFromLengths2(tree);
}
#ifdef LODEPNG_COMPILE_ENCODER
/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
/*chain node for boundary package merge*/
typedef struct BPMNode {
int weight; /*the sum of all weights in this chain*/
unsigned index; /*index of this leaf node (called "count" in the paper)*/
struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
int in_use;
} BPMNode;
/*lists of chains*/
typedef struct BPMLists {
/*memory pool*/
unsigned memsize;
BPMNode* memory;
unsigned numfree;
unsigned nextfree;
BPMNode** freelist;
/*two heads of lookahead chains per list*/
unsigned listsize;
BPMNode** chains0;
BPMNode** chains1;
} BPMLists;
/*creates a new chain node with the given parameters, from the memory in the lists */
static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) {
unsigned i;
BPMNode* result;
/*memory full, so garbage collect*/
if(lists->nextfree >= lists->numfree) {
/*mark only those that are in use*/
for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
for(i = 0; i != lists->listsize; ++i) {
BPMNode* node;
for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
}
/*collect those that are free*/
lists->numfree = 0;
for(i = 0; i != lists->memsize; ++i) {
if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
}
lists->nextfree = 0;
}
result = lists->freelist[lists->nextfree++];
result->weight = weight;
result->index = index;
result->tail = tail;
return result;
}
/*sort the leaves with stable mergesort*/
static void bpmnode_sort(BPMNode* leaves, size_t num) {
BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num);
size_t width, counter = 0;
for(width = 1; width < num; width *= 2) {
BPMNode* a = (counter & 1) ? mem : leaves;
BPMNode* b = (counter & 1) ? leaves : mem;
size_t p;
for(p = 0; p < num; p += 2 * width) {
size_t q = (p + width > num) ? num : (p + width);
size_t r = (p + 2 * width > num) ? num : (p + 2 * width);
size_t i = p, j = q, k;
for(k = p; k < r; k++) {
if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];
else b[k] = a[j++];
}
}
counter++;
}
if(counter & 1) memcpy(leaves, mem, sizeof(*leaves) * num);
lodepng_free(mem);
}
/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) {
unsigned lastindex = lists->chains1[c]->index;
if(c == 0) {
if(lastindex >= numpresent) return;
lists->chains0[c] = lists->chains1[c];
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
} else {
/*sum of the weights of the head nodes of the previous lookahead chains.*/
int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
lists->chains0[c] = lists->chains1[c];
if(lastindex < numpresent && sum > leaves[lastindex].weight) {
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
return;
}
lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
/*in the end we are only interested in the chain of the last list, so no
need to recurse if we're at the last one (this gives measurable speedup)*/
if(num + 1 < (int)(2 * numpresent - 2)) {
boundaryPM(lists, leaves, numpresent, c - 1, num);
boundaryPM(lists, leaves, numpresent, c - 1, num);
}
}
}
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
size_t numcodes, unsigned maxbitlen) {
unsigned error = 0;
unsigned i;
size_t numpresent = 0; /*number of symbols with non-zero frequency*/
BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/
leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
if(!leaves) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i) {
if(frequencies[i] > 0) {
leaves[numpresent].weight = (int)frequencies[i];
leaves[numpresent].index = i;
++numpresent;
}
}
for(i = 0; i != numcodes; ++i) lengths[i] = 0;
/*ensure at least two present symbols. There should be at least one symbol
according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
make these work as well ensure there are at least two symbols. The
Package-Merge code below also doesn't work correctly if there's only one
symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
if(numpresent == 0) {
lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
} else if(numpresent == 1) {
lengths[leaves[0].index] = 1;
lengths[leaves[0].index == 0 ? 1 : 0] = 1;
} else {
BPMLists lists;
BPMNode* node;
bpmnode_sort(leaves, numpresent);
lists.listsize = maxbitlen;
lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
lists.nextfree = 0;
lists.numfree = lists.memsize;
lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
if(!error) {
for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
bpmnode_create(&lists, leaves[0].weight, 1, 0);
bpmnode_create(&lists, leaves[1].weight, 2, 0);
for(i = 0; i != lists.listsize; ++i) {
lists.chains0[i] = &lists.memory[0];
lists.chains1[i] = &lists.memory[1];
}
/*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) {
for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
}
}
lodepng_free(lists.memory);
lodepng_free(lists.freelist);
lodepng_free(lists.chains0);
lodepng_free(lists.chains1);
}
lodepng_free(leaves);
return error;
}
/*Create the Huffman tree given the symbol frequencies*/
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen) {
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) {
return tree->tree1d[index];
}
static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) {
return tree->lengths[index];
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
static unsigned generateFixedLitLenTree(HuffmanTree* tree) {
unsigned i, error = 0;
unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
if(!bitlen) return 83; /*alloc fail*/
/*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
for(i = 0; i <= 143; ++i) bitlen[i] = 8;
for(i = 144; i <= 255; ++i) bitlen[i] = 9;
for(i = 256; i <= 279; ++i) bitlen[i] = 7;
for(i = 280; i <= 287; ++i) bitlen[i] = 8;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
static unsigned generateFixedDistanceTree(HuffmanTree* tree) {
unsigned i, error = 0;
unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
if(!bitlen) return 83; /*alloc fail*/
/*there are 32 distance codes, but 30-31 are unused*/
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
#ifdef LODEPNG_COMPILE_DECODER
/*
returns the code, or (unsigned)(-1) if error happened
inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
*/
static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp,
const HuffmanTree* codetree, size_t inbitlength) {
unsigned treepos = 0, ct;
for(;;) {
if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
/*
decode the symbol from the tree. The "readBitFromStream" code is inlined in
the expression below because this is the biggest bottleneck while decoding
*/
ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
++(*bp);
if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_DECODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / Inflator (Decompressor) / */
/* ////////////////////////////////////////////////////////////////////////// */
/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) {
/*TODO: check for out of memory errors*/
generateFixedLitLenTree(tree_ll);
generateFixedDistanceTree(tree_d);
}
/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
const unsigned char* in, size_t* bp, size_t inlength) {
/*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
unsigned error = 0;
unsigned n, HLIT, HDIST, HCLEN, i;
size_t inbitlength = inlength * 8;
/*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
unsigned* bitlen_ll = 0; /*lit,len code lengths*/
unsigned* bitlen_d = 0; /*dist code lengths*/
/*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
unsigned* bitlen_cl = 0;
HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/
/*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
HLIT = readBitsFromStream(bp, in, 5) + 257;
/*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
HDIST = readBitsFromStream(bp, in, 5) + 1;
/*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
HCLEN = readBitsFromStream(bp, in, 4) + 4;
if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/
HuffmanTree_init(&tree_cl);
while(!error) {
/*read the code length codes out of 3 * (amount of code length codes) bits*/
bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/);
for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) {
if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3);
else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/
}
error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
if(error) break;
/*now we can use this tree to read the lengths for the tree that this function will return*/
bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
/*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
i = 0;
while(i < HLIT + HDIST) {
unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
if(code <= 15) /*a length code*/ {
if(i < HLIT) bitlen_ll[i] = code;
else bitlen_d[i - HLIT] = code;
++i;
} else if(code == 16) /*repeat previous*/ {
unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
unsigned value; /*set value to the previous code*/
if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
replength += readBitsFromStream(bp, in, 2);
if(i < HLIT + 1) value = bitlen_ll[i - 1];
else value = bitlen_d[i - HLIT - 1];
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = value;
else bitlen_d[i - HLIT] = value;
++i;
}
} else if(code == 17) /*repeat "0" 3-10 times*/ {
unsigned replength = 3; /*read in the bits that indicate repeat length*/
if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
replength += readBitsFromStream(bp, in, 3);
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = 0;
else bitlen_d[i - HLIT] = 0;
++i;
}
} else if(code == 18) /*repeat "0" 11-138 times*/ {
unsigned replength = 11; /*read in the bits that indicate repeat length*/
if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
replength += readBitsFromStream(bp, in, 7);
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = 0;
else bitlen_d[i - HLIT] = 0;
++i;
}
} else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ {
if(code == (unsigned)(-1)) {
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
(10=no endcode, 11=wrong jump outside of tree)*/
error = (*bp) > inbitlength ? 10 : 11;
}
else error = 16; /*unexisting code, this can never happen*/
break;
}
}
if(error) break;
if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
/*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
if(error) break;
error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);