block_code.c 22.7 KB
Newer Older
Andreas Schmidt's avatar
Andreas Schmidt committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
 * fec.c -- forward error correction based on Vandermonde matrices
 * 980614
 * (C) 1997-98 Luigi Rizzo (luigi@iet.unipi.it)
 *
 * Portions derived from code by Phil Karn (karn@ka9q.ampr.org),
 * Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari
 * Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:

 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "block_code.h"
#include "../../util/common.h"

// static int count_num;
// static uint64_t tot_encoding_time;
// uint64_t myticks[10];       /* vars for timekeeping */
/*
 * Primitive polynomials - see Lin & Costello, Appendix A,
 * and  Lee & Messerschmitt, p. 453.
 */
static char *all_primitive_polynomials[] = {        /* GF_BITS	polynomial		*/
        NULL,                    /*  0	no code			*/
        NULL,                    /*  1	no code			*/
        "111",                    /*  2	1+x+x^2			*/
        "1101",                    /*  3	1+x+x^3			*/
        "11001",                /*  4	1+x+x^4			*/
        "101001",                /*  5	1+x^2+x^5		*/
        "1100001",                /*  6	1+x+x^6			*/
        "10010001",                /*  7	1 + x^3 + x^7		*/
        "101110001",            /*  8	1+x^2+x^3+x^4+x^8	*/
        "1000100001",            /*  9	1+x^4+x^9		*/
        "10010000001",            /* 10	1+x^3+x^10		*/
        "101000000001",            /* 11	1+x^2+x^11		*/
        "1100101000001",        /* 12	1+x+x^4+x^6+x^12	*/
        "11011000000001",        /* 13	1+x+x^3+x^4+x^13	*/
        "110000100010001",        /* 14	1+x+x^6+x^10+x^14	*/
        "1100000000000001",        /* 15	1+x+x^15		*/
        "11010000000010001"        /* 16	1+x+x^3+x^12+x^16	*/
};

/*
 * modnn(x) computes x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1,
 * without a slow divide.
 */
static inline gf modnn(int x) {
    while (x >= GF_SIZE) {
        x -= GF_SIZE;
        x = (x >> GF_BITS) + (x & GF_SIZE);
    }
    return x;
}

#define SWAP(a, b, t) {t tmp; tmp=a; a=b; b=tmp;}

/*
 * gf_mul(x,y) multiplies two numbers. If GF_BITS<=8, it is much
 * faster to use a multiplication table.
 *
 * USE_GF_MULC, GF_MULC0(c) and GF_ADDMULC(x) can be used when multiplying
 * many numbers by the same constant. In this case the first
 * call sets the constant, and others perform the multiplications.
 * A value related to the multiplication is held in a local variable
 * declared with USE_GF_MULC . See usage in addmul1().
 */
#if (GF_BITS <= 8)
// static gf gf_mul_table[GF_SIZE + 1][GF_SIZE + 1];

#define gf_mul(cod, x, y) (cod->gf_mul_table[x][y])

#define USE_GF_MULC register gf * __gf_mulc_
#define GF_MULC0(cod, c) __gf_mulc_ = cod->gf_mul_table[c]
#define GF_ADDMULC(cod, dst, x) dst ^= __gf_mulc_[x]

static void init_mul_table(PrrtCoder *cod) {
    int i, j;
    for (i = 0; i < GF_SIZE + 1; i++) {
        for (j = 0; j < GF_SIZE + 1; j++) {
            cod->gf_mul_table[i][j] = cod->gf_exp[modnn(cod->gf_log[i] + cod->gf_log[j])];
        }
    }

    for (j = 0; j < GF_SIZE + 1; j++) {
        cod->gf_mul_table[0][j] = cod->gf_mul_table[j][0] = 0;
    }
}

#else	/* GF_BITS > 8 */
static inline gf gf_mul(PrrtCoder *cod, x, y)
{
    if ( (x) == 0 || (y)==0 ) return 0;

    return cod->gf_exp[cod->gf_log[x] + cod->gf_log[y] ] ;
}
#define init_mul_table(cod)

#define USE_GF_MULC register gf * __gf_mulc_
#define GF_MULC0(cod, c) __gf_mulc_ = &(cod->gf_exp[ cod->gf_log[c] ])
#define GF_ADDMULC(cod, dst, x) { if (x) dst ^= __gf_mulc_[ cod->gf_log[x] ] ; }
#endif

