xref: /freebsd/contrib/xz/src/liblzma/rangecoder/price.h (revision f5463265955b829775bbb32e1fd0bc11dafc36ce)
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       price.h
4 /// \brief      Probability price calculation
5 //
6 //  Author:     Igor Pavlov
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12 
13 #ifndef LZMA_PRICE_H
14 #define LZMA_PRICE_H
15 
16 
17 #define RC_MOVE_REDUCING_BITS 4
18 #define RC_BIT_PRICE_SHIFT_BITS 4
19 #define RC_PRICE_TABLE_SIZE (RC_BIT_MODEL_TOTAL >> RC_MOVE_REDUCING_BITS)
20 
21 #define RC_INFINITY_PRICE (UINT32_C(1) << 30)
22 
23 
24 /// Lookup table for the inline functions defined in this file.
25 lzma_attr_visibility_hidden
26 extern const uint8_t lzma_rc_prices[RC_PRICE_TABLE_SIZE];
27 
28 
29 static inline uint32_t
30 rc_bit_price(const probability prob, const uint32_t bit)
31 {
32 	return lzma_rc_prices[(prob ^ ((UINT32_C(0) - bit)
33 			& (RC_BIT_MODEL_TOTAL - 1))) >> RC_MOVE_REDUCING_BITS];
34 }
35 
36 
37 static inline uint32_t
38 rc_bit_0_price(const probability prob)
39 {
40 	return lzma_rc_prices[prob >> RC_MOVE_REDUCING_BITS];
41 }
42 
43 
44 static inline uint32_t
45 rc_bit_1_price(const probability prob)
46 {
47 	return lzma_rc_prices[(prob ^ (RC_BIT_MODEL_TOTAL - 1))
48 			>> RC_MOVE_REDUCING_BITS];
49 }
50 
51 
52 static inline uint32_t
53 rc_bittree_price(const probability *const probs,
54 		const uint32_t bit_levels, uint32_t symbol)
55 {
56 	uint32_t price = 0;
57 	symbol += UINT32_C(1) << bit_levels;
58 
59 	do {
60 		const uint32_t bit = symbol & 1;
61 		symbol >>= 1;
62 		price += rc_bit_price(probs[symbol], bit);
63 	} while (symbol != 1);
64 
65 	return price;
66 }
67 
68 
69 static inline uint32_t
70 rc_bittree_reverse_price(const probability *const probs,
71 		uint32_t bit_levels, uint32_t symbol)
72 {
73 	uint32_t price = 0;
74 	uint32_t model_index = 1;
75 
76 	do {
77 		const uint32_t bit = symbol & 1;
78 		symbol >>= 1;
79 		price += rc_bit_price(probs[model_index], bit);
80 		model_index = (model_index << 1) + bit;
81 	} while (--bit_levels != 0);
82 
83 	return price;
84 }
85 
86 
87 static inline uint32_t
88 rc_direct_price(const uint32_t bits)
89 {
90 	 return bits << RC_BIT_PRICE_SHIFT_BITS;
91 }
92 
93 #endif
94