- for (state = 0; state < NUM_STATE; state++) {
- for (bit = 0; bit < 2; bit++) {
- int bit_cost = cost[p][state] + ao_cost(s, ao_fec_decode_table[state][bit]);
- uint8_t bit_state = ao_next_state(state, bit);
-
- /* Only track the minimal cost to reach
- * this state; the best path can never
- * go through the higher cost paths as
- * total path cost is cumulative
- */
- if (bit_cost < cost[n][bit_state]) {
- cost[n][bit_state] = bit_cost;
- bits[n][bit_state] = (bits[p][state] << 1) | (state & 1);
- }
- }
+
+ /* Ok, of course this is tricky, it's optimized.
+ *
+ * First, it's important to realize that we have 8
+ * states representing the combinations of the three
+ * most recent bits from the encoder. Flipping any
+ * of these three bits flips both output bits.
+ *
+ * 'state<<1' represents the target state for a new
+ * bit value of 0. '(state<<1)+1' represents the
+ * target state for a new bit value of 1.
+ *
+ * 'state' is the previous state with an oldest bit
+ * value of 0. 'state + 4' is the previous state with
+ * an oldest bit value of 1. These two states will
+ * either lead to 'state<<1' or '(state<<1)+1', depending
+ * on whether the next encoded bit was a zero or a one.
+ *
+ * m0 and m1 are the cost of coming to 'state<<1' from
+ * one of the two possible previous states 'state' and
+ * 'state + 4'.
+ *
+ * Because we know the expected values of each
+ * received bit are flipped between these two previous
+ * states:
+ *
+ * bitcost(state+4) = 510 - bitcost(state)
+ *
+ * With those two total costs in hand, we then pick
+ * the lower as the cost of the 'state<<1', and compute
+ * the path of bits leading to that state.
+ *
+ * Then, do the same for '(state<<1) + 1'. This time,
+ * instead of computing the m0 and m1 values from
+ * scratch, because the only difference is that we're
+ * expecting a one bit instead of a zero bit, we just
+ * flip the bitcost values around to match the
+ * expected transmitted bits with some tricky
+ * arithmetic which is equivalent to:
+ *
+ * m0 = cost[p][state] + (510 - bitcost);
+ * m1 = cost[p][state+4] + bitcost
+ *
+ * Then, the lowest cost and bit trace of the new state
+ * is saved.
+ */
+
+#define DO_STATE(state) { \
+ uint32_t bitcost; \
+ \
+ uint32_t m0; \
+ uint32_t m1; \
+ uint32_t bit; \
+ \
+ bitcost = ((uint32_t) (s0 ^ ao_fec_decode_table[(state<<1)]) + \
+ (uint32_t) (s1 ^ ao_fec_decode_table[(state<<1)|1])); \
+ \
+ m0 = cost[p][state] + bitcost; \
+ m1 = cost[p][state+4] + (510 - bitcost); \
+ bit = m0 > m1; \
+ cost[n][state<<1] = bit ? m1 : m0; \
+ bits[n][state<<1] = (bits[p][state + (bit<<2)] << 1) | (state&1); \
+ \
+ m0 -= (bitcost+bitcost-510); \
+ m1 += (bitcost+bitcost-510); \
+ bit = m0 > m1; \
+ cost[n][(state<<1)+1] = bit ? m1 : m0; \
+ bits[n][(state<<1)+1] = (bits[p][state + (bit<<2)] << 1) | (state&1); \