/*
 * Generate GF(2**m) from the irreducible polynomial p(X) in p[0]..p[m]
 * Lookup tables:
 *     index->polynomial form		gf_exp[] contains j= \alpha^i;
 *     polynomial form -> index form	gf_log[ j = \alpha^i ] = i
 * \alpha=x is the primitive element of GF(2^m)
 *
 * For efficiency, gf_exp[] has size 2*GF_SIZE, so that a simple
 * multiplication of two numbers can be resolved without calling modnn
 */

static void *block_code_malloc(int sz, char *err_string) {
    void *p = malloc(sz);
    if (p == NULL) {
        PERROR("Malloc failure allocating %s\n", err_string);
    }
    return p;
}

#define NEW_GF_MATRIX(rows, cols) \
    (gf *)block_code_malloc(rows * cols * sizeof(gf), " ## __LINE__ ## " )

/*
 * initialize the data structures used for computations in GF.
 */
static void generate_gf(PrrtCoder *cod) {
    int i;
    gf mask;
    char *primitive_polynomial = all_primitive_polynomials[GF_BITS];

    mask = 1;    /* x ** 0 = 1 */
    cod->gf_exp[GF_BITS] = 0; /* will be updated at the end of the 1st loop */
    /*
     * first, generate the (polynomial representation of) powers of \alpha,
     * which are stored in gf_exp[i] = \alpha ** i .
     * At the same time build gf_log[gf_exp[i]] = i .
     * The first GF_BITS powers are simply bits shifted to the left.
     */
    for (i = 0; i < GF_BITS; i++, mask <<= 1) {
        cod->gf_exp[i] = mask;
        cod->gf_log[cod->gf_exp[i]] = i;
        /*
         * If primitive_polynomial[i] == 1 then \alpha ** i occurs in poly-repr
         * gf_exp[GF_BITS] = \alpha ** GF_BITS
         */
        if (primitive_polynomial[i] == '1') {
            cod->gf_exp[GF_BITS] ^= mask;
        }
    }
    /*
     * now gf_exp[GF_BITS] = \alpha ** GF_BITS is complete, so can als
     * compute its inverse.
     */
    cod->gf_log[cod->gf_exp[GF_BITS]] = GF_BITS;
    /*
     * Poly-repr of \alpha ** (i+1) is given by poly-repr of
     * \alpha ** i shifted left one-bit and accounting for any
     * \alpha ** GF_BITS term that may occur when poly-repr of
     * \alpha ** i is shifted.
     */
    mask = 1 << (GF_BITS - 1);
    for (i = GF_BITS + 1; i < GF_SIZE; i++) {
        if (cod->gf_exp[i - 1] >= mask) {
            cod->gf_exp[i] = cod->gf_exp[GF_BITS] ^ ((cod->gf_exp[i - 1] ^ mask) << 1);
        }
        else {
            cod->gf_exp[i] = cod->gf_exp[i - 1] << 1;
        }
        cod->gf_log[cod->gf_exp[i]] = i;
    }
    /*
     * log(0) is not defined, so use a special value
     */
    cod->gf_log[0] = GF_SIZE;
    /* set the extended gf_exp values for fast multiply */
    for (i = 0; i < GF_SIZE; i++) {
        cod->gf_exp[i + GF_SIZE] = cod->gf_exp[i];
    }

    /*
     * again special cases. 0 has no inverse. This used to
     * be initialized to GF_SIZE, but it should make no difference
     * since noone is supposed to read from here.
     */
    cod->inverse[0] = 0;
    cod->inverse[1] = 1;
    for (i = 2; i <= GF_SIZE; i++) {
        cod->inverse[i] = cod->gf_exp[GF_SIZE - cod->gf_log[i]];
    }
}

/*
 * Various linear algebra operations that are used often.
 */

/*
 * addmul() computes dst[] = dst[] + c * src[]
 * This is used often, so better optimize it! Currently the loop is
 * unrolled 16 times, a good value for 486 and pentium-class machines.
 * The case c=0 is also optimized, whereas c=1 is not. These
 * calls are unfrequent in my typical apps so I did not bother.
 *
 * Note that gcc on
 */
#define addmul(cod, dst, src, c, sz) \
    if (c != 0) addmul1(cod, dst, src, c, sz)

#define UNROLL 16 /* 1, 4, 8, 16 */

