Debian Codegraph @

ppm_model.go

raw symbols SCIP
1 package rardecode
2
3 import (
4 "errors"
5 "io"
6 "math"
7 )
8
9 const (
10 rangeBottom = 1 << 15
11 rangeTop = 1 << 24
12
13 maxFreq = 124
14
15 intBits = 7
16 periodBits = 7
17 binScale = 1 << (intBits + periodBits)
18
19 n0 = 1
20 n1 = 4
21 n2 = 4
22 n3 = 4
23 n4 = (128 + 3 - 1*n1 - 2*n2 - 3*n3) / 4
24 nIndexes = n0 + n1 + n2 + n3 + n4
25
26 // memory is allocated in units. A unit contains unitSize number of bytes.
27 // A unit can store one context or two states.
28 unitSize = 12
29
30 freeMark = -1
31 )
32
33 var (
34 ErrCorruptPPM = errors.New("rardecode: corrupt ppm data")
35
36 expEscape = []byte{25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2}
37 initBinEsc = []uint16{0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}
38
39 ns2Index [256]byte
40 ns2BSIndex [256]byte
41
42 // units2Index maps the number of units in a block to a freelist index
43 units2Index [128 + 1]byte
44 // index2Units maps a freelist index to the size of the block in units
45 index2Units [nIndexes]int32
46 )
47
48 func init() {
49 ns2BSIndex[0] = 2 * 0
50 ns2BSIndex[1] = 2 * 1
51 for i := 2; i < 11; i++ {
52 ns2BSIndex[i] = 2 * 2
53 }
54 for i := 11; i < 256; i++ {
55 ns2BSIndex[i] = 2 * 3
56 }
57
58 var j, n byte
59 for i := range ns2Index {
60 ns2Index[i] = n
61 if j <= 3 {
62 n++
63 j = n
64 } else {
65 j--
66 }
67 }
68
69 var ii byte
70 var iu, units int32
71 for i, n := range []int{n0, n1, n2, n3, n4} {
72 for j := 0; j < n; j++ {
73 units += int32(i)
74 index2Units[ii] = units
75 for iu <= units {
76 units2Index[iu] = ii
77 iu++
78 }
79 ii++
80 }
81 }
82 }
83
84 type rangeCoder struct {
85 br io.ByteReader
86 code uint32
87 low uint32
88 rnge uint32
89 }
90
91 func (r *rangeCoder) init(br io.ByteReader) error {
92 r.br = br
93 r.low = 0
94 r.rnge = ^uint32(0)
95 for i := 0; i < 4; i++ {
96 c, err := r.br.ReadByte()
97 if err != nil {
98 return err
99 }
100 r.code = r.code<<8 | uint32(c)
101 }
102 return nil
103 }
104
105 func (r *rangeCoder) currentCount(scale uint32) uint32 {
106 r.rnge /= scale
107 return (r.code - r.low) / r.rnge
108 }
109
110 func (r *rangeCoder) normalize() error {
111 for {
112 if r.low^(r.low+r.rnge) >= rangeTop {
113 if r.rnge >= rangeBottom {
114 return nil
115 }
116 r.rnge = -r.low & (rangeBottom - 1)
117 }
118 c, err := r.br.ReadByte()
119 if err != nil {
120 return err
121 }
122 r.code = r.code<<8 | uint32(c)
123 r.rnge <<= 8
124 r.low <<= 8
125 }
126 }
127
128 func (r *rangeCoder) decode(lowCount, highCount uint32) error {
129 r.low += r.rnge * lowCount
130 r.rnge *= highCount - lowCount
131
132 return r.normalize()
133 }
134
135 type see2Context struct {
136 summ uint16
137 shift byte
138 count byte
139 }
140
141 func newSee2Context(i uint16) see2Context {
142 return see2Context{i << (periodBits - 4), (periodBits - 4), 4}
143 }
144
145 func (s *see2Context) mean() uint32 {
146 if s == nil {
147 return 1
148 }
149 n := s.summ >> s.shift
150 if n == 0 {
151 return 1
152 }
153 s.summ -= n
154 return uint32(n)
155 }
156
157 func (s *see2Context) update() {
158 if s == nil || s.shift >= periodBits {
159 return
160 }
161 s.count--
162 if s.count == 0 {
163 s.summ += s.summ
164 s.count = 3 << s.shift
165 s.shift++
166 }
167 }
168
169 type state struct {
170 sym byte
171 freq byte
172
173 // succ can point to a context or byte in memory.
174 // A context pointer is a positive integer. It is an index into the states
175 // array that points to the first of two states which the context is
176 // marshalled into.
177 // A byte pointer is a negative integer. The magnitude represents the position
178 // in bytes from the bottom of the memory. As memory is modelled as an array of
179 // states, this is used to calculate which state, and where in the state the
180 // byte is stored.
181 // A zero value represents a nil pointer.
182 succ int32
183 }
184
185 // uint16 return a uint16 stored in the sym and freq fields of a state
186 func (s state) uint16() uint16 { return uint16(s.sym) | uint16(s.freq)<<8 }
187
188 // setUint16 stores a uint16 in the sym and freq fields of a state
189 func (s *state) setUint16(n uint16) { s.sym = byte(n); s.freq = byte(n >> 8) }
190
191 // A context is marshalled into a slice of two states.
192 // The first state contains the number of states, and the suffix pointer.
193 // If there is only one state, the second state contains that state.
194 // If there is more than one state, the second state contains the summFreq
195 // and the index to the slice of states.
196 // The context is represented by the index into the states array for these two states.
197 type context int32
198
199 // succContext returns a context given a state.succ index
200 func succContext(i int32) context {
201 if i <= 0 {
202 return 0
203 }
204 return context(i)
205 }
206
207 type subAllocator struct {
208 // memory for allocation is split into two heaps
209
210 glueCount int
211 heap1MaxBytes int32 // maximum bytes available in heap1
212 heap1Lo int32 // heap1 bottom in number of bytes
213 heap1Hi int32 // heap1 top in number of bytes
214 heap2Lo int32 // heap2 bottom index in states
215 heap2Hi int32 // heap2 top index in states
216
217 // Each freeList entry contains an index into states for the beginning
218 // of a free block. The first state in that block may contain an index
219 // to another free block and so on. The size of the free block in units
220 // (2 states) for that freeList index can be determined from the
221 // index2Units array.
222 freeList [nIndexes]int32
223
224 // Instead of bytes, memory is represented by a slice of states.
225 // context's are marshalled to and from a pair of states.
226 // multiple bytes are stored in a state.
227 states []state
228 }
229
230 func (a *subAllocator) init(maxMB int) {
231 bytes := int32(maxMB) << 20
232 heap2Units := bytes / 8 / unitSize * 7
233 a.heap1MaxBytes = bytes - heap2Units*unitSize
234 // Add one for the case when bytes are not a multiple of unitSize
235 heap1Units := a.heap1MaxBytes/unitSize + 1
236 // Calculate total size in state's. Add 1 unit so we can reserve the first unit.
237 // This will allow us to use the zero index as a nil pointer.
238 n := int(1+heap1Units+heap2Units) * 2
239 if cap(a.states) > n {
240 a.states = a.states[:n]
241 } else {
242 a.states = make([]state, n)
243 }
244 }
245
246 func (a *subAllocator) restart() {
247 // Pad heap1 start by 1 unit and enough bytes so that there is no
248 // gap between heap1 end and heap2 start.
249 a.heap1Lo = unitSize + (unitSize - a.heap1MaxBytes%unitSize)
250 a.heap1Hi = unitSize + (a.heap1MaxBytes/unitSize+1)*unitSize
251 a.heap2Lo = a.heap1Hi / unitSize * 2
252 a.heap2Hi = int32(len(a.states))
253 a.glueCount = 0
254 clear(a.freeList[:])
255 }
256
257 // pushByte puts a byte on the heap and returns a state.succ index that
258 // can be used to retrieve it.
259 func (a *subAllocator) pushByte(c byte) int32 {
260 si := a.heap1Lo / 6 // state index
261 oi := a.heap1Lo % 6 // byte position in state
262 switch oi {
263 case 0:
264 a.states[si].sym = c
265 case 1:
266 a.states[si].freq = c
267 default:
268 n := (uint(oi) - 2) * 8
269 mask := ^(uint32(0xFF) << n)
270 succ := uint32(a.states[si].succ) & mask
271 succ |= uint32(c) << n
272 a.states[si].succ = int32(succ)
273 }
274 a.heap1Lo++
275 if a.heap1Lo >= a.heap1Hi {
276 return 0
277 }
278 return -a.heap1Lo
279 }
280
281 // popByte reverses the previous pushByte
282 func (a *subAllocator) popByte() { a.heap1Lo-- }
283
284 // succByte returns a byte from the heap given a state.succ index
285 func (a *subAllocator) succByte(i int32) byte {
286 i = -i
287 si := i / 6
288 oi := i % 6
289 switch oi {
290 case 0:
291 return a.states[si].sym
292 case 1:
293 return a.states[si].freq
294 default:
295 n := (uint(oi) - 2) * 8
296 succ := uint32(a.states[si].succ) >> n
297 return byte(succ & 0xff)
298 }
299 }
300
301 // nextByteAddr takes a state.succ value representing a pointer
302 // to a byte, and returns the next bytes address
303 func (a *subAllocator) nextByteAddr(n int32) int32 { return n - 1 }
304
305 func (a *subAllocator) removeFreeBlock(i byte) int32 {
306 n := a.freeList[i]
307 if n != 0 {
308 a.freeList[i] = a.states[n].succ
309 a.states[n] = state{}
310 }
311 return n
312 }
313
314 func (a *subAllocator) addFreeBlock(n int32, i byte) {
315 a.states[n].succ = a.freeList[i]
316 a.freeList[i] = n
317 }
318
319 func (a *subAllocator) freeUnits(n, u int32) {
320 i := units2Index[u]
321 if u != index2Units[i] {
322 i--
323 a.addFreeBlock(n, i)
324 u -= index2Units[i]
325 n += index2Units[i] << 1
326 i = units2Index[u]
327 }
328 a.addFreeBlock(n, i)
329 }
330
331 func (a *subAllocator) glueFreeBlocks() {
332 var freeIndex int32
333
334 for i, n := range a.freeList {
335 s := state{succ: freeMark}
336 s.setUint16(uint16(index2Units[i]))
337 for n != 0 {
338 states := a.states[n:]
339 states[1].succ = freeIndex
340 freeIndex = n
341 n = states[0].succ
342 states[0] = s
343 }
344 a.freeList[i] = 0
345 }
346
347 for i := freeIndex; i != 0; i = a.states[i+1].succ {
348 if a.states[i].succ != freeMark {
349 continue
350 }
351 u := int32(a.states[i].uint16())
352 states := a.states[i+u<<1:]
353 for len(states) > 0 && states[0].succ == freeMark {
354 u += int32(states[0].uint16())
355 if u > math.MaxUint16 {
356 break
357 }
358 states[0].succ = 0
359 a.states[i].setUint16(uint16(u))
360 states = a.states[i+u<<1:]
361 }
362 }
363
364 for n := freeIndex; n != 0; n = a.states[n+1].succ {
365 if a.states[n].succ != freeMark {
366 continue
367 }
368 a.states[n].succ = 0
369 u := int32(a.states[n].uint16())
370 m := n
371 for u > 128 {
372 a.addFreeBlock(m, nIndexes-1)
373 u -= 128
374 m += 256
375 }
376 a.freeUnits(m, u)
377 }
378 }
379
380 func (a *subAllocator) allocUnitsRare(index byte) int32 {
381 if a.glueCount == 0 {
382 a.glueCount = 255
383 a.glueFreeBlocks()
384 if n := a.removeFreeBlock(index); n > 0 {
385 return n
386 }
387 }
388 // try to find a larger free block and split it
389 for i := index + 1; i < nIndexes; i++ {
390 if n := a.removeFreeBlock(i); n > 0 {
391 u := index2Units[i] - index2Units[index]
392 a.freeUnits(n+index2Units[index]<<1, u)
393 return n
394 }
395 }
396 a.glueCount--
397
398 // try to allocate units from the top of heap1
399 n := a.heap1Hi - index2Units[index]*unitSize
400 if n > a.heap1Lo {
401 a.heap1Hi = n
402 return a.heap1Hi / unitSize * 2
403 }
404 return 0
405 }
406
407 func (a *subAllocator) allocUnits(i byte) int32 {
408 // try to allocate a free block
409 if n := a.removeFreeBlock(i); n > 0 {
410 return n
411 }
412 // try to allocate from the bottom of heap2
413 n := index2Units[i] << 1
414 if a.heap2Lo+n <= a.heap2Hi {
415 lo := a.heap2Lo
416 a.heap2Lo += n
417 return lo
418 }
419 return a.allocUnitsRare(i)
420 }
421
422 func (a *subAllocator) newContext(s state, suffix context) context {
423 var n int32
424 if a.heap2Lo < a.heap2Hi {
425 // allocate from top of heap2
426 a.heap2Hi -= 2
427 n = a.heap2Hi
428 } else if n = a.removeFreeBlock(1); n == 0 {
429 if n = a.allocUnitsRare(1); n == 0 {
430 return 0
431 }
432 }
433 // we don't need to set numStates to 1 as the default value of 0 in the sym
434 // field is always incremented by 1 to get numStates.
435 a.states[n] = state{succ: int32(suffix)}
436 a.states[n+1] = s
437 return context(n)
438 }
439
440 func (a *subAllocator) newContextSize(ns int) context {
441 c := a.newContext(state{}, context(0))
442 a.contextSetNumStates(c, ns)
443 i := units2Index[(ns+1)>>1]
444 n := a.allocUnits(i)
445 a.contextSetStatesIndex(c, n)
446 return c
447 }
448
449 // since number of states is always > 0 && <= 256, we can fit it in a single byte
450 func (a *subAllocator) contextNumStates(c context) int { return int(a.states[c].sym) + 1 }
451 func (a *subAllocator) contextSetNumStates(c context, n int) { a.states[c].sym = byte(n - 1) }
452
453 func (a *subAllocator) contextSummFreq(c context) uint16 { return a.states[c+1].uint16() }
454 func (a *subAllocator) contextSetSummFreq(c context, n uint16) { a.states[c+1].setUint16(n) }
455 func (a *subAllocator) contextIncSummFreq(c context, n uint16) {
456 a.states[c+1].setUint16(a.states[c+1].uint16() + n)
457 }
458
459 func (a *subAllocator) contextSuffix(c context) context { return succContext(a.states[c].succ) }
460
461 func (a *subAllocator) contextStatesIndex(c context) int32 { return a.states[c+1].succ }
462 func (a *subAllocator) contextSetStatesIndex(c context, n int32) { a.states[c+1].succ = n }
463
464 func (a *subAllocator) contextStates(c context) []state {
465 if ns := int32(a.states[c].sym) + 1; ns != 1 {
466 i := a.states[c+1].succ
467 return a.states[i : i+ns]
468 }
469 return a.states[c+1 : c+2]
470 }
471
472 // shrinkStates shrinks the state list down to size states
473 func (a *subAllocator) shrinkStates(c context, states []state, size int) []state {
474 i1 := units2Index[(len(states)+1)>>1]
475 i2 := units2Index[(size+1)>>1]
476
477 if size == 1 {
478 // store state in context, and free states block
479 n := a.contextStatesIndex(c)
480 a.states[c+1] = states[0]
481 states = a.states[c+1:]
482 a.addFreeBlock(n, i1)
483 } else if i1 != i2 {
484 if n := a.removeFreeBlock(i2); n > 0 {
485 // allocate new block and copy
486 copy(a.states[n:], states[:size])
487 states = a.states[n:]
488 // free old block
489 a.addFreeBlock(a.contextStatesIndex(c), i1)
490 a.contextSetStatesIndex(c, n)
491 } else {
492 // split current block, and free units not needed
493 n = a.contextStatesIndex(c) + index2Units[i2]<<1
494 u := index2Units[i1] - index2Units[i2]
495 a.freeUnits(n, u)
496 }
497 }
498 a.contextSetNumStates(c, size)
499 return states[:size]
500 }
501
502 // expandStates expands the states list by one
503 func (a *subAllocator) expandStates(c context) []state {
504 states := a.contextStates(c)
505 ns := len(states)
506 if ns == 1 {
507 s := states[0]
508 n := a.allocUnits(1)
509 if n == 0 {
510 return nil
511 }
512 a.contextSetStatesIndex(c, n)
513 states = a.states[n:]
514 states[0] = s
515 } else if ns&0x1 == 0 {
516 u := ns >> 1
517 i1 := units2Index[u]
518 i2 := units2Index[u+1]
519 if i1 != i2 {
520 n := a.allocUnits(i2)
521 if n == 0 {
522 return nil
523 }
524 copy(a.states[n:], states)
525 a.addFreeBlock(a.contextStatesIndex(c), i1)
526 a.contextSetStatesIndex(c, n)
527 states = a.states[n:]
528 }
529 }
530 a.contextSetNumStates(c, ns+1)
531 return states[:ns+1]
532 }
533
534 func (a *subAllocator) findState(c context, sym byte) *state {
535 var i int
536 states := a.contextStates(c)
537 for i = range states {
538 if states[i].sym == sym {
539 break
540 }
541 }
542 return &states[i]
543 }
544
545 type model struct {
546 maxOrder int
547 orderFall int
548 initRL int
549 runLength int
550 prevSuccess byte
551 escCount byte
552 prevSym byte
553 initEsc byte
554 c context
555 rc rangeCoder
556 a subAllocator
557 charMask [256]byte
558 binSumm [128][64]uint16
559 see2Cont [25][16]see2Context
560 ibuf [256]int
561 sbuf [256]*state
562 }
563
564 func (m *model) restart() {
565 clear(m.charMask[:])
566 m.escCount = 1
567
568 if m.maxOrder < 12 {
569 m.initRL = -m.maxOrder - 1
570 } else {
571 m.initRL = -12 - 1
572 }
573 m.orderFall = m.maxOrder
574 m.runLength = m.initRL
575 m.prevSuccess = 0
576
577 m.a.restart()
578
579 m.c = m.a.newContextSize(256)
580 m.a.contextSetSummFreq(m.c, 257)
581 states := m.a.contextStates(m.c)
582 for i := range states {
583 states[i] = state{sym: byte(i), freq: 1}
584 }
585
586 for i := range m.binSumm {
587 for j, esc := range initBinEsc {
588 n := binScale - esc/(uint16(i)+2)
589 for k := j; k < len(m.binSumm[i]); k += len(initBinEsc) {
590 m.binSumm[i][k] = n
591 }
592 }
593 }
594
595 for i := range m.see2Cont {
596 see := newSee2Context(5*uint16(i) + 10)
597 for j := range m.see2Cont[i] {
598 m.see2Cont[i][j] = see
599 }
600 }
601 }
602
603 func (m *model) init(br io.ByteReader, reset bool, maxOrder, maxMB int) error {
604 err := m.rc.init(br)
605 if err != nil {
606 return err
607 }
608 if !reset {
609 return nil
610 }
611
612 m.a.init(maxMB)
613
614 if maxOrder == 1 {
615 return ErrCorruptPPM
616 }
617 m.maxOrder = maxOrder
618 m.prevSym = 0
619 m.c = 0
620 return nil
621 }
622
623 func (m *model) rescale(c context, s *state) *state {
624 if s.freq <= maxFreq {
625 return s
626 }
627
628 var summFreq uint16
629
630 s.freq += 4
631 states := m.a.contextStates(c)
632 escFreq := m.a.contextSummFreq(c) + 4
633
634 for i := range states {
635 f := states[i].freq
636 escFreq -= uint16(f)
637 if m.orderFall != 0 {
638 f++
639 }
640 f >>= 1
641 summFreq += uint16(f)
642 states[i].freq = f
643
644 if i == 0 || f <= states[i-1].freq {
645 continue
646 }
647 j := i - 1
648 for j > 0 && f > states[j-1].freq {
649 j--
650 }
651 t := states[i]
652 copy(states[j+1:i+1], states[j:i])
653 states[j] = t
654 }
655
656 i := len(states) - 1
657 for states[i].freq == 0 {
658 i--
659 escFreq++
660 }
661 if i != len(states)-1 {
662 states = m.a.shrinkStates(c, states, i+1)
663 }
664 s = &states[0]
665 if i == 0 {
666 for {
667 s.freq -= s.freq >> 1
668 escFreq >>= 1
669 if escFreq <= 1 {
670 return s
671 }
672 }
673 }
674 summFreq += escFreq - (escFreq >> 1)
675 m.a.contextSetSummFreq(c, summFreq)
676 return s
677 }
678
679 func (m *model) decodeBinSymbol(c context) (*state, error) {
680 s := &m.a.contextStates(c)[0]
681
682 ns := m.a.contextNumStates(m.a.contextSuffix(c))
683 i := m.prevSuccess + ns2BSIndex[ns-1] + byte(m.runLength>>26)&0x20
684 if m.prevSym >= 64 {
685 i += 8
686 }
687 if s.sym >= 64 {
688 i += 2 * 8
689 }
690 bs := &m.binSumm[s.freq-1][i]
691 mean := (*bs + 1<<(periodBits-2)) >> periodBits
692
693 if m.rc.currentCount(binScale) < uint32(*bs) {
694 err := m.rc.decode(0, uint32(*bs))
695 if s.freq < 128 {
696 s.freq++
697 }
698 *bs += 1<<intBits - mean
699 m.prevSuccess = 1
700 m.runLength++
701 return s, err
702 }
703 err := m.rc.decode(uint32(*bs), binScale)
704 *bs -= mean
705 m.initEsc = expEscape[*bs>>10]
706 m.charMask[s.sym] = m.escCount
707 m.prevSuccess = 0
708 return nil, err
709 }
710
711 func (m *model) decodeSymbol1(c context) (*state, error) {
712 states := m.a.contextStates(c)
713 scale := uint32(m.a.contextSummFreq(c))
714 // protect against divide by zero
715 // TODO: look at why this happens, may be problem elsewhere
716 if scale == 0 {
717 return nil, ErrCorruptPPM
718 }
719 count := m.rc.currentCount(scale)
720 m.prevSuccess = 0
721
722 var n uint32
723 for i := range states {
724 s := &states[i]
725 n += uint32(s.freq)
726 if n <= count {
727 continue
728 }
729 err := m.rc.decode(n-uint32(s.freq), n)
730 s.freq += 4
731 m.a.contextSetSummFreq(c, uint16(scale+4))
732 if i == 0 {
733 if 2*n > scale {
734 m.prevSuccess = 1
735 m.runLength++
736 }
737 } else {
738 if s.freq <= states[i-1].freq {
739 return s, err
740 }
741 states[i-1], states[i] = states[i], states[i-1]
742 s = &states[i-1]
743 }
744 return m.rescale(c, s), err
745 }
746
747 for _, s := range states {
748 m.charMask[s.sym] = m.escCount
749 }
750 return nil, m.rc.decode(n, scale)
751 }
752
753 func (m *model) makeEscFreq(c context, numMasked int) *see2Context {
754 ns := m.a.contextNumStates(c)
755 if ns == 256 {
756 return nil
757 }
758 diff := ns - numMasked
759
760 var i int
761 if m.prevSym >= 64 {
762 i = 8
763 }
764 if diff < m.a.contextNumStates(m.a.contextSuffix(c))-ns {
765 i++
766 }
767 if int(m.a.contextSummFreq(c)) < 11*ns {
768 i += 2
769 }
770 if numMasked > diff {
771 i += 4
772 }
773 return &m.see2Cont[ns2Index[diff-1]][i]
774 }
775
776 func (m *model) decodeSymbol2(c context, numMasked int) (*state, error) {
777 see := m.makeEscFreq(c, numMasked)
778 scale := see.mean()
779
780 var i int
781 var hi uint32
782 states := m.a.contextStates(c)
783 n := len(states) - numMasked
784 sl := m.ibuf[:n]
785 for j := range sl {
786 for m.charMask[states[i].sym] == m.escCount {
787 i++
788 }
789 hi += uint32(states[i].freq)
790 sl[j] = i
791 i++
792 }
793
794 scale += hi
795 count := m.rc.currentCount(scale)
796
797 if count >= scale {
798 return nil, ErrCorruptPPM
799 }
800 if count >= hi {
801 err := m.rc.decode(hi, scale)
802 if see != nil {
803 see.summ += uint16(scale)
804 }
805 for _, i := range sl {
806 m.charMask[states[i].sym] = m.escCount
807 }
808 return nil, err
809 }
810
811 hi = uint32(states[sl[0]].freq)
812 n = 0
813 for hi <= count {
814 n++
815 hi += uint32(states[sl[n]].freq)
816 }
817 s := &states[sl[n]]
818
819 err := m.rc.decode(hi-uint32(s.freq), hi)
820
821 see.update()
822
823 m.escCount++
824 m.runLength = m.initRL
825
826 s.freq += 4
827 m.a.contextIncSummFreq(c, 4)
828 return m.rescale(c, s), err
829 }
830
831 func (m *model) createSuccessors(c context, s, ss *state) context {
832 sl := m.sbuf[:0]
833
834 if m.orderFall != 0 {
835 sl = append(sl, s)
836 }
837
838 for suff := m.a.contextSuffix(c); suff > 0; suff = m.a.contextSuffix(c) {
839 c = suff
840
841 if ss == nil {
842 ss = m.a.findState(c, s.sym)
843 }
844 if ss.succ != s.succ {
845 c = succContext(ss.succ)
846 break
847 }
848 sl = append(sl, ss)
849 ss = nil
850 }
851
852 if len(sl) == 0 {
853 return c
854 }
855
856 var up state
857 up.sym = m.a.succByte(s.succ)
858 up.succ = m.a.nextByteAddr(s.succ)
859
860 states := m.a.contextStates(c)
861 if len(states) > 1 {
862 s = m.a.findState(c, up.sym)
863
864 cf := uint16(s.freq) - 1
865 s0 := m.a.contextSummFreq(c) - uint16(len(states)) - cf
866
867 if 2*cf <= s0 {
868 if 5*cf > s0 {
869 up.freq = 2
870 } else {
871 up.freq = 1
872 }
873 } else {
874 up.freq = byte(1 + (2*cf+3*s0-1)/(2*s0))
875 }
876 } else {
877 up.freq = states[0].freq
878 }
879
880 for i := len(sl) - 1; i >= 0; i-- {
881 c = m.a.newContext(up, c)
882 if c == 0 {
883 return c
884 }
885 sl[i].succ = int32(c)
886 }
887 return c
888 }
889
890 func (m *model) update(minC, maxC context, s *state) context {
891 if m.orderFall == 0 {
892 if s.succ > 0 {
893 return context(s.succ)
894 }
895 }
896
897 if m.escCount == 0 {
898 m.escCount = 1
899 clear(m.charMask[:])
900 }
901
902 var ss *state // matching minC.suffix state
903
904 if s.freq < maxFreq/4 && m.a.contextSuffix(minC) > 0 {
905 c := m.a.contextSuffix(minC)
906 states := m.a.contextStates(c)
907
908 var i int
909 if len(states) > 1 {
910 for states[i].sym != s.sym {
911 i++
912 }
913 if i > 0 && states[i].freq >= states[i-1].freq {
914 states[i-1], states[i] = states[i], states[i-1]
915 i--
916 }
917 if states[i].freq < maxFreq-9 {
918 states[i].freq += 2
919 m.a.contextIncSummFreq(c, 2)
920 }
921 } else if states[0].freq < 32 {
922 states[0].freq++
923 }
924 ss = &states[i] // save later for createSuccessors
925 }
926
927 if m.orderFall == 0 {
928 minC = m.createSuccessors(minC, s, ss)
929 s.succ = int32(minC)
930 return minC
931 }
932
933 succ := m.a.pushByte(s.sym)
934 if succ == 0 {
935 return context(0)
936 }
937
938 var newC context
939 if s.succ == 0 {
940 s.succ = succ
941 newC = minC
942 } else {
943 if s.succ > 0 {
944 newC = context(s.succ)
945 } else {
946 newC = m.createSuccessors(minC, s, ss)
947 if newC == 0 {
948 return context(0)
949 }
950 }
951 m.orderFall--
952 if m.orderFall == 0 {
953 succ = int32(newC)
954 if maxC != minC {
955 m.a.popByte()
956 }
957 }
958 }
959
960 n := m.a.contextNumStates(minC)
961 s0 := int(m.a.contextSummFreq(minC)) - n - int(s.freq-1)
962 for c := maxC; c != minC; c = m.a.contextSuffix(c) {
963 var summFreq uint16
964
965 states := m.a.expandStates(c)
966 if states == nil {
967 return context(0)
968 }
969 if ns := len(states) - 1; ns != 1 {
970 summFreq = m.a.contextSummFreq(c)
971 if 4*ns <= n && int(summFreq) <= 8*ns {
972 summFreq += 2
973 }
974 if 2*ns < n {
975 summFreq++
976 }
977 } else {
978 p := &states[0]
979 if p.freq < maxFreq/4-1 {
980 p.freq += p.freq
981 } else {
982 p.freq = maxFreq - 4
983 }
984 summFreq = uint16(p.freq) + uint16(m.initEsc)
985 if n > 3 {
986 summFreq++
987 }
988 }
989
990 cf := 2 * int(s.freq) * int(summFreq+6)
991 sf := s0 + int(summFreq)
992 var freq byte
993 if cf >= 6*sf {
994 switch {
995 case cf >= 15*sf:
996 freq = 7
997 case cf >= 12*sf:
998 freq = 6
999 case cf >= 9*sf:
1000 freq = 5
1001 default:
1002 freq = 4
1003 }
1004 summFreq += uint16(freq)
1005 } else {
1006 switch {
1007 case cf >= 4*sf:
1008 freq = 3
1009 case cf > sf:
1010 freq = 2
1011 default:
1012 freq = 1
1013 }
1014 summFreq += 3
1015 }
1016 states[len(states)-1] = state{sym: s.sym, freq: freq, succ: succ}
1017 m.a.contextSetSummFreq(c, summFreq)
1018 }
1019 return newC
1020 }
1021
1022 func (m *model) ReadByte() (byte, error) {
1023 if m.c == 0 {
1024 m.restart()
1025 }
1026 minC := m.c
1027 maxC := minC
1028 var s *state
1029 var err error
1030 if m.a.contextNumStates(minC) == 1 {
1031 s, err = m.decodeBinSymbol(minC)
1032 } else {
1033 s, err = m.decodeSymbol1(minC)
1034 }
1035 for s == nil && err == nil {
1036 n := m.a.contextNumStates(minC)
1037 for m.a.contextNumStates(minC) == n {
1038 m.orderFall++
1039 minC = m.a.contextSuffix(minC)
1040 if minC <= 0 {
1041 return 0, ErrCorruptPPM
1042 }
1043 }
1044 s, err = m.decodeSymbol2(minC, n)
1045 }
1046 if err != nil {
1047 return 0, err
1048 }
1049
1050 m.c = m.update(minC, maxC, s)
1051 m.prevSym = s.sym
1052 return s.sym, nil
1053 }