forked from RandyGaul/cute_headers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtinydeflate.h
More file actions
2658 lines (2276 loc) · 66.7 KB
/
tinydeflate.h
File metadata and controls
2658 lines (2276 loc) · 66.7 KB
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
/*
tinydeflate - v1.0
SUMMARY:
This header is a conglomeration of a DEFLATE compliant decompressor, and some
functions for dealing with PNGs (load, save and atlas creation).
EXAMPLES:
Loading a PNG from disk, then freeing it
tdImage img = tdLoadPNG( "images/pic.png" );
...
free( img.pix );
memset( &img, 0, sizeof( img ) );
Loading a PNG from memory, then freeing it
tdImage img = tdLoadPNGMem( memory, sizeof( memory ) );
...
free( img.pix );
memset( &img, 0, sizeof( img ) );
Saving a PNG to disk
tdSavePNG( "images/example.png", &img );
// img is just a raw RGBA buffer, and can come from anywhere,
// not only from tdLoad*** functions
Creating a texture atlas
tdMakeAtlas( "atlas.png", "atlas.txt", 256, 256, imgs, imgs_count, image_names );
// just pass an array of pointers to images, and the array count
// outputs a png along with a txt file. The txt contains UV info in
// a very easy to parse format. The final parameter is optional.
Inflating a DEFLATE block
tdInflate( 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
LONG WINDED INFO:
Most of this code is either a direct port of Richard Mitton's tigr library. A
big thanks to Mitton for placing his code into public domain. Randy Gaul, the
author of this header, has made some modifications to Mitton's original code,
namely much faster Huffman decoding, some all new atlas creation code, some
optimized read/write functions, reduced memory allocations, much more error
reporting, etc. Also, a couple tricks were referenced from stb_image by Sean
Barrett. One was the lookup table for decoding, and I don't recall the other
tricks, though I am sure a few are laying around in the source. Cheers to Sean
for his great public domain library!
ENCODING IMAGES:
Currently saving images uses Mitton's very straight-forward RLE compression
scheme. This works out fairly well, though it will be replaced soon enough
with a GZIP-style compressor. The new compressor should be able to compress
any piece of memory, unlike the current specialized code coupled to the PNG
stuff.
*/
#if !defined( TINYDEFLATE_H )
#ifdef _WIN32
#define TD_INLINE __forceinline
#define _CRT_SECURE_NO_WARNINGS FUCK_YOU
#include <malloc.h> // alloca
#else
#define TD_INLINE __attribute__((always_inline))
#include <alloca.h> // alloca
#endif
#ifdef __GNUC__
#undef TD_INLINE
#define TD_INLINE __attribute__((always_inline)) inline
#endif
// turn these off to reduce compile time and compile size for un-needed features
// or to control various settings
#define TD_PNG 1 // png load/save
#define TD_ATLAS 1 // atlas creation
#define TD_ATLAS_MUST_FIT 1 // returns error from tdMakeAtlas if *any* input image does not fit
#define TD_ATLAS_FLIP_Y_AXIS_FOR_UV 1 // flips output uv coordinate's y. Can be useful to "flip image on load"
#if TD_ATLAS && !TD_PNG
#error TD_ATLAS requires TD_PNG to be set to 1
#endif
#include <stdint.h>
#if TD_PNG
typedef struct
{
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
} tdPixel;
#define TD_BPP sizeof( tdPixel )
typedef struct
{
int w;
int h;
tdPixel* pix;
} tdImage;
TD_INLINE tdPixel tdMakePixelA( uint8_t r, uint8_t g, uint8_t b, uint8_t a )
{
tdPixel p = { r, g, b, a };
return p;
}
TD_INLINE tdPixel tdMakePixel( uint8_t r, uint8_t g, uint8_t b )
{
tdPixel p = { r, g, b, 0xFF };
return p;
}
#endif // TD_PNG
// return 1 for success, 0 for failures
int tdInflate( void* in, int in_bytes, void* out, int out_bytes );
int tdSavePNG( const char* fileName, tdImage* img );
int tdMakeAtlas( const char* out_path_image, const char* out_path_atlas_txt, int atlasWidth, int atlasHeight, tdImage* pngs, int png_count, const char** names );
// these two functions return tdImage::pix as 0 in event of errors
tdImage tdLoadPNG( const char *fileName );
tdImage tdLoadPNGMem( const void *png_data, int png_length );
// read this whenever one of the above functions returns an error
extern const char* g_tdDeflateErrorReason;
#define TD_DEBUG_CHECKS 1
#if TD_DEBUG_CHECKS
#include <assert.h>
#define TD_ASSERT assert
#else
#define TD_ASSERT( ... )
#endif
#define TINYDEFLATE_H
#endif
#ifdef TINYDEFLATE_IMPL
#include <stdio.h> // fopen, fclose, etc.
#include <stdlib.h> // malloc, free, calloc
#include <string.h> // memcpy
const char* g_tdDeflateErrorReason;
#define TD_CHECK( X, Y ) do { if ( !(X) ) { g_tdDeflateErrorReason = Y; return 0; } } while ( 0 )
#define TD_CALL( X ) do { if ( !(X) ) goto td_error; } while ( 0 )
#define TD_LOOKUP_BITS 9
#define TD_LOOKUP_COUNT (1 << TD_LOOKUP_BITS)
#define TD_LOOKUP_MASK (TD_LOOKUP_COUNT - 1)
#define TD_DEFLATE_MAX_BITLEN 15
// DEFLATE tables from RFC 1951
uint8_t g_tdFixed[ 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 g_tdPermutationOrder[ 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 g_tdLenExtraBits[ 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 g_tdLenBase[ 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 g_tdDistExtraBits[ 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 g_tdDistBase[ 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 }; // 3.2.5
typedef struct
{
uint64_t bits;
int count;
uint32_t* words;
int word_count;
int word_index;
int bits_left;
char* final_bytes;
int last_bits;
char* out;
char* out_end;
uint16_t lookup[ TD_LOOKUP_COUNT ];
uint32_t lit[ 288 ];
uint32_t dst[ 32 ];
uint32_t len[ 19 ];
uint32_t nlit;
uint32_t ndst;
uint32_t nlen;
} tdIState;
TD_INLINE static int tdWouldOverflow( int bits_left, int num_bits )
{
return bits_left - num_bits < 0;
}
TD_INLINE static char* tdPtr( tdIState* s )
{
TD_ASSERT( !(s->bits_left & 7) );
return ((char*)s->words) + s->count;
}
TD_INLINE static uint64_t tdPeakBits( tdIState* s, int num_bits_to_read )
{
if ( s->count < num_bits_to_read )
{
if ( s->bits_left > s->last_bits )
{
s->bits |= (uint64_t)s->words[ s->word_index ] << s->count;
s->count += 32;
s->word_index += 1;
}
else
{
TD_ASSERT( s->bits_left <= 3 * 8 );
int bytes = s->bits_left / 8;
for ( int i = 0; i < bytes; ++i )
s->bits |= (uint64_t)(s->final_bytes[ i ]) << (i * 8);
s->count += s->bits_left;
}
}
return s->bits;
}
TD_INLINE static uint32_t tdConsumeBits( tdIState* s, int num_bits_to_read )
{
TD_ASSERT( s->count >= num_bits_to_read );
uint32_t bits = s->bits & (((uint64_t)1 << num_bits_to_read) - 1);
printf( "C val, bits: %d, %d\n", bits, num_bits_to_read );
s->bits >>= num_bits_to_read;
s->count -= num_bits_to_read;
s->bits_left -= num_bits_to_read;
return bits;
}
TD_INLINE static uint32_t tdReadBits( tdIState* s, int num_bits_to_read )
{
TD_ASSERT( num_bits_to_read <= 32 );
TD_ASSERT( num_bits_to_read >= 0 );
TD_ASSERT( s->bits_left > 0 );
TD_ASSERT( s->count <= 64 );
TD_ASSERT( !tdWouldOverflow( s->bits_left, num_bits_to_read ) );
tdPeakBits( s, num_bits_to_read );
uint32_t bits = tdConsumeBits( s, num_bits_to_read );
return bits;
}
static char* tdReadFileToMemory( const char* path, int* size )
{
char* data = 0;
FILE* fp = fopen( path, "rb" );
int sizeNum = 0;
if ( fp )
{
fseek( fp, 0, SEEK_END );
sizeNum = ftell( fp );
fseek( fp, 0, SEEK_SET );
data = (char*)malloc( sizeNum + 1 );
fread( data, sizeNum, 1, fp );
data[ sizeNum ] = 0;
fclose( fp );
}
if ( size ) *size = sizeNum;
return data;
}
TD_INLINE static uint32_t tdRev16( 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;
}
TD_INLINE static uint32_t tdRev( uint32_t a, uint32_t len )
{
return tdRev16( a ) >> (16 - len);
}
// RFC 1951 section 3.2.2
// Slots arrays starts as "bl_count"
// Added 2.5) to stransform slots from "bl_count" into an array that
// represents first indices for each code length in the final tree
static int tdBuild( tdIState* 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 ) memset( s->lookup, 0, sizeof( 512 * sizeof( uint32_t ) ) );
for ( int i = 0; i < sym_count; ++i )
{
int len = lens[ i ];
if ( len != 0 )
{
TD_ASSERT( len < 16 );
uint32_t code = codes[ len ]++;
uint32_t slot = first[ len ]++;
tree[ slot ] = (code << (32 - len)) | (i << 4) | len;
if ( s && len <= TD_LOOKUP_BITS )
{
int j = tdRev16( code ) >> (16 - len);
while ( j < (1 << TD_LOOKUP_BITS) )
{
s->lookup[ j ] = (uint16_t)((len << TD_LOOKUP_BITS) | i);
j += (1 << len);
}
}
}
}
int max_index = first[ 15 ];
return max_index;
}
static int tdStored( tdIState* s )
{
// 3.2.3
// skip any remaining bits in current partially processed byte
tdReadBits( s, s->count & 7 );
// 3.2.4
// read LEN and NLEN, should complement each other
uint32_t LEN = tdReadBits( s, 16 );
uint32_t NLEN = tdReadBits( s, 16 );
TD_CHECK( LEN == ~NLEN, "Failed to find LEN and NLEN as complements within stored (uncompressed) stream." );
TD_CHECK( s->bits_left * 8 <= (int)LEN, "Stored block extends beyond end of input stream." );
memcpy( s->out, tdPtr( s ), LEN );
s->out += LEN;
return 1;
}
// 3.2.6
TD_INLINE static int tdFixed( tdIState* s )
{
s->nlit = tdBuild( s, s->lit, g_tdFixed, 288 );
s->ndst = tdBuild( 0, s->dst, g_tdFixed + 288, 32 );
return 1;
}
static int tdDecode( tdIState* s, uint32_t* tree, int hi )
{
uint64_t bits = tdPeakBits( s, 16 );
uint32_t search = (tdRev16( (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 ];
if ( TD_DEBUG_CHECKS )
{
uint32_t len = (32 - (key & 0xF));
TD_ASSERT( (search >> len) == (key >> len) );
}
int code = tdConsumeBits( s, key & 0xF );
(void)code;
return (key >> 4) & 0xFFF;
}
static int tdTryLookup( tdIState* s, uint32_t* tree, int hi )
{
uint64_t bits = tdPeakBits( s, 16 );
int index = bits & TD_LOOKUP_MASK;
uint32_t code = s->lookup[ index ];
if ( code )
{
tdConsumeBits( s, code >> 9 );
return code & TD_LOOKUP_MASK;
}
return tdDecode( s, tree, hi );
}
// 3.2.7
static int tdDynamic( tdIState* s )
{
uint8_t lenlens[ 19 ] = { 0 };
int nlit = 257 + tdReadBits( s, 5 );
int ndst = 1 + tdReadBits( s, 5 );
int nlen = 4 + tdReadBits( s, 4 );
for ( int i = 0 ; i < nlen; ++i )
lenlens[ g_tdPermutationOrder[ i ] ] = (uint8_t)tdReadBits( s, 3 );
// Build the tree for decoding code lengths
int lenlens2[19] = { 0 };
for ( int i = 0; i < 19; ++i ) lenlens2[ i ] = lenlens[ i ];
s->nlen = tdBuild( 0, s->len, lenlens, 19 );
uint8_t lens[ 288 + 32 ];
for ( int n = 0; n < nlit + ndst; )
{
int sym = tdDecode( s, s->len, s->nlen );
switch ( sym )
{
case 16: for ( int i = 3 + tdReadBits( s, 2 ); i; --i, ++n ) lens[ n ] = lens[ n - 1 ]; break;
case 17: for ( int i = 3 + tdReadBits( s, 3 ); i; --i, ++n ) lens[ n ] = 0; break;
case 18: for ( int i = 11 + tdReadBits( s, 7 ); i; --i, ++n ) lens[ n ] = 0; break;
default: lens[ n++ ] = (uint8_t)sym; break;
}
}
s->nlit = tdBuild( s, s->lit, lens, nlit );
s->ndst = tdBuild( 0, s->dst, lens + nlit, ndst );
return 1;
}
// 3.2.3
static int tdBlock( tdIState* s )
{
for (;;)
{
int symbol = tdTryLookup( s, s->lit, s->nlit );
if ( symbol < 256 )
{
TD_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 = tdReadBits( s, g_tdLenExtraBits[ symbol ] ) + g_tdLenBase[ symbol ];
int distance_symbol = tdDecode( s, s->dst, s->ndst );
int backwards_distance = tdReadBits( s, g_tdDistExtraBits[ distance_symbol ] ) + g_tdDistBase[ distance_symbol ];
if ( s->out + length > s->out_end ) __debugbreak( );
TD_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
memset( dst, *src, length );
break;
default: while ( length-- ) *dst++ = *src++;
}
}
else break;
}
return 1;
}
// 3.2.3
int tdInflate( void* in, int in_bytes, void* out, int out_bytes )
{
tdIState* s = (tdIState*)calloc( 1, sizeof( tdIState ) );
s->bits = 0;
s->count = 0;
s->word_count = in_bytes / 4;
s->word_index = 0;
s->bits_left = in_bytes * 8;
int first_bytes = (int)((int)in & 3);
s->words = (uint32_t*)((char*)in + first_bytes);
s->last_bits = ((in_bytes - first_bytes) & 3) * 8;
s->final_bytes = (char*)in + in_bytes - s->last_bits;
for ( int i = 0; i < first_bytes; ++i )
s->bits |= (uint64_t)(((uint8_t*)in)[ i ]) << (i * 8);
s->count = first_bytes * 8;
s->out = (char*)out;
s->out_end = s->out + out_bytes;
int bfinal;
do
{
bfinal = tdReadBits( s, 1 );
int btype = tdReadBits( s, 2 );
switch ( btype )
{
case 0: TD_CALL( tdStored( s ) ); break;
case 1: tdFixed( s ); TD_CALL( tdBlock( s ) ); break;
case 2: tdDynamic( s ); TD_CALL( tdBlock( s ) ); break;
case 3: TD_CHECK( 0, "Detected unknown block type within input stream." );
}
}
while ( !bfinal );
free( s );
return 1;
td_error:
free( s );
return 0;
}
// if TD_HASH_COUNT is set to >= TD_WINDOW_SIZE we can use a rolling buffer
#define TD_WINDOW_SIZE (1024 * 32)
#define TD_HASH_COUNT TD_WINDOW_SIZE
#define TD_ENTRY_BUFFER_SIZE (TD_WINDOW_SIZE * 4)
#if TD_HASH_COUNT < TD_WINDOW_SIZE
#error rolling buffer implementation requires worst case size minimum for hash entry memory
#endif
TD_INLINE static uint32_t djb2( char* str, char* end )
{
uint32_t h = 5381;
uint32_t c;
while ( str != end )
{
c = *str;
h = ((h << 5) + h) + c;
++str;
}
return h;
}
typedef struct tdHash
{
uint32_t h;
char* start;
struct tdHash* next;
} tdHash;
typedef struct
{
char base_len;
char base_dst;
uint16_t symbol_index;
uint16_t len;
int dst;
} tdEntry;
typedef struct
{
int key;
int val;
} tdItem;
typedef struct
{
union
{
uint16_t freq;
uint16_t code;
};
union
{
uint16_t parent;
uint16_t len;
};
uint16_t depth;
uint16_t original;
#if TD_DEBUG_CHECKS
uint16_t left;
uint16_t right;
#endif
} tdNode;
typedef struct
{
uint16_t freq;
uint16_t code;
uint16_t len;
} tdLeaf;
typedef struct
{
char* in;
char* in_end;
char* out;
char* out_end;
char* window;
tdLeaf len[ 286 ];
tdLeaf dst[ 30 ];
uint64_t bits;
int count;
uint32_t* words;
int word_count;
int word_index;
int bits_left;
int max_chain_len;
int do_lazy_search;
int hash_rolling;
tdHash* buckets[ TD_HASH_COUNT ];
tdHash hashes[ TD_HASH_COUNT ];
int entry_count;
tdEntry entries[ TD_ENTRY_BUFFER_SIZE ];
} tdDState;
typedef struct
{
int max_chain_len;
int do_lazy_search;
} tdDeflateOptions;
#undef TD_CHECK
#define TD_FAIL( ) do { goto td_error; } while ( 0 )
#define TD_CHECK( X, Y ) do { if ( !(X) ) { g_tdDeflateErrorReason = Y; TD_FAIL( ); } } while ( 0 )
static void tdWriteBits( tdDState* s, uint32_t value, uint32_t num_bits_to_write )
{
TD_ASSERT( num_bits_to_write <= 32 );
TD_ASSERT( s->bits_left > 0 );
TD_ASSERT( s->count <= 32 );
TD_ASSERT( !tdWouldOverflow( s->bits_left, num_bits_to_write ) );
printf( "val, bits: %d, %d\n", value, num_bits_to_write );
s->bits |= (uint64_t)(value & (((uint64_t)1 << num_bits_to_write) - 1)) << s->count;
s->count += num_bits_to_write;
s->bits_left -= num_bits_to_write;
if ( s->count >= 32 )
{
s->words[ s->word_index ] = (uint32_t)(s->bits & ((uint32_t)~0));
s->bits >>= 32;
s->count -= 32;
s->word_index += 1;
}
}
static void tdWriteBitsRev( tdDState* s, uint32_t value, uint32_t num_bits_to_write )
{
tdWriteBits( s, tdRev( value, num_bits_to_write ), num_bits_to_write );
}
TD_INLINE static void tdFlush( tdDState* s )
{
TD_ASSERT( s->count <= 32 );
if ( s->count ) s->words[ s->word_index ] = (uint32_t)(s->bits & ((uint32_t)~0));
}
TD_INLINE static void tdMatchIndices( int len, int dst, int* base_len, int* base_dst )
{
TD_ASSERT( dst >= 0 && dst <= 32768 );
int dst_index = 0;
for ( int i = 0; i < 31; ++i )
{
int base = g_tdDistBase[ i ];
if ( base < dst ) dst_index = i;
else break;
}
int len_index = 0;
for ( int i = 0; i < 29; ++i )
{
int base = g_tdLenBase[ i ];
if ( base < len ) len_index = i;
else break;
}
TD_ASSERT( len_index >=0 && len_index <= 29 );
TD_ASSERT( dst_index >=0 && dst_index <= 31 );
*base_len = len_index;
*base_dst = dst_index;
}
TD_INLINE static int tdMatchCost( int len, int len_bits, int dst_bits )
{
int match_bits = len * 8;
return (len_bits + dst_bits) - match_bits;
}
#include <math.h> // log2f
TD_INLINE static float tdEntropy( tdLeaf freq_in[ 286 ] )
{
int sum = 0;
for ( int i = 0; i < 286; ++i ) sum += freq_in[ i ].freq;
float fsum = (float)sum;
float entropy = 0;
for ( int i = 0; i < 286; ++i )
{
int freq_int = freq_in[ i ].freq;
if ( freq_int )
{
float freq = (float)freq_int / fsum;
entropy -= freq * log2f( freq );
}
}
return entropy;
}
TD_INLINE static void tdLiteral( tdDState* s, int symbol )
{
tdEntry entry = { 0 };
entry.symbol_index = symbol;
s->window++;
s->entries[ s->entry_count++ ] = entry;
s->len[ symbol ].freq++;
}
TD_INLINE static int tdSmaller( tdItem a, tdItem b, tdNode* nodes )
{
if ( a.key < b.key ) return 1;
else if ( a.key == b.key && nodes[ a.val ].depth <= nodes[ b.val ].depth ) return 1;
return 0;
}
static void tdCascade( tdItem* items, int N, int i, tdNode* nodes )
{
int min = i;
tdItem min_val = items[ i ];
int i2 = 2 * i;
while ( i2 < N )
{
int left = i2;
int right = i2 + 1;
if ( tdSmaller( items[ left ], min_val, nodes ) ) min = left;
if ( right < N && tdSmaller( items[ right ], items[ min ], nodes ) ) min = right;
if ( min == i ) break;
items[ i ] = items[ min ];
items[ min ] = min_val;
i = min;
i2 = 2 * i;
}
}
static void tdMakeHeap( tdItem* items, int count, tdNode* nodes )
{
for ( int i = count / 2; i > 0; --i )
tdCascade( items, count, i, nodes );
}
static tdItem tdPopHeap( tdItem* items, int count, tdNode* nodes )
{
tdItem root = items[ 1 ];
items[ 1 ] = items[ count - 1 ];
tdCascade( items, count - 1, 1, nodes );
return root;
}
static void tdPushHeap( tdItem* items, int count, tdItem a, tdNode* nodes )
{
int i = count;
items[ count ] = a;
while ( i )
{
int j = i / 2;
tdItem child = items[ i ];
tdItem parent = items[ j ];
if ( tdSmaller( child, parent, nodes ) )
{
items[ i ] = parent;
items[ j ] = child;
}
i = j;
}
}
#if TD_DEBUG_CHECKS
#define tdAssertHeap( data, N, i, nodes ) tdAssertHeap_internal( data, N , i, nodes )
#else
#define tdAssertHeap( ... )
#endif
void tdAssertHeap_internal( tdItem* data, int N, int i, tdNode* nodes )
{
int left = i * 2;
int right = left + 1;
if ( left < N )
{
tdItem iVal = data[ i ];
tdItem lVal = data[ left ];
TD_ASSERT( tdSmaller( iVal, lVal, nodes ) );
if ( right < N )
{
tdItem rVal = data[ right ];
TD_ASSERT( tdSmaller( iVal, rVal, nodes ) );
tdAssertHeap( data, N, left, nodes );
tdAssertHeap( data, N, right, nodes );
}
}
}
void tdPrintHeap( tdItem* data, int count )
{
int i = 1;
int j = 2;
int N = count;
do
{
if ( j > N ) j = N;
for ( int index = 0; index < N / 2 - i; ++index ) printf( " " );
for ( int index = i; index < j; ++index ) printf( "(%2d %2d) ", data[ index ].key, data[ index ].val );
printf( "\n" );
i *= 2;
j = i * 2;
}
while ( i < N );
printf( "\n" );
}
TD_INLINE static tdMax( int a, int b )
{
return a > b ? a : b;
}
char depth[ 2056 ];
int di;
void Push( char c )
{
depth[ di++ ] = ' ';
depth[ di++ ] = c;
depth[ di++ ] = ' ';
depth[ di++ ] = ' ';
depth[ di ] = 0;
}
void tdPop( )
{
depth[ di -= 4 ] = 0;
}
void PrintCode( int code, int len, int L )
{
printf( "(" );
for ( int i = 0; i < len; ++i ) printf( "%d", code & (1 << i) ? 1 : 0 );
printf( ", %d)", len );
if ( L ) printf( " L" );
printf( "\n" );
}
void tdPrint( tdNode* tree, tdNode* nodes )
{
if ( tree->original != (uint16_t)~0 ) PrintCode( tree->code, tree->len, 1 );
else PrintCode( tree->freq, tree->len, 0 );
if ( tree->left != (uint16_t)~0 )
{
if ( tree->right != (uint16_t)~0 ) printf( "%s %c%c%c", depth, 195, 196, 196 );
else printf( "%s %c%c%c", depth, 192, 196, 196 );
Push( 179 );
tdPrint( nodes + tree->left, nodes );
tdPop( );
}
if ( tree->right != (uint16_t)~0 )
{
printf( "%s %c%c%c", depth, 192, 196, 196 );
Push( ' ' );
tdPrint( nodes + tree->right, nodes );
tdPop( );
}
}
typedef struct Node Node;
/*
Nodes forming chains. Also used to represent leaves.
*/
struct Node {
int weight; /* Total weight (symbol count) of this chain. */
Node* tail; /* Previous node(s) of this chain, or 0 if none. */
int count; /* Leaf symbol index, or number of leaves before this chain. */
};
/*
Memory pool for nodes.
*/
typedef struct NodePool {
Node* next; /* Pointer to a free node in the pool. */
} NodePool;
/*
Initializes a chain node with the given values and marks it as in use.
*/
static void InitNode(int weight, int count, Node* tail, Node* node) {
node->weight = weight;
node->count = count;
node->tail = tail;
}
/*
Performs a Boundary Package-Merge step. Puts a new chain in the given list. The
new chain is, depending on the weights, a leaf or a combination of two chains
from the previous list.
lists: The lists of chains.
maxbits: Number of lists.
leaves: The leaves, one per symbol.
numsymbols: Number of leaves.
pool: the node memory pool.
index: The index of the list in which a new chain or leaf is required.
*/
static void BoundaryPM(Node* (*lists)[2], Node* leaves, int numsymbols,
NodePool* pool, int index) {
Node* newchain;
Node* oldchain;
int lastcount = lists[index][1]->count; /* Count of last chain of list. */
if (index == 0 && lastcount >= numsymbols) return;
newchain = pool->next++;
oldchain = lists[index][1];
/* These are set up before the recursive calls below, so that there is a list
pointing to the new node, to let the garbage collection know it's in use. */
lists[index][0] = oldchain;
lists[index][1] = newchain;
if (index == 0) {
/* New leaf node in list 0. */
InitNode(leaves[lastcount].weight, lastcount + 1, 0, newchain);
} else {
int sum = lists[index - 1][0]->weight + lists[index - 1][1]->weight;
if (lastcount < numsymbols && sum > leaves[lastcount].weight) {
/* New leaf inserted in list, so count is incremented. */
InitNode(leaves[lastcount].weight, lastcount + 1, oldchain->tail,
newchain);
} else {
InitNode(sum, lastcount, lists[index - 1][1], newchain);
/* Two lookahead chains of previous list used up, create new ones. */
BoundaryPM(lists, leaves, numsymbols, pool, index - 1);
BoundaryPM(lists, leaves, numsymbols, pool, index - 1);
}
}
}
static void BoundaryPMFinal(Node* (*lists)[2],
Node* leaves, int numsymbols, NodePool* pool, int index) {
int lastcount = lists[index][1]->count; /* Count of last chain of list. */
int sum = lists[index - 1][0]->weight + lists[index - 1][1]->weight;
if (lastcount < numsymbols && sum > leaves[lastcount].weight) {
Node* newchain = pool->next;
Node* oldchain = lists[index][1]->tail;
lists[index][1] = newchain;
newchain->count = lastcount + 1;
newchain->tail = oldchain;
} else {
lists[index][1]->tail = lists[index - 1][1];
}
}
/*
Initializes each list with as lookahead chains the two leaves with lowest
weights.
*/
static void InitLists(
NodePool* pool, const Node* leaves, int maxbits, Node* (*lists)[2]) {
int i;
Node* node0 = pool->next++;
Node* node1 = pool->next++;
InitNode(leaves[0].weight, 1, 0, node0);