static void addmul1(PrrtCoder *cod, gf *dst1, gf *src1, gf c, int sz) {
    USE_GF_MULC;
    register gf *dst = dst1, *src = src1;
    gf *lim = &dst[sz - UNROLL + 1];

    GF_MULC0(cod, c);

#if (UNROLL > 1) /* unrolling by 8/16 is quite effective on the pentium */
    for (; dst < lim; dst += UNROLL, src += UNROLL) {
        GF_ADDMULC(cod, dst[0], src[0]);
        GF_ADDMULC(cod, dst[1], src[1]);
        GF_ADDMULC(cod, dst[2], src[2]);
        GF_ADDMULC(cod, dst[3], src[3]);
#if (UNROLL > 4)
        GF_ADDMULC(cod, dst[4], src[4]);
        GF_ADDMULC(cod, dst[5], src[5]);
        GF_ADDMULC(cod, dst[6], src[6]);
        GF_ADDMULC(cod, dst[7], src[7]);
#endif
#if (UNROLL > 8)
        GF_ADDMULC(cod, dst[8], src[8]);
        GF_ADDMULC(cod, dst[9], src[9]);
        GF_ADDMULC(cod, dst[10], src[10]);
        GF_ADDMULC(cod, dst[11], src[11]);
        GF_ADDMULC(cod, dst[12], src[12]);
        GF_ADDMULC(cod, dst[13], src[13]);
        GF_ADDMULC(cod, dst[14], src[14]);
        GF_ADDMULC(cod, dst[15], src[15]);
#endif
    }
#endif
    lim += UNROLL - 1;
    for (; dst < lim; dst++, src++) {
        GF_ADDMULC(cod, *dst, *src);
    }        /* final components */
}

/*
 * computes C = AB where A is n*k, B is k*m, C is n*m
 */
static void matmul(PrrtCoder *cod, gf *a, gf *b, gf *c, int n, int k, int m) {
    int row, col, i;

    for (row = 0; row < n; row++) {
        for (col = 0; col < m; col++) {
            gf *pa = &a[row * k];
            gf *pb = &b[col];
            gf acc = 0;
            for (i = 0; i < k; i++, pa++, pb += m) {
                acc ^= gf_mul(cod, *pa, *pb);
            }
            c[row * m + col] = acc;
        }
    }
}

/*
 * invert_mat() takes a matrix and produces its inverse
 * k is the size of the matrix.
 * (Gauss-Jordan, adapted from Numerical Recipes in C)
 * Return non-zero if singular.
 */

static int invert_mat(PrrtCoder *cod, gf *src, int k) {
    gf c, *p;
    int irow, icol, row, col, i, ix;

    int error = 1;
    int *indxc = (int *) block_code_malloc(k * sizeof(int), "indxc");
    int *indxr = (int *) block_code_malloc(k * sizeof(int), "indxr");
    int *ipiv = (int *) block_code_malloc(k * sizeof(int), "ipiv");
    gf *id_row = NEW_GF_MATRIX(1, k);
    gf *temp_row = NEW_GF_MATRIX(1, k);

    if (!indxc || !indxr || !ipiv || !id_row || !temp_row) {
        PERROR("Could not allocate ressources needed for invert_mat\n");
        goto fail;
    }

    bzero(id_row, k * sizeof(gf));
    /*
    * ipiv marks elements already used as pivots.
    */
    for (i = 0; i < k; i++)
        ipiv[i] = 0;

    for (col = 0; col < k; col++) {
        gf *pivot_row;
        /*
        * Zeroing column 'col', look for a non-zero element.
        * First try on the diagonal, if it fails, look elsewhere.
        */
        irow = icol = -1;
        if (ipiv[col] != 1 && src[col * k + col] != 0) {
            irow = col;
            icol = col;
            goto found_piv;
        }
        for (row = 0; row < k; row++) {
            if (ipiv[row] != 1) {
                for (ix = 0; ix < k; ix++) {
                    if (ipiv[ix] == 0) {
                        if (src[row * k + ix] != 0) {
                            irow = row;
                            icol = ix;
                            goto found_piv;
                        }
                    } else if (ipiv[ix] > 1) {
                        PERROR("singular matrix\n");
                        goto fail;
                    }
                }
            }
        }
        if (icol == -1) {
            PERROR("XXX pivot not found!\n");
            goto fail;
        }
        found_piv:
        ++(ipiv[icol]);
        /*
        * swap rows irow and icol, so afterwards the diagonal
        * element will be correct. Rarely done, not worth
        * optimizing.
        */
        if (irow != icol) {
            for (ix = 0; ix < k; ix++) {
                SWAP(src[irow * k + ix], src[icol * k + ix], gf);
            }
        }
        indxr[col] = irow;
        indxc[col] = icol;
        pivot_row = &src[icol * k];
        c = pivot_row[icol];
        if (c == 0) {
            PERROR("singular matrix 2\n");
            goto fail;
        }
        if (c != 1) { /* otherwhise this is a NOP */
            /*
            * this is done often , but optimizing is not so
            * fruitful, at least in the obvious ways (unrolling)
            */
            c = cod->inverse[c];
            pivot_row[icol] = 1;
            for (ix = 0; ix < k; ix++)
                pivot_row[ix] = gf_mul(cod, c, pivot_row[ix]);
        }
        /*
        * from all rows, remove multiples of the selected row
        * to zero the relevant entry (in fact, the entry is not zero
        * because we know it must be zero).
        * (Here, if we know that the pivot_row is the identity,
        * we can optimize the addmul).
        */
        id_row[icol] = 1;
        if (bcmp(pivot_row, id_row, k * sizeof(gf)) != 0) {
            for (p = src, ix = 0; ix < k; ix++, p += k) {
                if (ix != icol) {
                    c = p[icol];
                    p[icol] = 0;
                    addmul(cod, p, pivot_row, c, k);
                }
            }
        }
        id_row[icol] = 0;
    } /* done all columns */
    for (col = k - 1; col >= 0; col--) {
        if (indxr[col] < 0 || indxr[col] >= k) {
            PERROR("AARGH, indxr[col] %d\n", indxr[col]);
        } else if (indxc[col] < 0 || indxc[col] >= k) {
            PERROR("AARGH, indxc[col] %d\n", indxc[col]);
        } else if (indxr[col] != indxc[col]) {
            for (row = 0; row < k; row++) {
                SWAP(src[row * k + indxr[col]], src[row * k + indxc[col]], gf);
            }
        }
    }
    error = 0;
    fail:
    free(indxc);
    free(indxr);
    free(ipiv);
    free(id_row);
    free(temp_row);
    return error;
}

