You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.2KB

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