libtsfuncs is a library for mpeg PSI parsing and generation. https://georgi.unixsol.org/programs/libtsfuncs/

crc.c 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * CRC functions for mpeg PSI tables
  3. * Copyright (C) 2010-2011 Unix Solutions Ltd.
  4. *
  5. * Released under MIT license.
  6. * See LICENSE-MIT.txt for license terms.
  7. */
  8. #include <netdb.h>
  9. #include "tsfuncs.h"
  10. #define CRC32_POLY 0x04C11DB7L
  11. static int crc_table_initialized = 0;
  12. static uint32_t crc32_table[256];
  13. void ts_crc32_init() {
  14. int i, j;
  15. uint32_t crc;
  16. if (crc_table_initialized)
  17. return;
  18. crc_table_initialized = 1;
  19. for (i=0; i<256; i++) {
  20. crc = i << 24;
  21. for (j=0; j<8; j++) {
  22. if (crc & 0x80000000L)
  23. crc = (crc << 1) ^ CRC32_POLY;
  24. else
  25. crc = (crc << 1);
  26. }
  27. crc32_table[i] = crc;
  28. }
  29. crc_table_initialized = 1;
  30. }
  31. uint32_t ts_crc32(uint8_t *data, int data_size) {
  32. int i, j;
  33. uint32_t crc = 0xffffffff;
  34. if (!crc_table_initialized) {
  35. ts_crc32_init();
  36. }
  37. for (j=0; j<data_size; j++) {
  38. i = ((crc >> 24) ^ *data++) & 0xff;
  39. crc = (crc << 8) ^ crc32_table[i];
  40. }
  41. return crc;
  42. }
  43. u_int32_t ts_crc32_section(struct ts_section_header *section_header) {
  44. return ts_crc32(section_header->section_data, section_header->section_data_len);
  45. }
  46. int ts_crc32_section_check(struct ts_section_header *section_header, char *table) {
  47. uint32_t check_crc = ts_crc32(section_header->section_data, section_header->section_data_len);
  48. if (check_crc != 0) {
  49. ts_LOGf("!!! Wrong %s table CRC! It should be 0 but it is 0x%08x (CRC in data is 0x%08x)\n",
  50. table,
  51. check_crc,
  52. section_header->CRC);
  53. return 0;
  54. }
  55. return 1;
  56. }