/*
 * fast code for inverting a vandermonde matrix.
 * XXX NOTE: It assumes that the matrix
 * is not singular and _IS_ a vandermonde matrix. Only uses
 * the second column of the matrix, containing the p_i's.
 *
 * Algorithm borrowed from "Numerical recipes in C" -- sec.2.8, but
 * largely revised for my purposes.
 * p = coefficients of the matrix (p_i)
 * q = values of the polynomial (known)
 */

int invert_vdm(PrrtCoder *cod, gf *src, int k) {
    int i, j, row, col;
    gf *b, *c, *p;
    gf t, xx;
    int err = 0;

    if (k == 1) {
        /* degenerate case, matrix must be p^0 = 1 */
        return 0;
    }
    /*
    * c holds the coefficient of P(x) = Prod (x - p_i), i=0..k-1
    * b holds the coefficient for the matrix inversion
    */
    c = NEW_GF_MATRIX(1, k);
    b = NEW_GF_MATRIX(1, k);
    p = NEW_GF_MATRIX(1, k);

    if (!c || !b || !p) {
        err = -1;
        goto fail;
    }

    for (j = 1, i = 0; i < k; i++, j += k) {
        c[i] = 0;
        p[i] = src[j];    /* p[i] */
    }
    /*
    * construct coeffs. recursively. We know c[k] = 1 (implicit)
    * and start P_0 = x - p_0, then at each stage multiply by
    * x - p_i generating P_i = x P_{i-1} - p_i P_{i-1}
    * After k steps we are done.
    */
    c[k - 1] = p[0];    /* really -p(0), but x = -x in GF(2^m) */
    for (i = 1; i < k; i++) {
        gf p_i = p[i]; /* see above comment */
        for (j = k - 1 - (i - 1); j < k - 1; j++)
            c[j] ^= gf_mul(cod, p_i, c[j + 1]);
        c[k - 1] ^= p_i;
    }

    for (row = 0; row < k; row++) {
        /*
        * synthetic division etc.
        */
        xx = p[row];
        t = 1;
        b[k - 1] = 1; /* this is in fact c[k] */
        for (i = k - 2; i >= 0; i--) {
            b[i] = c[i + 1] ^ gf_mul(cod, xx, b[i + 1]);
            t = gf_mul(cod, xx, t) ^ b[i];
        }
        for (col = 0; col < k; col++)
            src[col * k + row] = gf_mul(cod, cod->inverse[t], b[col]);
    }

    fail:
    free(c);
    free(b);
    free(p);
    return err;
}

