Debian Codegraph @

crc.c

raw symbols SCIP
1 // Part of dump1090, a Mode S message decoder for RTLSDR devices.
2 //
3 // crc.h: Mode S CRC calculation and error correction.
4 //
5 // Copyright (c) 2014,2015 Oliver Jowett <[email protected]>
6 //
7 // This file is free software: you may copy, redistribute and/or modify it
8 // under the terms of the GNU General Public License as published by the
9 // Free Software Foundation, either version 2 of the License, or (at your
10 // option) any later version.
11 //
12 // This file is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 #include "dump1090.h"
21
22 #include <assert.h>
23
24 // Errorinfo for "no errors"
25 static struct errorinfo NO_ERRORS;
26
27 // Generator polynomial for the Mode S CRC:
28 #define MODES_GENERATOR_POLY 0xfff409U
29
30 // CRC values for all single-byte messages;
31 // used to speed up CRC calculation.
32 static uint32_t crc_table[256];
33
34 // Syndrome values for all single-bit errors;
35 // used to speed up construction of error-
36 // correction tables.
37 static uint32_t single_bit_syndrome[112];
38
39 static void initLookupTables()
40 {
41 int i;
42 uint8_t msg[112/8];
43
44 for (i = 0; i < 256; ++i) {
45 uint32_t c = i << 16;
46 int j;
47 for (j = 0; j < 8; ++j) {
48 if (c & 0x800000)
49 c = (c<<1) ^ MODES_GENERATOR_POLY;
50 else
51 c = (c<<1);
52 }
53
54 crc_table[i] = c & 0x00ffffff;
55 }
56
57 memset(msg, 0, sizeof(msg));
58 for (i = 0; i < 112; ++i) {
59 msg[i/8] ^= 1 << (7 - (i & 7));
60 single_bit_syndrome[i] = modesChecksum(msg, 112);
61 msg[i/8] ^= 1 << (7 - (i & 7));
62 }
63 }
64
65 uint32_t modesChecksum(uint8_t *message, int bits)
66 {
67 uint32_t rem = 0;
68 int i;
69 int n = bits/8;
70
71 assert(bits % 8 == 0);
72 assert(n >= 3);
73
74 for (i = 0; i < n-3; ++i) {
75 rem = (rem << 8) ^ crc_table[message[i] ^ ((rem & 0xff0000) >> 16)];
76 rem = rem & 0xffffff;
77 }
78
79 rem = rem ^ (message[n-3] << 16) ^ (message[n-2] << 8) ^ (message[n-1]);
80 return rem;
81 }
82
83 static struct errorinfo *bitErrorTable_short;
84 static int bitErrorTableSize_short;
85
86 static struct errorinfo *bitErrorTable_long;
87 static int bitErrorTableSize_long;
88
89 // compare two errorinfo structures
90 static int syndrome_compare(const void *x, const void *y) {
91 struct errorinfo *ex = (struct errorinfo*)x;
92 struct errorinfo *ey = (struct errorinfo*)y;
93 return (int)ex->syndrome - (int)ey->syndrome;
94 }
95
96 // (n k), the number of ways of selecting k distinct items from a set of n items
97 static int combinations(int n, int k)
98 {
99 int result = 1, i;
100
101 if (k == 0 || k == n)
102 return 1;
103
104 if (k > n)
105 return 0;
106
107 for (i = 1; i <= k; ++i) {
108 result = result * n / i;
109 n = n - 1;
110 }
111
112 return result;
113 }
114
115 // Recursively populates an errorinfo table with error syndromes
116 //
117 // in:
118 // table: the table to fill
119 // n: first entry to fill
120 // maxSize: max size of table
121 // offset: start bit offset for checksum calculation
122 // startbit: first bit to introduce errors into
123 // endbit: (one past) last bit to introduce errors info
124 // base_entry: template entry to start from
125 // error_bit: how many error bits have already been set
126 // max_errors: maximum total error bits to set
127 // out:
128 // returns: the next free entry in the table
129 // table: has been populated between [n, return value)
130 static int prepareSubtable(struct errorinfo *table, int n, int maxsize, int offset, int startbit, int endbit, struct errorinfo *base_entry, int error_bit, int max_errors)
131 {
132 int i = 0;
133
134 if (error_bit >= max_errors)
135 return n;
136
137 for (i = startbit; i < endbit; ++i) {
138 assert(n < maxsize);
139
140 table[n] = *base_entry;
141 table[n].syndrome ^= single_bit_syndrome[i + offset];
142 table[n].errors = error_bit+1;
143 table[n].bit[error_bit] = i;
144
145 ++n;
146 n = prepareSubtable(table, n, maxsize, offset, i + 1, endbit, &table[n-1], error_bit + 1, max_errors);
147 }
148
149 return n;
150 }
151
152 static int flagCollisions(struct errorinfo *table, int tablesize, int offset, int startbit, int endbit, uint32_t base_syndrome, int error_bit, int first_error, int last_error)
153 {
154 int i = 0;
155 int count = 0;
156
157 if (error_bit > last_error)
158 return 0;
159
160 for (i = startbit; i < endbit; ++i) {
161 struct errorinfo ei;
162
163 ei.syndrome = base_syndrome ^ single_bit_syndrome[i + offset];
164
165 if (error_bit >= first_error) {
166 struct errorinfo *collision = bsearch(&ei, table, tablesize, sizeof(struct errorinfo), syndrome_compare);
167 if (collision != NULL && collision->errors != -1) {
168 ++count;
169 collision->errors = -1;
170 }
171 }
172
173 count += flagCollisions(table, tablesize, offset, i+1, endbit, ei.syndrome, error_bit + 1, first_error, last_error);
174 }
175
176 return count;
177 }
178
179
180 // Allocate and build an error table for messages of length "bits" (max 112)
181 // returns a pointer to the new table and sets *size_out to the table length
182 static struct errorinfo *prepareErrorTable(int bits, int max_correct, int max_detect, int *size_out)
183 {
184 int maxsize, usedsize;
185 struct errorinfo *table;
186 struct errorinfo base_entry;
187 int i, j;
188
189 assert (bits >= 0 && bits <= 112);
190 assert (max_correct >=0 && max_correct <= MODES_MAX_BITERRORS);
191 assert (max_detect >= max_correct);
192
193 if (!max_correct) {
194 *size_out = 0;
195 return NULL;
196 }
197
198 maxsize = 0;
199 for (i = 1; i <= max_correct; ++i) {
200 maxsize += combinations(bits - 5, i); // space needed for all i-bit errors
201 }
202
203 #ifdef CRCDEBUG
204 fprintf(stderr, "Preparing syndrome table to correct up to %d-bit errors (detecting %d-bit errors) in a %d-bit message (max %d entries)\n", max_correct, max_detect, bits, maxsize);
205 #endif
206
207 table = malloc(maxsize * sizeof(struct errorinfo));
208 base_entry.syndrome = 0;
209 base_entry.errors = 0;
210 for (i = 0; i < MODES_MAX_BITERRORS; ++i)
211 base_entry.bit[i] = -1;
212
213 // ignore the first 5 bits (DF type)
214 usedsize = prepareSubtable(table, 0, maxsize, 112 - bits, 5, bits, &base_entry, 0, max_correct);
215
216 #ifdef CRCDEBUG
217 fprintf(stderr, "%d syndromes (expected %d).\n", usedsize, maxsize);
218 fprintf(stderr, "Sorting syndromes..\n");
219 #endif
220
221 qsort(table, usedsize, sizeof(struct errorinfo), syndrome_compare);
222
223 #ifdef CRCDEBUG
224 {
225 // Show the table stats
226 fprintf(stderr, "Undetectable errors:\n");
227 for (i = 1; i <= max_correct; ++i) {
228 int j, count;
229
230 count = 0;
231 for (j = 0; j < usedsize; ++j)
232 if (table[j].errors == i && table[j].syndrome == 0)
233 ++count;
234
235 fprintf(stderr, " %d undetectable %d-bit errors\n", count, i);
236 }
237 }
238 #endif
239
240 // Handle ambiguous cases, where there is more than one possible error pattern
241 // that produces a given syndrome (this happens with >2 bit errors).
242
243 #ifdef CRCDEBUG
244 fprintf(stderr, "Finding collisions..\n");
245 #endif
246 for (i = 0, j = 0; i < usedsize; ++i) {
247 if (i < usedsize-1 && table[i+1].syndrome == table[i].syndrome) {
248 // skip over this entry and all collisions
249 while (i < usedsize && table[i+1].syndrome == table[i].syndrome)
250 ++i;
251
252 // now table[i] is the last duplicate
253 continue;
254 }
255
256 if (i != j)
257 table[j] = table[i];
258 ++j;
259 }
260
261 if (j < usedsize) {
262 #ifdef CRCDEBUG
263 fprintf(stderr, "Discarded %d collisions.\n", usedsize - j);
264 #endif
265 usedsize = j;
266 }
267
268 // Flag collisions we want to detect but not correct
269 if (max_detect > max_correct) {
270 int flagged;
271
272 #ifdef CRCDEBUG
273 fprintf(stderr, "Flagging collisions between %d - %d bits..\n", max_correct+1, max_detect);
274 #endif
275
276 flagged = flagCollisions(table, usedsize, 112 - bits, 5, bits, 0, 1, max_correct+1, max_detect);
277
278 #ifdef CRCDEBUG
279 fprintf(stderr, "Flagged %d collisions for removal.\n", flagged);
280 #else
281 #endif
282
283 if (flagged > 0) {
284 for (i = 0, j = 0; i < usedsize; ++i) {
285 if (table[i].errors != -1) {
286 if (i != j)
287 table[j] = table[i];
288 ++j;
289 }
290 }
291
292 #ifdef CRCDEBUG
293 fprintf(stderr, "Discarded %d flagged collisions.\n", usedsize - j);
294 #endif
295 usedsize = j;
296 }
297 }
298
299 if (usedsize < maxsize) {
300 #ifdef CRCDEBUG
301 fprintf(stderr, "Shrinking table from %d to %d..\n", maxsize, usedsize);
302 table = realloc(table, usedsize * sizeof(struct errorinfo));
303 #endif
304 }
305
306 *size_out = usedsize;
307
308 #ifdef CRCDEBUG
309 {
310 // Check the table.
311 unsigned char *msg = malloc(bits/8);
312
313 for (i = 0; i < usedsize; ++i) {
314 int j;
315 struct errorinfo *ei;
316 uint32_t result;
317
318 memset(msg, 0, bits/8);
319 ei = &table[i];
320 for (j = 0; j < ei->errors; ++j) {
321 msg[ei->bit[j] >> 3] ^= 1 << (7 - (ei->bit[j]&7));
322 }
323
324 result = modesChecksum(msg, bits);
325 if (result != ei->syndrome) {
326 fprintf(stderr, "PROBLEM: entry %6d/%6d syndrome %06x errors %d bits ", i, usedsize, ei->syndrome, ei->errors);
327 for (j = 0; j < ei->errors; ++j)
328 fprintf(stderr, "%3d ", ei->bit[j]);
329 fprintf(stderr, " checksum %06x\n", result);
330 }
331 }
332 free(msg);
333
334 // Show the table stats
335 fprintf(stderr, "Syndrome table summary:\n");
336 for (i = 1; i <= max_correct; ++i) {
337 int j, count, possible;
338
339 count = 0;
340 for (j = 0; j < usedsize; ++j)
341 if (table[j].errors == i)
342 ++count;
343
344 possible = combinations(bits-5, i);
345 fprintf(stderr, " %d entries for %d-bit errors (%d possible, %d%% coverage)\n", count, i, possible, 100 * count / possible);
346 }
347
348 fprintf(stderr, " %d entries total\n", usedsize);
349 }
350 #endif
351
352 return table;
353 }
354
355 // Precompute syndrome tables for 56- and 112-bit messages.
356 void modesChecksumInit(int fixBits)
357 {
358 initLookupTables();
359
360 switch (fixBits) {
361 case 0:
362 bitErrorTable_short = bitErrorTable_long = NULL;
363 bitErrorTableSize_short = bitErrorTableSize_long = 0;
364 break;
365
366 case 1:
367 // For 1 bit correction, we have 100% coverage up to 4 bit detection, so don't bother
368 // with flagging collisions there.
369 bitErrorTable_short = prepareErrorTable(MODES_SHORT_MSG_BITS, 1, 1, &bitErrorTableSize_short);
370 bitErrorTable_long = prepareErrorTable(MODES_LONG_MSG_BITS, 1, 1, &bitErrorTableSize_long);
371 break;
372
373 default:
374 // Detect out to 4 bit errors; this reduces our 2-bit coverage to about 65%.
375 // This can take a little while - tell the user.
376 fprintf(stderr, "Preparing error correction tables.. ");
377 bitErrorTable_short = prepareErrorTable(MODES_SHORT_MSG_BITS, 2, 4, &bitErrorTableSize_short);
378 bitErrorTable_long = prepareErrorTable(MODES_LONG_MSG_BITS, 2, 4, &bitErrorTableSize_long);
379 fprintf(stderr, "done.\n");
380 break;
381 }
382 }
383
384 // Given an error syndrome and message length, return
385 // an error-correction descriptor, or NULL if the
386 // syndrome is uncorrectable
387 struct errorinfo *modesChecksumDiagnose(uint32_t syndrome, int bitlen)
388 {
389 struct errorinfo *table;
390 int tablesize;
391
392 struct errorinfo ei;
393
394 if (syndrome == 0)
395 return &NO_ERRORS;
396
397 assert (bitlen == 56 || bitlen == 112);
398 if (bitlen == 56) { table = bitErrorTable_short; tablesize = bitErrorTableSize_short; }
399 else { table = bitErrorTable_long; tablesize = bitErrorTableSize_long; }
400
401 if (!table)
402 return NULL;
403
404 ei.syndrome = syndrome;
405 return bsearch(&ei, table, tablesize, sizeof(struct errorinfo), syndrome_compare);
406 }
407
408 // Given a message and an error-correction descriptor,
409 // apply the error correction to the given message.
410 void modesChecksumFix(uint8_t *msg, struct errorinfo *info)
411 {
412 int i;
413
414 if (!info)
415 return;
416
417 for (i = 0; i < info->errors; ++i)
418 msg[info->bit[i] >> 3] ^= 1 << (7 - (info->bit[i] & 7));
419 }
420
421 #ifdef CRCDEBUG
422 int main(int argc, char **argv)
423 {
424 int shortlen, longlen;
425 int i;
426 struct errorinfo *shorttable, *longtable;
427
428 if (argc < 3) {
429 fprintf(stderr, "syntax: crctests <ncorrect> <ndetect>\n");
430 return 1;
431 }
432
433 initLookupTables();
434 shorttable = prepareErrorTable(MODES_SHORT_MSG_BITS, atoi(argv[1]), atoi(argv[2]), &shortlen);
435 longtable = prepareErrorTable(MODES_LONG_MSG_BITS, atoi(argv[1]), atoi(argv[2]), &longlen);
436
437 // check for DF11 correction syndromes where there is a syndrome with lower 7 bits all zero
438 // (which would be used for DF11 error correction), but there's also a syndrome which has
439 // the same upper 17 bits but nonzero lower 7 bits.
440
441 // empirically, with ncorrect=1 ndetect=2 we get no ambiguous syndromes;
442 // for ncorrect=2 ndetect=4 we get 11 ambiguous syndromes:
443
444 /*
445 syndrome 1 = 000C00 bits=[ 44 45 ]
446 syndrome 2 = 000C1B bits=[ 30 43 ]
447
448 syndrome 1 = 001400 bits=[ 43 45 ]
449 syndrome 2 = 00141B bits=[ 30 44 ]
450
451 syndrome 1 = 001800 bits=[ 43 44 ]
452 syndrome 2 = 00181B bits=[ 30 45 ]
453
454 syndrome 1 = 001800 bits=[ 43 44 ]
455 syndrome 2 = 001836 bits=[ 29 42 ]
456
457 syndrome 1 = 002400 bits=[ 42 45 ]
458 syndrome 2 = 00242D bits=[ 29 30 ]
459
460 syndrome 1 = 002800 bits=[ 42 44 ]
461 syndrome 2 = 002836 bits=[ 29 43 ]
462
463 syndrome 1 = 003000 bits=[ 42 43 ]
464 syndrome 2 = 003036 bits=[ 29 44 ]
465
466 syndrome 1 = 003000 bits=[ 42 43 ]
467 syndrome 2 = 00306C bits=[ 28 41 ]
468
469 syndrome 1 = 004800 bits=[ 41 44 ]
470 syndrome 2 = 00485A bits=[ 28 29 ]
471
472 syndrome 1 = 005000 bits=[ 41 43 ]
473 syndrome 2 = 00506C bits=[ 28 42 ]
474
475 syndrome 1 = 006000 bits=[ 41 42 ]
476 syndrome 2 = 00606C bits=[ 28 43 ]
477 */
478
479 // So in the DF11 correction logic, we just discard messages that require more than a 1 bit fix.
480
481 fprintf(stderr, "checking %d syndromes for DF11 collisions..\n", shortlen);
482 for (i = 0; i < shortlen; ++i) {
483 if ((shorttable[i].syndrome & 0xFF) == 0) {
484 int j;
485 // all syndromes with the same first 17 bits should sort immediately after entry i,
486 // so this is fairly easy
487 for (j = i+1; j < shortlen; ++j) {
488 if ((shorttable[i].syndrome & 0xFFFF80) == (shorttable[j].syndrome & 0xFFFF80)) {
489 int k;
490 int mismatch = 0;
491
492 // we don't care if the only differences are in bits that lie in the checksum
493 for (k = 0; k < shorttable[i].errors; ++k) {
494 int l, matched = 0;
495
496 if (shorttable[i].bit[k] >= 49)
497 continue; // bit is in the final 7 bits, we don't care
498
499 for (l = 0; l < shorttable[j].errors; ++l) {
500 if (shorttable[i].bit[k] == shorttable[j].bit[l]) {
501 matched = 1;
502 break;
503 }
504 }
505
506 if (!matched)
507 mismatch = 1;
508 }
509
510 for (k = 0; k < shorttable[j].errors; ++k) {
511 int l, matched = 0;
512
513 if (shorttable[j].bit[k] >= 49)
514 continue; // bit is in the final 7 bits, we don't care
515
516 for (l = 0; l < shorttable[i].errors; ++l) {
517 if (shorttable[j].bit[k] == shorttable[i].bit[l]) {
518 matched = 1;
519 break;
520 }
521 }
522
523 if (!matched)
524 mismatch = 1;
525 }
526
527 if (mismatch) {
528 fprintf(stderr,
529 "DF11 correction collision: \n"
530 " syndrome 1 = %06X bits=[",
531 shorttable[i].syndrome);
532 for (k = 0; k < shorttable[i].errors; ++k)
533 fprintf(stderr, " %d", shorttable[i].bit[k]);
534 fprintf(stderr, " ]\n");
535
536 fprintf(stderr,
537 " syndrome 2 = %06X bits=[",
538 shorttable[j].syndrome);
539 for (k = 0; k < shorttable[j].errors; ++k)
540 fprintf(stderr, " %d", shorttable[j].bit[k]);
541 fprintf(stderr, " ]\n");
542 }
543 } else {
544 break;
545 }
546 }
547 }
548 }
549
550 free(shorttable);
551 free(longtable);
552
553 return 0;
554 }
555 #endif