+ /* Fill in a table that maps range coding probabilities needed to code a
+ * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
+ * handle fractional costs) needed to code that bit X.
+ *
+ * Consider the range of the range decoder. To eliminate exactly half
+ * the range (logical probability of 0.5), we need exactly 1 bit. For
+ * lower probabilities we need more bits and for higher probabilities we
+ * need fewer bits. In general, a logical probability of N will
+ * eliminate the proportion 1 - N of the range; this information takes
+ * log2(1 / N) bits to encode.
+ *
+ * The below loop is simply calculating this number of bits for each
+ * possible probability allowed by the LZMS compression format, but
+ * without using real numbers. To handle fractional probabilities, each
+ * cost is multiplied by (1 << LZMS_COST_SHIFT). These techniques are
+ * based on those used by LZMA.
+ *
+ * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
+ * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
+ * 63 / 64.
+ */
+ for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
+ u32 prob = i;
+
+ if (prob == 0)
+ prob = 1;
+ else if (prob == LZMS_PROBABILITY_MAX)
+ prob = LZMS_PROBABILITY_MAX - 1;
+
+ #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
+ lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
+ (1 << LZMS_COST_SHIFT);
+ #else
+ u32 w = prob;
+ u32 bit_count = 0;
+ for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
+ w *= w;
+ bit_count <<= 1;
+ while (w >= (1U << 16)) {
+ w >>= 1;
+ ++bit_count;
+ }
+ }
+ lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
+ (15 + bit_count);
+ #endif
+ }
+}