//static int fec_initialized = 0 ;
static void init_fec(PrrtCoder *cod) {
    generate_gf(cod);
    init_mul_table(cod);
}

/*
 * This section contains the proper FEC encoding/decoding routines.
 * The encoding matrix is computed starting with a Vandermonde matrix,
 * and then transforming it into a systematic matrix.
 */

513
int prrt_coder_create(PrrtCoder **cod, uint8_t k, uint8_t n);
Andreas Schmidt's avatar
Andreas Schmidt committed
514

515
int PrrtCoder_get_coder(PrrtCoder **cod, uint8_t n, uint8_t k) {
Andreas Schmidt's avatar
Andreas Schmidt committed
516
517
518
519
520
521
    int err = 0;

    if (*cod == 0 ||
        (*cod)->params.n != n ||
        (*cod)->params.k != k) {
        PrrtCoder_destroy(*cod);
Andreas Schmidt's avatar
Andreas Schmidt committed
522
        err = prrt_coder_create(cod, k, n);
Andreas Schmidt's avatar
Andreas Schmidt committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    }

    return err;
}

void PrrtCoder_destroy(PrrtCoder *cod) {
    int k;
    int n;
    gf *enc_matrix;

    if (cod == 0)
        return;

    enc_matrix = cod->params.enc_matrix;
    k = cod->params.k;
    n = cod->params.n;

    if (cod->params.magic != (((FEC_MAGIC ^ k) ^ n) ^ (int) (enc_matrix))) {
        PERROR("bad parameters to fec_free\n");
        return;
    }
    free(enc_matrix);
    free(cod);
}

548
int prrt_coder_create(PrrtCoder **cod, uint8_t k, uint8_t n) {
Andreas Schmidt's avatar
Andreas Schmidt committed
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
    int row, col;
    gf *p, *tmp_m;
    int err = 0;

    if (k > GF_SIZE + 1 || n > GF_SIZE + 1 || k > n) {
        PERROR("Invalid parameters k %d n %d GF_SIZE %d\n", k, n, GF_SIZE);
        return -1;
    }

    *cod = malloc(sizeof(PrrtCoder));
    if (!(*cod)) {
        PERROR("Not enough memory for coder!\n");
        return -2;
    }

    /*set fec parameter*/
    (*cod)->params.k = k;
    (*cod)->params.n = n;
    (*cod)->params.enc_matrix = NEW_GF_MATRIX(n, k);
    if (!(*cod)->params.enc_matrix) {
        (*cod)->params.enc_matrix = 0;
        PERROR("Could not allocate enc_matrix for coder\n");
        err = -2;
        goto error;
    }

    (*cod)->params.magic = ((FEC_MAGIC ^ k) ^ n) ^ (int) ((*cod)->params.enc_matrix);

    /*init tables*/
    init_fec(*cod);

    /*init auxiliary*/
    (*cod)->count_num = 0;
    (*cod)->tot_encoding_time = 0;

    tmp_m = NEW_GF_MATRIX(n, k);
    if (!tmp_m) {
        PERROR("Could not allocate tmp_m matrix for new coder\n");
        err = -2;
        goto error;
    }
    /*
    * fill the matrix with powers of field elements, starting from 0.
    * The first row is special, cannot be computed with exp. table.
    */
    tmp_m[0] = 1;
    for (col = 1; col < k; col++) {
        tmp_m[col] = 0;
    }
    for (p = tmp_m + k, row = 0; row < n - 1; row++, p += k) {
        for (col = 0; col < k; col++) {
            p[col] = (*cod)->gf_exp[modnn(row * col)];
        }
    }

    /*
    * quick code to build systematic matrix: invert the top
    * k*k vandermonde matrix, multiply right the bottom n-k rows
    * by the inverse, and construct the identity matrix at the top.
    */
    err = invert_vdm(*cod, tmp_m, k); /* much faster than invert_mat */
    if (err < 0) {
        PERROR("Could not invert vdm matrix\n");
        err = -2;
        goto error;
    }

    matmul(*cod, tmp_m + k * k, tmp_m, (*cod)->params.enc_matrix + k * k, n - k, k, k);
    /*
    * the upper matrix is I so do not bother with a slow multiply
    */
    bzero((*cod)->params.enc_matrix, k * k * sizeof(gf));
    for (p = (*cod)->params.enc_matrix, col = 0; col < k; col++, p += k + 1) {
        *p = 1;
    }
    free(tmp_m);

    return 0;

    error:
    free(*cod);
    free((*cod)->params.enc_matrix);
    return err;
}

