libfec.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. /*
  2. * fec.c -- forward error correction based on Vandermonde matrices
  3. * 980624
  4. * (C) 1997-98 Luigi Rizzo (luigi@iet.unipi.it)
  5. *
  6. * Portions derived from code by Phil Karn (karn@ka9q.ampr.org),
  7. * Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari
  8. * Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions
  12. * are met:
  13. *
  14. * 1. Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. * 2. Redistributions in binary form must reproduce the above
  17. * copyright notice, this list of conditions and the following
  18. * disclaimer in the documentation and/or other materials
  19. * provided with the distribution.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND
  22. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  23. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  24. * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
  25. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  26. * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  27. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  28. * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  30. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  31. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  32. * OF SUCH DAMAGE.
  33. */
  34. /*
  35. * The following parameter defines how many bits are used for
  36. * field elements. The code supports any value from 2 to 16
  37. * but fastest operation is achieved with 8 bit elements
  38. * This is the only parameter you may want to change.
  39. */
  40. #ifndef GF_BITS
  41. #define GF_BITS 8 /* code over GF(2**GF_BITS) - change to suit */
  42. #endif
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include "libfec.h"
  47. /*
  48. * stuff used for testing purposes only
  49. */
  50. #ifdef TEST
  51. #define DEB(x)
  52. #define DDB(x) x
  53. #define DEBUG 0 /* minimal debugging */
  54. #ifdef MSDOS
  55. #include <time.h>
  56. struct timeval {
  57. unsigned long ticks;
  58. };
  59. #define gettimeofday(x, dummy) { (x)->ticks = clock() ; }
  60. #define DIFF_T(a,b) (1+ 1000000*(a.ticks - b.ticks) / CLOCKS_PER_SEC )
  61. #else /* typically, unix systems */
  62. #include <sys/time.h>
  63. #define DIFF_T(a,b) \
  64. (1+ 1000000*(a.tv_sec - b.tv_sec) + (a.tv_usec - b.tv_usec) )
  65. #endif
  66. #define TICK(t) \
  67. {struct timeval x ; \
  68. gettimeofday(&x, NULL) ; \
  69. t = x.tv_usec + 1000000* (x.tv_sec & 0xff ) ; \
  70. }
  71. #define TOCK(t) \
  72. { unsigned long t1 ; TICK(t1) ; \
  73. if (t1 < t) t = 256000000 + t1 - t ; \
  74. else t = t1 - t ; \
  75. if (t == 0) t = 1 ;}
  76. unsigned long ticks[10]; /* vars for timekeeping */
  77. #else
  78. #define DEB(x)
  79. #define DDB(x)
  80. #define TICK(x)
  81. #define TOCK(x)
  82. #endif /* TEST */
  83. /*
  84. * You should not need to change anything beyond this point.
  85. * The first part of the file implements linear algebra in GF.
  86. *
  87. * gf is the type used to store an element of the Galois Field.
  88. * Must constain at least GF_BITS bits.
  89. *
  90. * Note: unsigned char will work up to GF(256) but int seems to run
  91. * faster on the Pentium. We use int whenever have to deal with an
  92. * index, since they are generally faster.
  93. */
  94. #if (GF_BITS < 2 && GF_BITS >16)
  95. #error "GF_BITS must be 2 .. 16"
  96. #endif
  97. #if (GF_BITS <= 8)
  98. typedef unsigned char gf;
  99. #else
  100. typedef unsigned short gf;
  101. #endif
  102. #define GF_SIZE ((1 << GF_BITS) - 1) /* powers of \alpha */
  103. /*
  104. * Primitive polynomials - see Lin & Costello, Appendix A,
  105. * and Lee & Messerschmitt, p. 453.
  106. */
  107. static const char *allPp[] = { /* GF_BITS polynomial */
  108. NULL, /* 0 no code */
  109. NULL, /* 1 no code */
  110. "111", /* 2 1+x+x^2 */
  111. "1101", /* 3 1+x+x^3 */
  112. "11001", /* 4 1+x+x^4 */
  113. "101001", /* 5 1+x^2+x^5 */
  114. "1100001", /* 6 1+x+x^6 */
  115. "10010001", /* 7 1 + x^3 + x^7 */
  116. "101110001", /* 8 1+x^2+x^3+x^4+x^8 */
  117. "1000100001", /* 9 1+x^4+x^9 */
  118. "10010000001", /* 10 1+x^3+x^10 */
  119. "101000000001", /* 11 1+x^2+x^11 */
  120. "1100101000001", /* 12 1+x+x^4+x^6+x^12 */
  121. "11011000000001", /* 13 1+x+x^3+x^4+x^13 */
  122. "110000100010001", /* 14 1+x+x^6+x^10+x^14 */
  123. "1100000000000001", /* 15 1+x+x^15 */
  124. "11010000000010001" /* 16 1+x+x^3+x^12+x^16 */
  125. };
  126. /*
  127. * To speed up computations, we have tables for logarithm, exponent
  128. * and inverse of a number. If GF_BITS <= 8, we use a table for
  129. * multiplication as well (it takes 64K, no big deal even on a PDA,
  130. * especially because it can be pre-initialized an put into a ROM!),
  131. * otherwhise we use a table of logarithms.
  132. * In any case the macro gf_mul(x,y) takes care of multiplications.
  133. */
  134. static gf gf_exp[2*GF_SIZE]; /* index->poly form conversion table */
  135. static int gf_log[GF_SIZE + 1]; /* Poly->index form conversion table */
  136. static gf inverse[GF_SIZE+1]; /* inverse of field elem. */
  137. /* inv[\alpha**i]=\alpha**(GF_SIZE-i-1) */
  138. /*
  139. * modnn(x) computes x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1,
  140. * without a slow divide.
  141. */
  142. static inline gf
  143. modnn(int x)
  144. {
  145. while (x >= GF_SIZE) {
  146. x -= GF_SIZE;
  147. x = (x >> GF_BITS) + (x & GF_SIZE);
  148. }
  149. return x;
  150. }
  151. #define SWAP(a,b,t) {t tmp; tmp=a; a=b; b=tmp;}
  152. /*
  153. * gf_mul(x,y) multiplies two numbers. If GF_BITS<=8, it is much
  154. * faster to use a multiplication table.
  155. *
  156. * USE_GF_MULC, GF_MULC0(c) and GF_ADDMULC(x) can be used when multiplying
  157. * many numbers by the same constant. In this case the first
  158. * call sets the constant, and others perform the multiplications.
  159. * A value related to the multiplication is held in a local variable
  160. * declared with USE_GF_MULC . See usage in addmul1().
  161. */
  162. #if (GF_BITS <= 8)
  163. static gf gf_mul_table[GF_SIZE + 1][GF_SIZE + 1];
  164. #define gf_mul(x,y) gf_mul_table[x][y]
  165. #define USE_GF_MULC register gf * __gf_mulc_
  166. #define GF_MULC0(c) __gf_mulc_ = gf_mul_table[c]
  167. #define GF_ADDMULC(dst, x) dst ^= __gf_mulc_[x]
  168. static void
  169. init_mul_table(void)
  170. {
  171. int i, j;
  172. for (i=0; i< GF_SIZE+1; i++)
  173. for (j=0; j< GF_SIZE+1; j++)
  174. gf_mul_table[i][j] = gf_exp[modnn(gf_log[i] + gf_log[j]) ] ;
  175. for (j=0; j< GF_SIZE+1; j++)
  176. gf_mul_table[0][j] = gf_mul_table[j][0] = 0;
  177. }
  178. #else /* GF_BITS > 8 */
  179. static inline gf
  180. gf_mul(x,y)
  181. {
  182. if ( (x) == 0 || (y)==0 ) return 0;
  183. return gf_exp[gf_log[x] + gf_log[y] ] ;
  184. }
  185. #define init_mul_table()
  186. #define USE_GF_MULC register gf * __gf_mulc_
  187. #define GF_MULC0(c) __gf_mulc_ = &gf_exp[ gf_log[c] ]
  188. #define GF_ADDMULC(dst, x) { if (x) dst ^= __gf_mulc_[ gf_log[x] ] ; }
  189. #endif
  190. /*
  191. * Generate GF(2**m) from the irreducible polynomial p(X) in p[0]..p[m]
  192. * Lookup tables:
  193. * index->polynomial form gf_exp[] contains j= \alpha^i;
  194. * polynomial form -> index form gf_log[ j = \alpha^i ] = i
  195. * \alpha=x is the primitive element of GF(2^m)
  196. *
  197. * For efficiency, gf_exp[] has size 2*GF_SIZE, so that a simple
  198. * multiplication of two numbers can be resolved without calling modnn
  199. */
  200. /*
  201. * i use malloc so many times, it is easier to put checks all in
  202. * one place.
  203. */
  204. static void *
  205. my_malloc(int sz, const char *err_string)
  206. {
  207. void *p = malloc( sz );
  208. if (p == NULL) {
  209. fprintf(stderr, "-- malloc failure allocating %s\n", err_string);
  210. exit(1) ;
  211. }
  212. return p ;
  213. }
  214. #define NEW_GF_MATRIX(rows, cols) \
  215. (gf *)my_malloc(rows * cols * sizeof(gf), " ## __LINE__ ## " )
  216. /*
  217. * initialize the data structures used for computations in GF.
  218. */
  219. static void
  220. generate_gf(void)
  221. {
  222. int i;
  223. gf mask;
  224. const char *Pp = allPp[GF_BITS] ;
  225. mask = 1; /* x ** 0 = 1 */
  226. gf_exp[GF_BITS] = 0; /* will be updated at the end of the 1st loop */
  227. /*
  228. * first, generate the (polynomial representation of) powers of \alpha,
  229. * which are stored in gf_exp[i] = \alpha ** i .
  230. * At the same time build gf_log[gf_exp[i]] = i .
  231. * The first GF_BITS powers are simply bits shifted to the left.
  232. */
  233. for (i = 0; i < GF_BITS; i++, mask <<= 1 ) {
  234. gf_exp[i] = mask;
  235. gf_log[gf_exp[i]] = i;
  236. /*
  237. * If Pp[i] == 1 then \alpha ** i occurs in poly-repr
  238. * gf_exp[GF_BITS] = \alpha ** GF_BITS
  239. */
  240. if ( Pp[i] == '1' )
  241. gf_exp[GF_BITS] ^= mask;
  242. }
  243. /*
  244. * now gf_exp[GF_BITS] = \alpha ** GF_BITS is complete, so can als
  245. * compute its inverse.
  246. */
  247. gf_log[gf_exp[GF_BITS]] = GF_BITS;
  248. /*
  249. * Poly-repr of \alpha ** (i+1) is given by poly-repr of
  250. * \alpha ** i shifted left one-bit and accounting for any
  251. * \alpha ** GF_BITS term that may occur when poly-repr of
  252. * \alpha ** i is shifted.
  253. */
  254. mask = 1 << (GF_BITS - 1 ) ;
  255. for (i = GF_BITS + 1; i < GF_SIZE; i++) {
  256. if (gf_exp[i - 1] >= mask)
  257. gf_exp[i] = gf_exp[GF_BITS] ^ ((gf_exp[i - 1] ^ mask) << 1);
  258. else
  259. gf_exp[i] = gf_exp[i - 1] << 1;
  260. gf_log[gf_exp[i]] = i;
  261. }
  262. /*
  263. * log(0) is not defined, so use a special value
  264. */
  265. gf_log[0] = GF_SIZE ;
  266. /* set the extended gf_exp values for fast multiply */
  267. for (i = 0 ; i < GF_SIZE ; i++)
  268. gf_exp[i + GF_SIZE] = gf_exp[i] ;
  269. /*
  270. * again special cases. 0 has no inverse. This used to
  271. * be initialized to GF_SIZE, but it should make no difference
  272. * since noone is supposed to read from here.
  273. */
  274. inverse[0] = 0 ;
  275. inverse[1] = 1;
  276. for (i=2; i<=GF_SIZE; i++)
  277. inverse[i] = gf_exp[GF_SIZE-gf_log[i]];
  278. }
  279. /*
  280. * Various linear algebra operations that i use often.
  281. */
  282. /*
  283. * addmul() computes dst[] = dst[] + c * src[]
  284. * This is used often, so better optimize it! Currently the loop is
  285. * unrolled 16 times, a good value for 486 and pentium-class machines.
  286. * The case c=0 is also optimized, whereas c=1 is not. These
  287. * calls are unfrequent in my typical apps so I did not bother.
  288. *
  289. * Note that gcc on
  290. */
  291. #define addmul(dst, src, c, sz) \
  292. if (c != 0) addmul1(dst, src, c, sz)
  293. #define UNROLL 16 /* 1, 4, 8, 16 */
  294. static void
  295. addmul1(gf *dst1, gf *src1, gf c, int sz)
  296. {
  297. USE_GF_MULC ;
  298. register gf *dst = dst1, *src = src1 ;
  299. gf *lim = &dst[sz - UNROLL + 1] ;
  300. GF_MULC0(c) ;
  301. #if (UNROLL > 1) /* unrolling by 8/16 is quite effective on the pentium */
  302. for (; dst < lim ; dst += UNROLL, src += UNROLL ) {
  303. GF_ADDMULC( dst[0] , src[0] );
  304. GF_ADDMULC( dst[1] , src[1] );
  305. GF_ADDMULC( dst[2] , src[2] );
  306. GF_ADDMULC( dst[3] , src[3] );
  307. #if (UNROLL > 4)
  308. GF_ADDMULC( dst[4] , src[4] );
  309. GF_ADDMULC( dst[5] , src[5] );
  310. GF_ADDMULC( dst[6] , src[6] );
  311. GF_ADDMULC( dst[7] , src[7] );
  312. #endif
  313. #if (UNROLL > 8)
  314. GF_ADDMULC( dst[8] , src[8] );
  315. GF_ADDMULC( dst[9] , src[9] );
  316. GF_ADDMULC( dst[10] , src[10] );
  317. GF_ADDMULC( dst[11] , src[11] );
  318. GF_ADDMULC( dst[12] , src[12] );
  319. GF_ADDMULC( dst[13] , src[13] );
  320. GF_ADDMULC( dst[14] , src[14] );
  321. GF_ADDMULC( dst[15] , src[15] );
  322. #endif
  323. }
  324. #endif
  325. lim += UNROLL - 1 ;
  326. for (; dst < lim; dst++, src++ ) /* final components */
  327. GF_ADDMULC( *dst , *src );
  328. }
  329. /*
  330. * computes C = AB where A is n*k, B is k*m, C is n*m
  331. */
  332. static void
  333. matmul(gf *a, gf *b, gf *c, int n, int k, int m)
  334. {
  335. int row, col, i ;
  336. for (row = 0; row < n ; row++) {
  337. for (col = 0; col < m ; col++) {
  338. gf *pa = &a[ row * k ];
  339. gf *pb = &b[ col ];
  340. gf acc = 0 ;
  341. for (i = 0; i < k ; i++, pa++, pb += m )
  342. acc ^= gf_mul( *pa, *pb ) ;
  343. c[ row * m + col ] = acc ;
  344. }
  345. }
  346. }
  347. #ifdef DEBUG
  348. /*
  349. * returns 1 if the square matrix is identiy
  350. * (only for test)
  351. */
  352. static int
  353. is_identity(gf *m, int k)
  354. {
  355. int row, col ;
  356. for (row=0; row<k; row++)
  357. for (col=0; col<k; col++)
  358. if ( (row==col && *m != 1) ||
  359. (row!=col && *m != 0) )
  360. return 0 ;
  361. else
  362. m++ ;
  363. return 1 ;
  364. }
  365. #endif /* debug */
  366. /*
  367. * invert_mat() takes a matrix and produces its inverse
  368. * k is the size of the matrix.
  369. * (Gauss-Jordan, adapted from Numerical Recipes in C)
  370. * Return non-zero if singular.
  371. */
  372. DEB( int pivloops=0; int pivswaps=0 ; /* diagnostic */)
  373. static int
  374. invert_mat(gf *src, int k)
  375. {
  376. gf c, *p ;
  377. int irow, icol, row, col, i, ix ;
  378. int error = 1 ;
  379. int *indxc = my_malloc(k*sizeof(int), "indxc");
  380. int *indxr = my_malloc(k*sizeof(int), "indxr");
  381. int *ipiv = my_malloc(k*sizeof(int), "ipiv");
  382. gf *id_row = NEW_GF_MATRIX(1, k);
  383. gf *temp_row = NEW_GF_MATRIX(1, k);
  384. memset(id_row, '\0', k*sizeof(gf));
  385. DEB( pivloops=0; pivswaps=0 ; /* diagnostic */ )
  386. /*
  387. * ipiv marks elements already used as pivots.
  388. */
  389. for (i = 0; i < k ; i++)
  390. ipiv[i] = 0 ;
  391. for (col = 0; col < k ; col++) {
  392. gf *pivot_row ;
  393. /*
  394. * Zeroing column 'col', look for a non-zero element.
  395. * First try on the diagonal, if it fails, look elsewhere.
  396. */
  397. irow = icol = -1 ;
  398. if (ipiv[col] != 1 && src[col*k + col] != 0) {
  399. irow = col ;
  400. icol = col ;
  401. goto found_piv ;
  402. }
  403. for (row = 0 ; row < k ; row++) {
  404. if (ipiv[row] != 1) {
  405. for (ix = 0 ; ix < k ; ix++) {
  406. DEB( pivloops++ ; )
  407. if (ipiv[ix] == 0) {
  408. if (src[row*k + ix] != 0) {
  409. irow = row ;
  410. icol = ix ;
  411. goto found_piv ;
  412. }
  413. } else if (ipiv[ix] > 1) {
  414. fprintf(stderr, "singular matrix\n");
  415. goto fail ;
  416. }
  417. }
  418. }
  419. }
  420. if (icol == -1) {
  421. fprintf(stderr, "XXX pivot not found!\n");
  422. goto fail ;
  423. }
  424. found_piv:
  425. ++(ipiv[icol]) ;
  426. /*
  427. * swap rows irow and icol, so afterwards the diagonal
  428. * element will be correct. Rarely done, not worth
  429. * optimizing.
  430. */
  431. if (irow != icol) {
  432. for (ix = 0 ; ix < k ; ix++ ) {
  433. SWAP( src[irow*k + ix], src[icol*k + ix], gf) ;
  434. }
  435. }
  436. indxr[col] = irow ;
  437. indxc[col] = icol ;
  438. pivot_row = &src[icol*k] ;
  439. c = pivot_row[icol] ;
  440. if (c == 0) {
  441. fprintf(stderr, "singular matrix 2\n");
  442. goto fail ;
  443. }
  444. if (c != 1 ) { /* otherwhise this is a NOP */
  445. /*
  446. * this is done often , but optimizing is not so
  447. * fruitful, at least in the obvious ways (unrolling)
  448. */
  449. DEB( pivswaps++ ; )
  450. c = inverse[ c ] ;
  451. pivot_row[icol] = 1 ;
  452. for (ix = 0 ; ix < k ; ix++ )
  453. pivot_row[ix] = gf_mul(c, pivot_row[ix] );
  454. }
  455. /*
  456. * from all rows, remove multiples of the selected row
  457. * to zero the relevant entry (in fact, the entry is not zero
  458. * because we know it must be zero).
  459. * (Here, if we know that the pivot_row is the identity,
  460. * we can optimize the addmul).
  461. */
  462. id_row[icol] = 1;
  463. if (memcmp(pivot_row, id_row, k*sizeof(gf)) != 0) {
  464. for (p = src, ix = 0 ; ix < k ; ix++, p += k ) {
  465. if (ix != icol) {
  466. c = p[icol] ;
  467. p[icol] = 0 ;
  468. addmul(p, pivot_row, c, k );
  469. }
  470. }
  471. }
  472. id_row[icol] = 0;
  473. } /* done all columns */
  474. for (col = k-1 ; col >= 0 ; col-- ) {
  475. if (indxr[col] <0 || indxr[col] >= k)
  476. fprintf(stderr, "AARGH, indxr[col] %d\n", indxr[col]);
  477. else if (indxc[col] <0 || indxc[col] >= k)
  478. fprintf(stderr, "AARGH, indxc[col] %d\n", indxc[col]);
  479. else
  480. if (indxr[col] != indxc[col] ) {
  481. for (row = 0 ; row < k ; row++ ) {
  482. SWAP( src[row*k + indxr[col]], src[row*k + indxc[col]], gf) ;
  483. }
  484. }
  485. }
  486. error = 0 ;
  487. fail:
  488. free(indxc);
  489. free(indxr);
  490. free(ipiv);
  491. free(id_row);
  492. free(temp_row);
  493. return error ;
  494. }
  495. /*
  496. * fast code for inverting a vandermonde matrix.
  497. * XXX NOTE: It assumes that the matrix
  498. * is not singular and _IS_ a vandermonde matrix. Only uses
  499. * the second column of the matrix, containing the p_i's.
  500. *
  501. * Algorithm borrowed from "Numerical recipes in C" -- sec.2.8, but
  502. * largely revised for my purposes.
  503. * p = coefficients of the matrix (p_i)
  504. * q = values of the polynomial (known)
  505. */
  506. static int
  507. invert_vdm(gf *src, int k)
  508. {
  509. int i, j, row, col ;
  510. gf *b, *c, *p;
  511. gf t, xx ;
  512. if (k == 1) /* degenerate case, matrix must be p^0 = 1 */
  513. return 0 ;
  514. /*
  515. * c holds the coefficient of P(x) = Prod (x - p_i), i=0..k-1
  516. * b holds the coefficient for the matrix inversion
  517. */
  518. c = NEW_GF_MATRIX(1, k);
  519. b = NEW_GF_MATRIX(1, k);
  520. p = NEW_GF_MATRIX(1, k);
  521. for ( j=1, i = 0 ; i < k ; i++, j+=k ) {
  522. c[i] = 0 ;
  523. p[i] = src[j] ; /* p[i] */
  524. }
  525. /*
  526. * construct coeffs. recursively. We know c[k] = 1 (implicit)
  527. * and start P_0 = x - p_0, then at each stage multiply by
  528. * x - p_i generating P_i = x P_{i-1} - p_i P_{i-1}
  529. * After k steps we are done.
  530. */
  531. c[k-1] = p[0] ; /* really -p(0), but x = -x in GF(2^m) */
  532. for (i = 1 ; i < k ; i++ ) {
  533. gf p_i = p[i] ; /* see above comment */
  534. for (j = k-1 - ( i - 1 ) ; j < k-1 ; j++ )
  535. c[j] ^= gf_mul( p_i, c[j+1] ) ;
  536. c[k-1] ^= p_i ;
  537. }
  538. for (row = 0 ; row < k ; row++ ) {
  539. /*
  540. * synthetic division etc.
  541. */
  542. xx = p[row] ;
  543. t = 1 ;
  544. b[k-1] = 1 ; /* this is in fact c[k] */
  545. for (i = k-2 ; i >= 0 ; i-- ) {
  546. b[i] = c[i+1] ^ gf_mul(xx, b[i+1]) ;
  547. t = gf_mul(xx, t) ^ b[i] ;
  548. }
  549. for (col = 0 ; col < k ; col++ )
  550. src[col*k + row] = gf_mul(inverse[t], b[col] );
  551. }
  552. free(c) ;
  553. free(b) ;
  554. free(p) ;
  555. return 0 ;
  556. }
  557. static int fec_initialized = 0 ;
  558. static void
  559. init_fec(void)
  560. {
  561. TICK(ticks[0]);
  562. generate_gf();
  563. TOCK(ticks[0]);
  564. DDB(fprintf(stderr, "generate_gf took %ldus\n", ticks[0]);)
  565. TICK(ticks[0]);
  566. init_mul_table();
  567. TOCK(ticks[0]);
  568. DDB(fprintf(stderr, "init_mul_table took %ldus\n", ticks[0]);)
  569. fec_initialized = 1 ;
  570. }
  571. /*
  572. * This section contains the proper FEC encoding/decoding routines.
  573. * The encoding matrix is computed starting with a Vandermonde matrix,
  574. * and then transforming it into a systematic matrix.
  575. */
  576. #define FEC_MAGIC 0xFECC0DEC
  577. struct fec_parms {
  578. unsigned long magic ;
  579. int k, n ; /* parameters of the code */
  580. gf *enc_matrix ;
  581. } ;
  582. #define COMP_FEC_MAGIC(fec) \
  583. (((FEC_MAGIC ^ (fec)->k) ^ (fec)->n) ^ (unsigned long)((fec)->enc_matrix))
  584. void
  585. fec_free(struct fec_parms *p)
  586. {
  587. if (p==NULL || p->magic != COMP_FEC_MAGIC(p)) {
  588. fprintf(stderr, "bad parameters to fec_free\n");
  589. return ;
  590. }
  591. free(p->enc_matrix);
  592. free(p);
  593. }
  594. /*
  595. * create a new encoder, returning a descriptor. This contains k,n and
  596. * the encoding matrix.
  597. */
  598. struct fec_parms *
  599. fec_new(int k, int n)
  600. {
  601. int row, col ;
  602. gf *p, *tmp_m ;
  603. struct fec_parms *retval ;
  604. if (fec_initialized == 0)
  605. init_fec();
  606. if (k > GF_SIZE + 1 || n > GF_SIZE + 1 || k > n ) {
  607. fprintf(stderr, "Invalid parameters k %d n %d GF_SIZE %d\n",
  608. k, n, GF_SIZE );
  609. return NULL ;
  610. }
  611. retval = my_malloc(sizeof(struct fec_parms), "new_code");
  612. retval->k = k ;
  613. retval->n = n ;
  614. retval->enc_matrix = NEW_GF_MATRIX(n, k);
  615. retval->magic = COMP_FEC_MAGIC(retval);
  616. tmp_m = NEW_GF_MATRIX(n, k);
  617. /*
  618. * fill the matrix with powers of field elements, starting from 0.
  619. * The first row is special, cannot be computed with exp. table.
  620. */
  621. tmp_m[0] = 1 ;
  622. for (col = 1; col < k ; col++)
  623. tmp_m[col] = 0 ;
  624. for (p = tmp_m + k, row = 0; row < n-1 ; row++, p += k) {
  625. for ( col = 0 ; col < k ; col ++ )
  626. p[col] = gf_exp[modnn(row*col)];
  627. }
  628. /*
  629. * quick code to build systematic matrix: invert the top
  630. * k*k vandermonde matrix, multiply right the bottom n-k rows
  631. * by the inverse, and construct the identity matrix at the top.
  632. */
  633. TICK(ticks[3]);
  634. invert_vdm(tmp_m, k); /* much faster than invert_mat */
  635. matmul(tmp_m + k*k, tmp_m, retval->enc_matrix + k*k, n - k, k, k);
  636. /*
  637. * the upper matrix is I so do not bother with a slow multiply
  638. */
  639. memset(retval->enc_matrix, '\0', k*k*sizeof(gf) );
  640. for (p = retval->enc_matrix, col = 0 ; col < k ; col++, p += k+1 )
  641. *p = 1 ;
  642. free(tmp_m);
  643. TOCK(ticks[3]);
  644. DDB(fprintf(stderr, "--- %ld us to build encoding matrix\n",
  645. ticks[3]);)
  646. DEB(pr_matrix(retval->enc_matrix, n, k, "encoding_matrix");)
  647. return retval ;
  648. }
  649. /*
  650. * fec_encode accepts as input pointers to n data packets of size sz,
  651. * and produces as output a packet pointed to by fec, computed
  652. * with index "index".
  653. */
  654. void
  655. fec_encode(struct fec_parms *code, gf *src[], gf *fec, int index, int sz)
  656. {
  657. int i, k = code->k ;
  658. gf *p ;
  659. if (GF_BITS > 8)
  660. sz /= 2 ;
  661. if (index < k)
  662. memcpy(fec, src[index], sz*sizeof(gf) ) ;
  663. else if (index < code->n) {
  664. p = &(code->enc_matrix[index*k] );
  665. memset(fec, '\0', sz*sizeof(gf));
  666. for (i = 0; i < k ; i++)
  667. addmul(fec, src[i], p[i], sz ) ;
  668. } else
  669. fprintf(stderr, "Invalid index %d (max %d)\n",
  670. index, code->n - 1 );
  671. }
  672. void fec_encode_linear(struct fec_parms *code, gf *src, gf *fec, int index, int sz)
  673. {
  674. int i, k = code->k ;
  675. gf *p ;
  676. if (GF_BITS > 8)
  677. sz /= 2 ;
  678. if (index < k)
  679. memcpy(fec, src + (index * sz), sz*sizeof(gf) ) ;
  680. else if (index < code->n) {
  681. p = &(code->enc_matrix[index*k] );
  682. memset(fec, '\0', sz*sizeof(gf));
  683. for (i = 0; i < k ; i++)
  684. addmul(fec, src + (i * sz), p[i], sz ) ;
  685. } else
  686. fprintf(stderr, "Invalid index %d (max %d)\n",
  687. index, code->n - 1 );
  688. }
  689. /*
  690. * shuffle move src packets in their position
  691. */
  692. static int
  693. shuffle(gf *pkt[], int index[], int k)
  694. {
  695. int i;
  696. for ( i = 0 ; i < k ; ) {
  697. if (index[i] >= k || index[i] == i)
  698. i++ ;
  699. else {
  700. /*
  701. * put pkt in the right position (first check for conflicts).
  702. */
  703. int c = index[i] ;
  704. if (index[c] == c) {
  705. DEB(fprintf(stderr, "\nshuffle, error at %d\n", i);)
  706. return 1 ;
  707. }
  708. SWAP(index[i], index[c], int) ;
  709. SWAP(pkt[i], pkt[c], gf *) ;
  710. }
  711. }
  712. DEB( /* just test that it works... */
  713. for ( i = 0 ; i < k ; i++ ) {
  714. if (index[i] < k && index[i] != i) {
  715. fprintf(stderr, "shuffle: after\n");
  716. for (i=0; i<k ; i++) fprintf(stderr, "%3d ", index[i]);
  717. fprintf(stderr, "\n");
  718. return 1 ;
  719. }
  720. }
  721. )
  722. return 0 ;
  723. }
  724. /*
  725. * build_decode_matrix constructs the encoding matrix given the
  726. * indexes. The matrix must be already allocated as
  727. * a vector of k*k elements, in row-major order
  728. */
  729. static gf *
  730. build_decode_matrix(struct fec_parms *code, int index[])
  731. {
  732. int i , k = code->k ;
  733. gf *p, *matrix = NEW_GF_MATRIX(k, k);
  734. TICK(ticks[9]);
  735. for (i = 0, p = matrix ; i < k ; i++, p += k ) {
  736. #if 1 /* this is simply an optimization, not very useful indeed */
  737. if (index[i] < k) {
  738. memset(p, '\0', k*sizeof(gf) );
  739. p[i] = 1 ;
  740. } else
  741. #endif
  742. if (index[i] < code->n )
  743. memcpy(p, &(code->enc_matrix[index[i]*k]), k*sizeof(gf) );
  744. else {
  745. fprintf(stderr, "decode: invalid index %d (max %d)\n",
  746. index[i], code->n - 1 );
  747. free(matrix) ;
  748. return NULL ;
  749. }
  750. }
  751. TICK(ticks[9]);
  752. if (invert_mat(matrix, k)) {
  753. free(matrix);
  754. matrix = NULL ;
  755. }
  756. TOCK(ticks[9]);
  757. return matrix ;
  758. }
  759. /*
  760. * fec_decode receives as input a vector of packets, the indexes of
  761. * packets, and produces the correct vector as output.
  762. *
  763. * Input:
  764. * code: pointer to code descriptor
  765. * pkt: pointers to received packets. They are modified
  766. * to store the output packets (in place)
  767. * index: pointer to packet indexes (modified)
  768. * sz: size of each packet
  769. */
  770. int
  771. fec_decode(struct fec_parms *code, gf *pkt[], int index[], int sz)
  772. {
  773. gf *m_dec ;
  774. gf **new_pkt ;
  775. int row, col , k = code->k ;
  776. if (GF_BITS > 8)
  777. sz /= 2 ;
  778. if (shuffle(pkt, index, k)) /* error if true */
  779. return 1 ;
  780. m_dec = build_decode_matrix(code, index);
  781. if (m_dec == NULL)
  782. return 1 ; /* error */
  783. /*
  784. * do the actual decoding
  785. */
  786. new_pkt = my_malloc (k * sizeof (gf * ), "new pkt pointers" );
  787. for (row = 0 ; row < k ; row++ ) {
  788. if (index[row] >= k) {
  789. new_pkt[row] = my_malloc (sz * sizeof (gf), "new pkt buffer" );
  790. memset(new_pkt[row], '\0', sz * sizeof(gf) ) ;
  791. for (col = 0 ; col < k ; col++ )
  792. addmul(new_pkt[row], pkt[col], m_dec[row*k + col], sz) ;
  793. }
  794. }
  795. /*
  796. * move pkts to their final destination
  797. */
  798. for (row = 0 ; row < k ; row++ ) {
  799. if (index[row] >= k) {
  800. memcpy(pkt[row], new_pkt[row], sz*sizeof(gf));
  801. free(new_pkt[row]);
  802. }
  803. }
  804. free(new_pkt);
  805. free(m_dec);
  806. return 0;
  807. }
  808. /*********** end of FEC code -- beginning of test code ************/
  809. #if (TEST || DEBUG)
  810. void
  811. test_gf(void)
  812. {
  813. int i ;
  814. /*
  815. * test gf tables. Sufficiently tested...
  816. */
  817. for (i=0; i<= GF_SIZE; i++) {
  818. if (gf_exp[gf_log[i]] != i)
  819. fprintf(stderr, "bad exp/log i %d log %d exp(log) %d\n",
  820. i, gf_log[i], gf_exp[gf_log[i]]);
  821. if (i != 0 && gf_mul(i, inverse[i]) != 1)
  822. fprintf(stderr, "bad mul/inv i %d inv %d i*inv(i) %d\n",
  823. i, inverse[i], gf_mul(i, inverse[i]) );
  824. if (gf_mul(0,i) != 0)
  825. fprintf(stderr, "bad mul table 0,%d\n",i);
  826. if (gf_mul(i,0) != 0)
  827. fprintf(stderr, "bad mul table %d,0\n",i);
  828. }
  829. }
  830. #endif /* TEST */