Debian Codegraph @

zstd/blockenc.go

raw
1 // Copyright 2019+ Klaus Post. All rights reserved.
2 // License information can be found in the LICENSE file.
3 // Based on work by Yann Collet, released under BSD License.
4
5 package zstd
6
7 import (
8 "errors"
9 "fmt"
10 "math"
11 "math/bits"
12 "slices"
13
14 "github.com/klauspost/compress/huff0"
15 )
16
17 type blockEnc struct {
18 size int
19 literals []byte
20 sequences []seq
21 coders seqCoders
22 litEnc *huff0.Scratch
23 dictLitEnc *huff0.Scratch
24 wr bitWriter
25
26 extraLits int
27 output []byte
28 recentOffsets [3]uint32
29 prevRecentOffsets [3]uint32
30
31 last bool
32 lowMem bool
33 }
34
35 // init should be used once the block has been created.
36 // If called more than once, the effect is the same as calling reset.
37 func (b *blockEnc) init() {
38 if b.lowMem {
39 // 1K literals
40 if cap(b.literals) < 1<<10 {
41 b.literals = make([]byte, 0, 1<<10)
42 }
43 const defSeqs = 20
44 if cap(b.sequences) < defSeqs {
45 b.sequences = make([]seq, 0, defSeqs)
46 }
47 // 1K
48 if cap(b.output) < 1<<10 {
49 b.output = make([]byte, 0, 1<<10)
50 }
51 } else {
52 if cap(b.literals) < maxCompressedBlockSize {
53 b.literals = make([]byte, 0, maxCompressedBlockSize)
54 }
55 const defSeqs = 2000
56 if cap(b.sequences) < defSeqs {
57 b.sequences = make([]seq, 0, defSeqs)
58 }
59 if cap(b.output) < maxCompressedBlockSize {
60 b.output = make([]byte, 0, maxCompressedBlockSize)
61 }
62 }
63
64 if b.coders.mlEnc == nil {
65 b.coders.mlEnc = &fseEncoder{}
66 b.coders.mlPrev = &fseEncoder{}
67 b.coders.ofEnc = &fseEncoder{}
68 b.coders.ofPrev = &fseEncoder{}
69 b.coders.llEnc = &fseEncoder{}
70 b.coders.llPrev = &fseEncoder{}
71 }
72 b.litEnc = &huff0.Scratch{WantLogLess: 4}
73 b.reset(nil)
74 }
75
76 // initNewEncode can be used to reset offsets and encoders to the initial state.
77 func (b *blockEnc) initNewEncode() {
78 b.recentOffsets = [3]uint32{1, 4, 8}
79 b.litEnc.Reuse = huff0.ReusePolicyNone
80 b.coders.setPrev(nil, nil, nil)
81 b.dictLitEnc = nil
82 }
83
84 // reset will reset the block for a new encode, but in the same stream,
85 // meaning that state will be carried over, but the block content is reset.
86 // If a previous block is provided, the recent offsets are carried over.
87 func (b *blockEnc) reset(prev *blockEnc) {
88 b.extraLits = 0
89 b.literals = b.literals[:0]
90 b.size = 0
91 b.sequences = b.sequences[:0]
92 b.output = b.output[:0]
93 b.last = false
94 if prev != nil {
95 b.recentOffsets = prev.prevRecentOffsets
96 }
97 b.dictLitEnc = nil
98 }
99
100 // reset will reset the block for a new encode, but in the same stream,
101 // meaning that state will be carried over, but the block content is reset.
102 // If a previous block is provided, the recent offsets are carried over.
103 func (b *blockEnc) swapEncoders(prev *blockEnc) {
104 b.coders.swap(&prev.coders)
105 b.litEnc, prev.litEnc = prev.litEnc, b.litEnc
106 }
107
108 // blockHeader contains the information for a block header.
109 type blockHeader uint32
110
111 // setLast sets the 'last' indicator on a block.
112 func (h *blockHeader) setLast(b bool) {
113 if b {
114 *h = *h | 1
115 } else {
116 const mask = (1 << 24) - 2
117 *h = *h & mask
118 }
119 }
120
121 // setSize will store the compressed size of a block.
122 func (h *blockHeader) setSize(v uint32) {
123 const mask = 7
124 *h = (*h)&mask | blockHeader(v<<3)
125 }
126
127 // setType sets the block type.
128 func (h *blockHeader) setType(t blockType) {
129 const mask = 1 | (((1 << 24) - 1) ^ 7)
130 *h = (*h & mask) | blockHeader(t<<1)
131 }
132
133 // appendTo will append the block header to a slice.
134 func (h blockHeader) appendTo(b []byte) []byte {
135 return append(b, uint8(h), uint8(h>>8), uint8(h>>16))
136 }
137
138 // String returns a string representation of the block.
139 func (h blockHeader) String() string {
140 return fmt.Sprintf("Type: %d, Size: %d, Last:%t", (h>>1)&3, h>>3, h&1 == 1)
141 }
142
143 // literalsHeader contains literals header information.
144 type literalsHeader uint64
145
146 // setType can be used to set the type of literal block.
147 func (h *literalsHeader) setType(t literalsBlockType) {
148 const mask = math.MaxUint64 - 3
149 *h = (*h & mask) | literalsHeader(t)
150 }
151
152 // setSize can be used to set a single size, for uncompressed and RLE content.
153 func (h *literalsHeader) setSize(regenLen int) {
154 inBits := bits.Len32(uint32(regenLen))
155 // Only retain 2 bits
156 const mask = 3
157 lh := uint64(*h & mask)
158 switch {
159 case inBits < 5:
160 lh |= (uint64(regenLen) << 3) | (1 << 60)
161 if debugEncoder {
162 got := int(lh>>3) & 0xff
163 if got != regenLen {
164 panic(fmt.Sprint("litRegenSize = ", regenLen, "(want) != ", got, "(got)"))
165 }
166 }
167 case inBits < 12:
168 lh |= (1 << 2) | (uint64(regenLen) << 4) | (2 << 60)
169 case inBits < 20:
170 lh |= (3 << 2) | (uint64(regenLen) << 4) | (3 << 60)
171 default:
172 panic(fmt.Errorf("internal error: block too big (%d)", regenLen))
173 }
174 *h = literalsHeader(lh)
175 }
176
177 // setSizes will set the size of a compressed literals section and the input length.
178 func (h *literalsHeader) setSizes(compLen, inLen int, single bool) {
179 compBits, inBits := bits.Len32(uint32(compLen)), bits.Len32(uint32(inLen))
180 // Only retain 2 bits
181 const mask = 3
182 lh := uint64(*h & mask)
183 switch {
184 case compBits <= 10 && inBits <= 10:
185 if !single {
186 lh |= 1 << 2
187 }
188 lh |= (uint64(inLen) << 4) | (uint64(compLen) << (10 + 4)) | (3 << 60)
189 if debugEncoder {
190 const mmask = (1 << 24) - 1
191 n := (lh >> 4) & mmask
192 if int(n&1023) != inLen {
193 panic(fmt.Sprint("regensize:", int(n&1023), "!=", inLen, inBits))
194 }
195 if int(n>>10) != compLen {
196 panic(fmt.Sprint("compsize:", int(n>>10), "!=", compLen, compBits))
197 }
198 }
199 case compBits <= 14 && inBits <= 14:
200 lh |= (2 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (14 + 4)) | (4 << 60)
201 if single {
202 panic("single stream used with more than 10 bits length.")
203 }
204 case compBits <= 18 && inBits <= 18:
205 lh |= (3 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (18 + 4)) | (5 << 60)
206 if single {
207 panic("single stream used with more than 10 bits length.")
208 }
209 default:
210 panic("internal error: block too big")
211 }
212 *h = literalsHeader(lh)
213 }
214
215 // appendTo will append the literals header to a byte slice.
216 func (h literalsHeader) appendTo(b []byte) []byte {
217 size := uint8(h >> 60)
218 switch size {
219 case 1:
220 b = append(b, uint8(h))
221 case 2:
222 b = append(b, uint8(h), uint8(h>>8))
223 case 3:
224 b = append(b, uint8(h), uint8(h>>8), uint8(h>>16))
225 case 4:
226 b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24))
227 case 5:
228 b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24), uint8(h>>32))
229 default:
230 panic(fmt.Errorf("internal error: literalsHeader has invalid size (%d)", size))
231 }
232 return b
233 }
234
235 // size returns the output size with currently set values.
236 func (h literalsHeader) size() int {
237 return int(h >> 60)
238 }
239
240 func (h literalsHeader) String() string {
241 return fmt.Sprintf("Type: %d, SizeFormat: %d, Size: 0x%d, Bytes:%d", literalsBlockType(h&3), (h>>2)&3, h&((1<<60)-1)>>4, h>>60)
242 }
243
244 // pushOffsets will push the recent offsets to the backup store.
245 func (b *blockEnc) pushOffsets() {
246 b.prevRecentOffsets = b.recentOffsets
247 }
248
249 // pushOffsets will push the recent offsets to the backup store.
250 func (b *blockEnc) popOffsets() {
251 b.recentOffsets = b.prevRecentOffsets
252 }
253
254 // matchOffset will adjust recent offsets and return the adjusted one,
255 // if it matches a previous offset.
256 func (b *blockEnc) matchOffset(offset, lits uint32) uint32 {
257 // Check if offset is one of the recent offsets.
258 // Adjusts the output offset accordingly.
259 // Gives a tiny bit of compression, typically around 1%.
260 if true {
261 if lits > 0 {
262 switch offset {
263 case b.recentOffsets[0]:
264 offset = 1
265 case b.recentOffsets[1]:
266 b.recentOffsets[1] = b.recentOffsets[0]
267 b.recentOffsets[0] = offset
268 offset = 2
269 case b.recentOffsets[2]:
270 b.recentOffsets[2] = b.recentOffsets[1]
271 b.recentOffsets[1] = b.recentOffsets[0]
272 b.recentOffsets[0] = offset
273 offset = 3
274 default:
275 b.recentOffsets[2] = b.recentOffsets[1]
276 b.recentOffsets[1] = b.recentOffsets[0]
277 b.recentOffsets[0] = offset
278 offset += 3
279 }
280 } else {
281 switch offset {
282 case b.recentOffsets[1]:
283 b.recentOffsets[1] = b.recentOffsets[0]
284 b.recentOffsets[0] = offset
285 offset = 1
286 case b.recentOffsets[2]:
287 b.recentOffsets[2] = b.recentOffsets[1]
288 b.recentOffsets[1] = b.recentOffsets[0]
289 b.recentOffsets[0] = offset
290 offset = 2
291 case b.recentOffsets[0] - 1:
292 b.recentOffsets[2] = b.recentOffsets[1]
293 b.recentOffsets[1] = b.recentOffsets[0]
294 b.recentOffsets[0] = offset
295 offset = 3
296 default:
297 b.recentOffsets[2] = b.recentOffsets[1]
298 b.recentOffsets[1] = b.recentOffsets[0]
299 b.recentOffsets[0] = offset
300 offset += 3
301 }
302 }
303 } else {
304 offset += 3
305 }
306 return offset
307 }
308
309 // encodeRaw can be used to set the output to a raw representation of supplied bytes.
310 func (b *blockEnc) encodeRaw(a []byte) {
311 var bh blockHeader
312 bh.setLast(b.last)
313 bh.setSize(uint32(len(a)))
314 bh.setType(blockTypeRaw)
315 b.output = bh.appendTo(b.output[:0])
316 b.output = append(b.output, a...)
317 if debugEncoder {
318 println("Adding RAW block, length", len(a), "last:", b.last)
319 }
320 }
321
322 // encodeRaw can be used to set the output to a raw representation of supplied bytes.
323 func (b *blockEnc) encodeRawTo(dst, src []byte) []byte {
324 var bh blockHeader
325 bh.setLast(b.last)
326 bh.setSize(uint32(len(src)))
327 bh.setType(blockTypeRaw)
328 dst = bh.appendTo(dst)
329 dst = append(dst, src...)
330 if debugEncoder {
331 println("Adding RAW block, length", len(src), "last:", b.last)
332 }
333 return dst
334 }
335
336 // encodeLits can be used if the block is only litLen.
337 func (b *blockEnc) encodeLits(lits []byte, raw bool) error {
338 var bh blockHeader
339 bh.setLast(b.last)
340 bh.setSize(uint32(len(lits)))
341
342 // Don't compress extremely small blocks
343 if len(lits) < 8 || (len(lits) < 32 && b.dictLitEnc == nil) || raw {
344 if debugEncoder {
345 println("Adding RAW block, length", len(lits), "last:", b.last)
346 }
347 bh.setType(blockTypeRaw)
348 b.output = bh.appendTo(b.output)
349 b.output = append(b.output, lits...)
350 return nil
351 }
352
353 var (
354 out []byte
355 reUsed, single bool
356 err error
357 )
358 if b.dictLitEnc != nil {
359 b.litEnc.TransferCTable(b.dictLitEnc)
360 b.litEnc.Reuse = huff0.ReusePolicyAllow
361 b.dictLitEnc = nil
362 }
363 if len(lits) >= 1024 {
364 // Use 4 Streams.
365 out, reUsed, err = huff0.Compress4X(lits, b.litEnc)
366 } else if len(lits) > 16 {
367 // Use 1 stream
368 single = true
369 out, reUsed, err = huff0.Compress1X(lits, b.litEnc)
370 } else {
371 err = huff0.ErrIncompressible
372 }
373 if err == nil && len(out)+5 > len(lits) {
374 // If we are close, we may still be worse or equal to raw.
375 var lh literalsHeader
376 lh.setSizes(len(out), len(lits), single)
377 if len(out)+lh.size() >= len(lits) {
378 err = huff0.ErrIncompressible
379 }
380 }
381 switch err {
382 case huff0.ErrIncompressible:
383 if debugEncoder {
384 println("Adding RAW block, length", len(lits), "last:", b.last)
385 }
386 bh.setType(blockTypeRaw)
387 b.output = bh.appendTo(b.output)
388 b.output = append(b.output, lits...)
389 return nil
390 case huff0.ErrUseRLE:
391 if debugEncoder {
392 println("Adding RLE block, length", len(lits))
393 }
394 bh.setType(blockTypeRLE)
395 b.output = bh.appendTo(b.output)
396 b.output = append(b.output, lits[0])
397 return nil
398 case nil:
399 default:
400 return err
401 }
402 // Compressed...
403 // Now, allow reuse
404 b.litEnc.Reuse = huff0.ReusePolicyAllow
405 bh.setType(blockTypeCompressed)
406 var lh literalsHeader
407 if reUsed {
408 if debugEncoder {
409 println("Reused tree, compressed to", len(out))
410 }
411 lh.setType(literalsBlockTreeless)
412 } else {
413 if debugEncoder {
414 println("New tree, compressed to", len(out), "tree size:", len(b.litEnc.OutTable))
415 }
416 lh.setType(literalsBlockCompressed)
417 }
418 // Set sizes
419 lh.setSizes(len(out), len(lits), single)
420 bh.setSize(uint32(len(out) + lh.size() + 1))
421
422 // Write block headers.
423 b.output = bh.appendTo(b.output)
424 b.output = lh.appendTo(b.output)
425 // Add compressed data.
426 b.output = append(b.output, out...)
427 // No sequences.
428 b.output = append(b.output, 0)
429 return nil
430 }
431
432 // encodeRLE will encode an RLE block.
433 func (b *blockEnc) encodeRLE(val byte, length uint32) {
434 var bh blockHeader
435 bh.setLast(b.last)
436 bh.setSize(length)
437 bh.setType(blockTypeRLE)
438 b.output = bh.appendTo(b.output)
439 b.output = append(b.output, val)
440 }
441
442 // fuzzFseEncoder can be used to fuzz the FSE encoder.
443 func fuzzFseEncoder(data []byte) int {
444 if len(data) > maxSequences || len(data) < 2 {
445 return 0
446 }
447 enc := fseEncoder{}
448 hist := enc.Histogram()
449 maxSym := uint8(0)
450 for i, v := range data {
451 v = v & 63
452 data[i] = v
453 hist[v]++
454 if v > maxSym {
455 maxSym = v
456 }
457 }
458 if maxSym == 0 {
459 // All 0
460 return 0
461 }
462 cnt := int(slices.Max(hist[:maxSym]))
463 if cnt == len(data) {
464 // RLE
465 return 0
466 }
467 enc.HistogramFinished(maxSym, cnt)
468 err := enc.normalizeCount(len(data))
469 if err != nil {
470 return 0
471 }
472 _, err = enc.writeCount(nil)
473 if err != nil {
474 panic(err)
475 }
476 return 1
477 }
478
479 // encode will encode the block and append the output in b.output.
480 // Previous offset codes must be pushed if more blocks are expected.
481 func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error {
482 if len(b.sequences) == 0 {
483 return b.encodeLits(b.literals, rawAllLits)
484 }
485 if len(b.sequences) == 1 && len(org) > 0 && len(b.literals) <= 1 {
486 // Check common RLE cases.
487 seq := b.sequences[0]
488 if seq.litLen == uint32(len(b.literals)) && seq.offset-3 == 1 {
489 // Offset == 1 and 0 or 1 literals.
490 b.encodeRLE(org[0], b.sequences[0].matchLen+zstdMinMatch+seq.litLen)
491 return nil
492 }
493 }
494
495 // We want some difference to at least account for the headers.
496 saved := b.size - len(b.literals) - (b.size >> 6)
497 if saved < 16 {
498 if org == nil {
499 return errIncompressible
500 }
501 b.popOffsets()
502 return b.encodeLits(org, rawAllLits)
503 }
504
505 var bh blockHeader
506 var lh literalsHeader
507 bh.setLast(b.last)
508 bh.setType(blockTypeCompressed)
509 // Store offset of the block header. Needed when we know the size.
510 bhOffset := len(b.output)
511 b.output = bh.appendTo(b.output)
512
513 var (
514 out []byte
515 reUsed, single bool
516 err error
517 )
518 if b.dictLitEnc != nil {
519 b.litEnc.TransferCTable(b.dictLitEnc)
520 b.litEnc.Reuse = huff0.ReusePolicyAllow
521 b.dictLitEnc = nil
522 }
523 if len(b.literals) >= 1024 && !raw {
524 // Use 4 Streams.
525 out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc)
526 } else if len(b.literals) > 16 && !raw {
527 // Use 1 stream
528 single = true
529 out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc)
530 } else {
531 err = huff0.ErrIncompressible
532 }
533
534 if err == nil && len(out)+5 > len(b.literals) {
535 // If we are close, we may still be worse or equal to raw.
536 var lh literalsHeader
537 lh.setSize(len(b.literals))
538 szRaw := lh.size()
539 lh.setSizes(len(out), len(b.literals), single)
540 szComp := lh.size()
541 if len(out)+szComp >= len(b.literals)+szRaw {
542 err = huff0.ErrIncompressible
543 }
544 }
545 switch err {
546 case huff0.ErrIncompressible:
547 lh.setType(literalsBlockRaw)
548 lh.setSize(len(b.literals))
549 b.output = lh.appendTo(b.output)
550 b.output = append(b.output, b.literals...)
551 if debugEncoder {
552 println("Adding literals RAW, length", len(b.literals))
553 }
554 case huff0.ErrUseRLE:
555 lh.setType(literalsBlockRLE)
556 lh.setSize(len(b.literals))
557 b.output = lh.appendTo(b.output)
558 b.output = append(b.output, b.literals[0])
559 if debugEncoder {
560 println("Adding literals RLE")
561 }
562 case nil:
563 // Compressed litLen...
564 if reUsed {
565 if debugEncoder {
566 println("reused tree")
567 }
568 lh.setType(literalsBlockTreeless)
569 } else {
570 if debugEncoder {
571 println("new tree, size:", len(b.litEnc.OutTable))
572 }
573 lh.setType(literalsBlockCompressed)
574 if debugEncoder {
575 _, _, err := huff0.ReadTable(out, nil)
576 if err != nil {
577 panic(err)
578 }
579 }
580 }
581 lh.setSizes(len(out), len(b.literals), single)
582 if debugEncoder {
583 printf("Compressed %d literals to %d bytes", len(b.literals), len(out))
584 println("Adding literal header:", lh)
585 }
586 b.output = lh.appendTo(b.output)
587 b.output = append(b.output, out...)
588 b.litEnc.Reuse = huff0.ReusePolicyAllow
589 if debugEncoder {
590 println("Adding literals compressed")
591 }
592 default:
593 if debugEncoder {
594 println("Adding literals ERROR:", err)
595 }
596 return err
597 }
598 // Sequence compression
599
600 // Write the number of sequences
601 switch {
602 case len(b.sequences) < 128:
603 b.output = append(b.output, uint8(len(b.sequences)))
604 case len(b.sequences) < 0x7f00: // TODO: this could be wrong
605 n := len(b.sequences)
606 b.output = append(b.output, 128+uint8(n>>8), uint8(n))
607 default:
608 n := len(b.sequences) - 0x7f00
609 b.output = append(b.output, 255, uint8(n), uint8(n>>8))
610 }
611 if debugEncoder {
612 println("Encoding", len(b.sequences), "sequences")
613 }
614 b.genCodes()
615 llEnc := b.coders.llEnc
616 ofEnc := b.coders.ofEnc
617 mlEnc := b.coders.mlEnc
618 err = llEnc.normalizeCount(len(b.sequences))
619 if err != nil {
620 return err
621 }
622 err = ofEnc.normalizeCount(len(b.sequences))
623 if err != nil {
624 return err
625 }
626 err = mlEnc.normalizeCount(len(b.sequences))
627 if err != nil {
628 return err
629 }
630
631 // Choose the best compression mode for each type.
632 // Will evaluate the new vs predefined and previous.
633 chooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) {
634 // See if predefined/previous is better
635 hist := cur.count[:cur.symbolLen]
636 nSize := cur.approxSize(hist) + cur.maxHeaderSize()
637 predefSize := preDef.approxSize(hist)
638 prevSize := prev.approxSize(hist)
639
640 // Add a small penalty for new encoders.
641 // Don't bother with extremely small (<2 byte gains).
642 nSize = nSize + (nSize+2*8*16)>>4
643 switch {
644 case predefSize <= prevSize && predefSize <= nSize || forcePreDef:
645 if debugEncoder {
646 println("Using predefined", predefSize>>3, "<=", nSize>>3)
647 }
648 return preDef, compModePredefined
649 case prevSize <= nSize:
650 if debugEncoder {
651 println("Using previous", prevSize>>3, "<=", nSize>>3)
652 }
653 return prev, compModeRepeat
654 default:
655 if debugEncoder {
656 println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes")
657 println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen])
658 }
659 return cur, compModeFSE
660 }
661 }
662
663 // Write compression mode
664 var mode uint8
665 if llEnc.useRLE {
666 mode |= uint8(compModeRLE) << 6
667 llEnc.setRLE(b.sequences[0].llCode)
668 if debugEncoder {
669 println("llEnc.useRLE")
670 }
671 } else {
672 var m seqCompMode
673 llEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths])
674 mode |= uint8(m) << 6
675 }
676 if ofEnc.useRLE {
677 mode |= uint8(compModeRLE) << 4
678 ofEnc.setRLE(b.sequences[0].ofCode)
679 if debugEncoder {
680 println("ofEnc.useRLE")
681 }
682 } else {
683 var m seqCompMode
684 ofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets])
685 mode |= uint8(m) << 4
686 }
687
688 if mlEnc.useRLE {
689 mode |= uint8(compModeRLE) << 2
690 mlEnc.setRLE(b.sequences[0].mlCode)
691 if debugEncoder {
692 println("mlEnc.useRLE, code: ", b.sequences[0].mlCode, "value", b.sequences[0].matchLen)
693 }
694 } else {
695 var m seqCompMode
696 mlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths])
697 mode |= uint8(m) << 2
698 }
699 b.output = append(b.output, mode)
700 if debugEncoder {
701 printf("Compression modes: 0b%b", mode)
702 }
703 b.output, err = llEnc.writeCount(b.output)
704 if err != nil {
705 return err
706 }
707 start := len(b.output)
708 b.output, err = ofEnc.writeCount(b.output)
709 if err != nil {
710 return err
711 }
712 if false {
713 println("block:", b.output[start:], "tablelog", ofEnc.actualTableLog, "maxcount:", ofEnc.maxCount)
714 fmt.Printf("selected TableLog: %d, Symbol length: %d\n", ofEnc.actualTableLog, ofEnc.symbolLen)
715 for i, v := range ofEnc.norm[:ofEnc.symbolLen] {
716 fmt.Printf("%3d: %5d -> %4d \n", i, ofEnc.count[i], v)
717 }
718 }
719 b.output, err = mlEnc.writeCount(b.output)
720 if err != nil {
721 return err
722 }
723
724 // Maybe in block?
725 wr := &b.wr
726 wr.reset(b.output)
727
728 var ll, of, ml cState
729
730 // Current sequence
731 seq := len(b.sequences) - 1
732 s := b.sequences[seq]
733 llEnc.setBits(llBitsTable[:])
734 mlEnc.setBits(mlBitsTable[:])
735 ofEnc.setBits(nil)
736
737 llTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256]
738
739 // We have 3 bounds checks here (and in the loop).
740 // Since we are iterating backwards it is kinda hard to avoid.
741 llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode]
742 ll.init(wr, &llEnc.ct, llB)
743 of.init(wr, &ofEnc.ct, ofB)
744 wr.flush32()
745 ml.init(wr, &mlEnc.ct, mlB)
746
747 // Each of these lookups also generates a bounds check.
748 wr.addBits32NC(s.litLen, llB.outBits)
749 wr.addBits32NC(s.matchLen, mlB.outBits)
750 wr.flush32()
751 wr.addBits32NC(s.offset, ofB.outBits)
752 if debugSequences {
753 println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB)
754 }
755 seq--
756 // Store sequences in reverse...
757 for seq >= 0 {
758 s = b.sequences[seq]
759
760 ofB := ofTT[s.ofCode]
761 wr.flush32() // tablelog max is below 8 for each, so it will fill max 24 bits.
762 //of.encode(ofB)
763 nbBitsOut := (uint32(of.state) + ofB.deltaNbBits) >> 16
764 dstState := int32(of.state>>(nbBitsOut&15)) + int32(ofB.deltaFindState)
765 wr.addBits16NC(of.state, uint8(nbBitsOut))
766 of.state = of.stateTable[dstState]
767
768 // Accumulate extra bits.
769 outBits := ofB.outBits & 31
770 extraBits := uint64(s.offset & bitMask32[outBits])
771 extraBitsN := outBits
772
773 mlB := mlTT[s.mlCode]
774 //ml.encode(mlB)
775 nbBitsOut = (uint32(ml.state) + mlB.deltaNbBits) >> 16
776 dstState = int32(ml.state>>(nbBitsOut&15)) + int32(mlB.deltaFindState)
777 wr.addBits16NC(ml.state, uint8(nbBitsOut))
778 ml.state = ml.stateTable[dstState]
779
780 outBits = mlB.outBits & 31
781 extraBits = extraBits<<outBits | uint64(s.matchLen&bitMask32[outBits])
782 extraBitsN += outBits
783
784 llB := llTT[s.llCode]
785 //ll.encode(llB)
786 nbBitsOut = (uint32(ll.state) + llB.deltaNbBits) >> 16
787 dstState = int32(ll.state>>(nbBitsOut&15)) + int32(llB.deltaFindState)
788 wr.addBits16NC(ll.state, uint8(nbBitsOut))
789 ll.state = ll.stateTable[dstState]
790
791 outBits = llB.outBits & 31
792 extraBits = extraBits<<outBits | uint64(s.litLen&bitMask32[outBits])
793 extraBitsN += outBits
794
795 wr.flush32()
796 wr.addBits64NC(extraBits, extraBitsN)
797
798 if debugSequences {
799 println("Encoded seq", seq, s)
800 }
801
802 seq--
803 }
804 ml.flush(mlEnc.actualTableLog)
805 of.flush(ofEnc.actualTableLog)
806 ll.flush(llEnc.actualTableLog)
807 wr.close()
808 b.output = wr.out
809
810 // Maybe even add a bigger margin.
811 if len(b.output)-3-bhOffset >= b.size {
812 // Discard and encode as raw block.
813 b.output = b.encodeRawTo(b.output[:bhOffset], org)
814 b.popOffsets()
815 b.litEnc.Reuse = huff0.ReusePolicyNone
816 return nil
817 }
818
819 // Size is output minus block header.
820 bh.setSize(uint32(len(b.output)-bhOffset) - 3)
821 if debugEncoder {
822 println("Rewriting block header", bh)
823 }
824 _ = bh.appendTo(b.output[bhOffset:bhOffset])
825 b.coders.setPrev(llEnc, mlEnc, ofEnc)
826 return nil
827 }
828
829 var errIncompressible = errors.New("incompressible")
830
831 func (b *blockEnc) genCodes() {
832 if len(b.sequences) == 0 {
833 // nothing to do
834 return
835 }
836 if len(b.sequences) > math.MaxUint16 {
837 panic("can only encode up to 64K sequences")
838 }
839 // No bounds checks after here:
840 llH := b.coders.llEnc.Histogram()
841 ofH := b.coders.ofEnc.Histogram()
842 mlH := b.coders.mlEnc.Histogram()
843 for i := range llH {
844 llH[i] = 0
845 }
846 for i := range ofH {
847 ofH[i] = 0
848 }
849 for i := range mlH {
850 mlH[i] = 0
851 }
852
853 var llMax, ofMax, mlMax uint8
854 for i := range b.sequences {
855 seq := &b.sequences[i]
856 v := llCode(seq.litLen)
857 seq.llCode = v
858 llH[v]++
859 if v > llMax {
860 llMax = v
861 }
862
863 v = ofCode(seq.offset)
864 seq.ofCode = v
865 ofH[v]++
866 if v > ofMax {
867 ofMax = v
868 }
869
870 v = mlCode(seq.matchLen)
871 seq.mlCode = v
872 mlH[v]++
873 if v > mlMax {
874 mlMax = v
875 if debugAsserts && mlMax > maxMatchLengthSymbol {
876 panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d), matchlen: %d", mlMax, seq.matchLen))
877 }
878 }
879 }
880 if debugAsserts && mlMax > maxMatchLengthSymbol {
881 panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d)", mlMax))
882 }
883 if debugAsserts && ofMax > maxOffsetBits {
884 panic(fmt.Errorf("ofMax > maxOffsetBits (%d)", ofMax))
885 }
886 if debugAsserts && llMax > maxLiteralLengthSymbol {
887 panic(fmt.Errorf("llMax > maxLiteralLengthSymbol (%d)", llMax))
888 }
889
890 b.coders.mlEnc.HistogramFinished(mlMax, int(slices.Max(mlH[:mlMax+1])))
891 b.coders.ofEnc.HistogramFinished(ofMax, int(slices.Max(ofH[:ofMax+1])))
892 b.coders.llEnc.HistogramFinished(llMax, int(slices.Max(llH[:llMax+1])))
893 }