-
Notifications
You must be signed in to change notification settings - Fork 51
/
ufbx.c
8139 lines (6902 loc) · 260 KB
/
ufbx.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "ufbx.h"
#ifndef UFBX_UFBX_C_INLCUDED
#define UFBX_UFBX_C_INLCUDED
// -- Configuration
#define UFBXI_MAX_ALLOCATION_SIZE 0x10000000
#define UFBXI_MAX_NON_ARRAY_VALUES 7
// -- Headers
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
// -- Platform
#if defined(_MSC_VER)
#define ufbxi_noinline __declspec(noinline)
#define ufbxi_forceinline __forceinline
#if defined(__cplusplus) && _MSC_VER >= 1900
#define ufbxi_nodiscard [[nodiscard]]
#else
#define ufbxi_nodiscard _Check_return_
#endif
#elif defined(__GNUC__) || defined(__clang__)
#define ufbxi_noinline __attribute__((noinline))
#define ufbxi_forceinline inline __attribute__((always_inline))
#define ufbxi_nodiscard __attribute__((warn_unused_result))
#else
#define ufbxi_noinline
#define ufbxi_forceinline
#define ufbxi_nodiscard
#endif
#if defined(__GNUC__) && !defined(__clang__)
#define ufbxi_ignore(cond) (void)!(cond)
#else
#define ufbxi_ignore(cond) (void)(cond)
#endif
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4200) // nonstandard extension used: zero-sized array in struct/union
#pragma warning(disable: 4201) // nonstandard extension used: nameless struct/union
#pragma warning(disable: 4127) // conditional expression is constant
#pragma warning(disable: 4706) // assignment within conditional expression
#pragma warning(disable: 4789) // buffer 'type_and_name' of size 8 bytes will be overrun; 16 bytes will be written starting at offset 0
#endif
#ifndef ufbx_assert
#include <assert.h>
#define ufbx_assert(cond) assert(cond)
#endif
#if !defined(ufbx_static_assert)
#if defined(__cplusplus) && __cplusplus >= 201103
#define ufbx_static_assert(desc, cond) static_assert(cond, #desc ": " #cond)
#else
#define ufbx_static_assert(desc, cond) typedef char ufbxi_static_assert_##desc[(cond)?1:-1]
#endif
#endif
#define ufbxi_read_u8(ptr) (*(const uint8_t*)(ptr))
#if (defined(_M_IX86) || defined(__i386__) || defined(_M_X64) || defined(__x86_64__) || defined(_M_ARM64) || defined(__aarch64__)) && !defined(UFBX_NO_UNALIGNED_LOADS) || defined(UFBX_USE_UNALIGNED_LOADS)
#define ufbxi_read_u16(ptr) (*(const uint16_t*)(ptr))
#define ufbxi_read_u32(ptr) (*(const uint32_t*)(ptr))
#define ufbxi_read_u64(ptr) (*(const uint64_t*)(ptr))
#define ufbxi_read_f32(ptr) (*(const float*)(ptr))
#define ufbxi_read_f64(ptr) (*(const double*)(ptr))
#elif defined(__wasm__) || defined(__EMSCRIPTEN__)
#define ufbxi_read_u16(ptr) ((uint16_t)*(const unsigned short ((aligned(1)))*)(ptr))
#define ufbxi_read_u32(ptr) ((uint32_t)*(const unsigned int ((aligned(1)))*)(ptr))
#define ufbxi_read_u64(ptr) ((uint64_t)*(const unsigned long long ((aligned(1)))*)(ptr))
#define ufbxi_read_f32(ptr) ((float)*(const float ((aligned(1)))*)(ptr))
#define ufbxi_read_f64(ptr) ((double)*(const double ((aligned(1)))*)(ptr))
#else
static ufbxi_forceinline uint16_t ufbxi_read_u16(const void *ptr) {
const char *p = ptr;
return (uint16_t)(
(unsigned)(uint8_t)p[0] << 0u |
(unsigned)(uint8_t)p[1] << 8u );
}
static ufbxi_forceinline uint32_t ufbxi_read_u32(const void *ptr) {
const char *p = ptr;
return (uint32_t)(
(unsigned)(uint8_t)p[0] << 0u |
(unsigned)(uint8_t)p[1] << 8u |
(unsigned)(uint8_t)p[2] << 16u |
(unsigned)(uint8_t)p[3] << 24u );
}
static ufbxi_forceinline uint64_t ufbxi_read_u64(const void *ptr) {
const char *p = ptr;
return (uint64_t)(
(uint64_t)(uint8_t)p[0] << 0u |
(uint64_t)(uint8_t)p[1] << 8u |
(uint64_t)(uint8_t)p[2] << 16u |
(uint64_t)(uint8_t)p[3] << 24u |
(uint64_t)(uint8_t)p[4] << 32u |
(uint64_t)(uint8_t)p[5] << 40u |
(uint64_t)(uint8_t)p[6] << 48u |
(uint64_t)(uint8_t)p[7] << 56u );
}
static ufbxi_forceinline float ufbxi_read_f32(const void *ptr) {
uint32_t u = ufbxi_read_u32(ptr);
float f;
memcpy(&f, &u, 4);
return f;
}
static ufbxi_forceinline double ufbxi_read_f64(const void *ptr) {
uint64_t u = ufbxi_read_u64(ptr);
double f;
memcpy(&f, &u, 8);
return f;
}
#endif
#define ufbxi_read_i8(ptr) (int8_t)(ufbxi_read_u8(ptr))
#define ufbxi_read_i16(ptr) (int16_t)(ufbxi_read_u16(ptr))
#define ufbxi_read_i32(ptr) (int32_t)(ufbxi_read_u32(ptr))
#define ufbxi_read_i64(ptr) (int64_t)(ufbxi_read_u64(ptr))
ufbx_static_assert(sizeof_bool, sizeof(bool) == 1);
ufbx_static_assert(sizeof_i8, sizeof(int8_t) == 1);
ufbx_static_assert(sizeof_i16, sizeof(int16_t) == 2);
ufbx_static_assert(sizeof_i32, sizeof(int32_t) == 4);
ufbx_static_assert(sizeof_i64, sizeof(int64_t) == 8);
ufbx_static_assert(sizeof_u8, sizeof(uint8_t) == 1);
ufbx_static_assert(sizeof_u16, sizeof(uint16_t) == 2);
ufbx_static_assert(sizeof_u32, sizeof(uint32_t) == 4);
ufbx_static_assert(sizeof_u64, sizeof(uint64_t) == 8);
ufbx_static_assert(sizeof_f32, sizeof(float) == 4);
ufbx_static_assert(sizeof_f64, sizeof(double) == 8);
// -- Utility
#define ufbxi_arraycount(arr) (sizeof(arr) / sizeof(*(arr)))
#define ufbxi_for(m_type, m_name, m_begin, m_num) for (m_type *m_name = m_begin, *m_name##_end = m_name + (m_num); m_name != m_name##_end; m_name++)
#define ufbxi_for_ptr(m_type, m_name, m_begin, m_num) for (m_type **m_name = m_begin, **m_name##_end = m_name + (m_num); m_name != m_name##_end; m_name++)
static ufbxi_forceinline uint32_t ufbxi_min32(uint32_t a, uint32_t b) { return a < b ? a : b; }
static ufbxi_forceinline uint32_t ufbxi_max32(uint32_t a, uint32_t b) { return a < b ? b : a; }
static ufbxi_forceinline uint64_t ufbxi_min64(uint64_t a, uint64_t b) { return a < b ? a : b; }
static ufbxi_forceinline uint64_t ufbxi_max64(uint64_t a, uint64_t b) { return a < b ? b : a; }
static ufbxi_forceinline size_t ufbxi_min_sz(size_t a, size_t b) { return a < b ? a : b; }
static ufbxi_forceinline size_t ufbxi_max_sz(size_t a, size_t b) { return a < b ? b : a; }
#ifndef RHMAP_H_INCLUDED
#define RHMAP_H_INCLUDED
#ifndef RHMAP_NO_STDINT
#include <stddef.h>
#include <stdint.h>
#endif
typedef struct rhmap_s {
uint64_t *entries;
uint32_t mask;
uint32_t capacity;
uint32_t size;
} rhmap;
typedef struct rhmap_iter_s {
rhmap *map;
uint32_t hash;
uint32_t scan;
} rhmap_iter;
#endif
// -- Inline rhmap.h
#define RHMAP_INLINE static ufbxi_forceinline
#if defined(RHMAP_IMPLEMENTATION) || defined(RHMAP_INLINE)
#if (defined(RHMAP_IMPLEMENTATION) && !defined(RHMAP_H_IMPLEMENTED)) || (defined(RHMAP_INLINE) && !defined(RHMAP_H_INLINED))
#ifdef RHMAP_IMPLEMENTATION
#define RHMAP_H_IMPLEMENTED
#endif
#ifdef RHMAP_INLINE
#define RHMAP_H_INLINED
#endif
#ifndef RHMAP_MEMSET
#ifdef RHMAP_NO_STDLIB
static void rhmap_imp_memset(void *data, int value, size_t num)
{
uint64_t *ptr = (uint64_t*)data, *end = ptr + num / 8;
while (ptr != end) *ptr++ = 0;
}
#define RHMAP_MEMSET rhmap_imp_memset
#else
#include <string.h>
#define RHMAP_MEMSET memset
#endif
#endif
#ifdef RHMAP_INLINE
RHMAP_INLINE void *rhmap_reset_inline(rhmap *map)
#else
void *rhmap_reset(rhmap *map)
#endif
{
void *data = map->entries;
map->entries = 0;
map->mask = map->capacity = map->size = 0;
return data;
}
#ifdef RHMAP_INLINE
RHMAP_INLINE void rhmap_grow_inline(rhmap *map, size_t *count, size_t *alloc_size, size_t min_size, double load_factor)
#else
void rhmap_grow(rhmap *map, size_t *count, size_t *alloc_size, size_t min_size, double load_factor)
#endif
{
size_t num_entries = map->mask + 1;
size_t size = (size_t)((double)num_entries * load_factor);
if (min_size < map->capacity + 1) min_size = map->capacity + 1;
while (size < min_size) {
num_entries *= 2;
size = (size_t)((double)num_entries * load_factor);
}
*count = size;
*alloc_size = num_entries * sizeof(uint64_t);
}
#ifdef RHMAP_INLINE
RHMAP_INLINE int rhmap_find_inline(rhmap_iter *iter, uint32_t *value)
#else
int rhmap_find(rhmap_iter *iter, uint32_t *value)
#endif
{
rhmap *map = iter->map;
uint64_t *entries = map->entries;
uint32_t mask = map->mask, hash = iter->hash, scan = iter->scan;
uint32_t ref = hash & ~mask;
if (!mask) return 0;
for (;;) {
uint64_t entry = entries[(hash + scan) & mask];
scan += 1;
if ((uint32_t)entry == ref + scan) {
iter->scan = scan;
*value = (uint32_t)(entry >> 32u);
return 1;
} else if ((entry & mask) < scan) {
iter->scan = scan - 1;
return 0;
}
}
}
#ifdef RHMAP_INLINE
RHMAP_INLINE void rhmap_insert_inline(rhmap_iter *iter, uint32_t value)
#else
void rhmap_insert(rhmap_iter *iter, uint32_t value)
#endif
{
rhmap *map = iter->map;
uint64_t *entries = map->entries;
uint32_t mask = map->mask, hash = iter->hash, scan = iter->scan;
uint32_t slot = (hash + scan) & mask;
uint64_t entry, new_entry = (uint64_t)value << 32u | (hash & ~mask);
scan += 1;
while ((entry = entries[slot]) != 0) {
uint32_t entry_scan = (entry & mask);
if (entry_scan < scan) {
entries[slot] = new_entry + scan;
new_entry = (entry & ~(uint64_t)mask);
scan = entry_scan;
}
scan += 1;
slot = (slot + 1) & mask;
}
entries[slot] = new_entry + scan;
map->size++;
}
#ifdef RHMAP_INLINE
RHMAP_INLINE void *rhmap_rehash_inline(rhmap *map, size_t count, size_t alloc_size, void *data_ptr)
#else
void *rhmap_rehash(rhmap *map, size_t count, size_t alloc_size, void *data_ptr)
#endif
{
rhmap old_map = *map;
size_t num_entries = alloc_size / sizeof(uint64_t);
uint64_t *entries = (uint64_t*)data_ptr;
uint32_t mask = old_map.mask;
map->entries = entries;
map->mask = (uint32_t)(num_entries) - 1;
map->capacity = (uint32_t)count;
map->size = 0;
RHMAP_MEMSET(entries, 0, sizeof(uint64_t) * num_entries);
if (old_map.mask) {
uint32_t i;
for (i = 0; i <= old_map.mask; i++) {
uint64_t entry = old_map.entries[i];
if (entry) {
uint32_t scan = (uint32_t)(entry & mask) - 1;
uint32_t hash = ((uint32_t)entry & ~mask) | ((i - scan) & mask);
uint32_t value = (uint32_t)(entry >> 32u);
rhmap_iter iter;
iter.map = map;
iter.hash = hash;
iter.scan = 0;
#ifdef RHMAP_INLINE
rhmap_insert_inline(&iter, value);
#else
rhmap_insert(&iter, value);
#endif
}
}
}
return old_map.entries;
}
#ifdef RHMAP_INLINE
RHMAP_INLINE int rhmap_next_inline(rhmap_iter *iter, uint32_t *hash, uint32_t *value)
#else
int rhmap_next(rhmap_iter *iter, uint32_t *hash, uint32_t *value)
#endif
{
rhmap *map = iter->map;
uint64_t *entries = map->entries;
uint32_t mask = map->mask;
uint32_t scan = (iter->hash & mask) + iter->scan;
if (!mask) return 0;
while (scan != mask + 1) {
uint64_t entry = entries[scan & mask];
scan += 1;
if (entry) {
uint32_t ref_scan = (uint32_t)(entry & mask) - 1;
uint32_t ref_hash = ((uint32_t)entry & ~mask) | ((scan - ref_scan - 1) & mask);
*hash = ref_hash;
*value = (uint64_t)entry >> 32u;
iter->hash = ref_hash;
iter->scan = ref_scan + 1;
return 1;
}
}
return 0;
}
#endif
#endif
// -- DEFLATE implementation
// Pretty much based on Sean Barrett's `stb_image` deflate
#if !defined(ufbx_inflate)
// Lookup data: [0:13] extra mask [13:17] extra bits [17:32] base value
// Generated by `misc/deflate_lut.py`
static const uint32_t ufbxi_deflate_length_lut[] = {
0x00060000, 0x00080000, 0x000a0000, 0x000c0000, 0x000e0000, 0x00100000, 0x00120000, 0x00140000,
0x00162001, 0x001a2001, 0x001e2001, 0x00222001, 0x00264003, 0x002e4003, 0x00364003, 0x003e4003,
0x00466007, 0x00566007, 0x00666007, 0x00766007, 0x0086800f, 0x00a6800f, 0x00c6800f, 0x00e6800f,
0x0106a01f, 0x0146a01f, 0x0186a01f, 0x01c6a01f, 0x02040000, 0x00000000, 0x00000000,
};
static const uint32_t ufbxi_deflate_dist_lut[] = {
0x00020000, 0x00040000, 0x00060000, 0x00080000, 0x000a2001, 0x000e2001, 0x00124003, 0x001a4003,
0x00226007, 0x00326007, 0x0042800f, 0x0062800f, 0x0082a01f, 0x00c2a01f, 0x0102c03f, 0x0182c03f,
0x0202e07f, 0x0302e07f, 0x040300ff, 0x060300ff, 0x080321ff, 0x0c0321ff, 0x100343ff, 0x180343ff,
0x200367ff, 0x300367ff, 0x40038fff, 0x60038fff, 0x8003bfff, 0xc003bfff,
};
static const uint8_t ufbxi_deflate_code_length_permutation[] = {
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,
};
#define UFBXI_HUFF_MAX_BITS 16
#define UFBXI_HUFF_MAX_VALUE 288
#define UFBXI_HUFF_FAST_BITS 9
#define UFBXI_HUFF_FAST_SIZE (1 << UFBXI_HUFF_FAST_BITS)
#define UFBXI_HUFF_FAST_MASK (UFBXI_HUFF_FAST_SIZE - 1)
typedef struct {
// Number of bytes left to read from `read_fn()`
size_t input_left;
// User-supplied read callback
ufbx_read_fn *read_fn;
void *read_user;
// Buffer to read to from `read_fn()`, may point to `local_buffer` if user
// didn't supply a suitable buffer.
char *buffer;
size_t buffer_size;
// Current chunk of data to process, either the initial buffer of input
// or part of `buffer`.
const char *chunk_begin; // < Begin of the buffer
const char *chunk_ptr; // < Next bytes to read to `bits`
const char *chunk_end; // < End of data before needing to call `ufbxi_bit_refill()`
const char *chunk_real_end; // < Actual end of the data buffer
uint64_t bits; // < Buffered bits
size_t left; // < Number of valid low bits in `bits`
char local_buffer[64];
} ufbxi_bit_stream;
typedef struct {
uint32_t num_symbols;
uint16_t sorted_to_sym[UFBXI_HUFF_MAX_VALUE]; // < Sorted symbol index to symbol
uint16_t past_max_code[UFBXI_HUFF_MAX_BITS]; // < One past maximum code value per bit length
int16_t code_to_sorted[UFBXI_HUFF_MAX_BITS]; // < Code to sorted symbol index per bit length
uint16_t fast_sym[UFBXI_HUFF_FAST_SIZE]; // < Fast symbol lookup [0:12] symbol [12:16] bits
} ufbxi_huff_tree;
typedef struct {
ufbxi_huff_tree lit_length;
ufbxi_huff_tree dist;
} ufbxi_trees;
typedef struct {
bool initialized;
ufbxi_trees static_trees;
} ufbxi_inflate_retain_imp;
ufbx_static_assert(inflate_retain_size, sizeof(ufbxi_inflate_retain_imp) <= sizeof(ufbx_inflate_retain));
typedef struct {
ufbxi_bit_stream stream;
char *out_begin;
char *out_ptr;
char *out_end;
} ufbxi_deflate_context;
static ufbxi_forceinline uint32_t
ufbxi_bit_reverse(uint32_t mask, uint32_t num_bits)
{
ufbx_assert(num_bits <= 16);
uint32_t x = mask;
x = (((x & 0xaaaa) >> 1) | ((x & 0x5555) << 1));
x = (((x & 0xcccc) >> 2) | ((x & 0x3333) << 2));
x = (((x & 0xf0f0) >> 4) | ((x & 0x0f0f) << 4));
x = (((x & 0xff00) >> 8) | ((x & 0x00ff) << 8));
return x >> (16 - num_bits);
}
static ufbxi_noinline const char *
ufbxi_bit_chunk_refill(ufbxi_bit_stream *s, const char *ptr)
{
// Copy any left-over data to the beginning of `buffer`
size_t left = s->chunk_real_end - ptr;
ufbx_assert(left < 64);
memmove(s->buffer, ptr, left);
// Read more user data if the user supplied a `read_fn()`, otherwise
// we assume the initial data chunk is the whole input buffer.
if (s->read_fn) {
size_t to_read = ufbxi_min_sz(s->input_left, s->buffer_size - left);
if (to_read > 0) {
size_t num_read = s->read_fn(s->read_user, s->buffer + left, to_read);
if (num_read > to_read) num_read = 0;
ufbx_assert(s->input_left >= num_read);
s->input_left -= num_read;
left += num_read;
}
}
// Pad the rest with zeros
if (left < 64) {
memset(s->buffer + left, 0, 64 - left);
left = 64;
}
s->chunk_begin = s->buffer;
s->chunk_ptr = s->buffer;
s->chunk_end = s->buffer + left - 8;
s->chunk_real_end = s->buffer + left;
return s->buffer;
}
static void ufbxi_bit_stream_init(ufbxi_bit_stream *s, const ufbx_inflate_input *input)
{
size_t data_size = input->data_size;
if (data_size > input->total_size) {
data_size = input->total_size;
}
s->read_fn = input->read_fn;
s->read_user = input->read_user;
s->chunk_begin = (const char*)input->data;
s->chunk_ptr = (const char*)input->data;
s->chunk_end = (const char*)input->data + data_size - 8;
s->chunk_real_end = (const char*)input->data + data_size;
s->input_left = input->total_size - data_size;
// Use the user buffer if it's large enough, otherwise `local_buffer`
if (input->buffer_size >= 64) {
s->buffer = (char*)input->buffer;
s->buffer_size = input->buffer_size;
} else {
s->buffer = s->local_buffer;
s->buffer_size = sizeof(s->local_buffer);
}
// Clear the initial bit buffer
s->bits = 0;
s->left = 0;
// If the initial data buffer is not large enough to be read directly
// from refill the chunk once.
if (data_size < 64) {
ufbxi_bit_chunk_refill(s, s->chunk_begin);
}
}
static ufbxi_forceinline void
ufbxi_bit_refill(uint64_t *p_bits, size_t *p_left, const char **p_data, ufbxi_bit_stream *s)
{
if (*p_data > s->chunk_end) {
*p_data = ufbxi_bit_chunk_refill(s, *p_data);
}
// See https://fgiesen.wordpress.com/2018/02/20/reading-bits-in-far-too-many-ways-part-2/
// variant 4. This branchless refill guarantees [56,63] bits to be valid in `*p_bits`.
*p_bits |= ufbxi_read_u64(*p_data) << *p_left;
*p_data += (63 - *p_left) >> 3;
*p_left |= 56;
}
static int
ufbxi_bit_copy_bytes(void *dst, ufbxi_bit_stream *s, size_t len)
{
ufbx_assert(s->left % 8 == 0);
char *ptr = (char*)dst;
// Copy the buffered bits first
while (len > 0 && s->left > 0) {
*ptr++ = (char)(uint8_t)s->bits;
len -= 1;
s->bits >>= 8;
s->left -= 8;
}
// We need to clear the top bits as there may be data
// read ahead past `s->left` in some cases
s->bits = 0;
// Copy the current chunk
size_t chunk_left = s->chunk_real_end - s->chunk_ptr;
if (chunk_left >= len) {
memcpy(ptr, s->chunk_ptr, len);
s->chunk_ptr += len;
return 1;
} else {
memcpy(ptr, s->chunk_ptr, chunk_left);
s->chunk_ptr += chunk_left;
ptr += chunk_left;
len -= chunk_left;
}
// Read extra bytes from user
if (len > s->input_left) return 0;
size_t num_read = 0;
if (s->read_fn) {
num_read = s->read_fn(s->read_user, ptr, len);
s->input_left -= num_read;
}
return num_read == len;
}
// 0: Success
// -1: Overfull
// -2: Underfull
static ufbxi_noinline ptrdiff_t
ufbxi_huff_build(ufbxi_huff_tree *tree, uint8_t *sym_bits, uint32_t sym_count)
{
ufbx_assert(sym_count <= UFBXI_HUFF_MAX_VALUE);
tree->num_symbols = sym_count;
// Count the number of codes per bit length
// `bit_counts[0]` contains the number of non-used symbols
uint32_t bits_counts[UFBXI_HUFF_MAX_BITS];
memset(bits_counts, 0, sizeof(bits_counts));
for (uint32_t i = 0; i < sym_count; i++) {
uint32_t bits = sym_bits[i];
ufbx_assert(bits < UFBXI_HUFF_MAX_BITS);
bits_counts[bits]++;
}
uint32_t nonzero_sym_count = sym_count - bits_counts[0];
uint32_t total_syms[UFBXI_HUFF_MAX_BITS];
uint32_t first_code[UFBXI_HUFF_MAX_BITS];
tree->code_to_sorted[0] = INT16_MAX;
tree->past_max_code[0] = 0;
total_syms[0] = 0;
// Resolve the maximum code per bit length and ensure that the tree is not
// overfull or underfull.
{
int num_codes_left = 1;
uint32_t code = 0;
uint32_t prev_count = 0;
for (uint32_t bits = 1; bits < UFBXI_HUFF_MAX_BITS; bits++) {
uint32_t count = bits_counts[bits];
code = (code + prev_count) << 1;
first_code[bits] = code;
tree->past_max_code[bits] = (uint16_t)(code + count);
uint32_t prev_syms = total_syms[bits - 1];
total_syms[bits] = prev_syms + count;
// Each bit level doubles the amount of codes and potentially removes some
num_codes_left = (num_codes_left << 1) - count;
if (num_codes_left < 0) {
return -1;
}
if (count > 0) {
tree->code_to_sorted[bits] = (int16_t)((int)prev_syms - (int)code);
} else {
tree->code_to_sorted[bits] = INT16_MAX;
}
prev_count = count;
}
// All codes should be used if there's more than one symbol
if (nonzero_sym_count > 1 && num_codes_left != 0) {
return -2;
}
}
// Generate per-length sorted-to-symbol and fast lookup tables
uint32_t bits_index[UFBXI_HUFF_MAX_BITS] = { 0 };
memset(tree->sorted_to_sym, 0xff, sizeof(tree->sorted_to_sym));
memset(tree->fast_sym, 0, sizeof(tree->fast_sym));
for (uint32_t i = 0; i < sym_count; i++) {
uint32_t bits = sym_bits[i];
if (bits == 0) continue;
uint32_t index = bits_index[bits]++;
uint32_t sorted = total_syms[bits - 1] + index;
tree->sorted_to_sym[sorted] = (uint16_t)i;
// Reverse the code and fill all fast lookups with the reversed prefix
uint32_t code = first_code[bits] + index;
uint32_t rev_code = ufbxi_bit_reverse(code, bits);
if (bits <= UFBXI_HUFF_FAST_BITS) {
uint16_t fast_sym = (uint16_t)(i | bits << 12);
uint32_t hi_max = 1 << (UFBXI_HUFF_FAST_BITS - bits);
for (uint32_t hi = 0; hi < hi_max; hi++) {
ufbx_assert(tree->fast_sym[rev_code | hi << bits] == 0);
tree->fast_sym[rev_code | hi << bits] = fast_sym;
}
}
}
return 0;
}
static ufbxi_forceinline uint32_t
ufbxi_huff_decode_bits(const ufbxi_huff_tree *tree, uint64_t *p_bits, size_t *p_left)
{
// If the code length is less than or equal UFBXI_HUFF_FAST_BITS we can
// resolve the symbol and bit length directly from a lookup table.
uint32_t fast_sym_bits = tree->fast_sym[*p_bits & UFBXI_HUFF_FAST_MASK];
if (fast_sym_bits != 0) {
uint32_t bits = fast_sym_bits >> 12;
*p_bits >>= bits;
*p_left -= bits;
return fast_sym_bits & 0x3ff;
}
// The code length must be longer than UFBXI_HUFF_FAST_BITS, reverse the prefix
// and build the code one bit at a time until we are in range for the bit length.
uint32_t code = ufbxi_bit_reverse((uint32_t)*p_bits, UFBXI_HUFF_FAST_BITS + 1);
*p_bits >>= UFBXI_HUFF_FAST_BITS + 1;
*p_left -= UFBXI_HUFF_FAST_BITS + 1;
for (uint32_t bits = UFBXI_HUFF_FAST_BITS + 1; bits < UFBXI_HUFF_MAX_BITS; bits++) {
if (code < tree->past_max_code[bits]) {
uint32_t sorted = code + tree->code_to_sorted[bits];
if (sorted >= tree->num_symbols) return ~0u;
return tree->sorted_to_sym[sorted];
}
code = code << 1 | (uint32_t)(*p_bits & 1);
*p_bits >>= 1;
*p_left -= 1;
}
// We shouldn't get here unless the tree is underfull _or_ has only
// one symbol where the code `1` is invalid.
return ~0u;
}
static void ufbxi_init_static_huff(ufbxi_trees *trees)
{
ptrdiff_t err = 0;
// 0-143: 8 bits, 144-255: 9 bits, 256-279: 7 bits, 280-287: 8 bits
uint8_t lit_length_bits[288];
memset(lit_length_bits + 0, 8, 144 - 0);
memset(lit_length_bits + 144, 9, 256 - 144);
memset(lit_length_bits + 256, 7, 280 - 256);
memset(lit_length_bits + 280, 8, 288 - 280);
err |= ufbxi_huff_build(&trees->lit_length, lit_length_bits, sizeof(lit_length_bits));
// "Distance codes 0-31 are represented by (fixed-length) 5-bit codes"
uint8_t dist_bits[32];
memset(dist_bits + 0, 5, 32 - 0);
err |= ufbxi_huff_build(&trees->dist, dist_bits, sizeof(dist_bits));
// Building the static trees cannot fail as we use pre-defined code lengths.
ufbx_assert(err == 0);
}
// 0: Success
// -1: Huffman Overfull
// -2: Huffman Underfull
// -3: Code 16 repeat overflow
// -4: Code 17 repeat overflow
// -5: Code 18 repeat overflow
// -6: Bad length code
static ufbxi_noinline ptrdiff_t
ufbxi_init_dynamic_huff_tree(ufbxi_deflate_context *dc, const ufbxi_huff_tree *huff_code_length,
ufbxi_huff_tree *tree, uint32_t num_symbols)
{
uint8_t code_lengths[UFBXI_HUFF_MAX_VALUE];
ufbx_assert(num_symbols <= UFBXI_HUFF_MAX_VALUE);
uint64_t bits = dc->stream.bits;
size_t left = dc->stream.left;
const char *data = dc->stream.chunk_ptr;
uint32_t symbol_index = 0;
uint8_t prev = 0;
while (symbol_index < num_symbols) {
ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
uint32_t inst = ufbxi_huff_decode_bits(huff_code_length, &bits, &left);
if (inst <= 15) {
// "0 - 15: Represent code lengths of 0 - 15"
prev = (uint8_t)inst;
code_lengths[symbol_index++] = (uint8_t)inst;
} else if (inst == 16) {
// "16: Copy the previous code length 3 - 6 times. The next 2 bits indicate repeat length."
uint32_t num = 3 + ((uint32_t)bits & 0x3);
bits >>= 2;
left -= 2;
if (symbol_index + num > num_symbols) return -3;
memset(code_lengths + symbol_index, prev, num);
symbol_index += num;
} else if (inst == 17) {
// "17: Repeat a code length of 0 for 3 - 10 times. (3 bits of length)"
uint32_t num = 3 + ((uint32_t)bits & 0x7);
bits >>= 3;
left -= 3;
if (symbol_index + num > num_symbols) return -4;
memset(code_lengths + symbol_index, 0, num);
symbol_index += num;
prev = 0;
} else if (inst == 18) {
// "18: Repeat a code length of 0 for 11 - 138 times (7 bits of length)"
uint32_t num = 11 + ((uint32_t)bits & 0x7f);
bits >>= 7;
left -= 7;
if (symbol_index + num > num_symbols) return -5;
memset(code_lengths + symbol_index, 0, num);
symbol_index += num;
prev = 0;
} else {
return -6;
}
}
ptrdiff_t err = ufbxi_huff_build(tree, code_lengths, num_symbols);
if (err != 0) return err;
dc->stream.bits = bits;
dc->stream.left = left;
dc->stream.chunk_ptr = data;
return 0;
}
static ptrdiff_t
ufbxi_init_dynamic_huff(ufbxi_deflate_context *dc, ufbxi_trees *trees)
{
uint64_t bits = dc->stream.bits;
size_t left = dc->stream.left;
const char *data = dc->stream.chunk_ptr;
ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
// The header contains the number of Huffman codes in each of the three trees.
uint32_t num_lit_lengths = 257 + (bits & 0x1f);
uint32_t num_dists = 1 + (bits >> 5 & 0x1f);
uint32_t num_code_lengths = 4 + (bits >> 10 & 0xf);
bits >>= 14;
left -= 14;
// Code lengths for the "code length" Huffman tree are represented literally
// 3 bits in order of: 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 up to
// `num_code_lengths`, rest of the code lengths are 0 (unused)
uint8_t code_lengths[19];
memset(code_lengths, 0, sizeof(code_lengths));
for (size_t len_i = 0; len_i < num_code_lengths; len_i++) {
if (len_i == 14) ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
code_lengths[ufbxi_deflate_code_length_permutation[len_i]] = (uint32_t)bits & 0x7;
bits >>= 3;
left -= 3;
}
dc->stream.bits = bits;
dc->stream.left = left;
dc->stream.chunk_ptr = data;
ufbxi_huff_tree huff_code_length;
ptrdiff_t err;
// Build the temporary "code length" Huffman tree used to encode the actual
// trees used to compress the data. Use that to build the literal/length and
// distance trees.
err = ufbxi_huff_build(&huff_code_length, code_lengths, ufbxi_arraycount(code_lengths));
if (err) return -14 + 1 + err;
err = ufbxi_init_dynamic_huff_tree(dc, &huff_code_length, &trees->lit_length, num_lit_lengths);
if (err) return -16 + 1 + err;
err = ufbxi_init_dynamic_huff_tree(dc, &huff_code_length, &trees->dist, num_dists);
if (err) return -22 + 1 + err;
return 0;
}
static uint32_t ufbxi_adler32(const void *data, size_t size)
{
size_t a = 1, b = 0;
const char *p = (const char*)data;
// Adler-32 consists of two running sums modulo 65521. As an optimization
// we can accumulate N sums before applying the modulo, where N depends on
// the size of the type holding the sum.
const size_t num_before_wrap = sizeof(size_t) == 8 ? 380368439u : 5552u;
size_t size_left = size;
while (size_left > 0) {
size_t num = size_left <= num_before_wrap ? size_left : num_before_wrap;
size_left -= num;
const char *end = p + num;
while (end - p >= 8) {
a += (size_t)(uint8_t)p[0]; b += a;
a += (size_t)(uint8_t)p[1]; b += a;
a += (size_t)(uint8_t)p[2]; b += a;
a += (size_t)(uint8_t)p[3]; b += a;
a += (size_t)(uint8_t)p[4]; b += a;
a += (size_t)(uint8_t)p[5]; b += a;
a += (size_t)(uint8_t)p[6]; b += a;
a += (size_t)(uint8_t)p[7]; b += a;
p += 8;
}
while (p != end) {
a += (size_t)(uint8_t)p[0]; b += a;
p++;
}
a %= 65521u;
b %= 65521u;
}
return (uint32_t)((b << 16) | (a & 0xffff));
}
static int
ufbxi_inflate_block(ufbxi_deflate_context *dc, ufbxi_trees *trees)
{
char *out_ptr = dc->out_ptr;
char *const out_begin = dc->out_begin;
char *const out_end = dc->out_end;
uint64_t bits = dc->stream.bits;
size_t left = dc->stream.left;
const char *data = dc->stream.chunk_ptr;
for (;;) {
ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
// Decode literal/length value from input stream
uint32_t lit_length = ufbxi_huff_decode_bits(&trees->lit_length, &bits, &left);
// If value < 256: copy value (literal byte) to output stream
if (lit_length < 256) {
if (out_ptr == out_end) {
return -10;
}
*out_ptr++ = (char)lit_length;
} else if (lit_length - 257 <= 285 - 257) {
// If value = 257..285: Decode extra length and distance and copy `length` bytes
// from `distance` bytes before in the buffer.
uint32_t length, distance;
// Length: Look up base length and add optional additional bits
{
uint32_t lut = ufbxi_deflate_length_lut[lit_length - 257];
uint32_t base = lut >> 17;
uint32_t offset = ((uint32_t)bits & lut & 0x1fff);
uint32_t offset_bits = (lut >> 13) & 0xf;
bits >>= offset_bits;
left -= offset_bits;
length = base + offset;
}
// Distance: Decode as a Huffman code and add optional additional bits
{
uint32_t dist = ufbxi_huff_decode_bits(&trees->dist, &bits, &left);
if (dist >= 30) {
return -11;
}
uint32_t lut = ufbxi_deflate_dist_lut[dist];
uint32_t base = lut >> 17;
uint32_t offset = ((uint32_t)bits & lut & 0x1fff);
uint32_t offset_bits = (lut >> 13) & 0xf;
bits >>= offset_bits;
left -= offset_bits;
distance = base + offset;
}
if ((ptrdiff_t)distance > out_ptr - out_begin || (ptrdiff_t)length > out_end - out_ptr) {
return -12;
}
ufbx_assert(length > 0);
const char *src = out_ptr - distance;
char *dst = out_ptr;
out_ptr += length;
{
// TODO: Do something better than per-byte copy
char *end = dst + length;
while (end - dst >= 4) {
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
dst += 4;
src += 4;
}
while (dst != end) {
*dst++ = *src++;
}
}
} else if (lit_length == 256) {
break;
} else {
return -13;
}
}
dc->out_ptr = out_ptr;
dc->stream.bits = bits;
dc->stream.left = left;
dc->stream.chunk_ptr = data;
return 0;
}
// TODO: Error codes should have a quick test if the destination buffer overflowed
// Returns actual number of decompressed bytes or negative error:
// -1: Bad compression method (ZLIB header)
// -2: Requires dictionary (ZLIB header)
// -3: Bad FCHECK (ZLIB header)
// -4: Bad NLEN (Uncompressed LEN != ~NLEN)
// -5: Uncompressed source overflow
// -6: Uncompressed destination overflow
// -7: Bad block type
// -8: Truncated checksum (deprecated, reported as -9)
// -9: Checksum mismatch
// -10: Literal destination overflow
// -11: Bad distance code or distance of (30..31)
// -12: Match out of bounds
// -13: Bad lit/length code
// -14: Codelen Huffman Overfull
// -15: Codelen Huffman Underfull
// -16 - -21: Litlen Huffman: Overfull / Underfull / Repeat 16/17/18 overflow / Bad length code
// -22 - -27: Distance Huffman: Overfull / Underfull / Repeat 16/17/18 overflow / Bad length code
ptrdiff_t ufbx_inflate(void *dst, size_t dst_size, const ufbx_inflate_input *input, ufbx_inflate_retain *retain)
{
ufbxi_inflate_retain_imp *ret_imp = (ufbxi_inflate_retain_imp*)retain;
ptrdiff_t err;
ufbxi_deflate_context dc;
ufbxi_bit_stream_init(&dc.stream, input);
dc.out_begin = (char*)dst;
dc.out_ptr = (char*)dst;
dc.out_end = (char*)dst + dst_size;
uint64_t bits = dc.stream.bits;