/*
 * PrrtCoder_encode accepts as input pointers to n data packets of size sz,
 * and produces as output a packet pointed to by fec, computed
 * with index "index".
 */
void PrrtCoder_encode(PrrtCoder *cod, gf **src, gf *fec, int index, int sz) {
    int i, k = cod->params.k;
    gf *p;

    if (GF_BITS > 8) {
        sz /= 2;
    }

    if (index < k) {
        bcopy(src[index], fec, sz * sizeof(gf));
    }
    else if (index < cod->params.n) {
        p = &(cod->params.enc_matrix[index * k]);
        bzero(fec, sz * sizeof(gf));
        for (i = 0; i < k; i++) {
            addmul(cod, fec, src[i], p[i], sz);
        }
    } else {
        PERROR("Invalid index %d (max %d)\n", index, cod->params.n - 1);
    }
}

/*
 * PrrtCoder_build_matrix constructs the encoding matrix given the
 * indexes. The matrix must be already allocated as
 * a vector of k*k elements, in row-major order
 */
Andreas Schmidt's avatar
Andreas Schmidt committed
666
static gf *prrt_coder_build_matrix(PrrtCoder *cod, int *index) {
Andreas Schmidt's avatar
Andreas Schmidt committed
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
    int i, k = cod->params.k;
    gf *p, *matrix = NEW_GF_MATRIX(k, k);
    if (!matrix)
        goto out;

    for (i = 0, p = matrix; i < k; i++, p += k) {
#if 1 /* this is simply an optimization, not very useful indeed */
        if (index[i] < k) {
            bzero(p, k * sizeof(gf));
            p[i] = 1;
        } else
#endif
        if (index[i] < cod->params.n) {
            bcopy(&(cod->params.enc_matrix[index[i] * k]), p, k * sizeof(gf));
        }
        else {
            PERROR("decode: invalid index %d (max %d)\n",
                   index[i], cod->params.n - 1);
            free(matrix);
            return NULL;
        }
    }
    if (invert_mat(cod, matrix, k)) {
        free(matrix);
        matrix = NULL;
    }
    out:
    return matrix;
}

int PrrtCoder_decode(PrrtCoder *cod, gf **pkt, int *index, int sz) {
    gf *m_dec = 0;
    gf **new_pkt = 0;
    int row, col, k = cod->params.k;
    int err = 0;
    int i = 0;

    /*check input fields*/
    for (i = 0; i < k; i++) {
        if (pkt[i] == 0 || index[i] == -1) {
            PERROR("Input data not valid, missing packet at position %d\n", i);
            return -1;
        }
    }

    if (GF_BITS > 8) {
        sz /= 2;
    }

Andreas Schmidt's avatar
Andreas Schmidt committed
716
    m_dec = prrt_coder_build_matrix(cod, index);
Andreas Schmidt's avatar
Andreas Schmidt committed
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774

    if (!m_dec) {
        PERROR("Could not build decode matrix\n");
        err = -1; /* error */
        goto error;
    }
    /*
    * do the actual decoding
    */
    new_pkt = (gf **) block_code_malloc(k * sizeof(gf *), "new pkt pointers");
    if (!new_pkt) {
        PERROR("Could not allocate memory for temporary packet\n");
        err = -1;
        goto error;
    }
    bzero(new_pkt, k * sizeof(gf *));

    for (row = 0; row < k; row++) {
        if (index[row] >= k) {
            new_pkt[row] = (gf *) block_code_malloc(sz * sizeof(gf), "new pkt buffer");
            if (!new_pkt[row]) {
                PERROR("No memory for packet row\n");
                goto free_rows;
            }
            bzero(new_pkt[row], sz * sizeof(gf));
            for (col = 0; col < k; col++) {
                addmul(cod, new_pkt[row], pkt[col], m_dec[row * k + col], sz);
            }
        }
    }
    /*
    * move pkts to their final destination
    */
    for (row = 0; row < k; row++) {
        if (index[row] >= k) {
            bcopy(new_pkt[row], pkt[row], sz * sizeof(gf));
            free(new_pkt[row]);
        }
    }
    error:
    free(new_pkt);
    free(m_dec);


    return err;

    free_rows:
    for (row = 0; row < k; row++) {
        if (index[row] >= k) {
            free(new_pkt[row]);
        }
    }

    free(new_pkt);
    free(m_dec);

    return -1;
}