libtsfuncs is a library for mpeg PSI parsing and generation. https://georgi.unixsol.org/programs/libtsfuncs/
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.

tsfuncs_crc.c 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <netdb.h>
  2. #include "tsfuncs.h"
  3. #define CRC32_POLY 0x04C11DB7L
  4. static int crc_table_initialized = 0;
  5. static uint32_t crc32_table[256];
  6. void ts_crc32_init() {
  7. int i, j;
  8. uint32_t crc;
  9. if (crc_table_initialized)
  10. return;
  11. crc_table_initialized = 1;
  12. for (i=0; i<256; i++) {
  13. crc = i << 24;
  14. for (j=0; j<8; j++) {
  15. if (crc & 0x80000000L)
  16. crc = (crc << 1) ^ CRC32_POLY;
  17. else
  18. crc = (crc << 1);
  19. }
  20. crc32_table[i] = crc;
  21. }
  22. crc_table_initialized = 1;
  23. }
  24. uint32_t ts_crc32(uint8_t *data, int data_size) {
  25. int i, j;
  26. uint32_t crc = 0xffffffff;
  27. if (!crc_table_initialized) {
  28. ts_crc32_init();
  29. }
  30. for (j=0; j<data_size; j++) {
  31. i = ((crc >> 24) ^ *data++) & 0xff;
  32. crc = (crc << 8) ^ crc32_table[i];
  33. }
  34. return crc;
  35. }
  36. u_int32_t ts_crc32_section(struct ts_section_header *section_header) {
  37. // +3 to include the first 3 bytes before section_length field
  38. return ts_crc32(section_header->section_data, section_header->section_length + 3);
  39. }
  40. int ts_crc32_section_check(struct ts_section_header *section_header, char *table) {
  41. // +3 to include the first 3 bytes before section_length field
  42. uint32_t check_crc = ts_crc32(section_header->section_data, section_header->section_length + 3);
  43. if (check_crc != 0) {
  44. ts_LOGf("!!! Wrong %s table CRC! It should be 0 but it is 0x%08x (CRC in data is 0x%08x)\n",
  45. table,
  46. check_crc,
  47. section_header->CRC);
  48. return 0;
  49. }
  50. return 1;
  51. }