30
|
1 #include "common.h"
|
|
2 #include "crc.h"
|
|
3
|
|
4 AVCRC *av_crcEDB88320;
|
|
5 AVCRC *av_crc04C11DB7;
|
|
6 AVCRC *av_crc8005 ;
|
|
7 AVCRC *av_crc07 ;
|
|
8
|
|
9 /**
|
|
10 * Inits a crc table.
|
|
11 * @param ctx must be an array of sizeof(AVCRC)*257 or sizeof(AVCRC)*1024
|
|
12 * @param cts_size size of ctx in bytes
|
|
13 * @return <0 on failure
|
|
14 */
|
|
15 int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size){
|
|
16 int i, j;
|
|
17 uint32_t c;
|
|
18
|
|
19 if (bits < 8 || bits > 32 || poly >= (1LL<<bits))
|
|
20 return -1;
|
|
21 if (ctx_size != sizeof(AVCRC)*257 && ctx_size != sizeof(AVCRC)*1024)
|
|
22 return -1;
|
|
23
|
|
24 for (i = 0; i < 256; i++) {
|
|
25 if (le) {
|
|
26 for (c = i, j = 0; j < 8; j++)
|
|
27 c = (c>>1)^(poly & (-(c&1)));
|
|
28 ctx[i] = c;
|
|
29 } else {
|
|
30 for (c = i << 24, j = 0; j < 8; j++)
|
|
31 c = (c<<1) ^ ((poly<<(32-bits)) & (((int32_t)c)>>31) );
|
|
32 ctx[i] = bswap_32(c);
|
|
33 }
|
|
34 }
|
|
35 ctx[256]=1;
|
|
36 if(ctx_size >= sizeof(AVCRC)*1024)
|
|
37 for (i = 0; i < 256; i++)
|
|
38 for(j=0; j<3; j++)
|
|
39 ctx[256*(j+1) + i]= (ctx[256*j + i]>>8) ^ ctx[ ctx[256*j + i]&0xFF ];
|
|
40
|
|
41 return 0;
|
|
42 }
|
|
43
|
|
44 uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length){
|
|
45 const uint8_t *end= buffer+length;
|
|
46
|
|
47 if(!ctx[256])
|
|
48 while(buffer<end-3){
|
|
49 crc ^= le2me_32(*(uint32_t*)buffer); buffer+=4;
|
|
50 crc = ctx[3*256 + ( crc &0xFF)]
|
|
51 ^ctx[2*256 + ((crc>>8 )&0xFF)]
|
|
52 ^ctx[1*256 + ((crc>>16)&0xFF)]
|
|
53 ^ctx[0*256 + ((crc>>24) )];
|
|
54 }
|
|
55 while(buffer<end)
|
|
56 crc = ctx[((uint8_t)crc) ^ *buffer++] ^ (crc >> 8);
|
|
57
|
|
58 return crc;
|
|
59 }
|
|
60
|
|
61 #ifdef TEST
|
|
62 #undef printf
|
|
63 main(){
|
|
64 uint8_t buf[1999];
|
|
65 int i;
|
|
66 int p[4][4]={{1, 32, 0xedb88320L, 0x3D5CDD04},
|
|
67 {0, 32, 0x04c11db7L, 0xC0F5BAE0},
|
|
68 {0, 16, 0x8005 , 0x1FBB },
|
|
69 {0, 8, 0x07 , 0xE3 },};
|
|
70 AVCRC ctx[1 ? 1024:257];
|
|
71
|
|
72 for(i=0; i<sizeof(buf); i++)
|
|
73 buf[i]= i+i*i;
|
|
74
|
|
75 for(i=0; i<4; i++){
|
|
76 av_crc_init(ctx, p[i][0], p[i][1], p[i][2], sizeof(ctx));
|
|
77 printf("crc %08X =%X\n", p[i][2], av_crc(ctx, 0, buf, sizeof(buf)));
|
|
78 }
|
|
79 }
|
|
80 #endif
|