forked from andybalholm/brotli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
2632 lines (2243 loc) · 68.5 KB
/
decode.go
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
package brotli
/* Copyright 2013 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
const (
decoderResultError = 0
decoderResultSuccess = 1
decoderResultNeedsMoreInput = 2
decoderResultNeedsMoreOutput = 3
)
/**
* Error code for detailed logging / production debugging.
*
* See ::BrotliDecoderGetErrorCode and ::BROTLI_LAST_ERROR_CODE.
*/
const (
decoderNoError = 0
decoderSuccess = 1
decoderNeedsMoreInput = 2
decoderNeedsMoreOutput = 3
decoderErrorFormatExuberantNibble = -1
decoderErrorFormatReserved = -2
decoderErrorFormatExuberantMetaNibble = -3
decoderErrorFormatSimpleHuffmanAlphabet = -4
decoderErrorFormatSimpleHuffmanSame = -5
decoderErrorFormatClSpace = -6
decoderErrorFormatHuffmanSpace = -7
decoderErrorFormatContextMapRepeat = -8
decoderErrorFormatBlockLength1 = -9
decoderErrorFormatBlockLength2 = -10
decoderErrorFormatTransform = -11
decoderErrorFormatDictionary = -12
decoderErrorFormatWindowBits = -13
decoderErrorFormatPadding1 = -14
decoderErrorFormatPadding2 = -15
decoderErrorFormatDistance = -16
decoderErrorDictionaryNotSet = -19
decoderErrorInvalidArguments = -20
decoderErrorAllocContextModes = -21
decoderErrorAllocTreeGroups = -22
decoderErrorAllocContextMap = -25
decoderErrorAllocRingBuffer1 = -26
decoderErrorAllocRingBuffer2 = -27
decoderErrorAllocBlockTypeTrees = -30
decoderErrorUnreachable = -31
)
/**
* The value of the last error code, negative integer.
*
* All other error code values are in the range from ::lastErrorCode
* to @c -1. There are also 4 other possible non-error codes @c 0 .. @c 3 in
* ::BrotliDecoderErrorCode enumeration.
*/
const lastErrorCode = decoderErrorUnreachable
/** Options to be used with ::BrotliDecoderSetParameter. */
const (
decoderParamDisableRingBufferReallocation = 0
decoderParamLargeWindow = 1
)
const huffmanTableBits = 8
const huffmanTableMask = 0xFF
/* We need the slack region for the following reasons:
- doing up to two 16-byte copies for fast backward copying
- inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
const kRingBufferWriteAheadSlack uint32 = 42
var kCodeLengthCodeOrder = [codeLengthCodes]byte{1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15}
/* Static prefix code for the complex code length code lengths. */
var kCodeLengthPrefixLength = [16]byte{2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4}
var kCodeLengthPrefixValue = [16]byte{0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5}
func decoderSetParameter(state *Reader, p int, value uint32) bool {
if state.state != stateUninited {
return false
}
switch p {
case decoderParamDisableRingBufferReallocation:
if !(value == 0) {
state.canny_ringbuffer_allocation = 0
} else {
state.canny_ringbuffer_allocation = 1
}
return true
case decoderParamLargeWindow:
state.large_window = (!(value == 0))
return true
default:
return false
}
}
/* Saves error code and converts it to BrotliDecoderResult. */
func saveErrorCode(s *Reader, e int) int {
s.error_code = int(e)
switch e {
case decoderSuccess:
return decoderResultSuccess
case decoderNeedsMoreInput:
return decoderResultNeedsMoreInput
case decoderNeedsMoreOutput:
return decoderResultNeedsMoreOutput
default:
return decoderResultError
}
}
/* Decodes WBITS by reading 1 - 7 bits, or 0x11 for "Large Window Brotli".
Precondition: bit-reader accumulator has at least 8 bits. */
func decodeWindowBits(s *Reader, br *bitReader) int {
var n uint32
var large_window bool = s.large_window
s.large_window = false
takeBits(br, 1, &n)
if n == 0 {
s.window_bits = 16
return decoderSuccess
}
takeBits(br, 3, &n)
if n != 0 {
s.window_bits = 17 + n
return decoderSuccess
}
takeBits(br, 3, &n)
if n == 1 {
if large_window {
takeBits(br, 1, &n)
if n == 1 {
return decoderErrorFormatWindowBits
}
s.large_window = true
return decoderSuccess
} else {
return decoderErrorFormatWindowBits
}
}
if n != 0 {
s.window_bits = 8 + n
return decoderSuccess
}
s.window_bits = 17
return decoderSuccess
}
/* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
func decodeVarLenUint8(s *Reader, br *bitReader, value *uint32) int {
var bits uint32
switch s.substate_decode_uint8 {
case stateDecodeUint8None:
if !safeReadBits(br, 1, &bits) {
return decoderNeedsMoreInput
}
if bits == 0 {
*value = 0
return decoderSuccess
}
fallthrough
/* Fall through. */
case stateDecodeUint8Short:
if !safeReadBits(br, 3, &bits) {
s.substate_decode_uint8 = stateDecodeUint8Short
return decoderNeedsMoreInput
}
if bits == 0 {
*value = 1
s.substate_decode_uint8 = stateDecodeUint8None
return decoderSuccess
}
/* Use output value as a temporary storage. It MUST be persisted. */
*value = bits
fallthrough
/* Fall through. */
case stateDecodeUint8Long:
if !safeReadBits(br, *value, &bits) {
s.substate_decode_uint8 = stateDecodeUint8Long
return decoderNeedsMoreInput
}
*value = (1 << *value) + bits
s.substate_decode_uint8 = stateDecodeUint8None
return decoderSuccess
default:
return decoderErrorUnreachable
}
}
/* Decodes a metablock length and flags by reading 2 - 31 bits. */
func decodeMetaBlockLength(s *Reader, br *bitReader) int {
var bits uint32
var i int
for {
switch s.substate_metablock_header {
case stateMetablockHeaderNone:
if !safeReadBits(br, 1, &bits) {
return decoderNeedsMoreInput
}
if bits != 0 {
s.is_last_metablock = 1
} else {
s.is_last_metablock = 0
}
s.meta_block_remaining_len = 0
s.is_uncompressed = 0
s.is_metadata = 0
if s.is_last_metablock == 0 {
s.substate_metablock_header = stateMetablockHeaderNibbles
break
}
s.substate_metablock_header = stateMetablockHeaderEmpty
fallthrough
/* Fall through. */
case stateMetablockHeaderEmpty:
if !safeReadBits(br, 1, &bits) {
return decoderNeedsMoreInput
}
if bits != 0 {
s.substate_metablock_header = stateMetablockHeaderNone
return decoderSuccess
}
s.substate_metablock_header = stateMetablockHeaderNibbles
fallthrough
/* Fall through. */
case stateMetablockHeaderNibbles:
if !safeReadBits(br, 2, &bits) {
return decoderNeedsMoreInput
}
s.size_nibbles = uint(byte(bits + 4))
s.loop_counter = 0
if bits == 3 {
s.is_metadata = 1
s.substate_metablock_header = stateMetablockHeaderReserved
break
}
s.substate_metablock_header = stateMetablockHeaderSize
fallthrough
/* Fall through. */
case stateMetablockHeaderSize:
i = s.loop_counter
for ; i < int(s.size_nibbles); i++ {
if !safeReadBits(br, 4, &bits) {
s.loop_counter = i
return decoderNeedsMoreInput
}
if uint(i+1) == s.size_nibbles && s.size_nibbles > 4 && bits == 0 {
return decoderErrorFormatExuberantNibble
}
s.meta_block_remaining_len |= int(bits << uint(i*4))
}
s.substate_metablock_header = stateMetablockHeaderUncompressed
fallthrough
/* Fall through. */
case stateMetablockHeaderUncompressed:
if s.is_last_metablock == 0 {
if !safeReadBits(br, 1, &bits) {
return decoderNeedsMoreInput
}
if bits != 0 {
s.is_uncompressed = 1
} else {
s.is_uncompressed = 0
}
}
s.meta_block_remaining_len++
s.substate_metablock_header = stateMetablockHeaderNone
return decoderSuccess
case stateMetablockHeaderReserved:
if !safeReadBits(br, 1, &bits) {
return decoderNeedsMoreInput
}
if bits != 0 {
return decoderErrorFormatReserved
}
s.substate_metablock_header = stateMetablockHeaderBytes
fallthrough
/* Fall through. */
case stateMetablockHeaderBytes:
if !safeReadBits(br, 2, &bits) {
return decoderNeedsMoreInput
}
if bits == 0 {
s.substate_metablock_header = stateMetablockHeaderNone
return decoderSuccess
}
s.size_nibbles = uint(byte(bits))
s.substate_metablock_header = stateMetablockHeaderMetadata
fallthrough
/* Fall through. */
case stateMetablockHeaderMetadata:
i = s.loop_counter
for ; i < int(s.size_nibbles); i++ {
if !safeReadBits(br, 8, &bits) {
s.loop_counter = i
return decoderNeedsMoreInput
}
if uint(i+1) == s.size_nibbles && s.size_nibbles > 1 && bits == 0 {
return decoderErrorFormatExuberantMetaNibble
}
s.meta_block_remaining_len |= int(bits << uint(i*8))
}
s.meta_block_remaining_len++
s.substate_metablock_header = stateMetablockHeaderNone
return decoderSuccess
default:
return decoderErrorUnreachable
}
}
}
/* Decodes the Huffman code.
This method doesn't read data from the bit reader, BUT drops the amount of
bits that correspond to the decoded symbol.
bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */
func decodeSymbol(bits uint32, table []huffmanCode, br *bitReader) uint32 {
table = table[bits&huffmanTableMask:]
if table[0].bits > huffmanTableBits {
var nbits uint32 = uint32(table[0].bits) - huffmanTableBits
dropBits(br, huffmanTableBits)
table = table[uint32(table[0].value)+((bits>>huffmanTableBits)&bitMask(nbits)):]
}
dropBits(br, uint32(table[0].bits))
return uint32(table[0].value)
}
/* Reads and decodes the next Huffman code from bit-stream.
This method peeks 16 bits of input and drops 0 - 15 of them. */
func readSymbol(table []huffmanCode, br *bitReader) uint32 {
return decodeSymbol(get16BitsUnmasked(br), table, br)
}
/* Same as DecodeSymbol, but it is known that there is less than 15 bits of
input are currently available. */
func safeDecodeSymbol(table []huffmanCode, br *bitReader, result *uint32) bool {
var val uint32
var available_bits uint32 = getAvailableBits(br)
if available_bits == 0 {
if table[0].bits == 0 {
*result = uint32(table[0].value)
return true
}
return false /* No valid bits at all. */
}
val = uint32(getBitsUnmasked(br))
table = table[val&huffmanTableMask:]
if table[0].bits <= huffmanTableBits {
if uint32(table[0].bits) <= available_bits {
dropBits(br, uint32(table[0].bits))
*result = uint32(table[0].value)
return true
} else {
return false /* Not enough bits for the first level. */
}
}
if available_bits <= huffmanTableBits {
return false /* Not enough bits to move to the second level. */
}
/* Speculatively drop HUFFMAN_TABLE_BITS. */
val = (val & bitMask(uint32(table[0].bits))) >> huffmanTableBits
available_bits -= huffmanTableBits
table = table[uint32(table[0].value)+val:]
if available_bits < uint32(table[0].bits) {
return false /* Not enough bits for the second level. */
}
dropBits(br, huffmanTableBits+uint32(table[0].bits))
*result = uint32(table[0].value)
return true
}
func safeReadSymbol(table []huffmanCode, br *bitReader, result *uint32) bool {
var val uint32
if safeGetBits(br, 15, &val) {
*result = decodeSymbol(val, table, br)
return true
}
return safeDecodeSymbol(table, br, result)
}
/* Makes a look-up in first level Huffman table. Peeks 8 bits. */
func preloadSymbol(safe int, table []huffmanCode, br *bitReader, bits *uint32, value *uint32) {
if safe != 0 {
return
}
table = table[getBits(br, huffmanTableBits):]
*bits = uint32(table[0].bits)
*value = uint32(table[0].value)
}
/* Decodes the next Huffman code using data prepared by PreloadSymbol.
Reads 0 - 15 bits. Also peeks 8 following bits. */
func readPreloadedSymbol(table []huffmanCode, br *bitReader, bits *uint32, value *uint32) uint32 {
var result uint32 = *value
var ext []huffmanCode
if *bits > huffmanTableBits {
var val uint32 = get16BitsUnmasked(br)
ext = table[val&huffmanTableMask:][*value:]
var mask uint32 = bitMask((*bits - huffmanTableBits))
dropBits(br, huffmanTableBits)
ext = ext[(val>>huffmanTableBits)&mask:]
dropBits(br, uint32(ext[0].bits))
result = uint32(ext[0].value)
} else {
dropBits(br, *bits)
}
preloadSymbol(0, table, br, bits, value)
return result
}
func log2Floor(x uint32) uint32 {
var result uint32 = 0
for x != 0 {
x >>= 1
result++
}
return result
}
/* Reads (s->symbol + 1) symbols.
Totally 1..4 symbols are read, 1..11 bits each.
The list of symbols MUST NOT contain duplicates. */
func readSimpleHuffmanSymbols(alphabet_size uint32, max_symbol uint32, s *Reader) int {
var br *bitReader = &s.br
var max_bits uint32 = log2Floor(alphabet_size - 1)
var i uint32 = s.sub_loop_counter
/* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */
var num_symbols uint32 = s.symbol
for i <= num_symbols {
var v uint32
if !safeReadBits(br, max_bits, &v) {
s.sub_loop_counter = i
s.substate_huffman = stateHuffmanSimpleRead
return decoderNeedsMoreInput
}
if v >= max_symbol {
return decoderErrorFormatSimpleHuffmanAlphabet
}
s.symbols_lists_array[i] = uint16(v)
i++
}
for i = 0; i < num_symbols; i++ {
var k uint32 = i + 1
for ; k <= num_symbols; k++ {
if s.symbols_lists_array[i] == s.symbols_lists_array[k] {
return decoderErrorFormatSimpleHuffmanSame
}
}
}
return decoderSuccess
}
/* Process single decoded symbol code length:
A) reset the repeat variable
B) remember code length (if it is not 0)
C) extend corresponding index-chain
D) reduce the Huffman space
E) update the histogram */
func processSingleCodeLength(code_len uint32, symbol *uint32, repeat *uint32, space *uint32, prev_code_len *uint32, symbol_lists symbolList, code_length_histo []uint16, next_symbol []int) {
*repeat = 0
if code_len != 0 { /* code_len == 1..15 */
symbolListPut(symbol_lists, next_symbol[code_len], uint16(*symbol))
next_symbol[code_len] = int(*symbol)
*prev_code_len = code_len
*space -= 32768 >> code_len
code_length_histo[code_len]++
}
(*symbol)++
}
/* Process repeated symbol code length.
A) Check if it is the extension of previous repeat sequence; if the decoded
value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new
symbol-skip
B) Update repeat variable
C) Check if operation is feasible (fits alphabet)
D) For each symbol do the same operations as in ProcessSingleCodeLength
PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or
code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH */
func processRepeatedCodeLength(code_len uint32, repeat_delta uint32, alphabet_size uint32, symbol *uint32, repeat *uint32, space *uint32, prev_code_len *uint32, repeat_code_len *uint32, symbol_lists symbolList, code_length_histo []uint16, next_symbol []int) {
var old_repeat uint32 /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */ /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
var extra_bits uint32 = 3
var new_len uint32 = 0
if code_len == repeatPreviousCodeLength {
new_len = *prev_code_len
extra_bits = 2
}
if *repeat_code_len != new_len {
*repeat = 0
*repeat_code_len = new_len
}
old_repeat = *repeat
if *repeat > 0 {
*repeat -= 2
*repeat <<= extra_bits
}
*repeat += repeat_delta + 3
repeat_delta = *repeat - old_repeat
if *symbol+repeat_delta > alphabet_size {
*symbol = alphabet_size
*space = 0xFFFFF
return
}
if *repeat_code_len != 0 {
var last uint = uint(*symbol + repeat_delta)
var next int = next_symbol[*repeat_code_len]
for {
symbolListPut(symbol_lists, next, uint16(*symbol))
next = int(*symbol)
(*symbol)++
if (*symbol) == uint32(last) {
break
}
}
next_symbol[*repeat_code_len] = next
*space -= repeat_delta << (15 - *repeat_code_len)
code_length_histo[*repeat_code_len] = uint16(uint32(code_length_histo[*repeat_code_len]) + repeat_delta)
} else {
*symbol += repeat_delta
}
}
/* Reads and decodes symbol codelengths. */
func readSymbolCodeLengths(alphabet_size uint32, s *Reader) int {
var br *bitReader = &s.br
var symbol uint32 = s.symbol
var repeat uint32 = s.repeat
var space uint32 = s.space
var prev_code_len uint32 = s.prev_code_len
var repeat_code_len uint32 = s.repeat_code_len
var symbol_lists symbolList = s.symbol_lists
var code_length_histo []uint16 = s.code_length_histo[:]
var next_symbol []int = s.next_symbol[:]
if !warmupBitReader(br) {
return decoderNeedsMoreInput
}
var p []huffmanCode
for symbol < alphabet_size && space > 0 {
p = s.table[:]
var code_len uint32
if !checkInputAmount(br, shortFillBitWindowRead) {
s.symbol = symbol
s.repeat = repeat
s.prev_code_len = prev_code_len
s.repeat_code_len = repeat_code_len
s.space = space
return decoderNeedsMoreInput
}
fillBitWindow16(br)
p = p[getBitsUnmasked(br)&uint64(bitMask(huffmanMaxCodeLengthCodeLength)):]
dropBits(br, uint32(p[0].bits)) /* Use 1..5 bits. */
code_len = uint32(p[0].value) /* code_len == 0..17 */
if code_len < repeatPreviousCodeLength {
processSingleCodeLength(code_len, &symbol, &repeat, &space, &prev_code_len, symbol_lists, code_length_histo, next_symbol) /* code_len == 16..17, extra_bits == 2..3 */
} else {
var extra_bits uint32
if code_len == repeatPreviousCodeLength {
extra_bits = 2
} else {
extra_bits = 3
}
var repeat_delta uint32 = uint32(getBitsUnmasked(br)) & bitMask(extra_bits)
dropBits(br, extra_bits)
processRepeatedCodeLength(code_len, repeat_delta, alphabet_size, &symbol, &repeat, &space, &prev_code_len, &repeat_code_len, symbol_lists, code_length_histo, next_symbol)
}
}
s.space = space
return decoderSuccess
}
func safeReadSymbolCodeLengths(alphabet_size uint32, s *Reader) int {
var br *bitReader = &s.br
var get_byte bool = false
var p []huffmanCode
for s.symbol < alphabet_size && s.space > 0 {
p = s.table[:]
var code_len uint32
var available_bits uint32
var bits uint32 = 0
if get_byte && !pullByte(br) {
return decoderNeedsMoreInput
}
get_byte = false
available_bits = getAvailableBits(br)
if available_bits != 0 {
bits = uint32(getBitsUnmasked(br))
}
p = p[bits&bitMask(huffmanMaxCodeLengthCodeLength):]
if uint32(p[0].bits) > available_bits {
get_byte = true
continue
}
code_len = uint32(p[0].value) /* code_len == 0..17 */
if code_len < repeatPreviousCodeLength {
dropBits(br, uint32(p[0].bits))
processSingleCodeLength(code_len, &s.symbol, &s.repeat, &s.space, &s.prev_code_len, s.symbol_lists, s.code_length_histo[:], s.next_symbol[:]) /* code_len == 16..17, extra_bits == 2..3 */
} else {
var extra_bits uint32 = code_len - 14
var repeat_delta uint32 = (bits >> p[0].bits) & bitMask(extra_bits)
if available_bits < uint32(p[0].bits)+extra_bits {
get_byte = true
continue
}
dropBits(br, uint32(p[0].bits)+extra_bits)
processRepeatedCodeLength(code_len, repeat_delta, alphabet_size, &s.symbol, &s.repeat, &s.space, &s.prev_code_len, &s.repeat_code_len, s.symbol_lists, s.code_length_histo[:], s.next_symbol[:])
}
}
return decoderSuccess
}
/* Reads and decodes 15..18 codes using static prefix code.
Each code is 2..4 bits long. In total 30..72 bits are used. */
func readCodeLengthCodeLengths(s *Reader) int {
var br *bitReader = &s.br
var num_codes uint32 = s.repeat
var space uint32 = s.space
var i uint32 = s.sub_loop_counter
for ; i < codeLengthCodes; i++ {
var code_len_idx byte = kCodeLengthCodeOrder[i]
var ix uint32
var v uint32
if !safeGetBits(br, 4, &ix) {
var available_bits uint32 = getAvailableBits(br)
if available_bits != 0 {
ix = uint32(getBitsUnmasked(br) & 0xF)
} else {
ix = 0
}
if uint32(kCodeLengthPrefixLength[ix]) > available_bits {
s.sub_loop_counter = i
s.repeat = num_codes
s.space = space
s.substate_huffman = stateHuffmanComplex
return decoderNeedsMoreInput
}
}
v = uint32(kCodeLengthPrefixValue[ix])
dropBits(br, uint32(kCodeLengthPrefixLength[ix]))
s.code_length_code_lengths[code_len_idx] = byte(v)
if v != 0 {
space = space - (32 >> v)
num_codes++
s.code_length_histo[v]++
if space-1 >= 32 {
/* space is 0 or wrapped around. */
break
}
}
}
if num_codes != 1 && space != 0 {
return decoderErrorFormatClSpace
}
return decoderSuccess
}
/* Decodes the Huffman tables.
There are 2 scenarios:
A) Huffman code contains only few symbols (1..4). Those symbols are read
directly; their code lengths are defined by the number of symbols.
For this scenario 4 - 49 bits will be read.
B) 2-phase decoding:
B.1) Small Huffman table is decoded; it is specified with code lengths
encoded with predefined entropy code. 32 - 74 bits are used.
B.2) Decoded table is used to decode code lengths of symbols in resulting
Huffman table. In worst case 3520 bits are read. */
func readHuffmanCode(alphabet_size uint32, max_symbol uint32, table []huffmanCode, opt_table_size *uint32, s *Reader) int {
var br *bitReader = &s.br
/* Unnecessary masking, but might be good for safety. */
alphabet_size &= 0x7FF
/* State machine. */
for {
switch s.substate_huffman {
case stateHuffmanNone:
if !safeReadBits(br, 2, &s.sub_loop_counter) {
return decoderNeedsMoreInput
}
/* The value is used as follows:
1 for simple code;
0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
if s.sub_loop_counter != 1 {
s.space = 32
s.repeat = 0 /* num_codes */
var i int
for i = 0; i <= huffmanMaxCodeLengthCodeLength; i++ {
s.code_length_histo[i] = 0
}
for i = 0; i < codeLengthCodes; i++ {
s.code_length_code_lengths[i] = 0
}
s.substate_huffman = stateHuffmanComplex
continue
}
fallthrough
/* Read symbols, codes & code lengths directly. */
case stateHuffmanSimpleSize:
if !safeReadBits(br, 2, &s.symbol) { /* num_symbols */
s.substate_huffman = stateHuffmanSimpleSize
return decoderNeedsMoreInput
}
s.sub_loop_counter = 0
fallthrough
case stateHuffmanSimpleRead:
{
var result int = readSimpleHuffmanSymbols(alphabet_size, max_symbol, s)
if result != decoderSuccess {
return result
}
}
fallthrough
case stateHuffmanSimpleBuild:
var table_size uint32
if s.symbol == 3 {
var bits uint32
if !safeReadBits(br, 1, &bits) {
s.substate_huffman = stateHuffmanSimpleBuild
return decoderNeedsMoreInput
}
s.symbol += bits
}
table_size = buildSimpleHuffmanTable(table, huffmanTableBits, s.symbols_lists_array[:], s.symbol)
if opt_table_size != nil {
*opt_table_size = table_size
}
s.substate_huffman = stateHuffmanNone
return decoderSuccess
/* Decode Huffman-coded code lengths. */
case stateHuffmanComplex:
{
var i uint32
var result int = readCodeLengthCodeLengths(s)
if result != decoderSuccess {
return result
}
buildCodeLengthsHuffmanTable(s.table[:], s.code_length_code_lengths[:], s.code_length_histo[:])
for i = 0; i < 16; i++ {
s.code_length_histo[i] = 0
}
for i = 0; i <= huffmanMaxCodeLength; i++ {
s.next_symbol[i] = int(i) - (huffmanMaxCodeLength + 1)
symbolListPut(s.symbol_lists, s.next_symbol[i], 0xFFFF)
}
s.symbol = 0
s.prev_code_len = initialRepeatedCodeLength
s.repeat = 0
s.repeat_code_len = 0
s.space = 32768
s.substate_huffman = stateHuffmanLengthSymbols
}
fallthrough
case stateHuffmanLengthSymbols:
var table_size uint32
var result int = readSymbolCodeLengths(max_symbol, s)
if result == decoderNeedsMoreInput {
result = safeReadSymbolCodeLengths(max_symbol, s)
}
if result != decoderSuccess {
return result
}
if s.space != 0 {
return decoderErrorFormatHuffmanSpace
}
table_size = buildHuffmanTable(table, huffmanTableBits, s.symbol_lists, s.code_length_histo[:])
if opt_table_size != nil {
*opt_table_size = table_size
}
s.substate_huffman = stateHuffmanNone
return decoderSuccess
default:
return decoderErrorUnreachable
}
}
}
/* Decodes a block length by reading 3..39 bits. */
func readBlockLength(table []huffmanCode, br *bitReader) uint32 {
var code uint32
var nbits uint32
code = readSymbol(table, br)
nbits = kBlockLengthPrefixCode[code].nbits /* nbits == 2..24 */
return kBlockLengthPrefixCode[code].offset + readBits(br, nbits)
}
/* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
reading can't be continued with ReadBlockLength. */
func safeReadBlockLength(s *Reader, result *uint32, table []huffmanCode, br *bitReader) bool {
var index uint32
if s.substate_read_block_length == stateReadBlockLengthNone {
if !safeReadSymbol(table, br, &index) {
return false
}
} else {
index = s.block_length_index
}
{
var bits uint32 /* nbits == 2..24 */
var nbits uint32 = kBlockLengthPrefixCode[index].nbits
if !safeReadBits(br, nbits, &bits) {
s.block_length_index = index
s.substate_read_block_length = stateReadBlockLengthSuffix
return false
}
*result = kBlockLengthPrefixCode[index].offset + bits
s.substate_read_block_length = stateReadBlockLengthNone
return true
}
}
/* Transform:
1) initialize list L with values 0, 1,... 255
2) For each input element X:
2.1) let Y = L[X]
2.2) remove X-th element from L
2.3) prepend Y to L
2.4) append Y to output
In most cases max(Y) <= 7, so most of L remains intact.
To reduce the cost of initialization, we reuse L, remember the upper bound
of Y values, and reinitialize only first elements in L.
Most of input values are 0 and 1. To reduce number of branches, we replace
inner for loop with do-while. */
func inverseMoveToFrontTransform(v []byte, v_len uint32, state *Reader) {
var mtf [256]byte
var i int
for i = 1; i < 256; i++ {
mtf[i] = byte(i)
}
var mtf_1 byte
/* Transform the input. */
for i = 0; uint32(i) < v_len; i++ {
var index int = int(v[i])
var value byte = mtf[index]
v[i] = value
mtf_1 = value
for index >= 1 {
index--
mtf[index+1] = mtf[index]
}
mtf[0] = mtf_1
}
}
/* Decodes a series of Huffman table using ReadHuffmanCode function. */
func huffmanTreeGroupDecode(group *huffmanTreeGroup, s *Reader) int {
if s.substate_tree_group != stateTreeGroupLoop {
s.next = group.codes
s.htree_index = 0
s.substate_tree_group = stateTreeGroupLoop
}
for s.htree_index < int(group.num_htrees) {
var table_size uint32
var result int = readHuffmanCode(uint32(group.alphabet_size), uint32(group.max_symbol), s.next, &table_size, s)
if result != decoderSuccess {
return result
}
group.htrees[s.htree_index] = s.next
s.next = s.next[table_size:]
s.htree_index++
}
s.substate_tree_group = stateTreeGroupNone
return decoderSuccess
}
/* Decodes a context map.
Decoding is done in 4 phases:
1) Read auxiliary information (6..16 bits) and allocate memory.
In case of trivial context map, decoding is finished at this phase.
2) Decode Huffman table using ReadHuffmanCode function.
This table will be used for reading context map items.
3) Read context map items; "0" values could be run-length encoded.
4) Optionally, apply InverseMoveToFront transform to the resulting map. */
func decodeContextMap(context_map_size uint32, num_htrees *uint32, context_map_arg *[]byte, s *Reader) int {
var br *bitReader = &s.br
var result int = decoderSuccess
switch int(s.substate_context_map) {
case stateContextMapNone:
result = decodeVarLenUint8(s, br, num_htrees)
if result != decoderSuccess {
return result
}
(*num_htrees)++
s.context_index = 0
*context_map_arg = make([]byte, uint(context_map_size))
if *context_map_arg == nil {
return decoderErrorAllocContextMap
}