altos: Rename 'core' to 'kernel'
[fw/altos] / src / kernel / ao_fec_rx.c
1 /*
2  * Copyright © 2012 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include <ao_fec.h>
19 #include <stdio.h>
20
21 #ifdef TELEMEGA
22 #include <ao.h>
23 #endif
24
25 #if AO_PROFILE
26 #include <ao_profile.h>
27
28 uint32_t        ao_fec_decode_start, ao_fec_decode_end;
29 #endif
30
31 /* 
32  * byte order repeats through 3 2 1 0
33  *      
34  * bit-pair order repeats through
35  *
36  *  1/0 3/2 5/4 7/6
37  *
38  * So, the over all order is:
39  *
40  *      3,1/0   2,1/0   1,1/0   0,1/0
41  *      3,3/2   2,3/2   1,3/2   0,3/2
42  *      3,5/4   2,5/4   1,5/4   0,5/4
43  *      3,7/6   2,7/6   1,7/6   0,7/6
44  *
45  * The raw bit order is thus
46  *
47  *      1e/1f   16/17   0e/0f   06/07
48  *      1c/1d   14/15   0c/0d   04/05
49  *      1a/1b   12/13   0a/0b   02/03
50  *      18/19   10/11   08/09   00/01
51  */
52
53 static const uint8_t ao_interleave_order[] = {
54         0x1e, 0x16, 0x0e, 0x06,
55         0x1c, 0x14, 0x0c, 0x04,
56         0x1a, 0x12, 0x0a, 0x02,
57         0x18, 0x10, 0x08, 0x00
58 };
59
60 static inline uint16_t ao_interleave_index(uint16_t i) {
61         return (i & ~0x1e) | ao_interleave_order[(i & 0x1e) >> 1];
62 }
63
64 #define NUM_STATE       8
65 #define NUM_HIST        24
66
67 typedef uint32_t        bits_t;
68
69 #define V_0             0xff
70 #define V_1             0x00
71
72 /*
73  * These are just the 'zero' states; the 'one' states mirror them
74  */
75 static const uint8_t ao_fec_decode_table[NUM_STATE*2] = {
76         V_0, V_0,       /* 000 */
77         V_0, V_1,       /* 001 */
78         V_1, V_1,       /* 010 */
79         V_1, V_0,       /* 011 */
80         V_1, V_1,       /* 100 */
81         V_1, V_0,       /* 101 */
82         V_0, V_0,       /* 110 */
83         V_0, V_1        /* 111 */
84 };
85
86 static inline uint8_t
87 ao_next_state(uint8_t state, uint8_t bit)
88 {
89         return ((state << 1) | bit) & 0x7;
90 }
91
92 /*
93  * 'in' is 8-bits per symbol soft decision data
94  * 'len' is input byte length. 'out' must be
95  * 'len'/16 bytes long
96  */
97
98 uint8_t
99 ao_fec_decode(const uint8_t *in, uint16_t len, uint8_t *out, uint8_t out_len, uint16_t (*callback)(void))
100 {
101         static uint32_t cost[2][NUM_STATE];             /* path cost */
102         static bits_t   bits[2][NUM_STATE];             /* save bits to quickly output them */
103
104         uint16_t        i;                              /* input byte index */
105         uint16_t        b;                              /* encoded symbol index (bytes/2) */
106         uint16_t        o;                              /* output bit index */
107         uint8_t         p;                              /* previous cost/bits index */
108         uint8_t         n;                              /* next cost/bits index */
109         uint8_t         state;                          /* state index */
110         const uint8_t   *whiten = ao_fec_whiten_table;
111         uint16_t        interleave;                     /* input byte array index */
112         uint8_t         s0, s1;
113         uint16_t        avail;
114         uint16_t        crc = AO_FEC_CRC_INIT;
115 #if AO_PROFILE
116         uint32_t        start_tick;
117 #endif
118
119         p = 0;
120         for (state = 0; state < NUM_STATE; state++) {
121                 cost[0][state] = 0x7fffffff;
122                 bits[0][state] = 0;
123         }
124         cost[0][0] = 0;
125
126         if (callback)
127                 avail = 0;
128         else
129                 avail = len;
130
131 #if AO_PROFILE
132         if (!avail) {
133                 avail = callback();
134                 if (!avail)
135                         return 0;
136         }
137         start_tick = ao_profile_tick();
138 #endif
139         o = 0;
140         for (i = 0; i < len; i += 2) {
141                 b = i/2;
142                 n = p ^ 1;
143
144                 if (!avail) {
145                         avail = callback();
146                         if (!avail)
147                                 return 0;
148                 }
149
150                 /* Fetch one pair of input bytes, de-interleaving
151                  * the input.
152                  */
153                 interleave = ao_interleave_index(i);
154                 s0 = in[interleave];
155                 s1 = in[interleave+1];
156
157                 avail -= 2;
158
159                 /* Compute path costs and accumulate output bit path
160                  * for each state and encoded bit value. Unrolling
161                  * this loop is worth about > 30% performance boost.
162                  * Decoding 76-byte remote access packets is reduced
163                  * from 14.700ms to 9.3ms. Redoing the loop to
164                  * directly compare the two pasts for each future state
165                  * reduces this down to 5.7ms
166                  */
167
168                 /* Ok, of course this is tricky, it's optimized.
169                  *
170                  * First, it's important to realize that we have 8
171                  * states representing the combinations of the three
172                  * most recent bits from the encoder. Flipping any
173                  * of these three bits flips both output bits.
174                  *
175                  * 'state<<1' represents the target state for a new
176                  * bit value of 0. '(state<<1)+1' represents the
177                  * target state for a new bit value of 1.
178                  *
179                  * 'state' is the previous state with an oldest bit
180                  * value of 0. 'state + 4' is the previous state with
181                  * an oldest bit value of 1. These two states will
182                  * either lead to 'state<<1' or '(state<<1)+1', depending
183                  * on whether the next encoded bit was a zero or a one.
184                  *
185                  * m0 and m1 are the cost of coming to 'state<<1' from
186                  * one of the two possible previous states 'state' and
187                  * 'state + 4'.
188                  *
189                  * Because we know the expected values of each
190                  * received bit are flipped between these two previous
191                  * states:
192                  * 
193                  *      bitcost(state+4) = 510 - bitcost(state)
194                  *
195                  * With those two total costs in hand, we then pick
196                  * the lower as the cost of the 'state<<1', and compute
197                  * the path of bits leading to that state.
198                  *
199                  * Then, do the same for '(state<<1) + 1'. This time,
200                  * instead of computing the m0 and m1 values from
201                  * scratch, because the only difference is that we're
202                  * expecting a one bit instead of a zero bit, we just
203                  * flip the bitcost values around to match the
204                  * expected transmitted bits with some tricky
205                  * arithmetic which is equivalent to:
206                  *
207                  *      m0 = cost[p][state] + (510 - bitcost);
208                  *      m1 = cost[p][state+4] + bitcost
209                  *
210                  * Then, the lowest cost and bit trace of the new state
211                  * is saved.
212                  */
213
214 #define DO_STATE(state) {                                               \
215                         uint32_t        bitcost;                        \
216                                                                         \
217                         uint32_t        m0;                             \
218                         uint32_t        m1;                             \
219                         uint32_t        bit;                            \
220                                                                         \
221                         bitcost = ((uint32_t) (s0 ^ ao_fec_decode_table[(state<<1)]) + \
222                                    (uint32_t) (s1 ^ ao_fec_decode_table[(state<<1)|1])); \
223                                                                         \
224                         m0 = cost[p][state] + bitcost;                  \
225                         m1 = cost[p][state+4] + (510 - bitcost);        \
226                         bit = m0 > m1;                                  \
227                         cost[n][state<<1] = bit ? m1 : m0;              \
228                         bits[n][state<<1] = (bits[p][state + (bit<<2)] << 1) | (state&1); \
229                                                                         \
230                         m0 -= (bitcost+bitcost-510);                    \
231                         m1 += (bitcost+bitcost-510);                    \
232                         bit = m0 > m1;                                  \
233                         cost[n][(state<<1)+1] = bit ? m1 : m0;          \
234                         bits[n][(state<<1)+1] = (bits[p][state + (bit<<2)] << 1) | (state&1); \
235                 }
236
237                 DO_STATE(0);
238                 DO_STATE(1);
239                 DO_STATE(2);
240                 DO_STATE(3);
241
242 #if 0
243                 printf ("bit %3d symbol %2x %2x:", i/2, s0, s1);
244                 for (state = 0; state < NUM_STATE; state++) {
245                         printf (" %8u(%08x)", cost[n][state], bits[n][state]);
246                 }
247                 printf ("\n");
248 #endif
249                 p = n;
250
251                 /* A loop is needed to handle the last output byte. It
252                  * won't have any bits of future data to perform full
253                  * error correction, but we might as well give the
254                  * best possible answer anyways.
255                  */
256                 while ((b - o) >= (8 + NUM_HIST) || (i + 2 >= len && b > o)) {
257
258                         /* Compute number of bits to the end of the
259                          * last full byte of data. This is generally
260                          * NUM_HIST, unless we've reached
261                          * the end of the input, in which case
262                          * it will be seven.
263                          */
264                         int8_t          dist = b - (o + 8);     /* distance to last ready-for-writing bit */
265                         uint32_t        min_cost;               /* lowest cost */
266                         uint8_t         min_state;              /* lowest cost state */
267                         uint8_t         byte;
268
269                         /* Find the best fit at the current point
270                          * of the decode.
271                          */
272                         min_cost = cost[p][0];
273                         min_state = 0;
274                         for (state = 1; state < NUM_STATE; state++) {
275                                 if (cost[p][state] < min_cost) {
276                                         min_cost = cost[p][state];
277                                         min_state = state;
278                                 }
279                         }
280
281                         /* The very last byte of data has the very last bit
282                          * of data left in the state value; just smash the
283                          * bits value in place and reset the 'dist' from
284                          * -1 to 0 so that the full byte is read out
285                          */
286                         if (dist < 0) {
287                                 bits[p][min_state] = (bits[p][min_state] << 1) | (min_state & 1);
288                                 dist = 0;
289                         }
290
291 #if 0
292                         printf ("\tbit %3d min_cost %5d old bit %3d old_state %x bits %02x whiten %0x\n",
293                                 i/2, min_cost, o + 8, min_state, (bits[p][min_state] >> dist) & 0xff, *whiten);
294 #endif
295                         byte = (bits[p][min_state] >> dist) ^ *whiten++;
296                         *out++ = byte;
297                         if (out_len > 2)
298                                 crc = ao_fec_crc_byte(byte, crc);
299
300                         if (!--out_len) {
301                                 if ((out[-2] == (uint8_t) (crc >> 8)) &&
302                                     out[-1] == (uint8_t) crc)
303                                         out[-1] = AO_FEC_DECODE_CRC_OK;
304                                 else
305                                         out[-1] = 0;
306                                 out[-2] = 0;
307                                 goto done;
308                         }
309                         o += 8;
310                 }
311         }
312 done:
313 #if AO_PROFILE
314         ao_fec_decode_start = start_tick;
315         ao_fec_decode_end = ao_profile_tick();
316 #endif
317         return 1;
318 }