2 * zfec -- fast forward error correction library with Python interface
13 * Primitive polynomials - see Lin & Costello, Appendix A,
14 * and Lee & Messerschmitt, p. 453.
16 static const char*const Pp="101110001";
20 * To speed up computations, we have tables for logarithm, exponent and
21 * inverse of a number. We use a table for multiplication as well (it takes
22 * 64K, no big deal even on a PDA, especially because it can be
23 * pre-initialized an put into a ROM!), otherwhise we use a table of
24 * logarithms. In any case the macro gf_mul(x,y) takes care of
28 static gf gf_exp[510]; /* index->poly form conversion table */
29 static int gf_log[256]; /* Poly->index form conversion table */
30 static gf inverse[256]; /* inverse of field elem. */
31 /* inv[\alpha**i]=\alpha**(GF_SIZE-i-1) */
34 * modnn(x) computes x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1,
35 * without a slow divide.
41 x = (x >> 8) + (x & 255);
46 #define SWAP(a,b,t) {t tmp; tmp=a; a=b; b=tmp;}
49 * gf_mul(x,y) multiplies two numbers. It is much faster to use a
50 * multiplication table.
52 * USE_GF_MULC, GF_MULC0(c) and GF_ADDMULC(x) can be used when multiplying
53 * many numbers by the same constant. In this case the first call sets the
54 * constant, and others perform the multiplications. A value related to the
55 * multiplication is held in a local variable declared with USE_GF_MULC . See
56 * usage in _addmul1().
58 static gf gf_mul_table[256][256];
60 #define gf_mul(x,y) gf_mul_table[x][y]
62 #define USE_GF_MULC register gf * __gf_mulc_
64 #define GF_MULC0(c) __gf_mulc_ = gf_mul_table[c]
65 #define GF_ADDMULC(dst, x) dst ^= __gf_mulc_[x]
68 * Generate GF(2**m) from the irreducible polynomial p(X) in p[0]..p[m]
70 * index->polynomial form gf_exp[] contains j= \alpha^i;
71 * polynomial form -> index form gf_log[ j = \alpha^i ] = i
72 * \alpha=x is the primitive element of GF(2^m)
74 * For efficiency, gf_exp[] has size 2*GF_SIZE, so that a simple
75 * multiplication of two numbers can be resolved without calling modnn
78 _init_mul_table(void) {
80 for (i = 0; i < 256; i++)
81 for (j = 0; j < 256; j++)
82 gf_mul_table[i][j] = gf_exp[modnn (gf_log[i] + gf_log[j])];
84 for (j = 0; j < 256; j++)
85 gf_mul_table[0][j] = gf_mul_table[j][0] = 0;
88 #define NEW_GF_MATRIX(rows, cols) \
89 (gf*)malloc(rows * cols)
92 * initialize the data structures used for computations in GF.
99 mask = 1; /* x ** 0 = 1 */
100 gf_exp[8] = 0; /* will be updated at the end of the 1st loop */
102 * first, generate the (polynomial representation of) powers of \alpha,
103 * which are stored in gf_exp[i] = \alpha ** i .
104 * At the same time build gf_log[gf_exp[i]] = i .
105 * The first 8 powers are simply bits shifted to the left.
107 for (i = 0; i < 8; i++, mask <<= 1) {
109 gf_log[gf_exp[i]] = i;
111 * If Pp[i] == 1 then \alpha ** i occurs in poly-repr
112 * gf_exp[8] = \alpha ** 8
118 * now gf_exp[8] = \alpha ** 8 is complete, so can also
119 * compute its inverse.
121 gf_log[gf_exp[8]] = 8;
123 * Poly-repr of \alpha ** (i+1) is given by poly-repr of
124 * \alpha ** i shifted left one-bit and accounting for any
125 * \alpha ** 8 term that may occur when poly-repr of
126 * \alpha ** i is shifted.
129 for (i = 9; i < 255; i++) {
130 if (gf_exp[i - 1] >= mask)
131 gf_exp[i] = gf_exp[8] ^ ((gf_exp[i - 1] ^ mask) << 1);
133 gf_exp[i] = gf_exp[i - 1] << 1;
134 gf_log[gf_exp[i]] = i;
137 * log(0) is not defined, so use a special value
140 /* set the extended gf_exp values for fast multiply */
141 for (i = 0; i < 255; i++)
142 gf_exp[i + 255] = gf_exp[i];
145 * again special cases. 0 has no inverse. This used to
146 * be initialized to 255, but it should make no difference
147 * since noone is supposed to read from here.
151 for (i = 2; i <= 255; i++)
152 inverse[i] = gf_exp[255 - gf_log[i]];
156 * Various linear algebra operations that i use often.
160 * addmul() computes dst[] = dst[] + c * src[]
161 * This is used often, so better optimize it! Currently the loop is
162 * unrolled 16 times, a good value for 486 and pentium-class machines.
163 * The case c=0 is also optimized, whereas c=1 is not. These
164 * calls are unfrequent in my typical apps so I did not bother.
166 #define addmul(dst, src, c, sz) \
167 if (c != 0) _addmul1(dst, src, c, sz)
169 #define UNROLL 16 /* 1, 4, 8, 16 */
171 _addmul1(register gf*restrict dst, const register gf*restrict src, gf c, size_t sz) {
173 const gf* lim = &dst[sz - UNROLL + 1];
177 #if (UNROLL > 1) /* unrolling by 8/16 is quite effective on the pentium */
178 for (; dst < lim; dst += UNROLL, src += UNROLL) {
179 GF_ADDMULC (dst[0], src[0]);
180 GF_ADDMULC (dst[1], src[1]);
181 GF_ADDMULC (dst[2], src[2]);
182 GF_ADDMULC (dst[3], src[3]);
184 GF_ADDMULC (dst[4], src[4]);
185 GF_ADDMULC (dst[5], src[5]);
186 GF_ADDMULC (dst[6], src[6]);
187 GF_ADDMULC (dst[7], src[7]);
190 GF_ADDMULC (dst[8], src[8]);
191 GF_ADDMULC (dst[9], src[9]);
192 GF_ADDMULC (dst[10], src[10]);
193 GF_ADDMULC (dst[11], src[11]);
194 GF_ADDMULC (dst[12], src[12]);
195 GF_ADDMULC (dst[13], src[13]);
196 GF_ADDMULC (dst[14], src[14]);
197 GF_ADDMULC (dst[15], src[15]);
202 for (; dst < lim; dst++, src++) /* final components */
203 GF_ADDMULC (*dst, *src);
207 * computes C = AB where A is n*k, B is k*m, C is n*m
210 _matmul(gf * a, gf * b, gf * c, unsigned n, unsigned k, unsigned m) {
211 unsigned row, col, i;
213 for (row = 0; row < n; row++) {
214 for (col = 0; col < m; col++) {
215 gf *pa = &a[row * k];
218 for (i = 0; i < k; i++, pa++, pb += m)
219 acc ^= gf_mul (*pa, *pb);
220 c[row * m + col] = acc;
226 * _invert_mat() takes a matrix and produces its inverse
227 * k is the size of the matrix.
228 * (Gauss-Jordan, adapted from Numerical Recipes in C)
229 * Return non-zero if singular.
232 _invert_mat(gf* src, size_t k) {
237 unsigned* indxc = (unsigned*) malloc (k * sizeof(unsigned));
238 unsigned* indxr = (unsigned*) malloc (k * sizeof(unsigned));
239 unsigned* ipiv = (unsigned*) malloc (k * sizeof(unsigned));
240 gf *id_row = NEW_GF_MATRIX (1, k);
242 memset (id_row, '\0', k * sizeof (gf));
244 * ipiv marks elements already used as pivots.
246 for (size_t i = 0; i < k; i++)
249 for (size_t col = 0; col < k; col++) {
252 * Zeroing column 'col', look for a non-zero element.
253 * First try on the diagonal, if it fails, look elsewhere.
255 if (ipiv[col] != 1 && src[col * k + col] != 0) {
260 for (size_t row = 0; row < k; row++) {
261 if (ipiv[row] != 1) {
262 for (size_t ix = 0; ix < k; ix++) {
264 if (src[row * k + ix] != 0) {
270 assert (ipiv[ix] <= 1);
277 * swap rows irow and icol, so afterwards the diagonal
278 * element will be correct. Rarely done, not worth
282 for (size_t ix = 0; ix < k; ix++)
283 SWAP (src[irow * k + ix], src[icol * k + ix], gf);
286 pivot_row = &src[icol * k];
289 if (c != 1) { /* otherwhise this is a NOP */
291 * this is done often , but optimizing is not so
292 * fruitful, at least in the obvious ways (unrolling)
296 for (size_t ix = 0; ix < k; ix++)
297 pivot_row[ix] = gf_mul (c, pivot_row[ix]);
300 * from all rows, remove multiples of the selected row
301 * to zero the relevant entry (in fact, the entry is not zero
302 * because we know it must be zero).
303 * (Here, if we know that the pivot_row is the identity,
304 * we can optimize the addmul).
307 if (memcmp (pivot_row, id_row, k * sizeof (gf)) != 0) {
309 for (size_t ix = 0; ix < k; ix++, p += k) {
313 addmul (p, pivot_row, c, k);
318 } /* done all columns */
319 for (size_t col = k; col > 0; col--)
320 if (indxr[col-1] != indxc[col-1])
321 for (size_t row = 0; row < k; row++)
322 SWAP (src[row * k + indxr[col-1]], src[row * k + indxc[col-1]], gf);
326 * fast code for inverting a vandermonde matrix.
328 * NOTE: It assumes that the matrix is not singular and _IS_ a vandermonde
329 * matrix. Only uses the second column of the matrix, containing the p_i's.
331 * Algorithm borrowed from "Numerical recipes in C" -- sec.2.8, but largely
332 * revised for my purposes.
333 * p = coefficients of the matrix (p_i)
334 * q = values of the polynomial (known)
337 _invert_vdm (gf* src, unsigned k) {
338 unsigned i, j, row, col;
342 if (k == 1) /* degenerate case, matrix must be p^0 = 1 */
345 * c holds the coefficient of P(x) = Prod (x - p_i), i=0..k-1
346 * b holds the coefficient for the matrix inversion
348 c = NEW_GF_MATRIX (1, k);
349 b = NEW_GF_MATRIX (1, k);
351 p = NEW_GF_MATRIX (1, k);
353 for (j = 1, i = 0; i < k; i++, j += k) {
355 p[i] = src[j]; /* p[i] */
358 * construct coeffs. recursively. We know c[k] = 1 (implicit)
359 * and start P_0 = x - p_0, then at each stage multiply by
360 * x - p_i generating P_i = x P_{i-1} - p_i P_{i-1}
361 * After k steps we are done.
363 c[k - 1] = p[0]; /* really -p(0), but x = -x in GF(2^m) */
364 for (i = 1; i < k; i++) {
365 gf p_i = p[i]; /* see above comment */
366 for (j = k - 1 - (i - 1); j < k - 1; j++)
367 c[j] ^= gf_mul (p_i, c[j + 1]);
371 for (row = 0; row < k; row++) {
373 * synthetic division etc.
377 b[k - 1] = 1; /* this is in fact c[k] */
378 for (i = k - 1; i > 0; i--) {
379 b[i-1] = c[i] ^ gf_mul (xx, b[i]);
380 t = gf_mul (xx, t) ^ b[i-1];
382 for (col = 0; col < k; col++)
383 src[col * k + row] = gf_mul (inverse[t], b[col]);
391 static int fec_initialized = 0;
400 * This section contains the proper FEC encoding/decoding routines.
401 * The encoding matrix is computed starting with a Vandermonde matrix,
402 * and then transforming it into a systematic matrix.
405 #define FEC_MAGIC 0xFECC0DEC
408 fec_free (fec_t *p) {
409 assert (p != NULL && p->magic == (((FEC_MAGIC ^ p->k) ^ p->n) ^ (unsigned long) (p->enc_matrix)));
410 free (p->enc_matrix);
415 fec_new(unsigned short k, unsigned short n) {
421 if (fec_initialized == 0)
424 retval = (fec_t *) malloc (sizeof (fec_t));
427 retval->enc_matrix = NEW_GF_MATRIX (n, k);
428 retval->magic = ((FEC_MAGIC ^ k) ^ n) ^ (unsigned long) (retval->enc_matrix);
429 tmp_m = NEW_GF_MATRIX (n, k);
431 * fill the matrix with powers of field elements, starting from 0.
432 * The first row is special, cannot be computed with exp. table.
435 for (col = 1; col < k; col++)
437 for (p = tmp_m + k, row = 0; row < n - 1; row++, p += k)
438 for (col = 0; col < k; col++)
439 p[col] = gf_exp[modnn (row * col)];
442 * quick code to build systematic matrix: invert the top
443 * k*k vandermonde matrix, multiply right the bottom n-k rows
444 * by the inverse, and construct the identity matrix at the top.
446 _invert_vdm (tmp_m, k); /* much faster than _invert_mat */
447 _matmul(tmp_m + k * k, tmp_m, retval->enc_matrix + k * k, n - k, k, k);
449 * the upper matrix is I so do not bother with a slow multiply
451 memset (retval->enc_matrix, '\0', k * k * sizeof (gf));
452 for (p = retval->enc_matrix, col = 0; col < k; col++, p += k + 1)
459 /* To make sure that we stay within cache in the inner loops of fec_encode(). (It would
460 probably help to also do this for fec_decode(). */
466 fec_encode(const fec_t* code, const gf*restrict const*restrict const src, gf*restrict const*restrict const fecs, const unsigned*restrict const block_nums, size_t num_block_nums, size_t sz) {
472 for (k = 0; k < sz; k += STRIDE) {
473 size_t stride = ((sz-k) < STRIDE)?(sz-k):STRIDE;
474 for (i=0; i<num_block_nums; i++) {
475 fecnum=block_nums[i];
476 assert (fecnum >= code->k);
477 memset(fecs[i]+k, 0, stride);
478 p = &(code->enc_matrix[fecnum * code->k]);
479 for (j = 0; j < code->k; j++)
480 addmul(fecs[i]+k, src[j]+k, p[j], stride);
486 * Build decode matrix into some memory space.
488 * @param matrix a space allocated for a k by k matrix
491 build_decode_matrix_into_space(const fec_t*restrict const code, const unsigned*const restrict index, const unsigned k, gf*restrict const matrix) {
494 for (i=0, p=matrix; i < k; i++, p += k) {
499 memcpy(p, &(code->enc_matrix[index[i] * code->k]), k);
502 _invert_mat (matrix, k);
506 fec_decode(const fec_t* code, const gf*restrict const*restrict const inpkts, gf*restrict const*restrict const outpkts, const unsigned*restrict const index, size_t sz) {
507 gf* m_dec = (gf*)alloca(code->k * code->k);
508 unsigned char outix=0;
511 build_decode_matrix_into_space(code, index, code->k, m_dec);
513 for (row=0; row<code->k; row++) {
514 assert ((index[row] >= code->k) || (index[row] == row)); /* If the block whose number is i is present, then it is required to be in the i'th element. */
515 if (index[row] >= code->k) {
516 memset(outpkts[outix], 0, sz);
517 for (col=0; col < code->k; col++)
518 addmul(outpkts[outix], inpkts[col], m_dec[row * code->k + col], sz);
525 * zfec -- fast forward error correction library with Python interface
527 * Copyright (C) 2007-2010 Zooko Wilcox-O'Hearn
528 * Author: Zooko Wilcox-O'Hearn
530 * This file is part of zfec.
532 * See README.rst for licensing information.
536 * This work is derived from the "fec" software by Luigi Rizzo, et al., the
537 * copyright notice and licence terms of which are included below for reference.
538 * fec.c -- forward error correction based on Vandermonde matrices 980624 (C)
539 * 1997-98 Luigi Rizzo (luigi@iet.unipi.it)
541 * Portions derived from code by Phil Karn (karn@ka9q.ampr.org),
542 * Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari
543 * Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995
545 * Modifications by Dan Rubenstein (see Modifications.txt for
547 * Modifications (C) 1998 Dan Rubenstein (drubenst@cs.umass.edu)
549 * Redistribution and use in source and binary forms, with or without
550 * modification, are permitted provided that the following conditions
553 * 1. Redistributions of source code must retain the above copyright
554 * notice, this list of conditions and the following disclaimer.
555 * 2. Redistributions in binary form must reproduce the above
556 * copyright notice, this list of conditions and the following
557 * disclaimer in the documentation and/or other materials
558 * provided with the distribution.
560 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND
561 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
562 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
563 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
564 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
565 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
566 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
567 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
568 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
569 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
570 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY