1// SPDX-License-Identifier: 0BSD
2
3///////////////////////////////////////////////////////////////////////////////
4//
5/// \file       price_tablegen.c
6/// \brief      Probability price table generator
7///
8/// Compiling: gcc -std=c99 -o price_tablegen price_tablegen.c
9///
10//  Authors:    Igor Pavlov
11//              Lasse Collin
12//
13///////////////////////////////////////////////////////////////////////////////
14
15#include <inttypes.h>
16#include <stdio.h>
17
18// Make it compile without common.h.
19#define BUILDING_PRICE_TABLEGEN
20#define lzma_attr_visibility_hidden
21
22#include "range_common.h"
23#include "price.h"
24
25
26static uint32_t rc_prices[RC_PRICE_TABLE_SIZE];
27
28
29static void
30init_price_table(void)
31{
32	for (uint32_t i = (UINT32_C(1) << RC_MOVE_REDUCING_BITS) / 2;
33			i < RC_BIT_MODEL_TOTAL;
34			i += (UINT32_C(1) << RC_MOVE_REDUCING_BITS)) {
35		const uint32_t cycles_bits = RC_BIT_PRICE_SHIFT_BITS;
36		uint32_t w = i;
37		uint32_t bit_count = 0;
38
39		for (uint32_t j = 0; j < cycles_bits; ++j) {
40			w *= w;
41			bit_count <<= 1;
42
43			while (w >= (UINT32_C(1) << 16)) {
44				w >>= 1;
45				++bit_count;
46			}
47		}
48
49		rc_prices[i >> RC_MOVE_REDUCING_BITS]
50				= (RC_BIT_MODEL_TOTAL_BITS << cycles_bits)
51				- 15 - bit_count;
52	}
53
54	return;
55}
56
57
58static void
59print_price_table(void)
60{
61	// Split the SPDX string so that it won't accidentally match
62	// when tools search for the string.
63	printf("// SPDX" "-License-Identifier" ": 0BSD\n\n"
64		"// This file has been generated by price_tablegen.c.\n\n"
65		"#include \"range_encoder.h\"\n\n"
66		"const uint8_t lzma_rc_prices["
67		"RC_PRICE_TABLE_SIZE] = {");
68
69	const size_t array_size = sizeof(lzma_rc_prices)
70			/ sizeof(lzma_rc_prices[0]);
71	for (size_t i = 0; i < array_size; ++i) {
72		if (i % 8 == 0)
73			printf("\n\t");
74
75		printf("%4" PRIu32, rc_prices[i]);
76
77		if (i != array_size - 1)
78			printf(",");
79	}
80
81	printf("\n};\n");
82
83	return;
84}
85
86
87int
88main(void)
89{
90	init_price_table();
91	print_price_table();
92	return 0;
93}
94