gocrc32transport-stream

Formation of CRC-32 for SDT to ts. file


My task is to capture the videostream from the server and write it to ts. files. I ran into a problem when trying to write a SDT package to ts. I form the packet manually by bytes and I can’t figure out how to calculate 4 bytes of CRC-32 for the end of SDT. (used golang)

I tried to get the CRC based on the checksum of the data already written to the SDT packet, but it doesn't work. In the byte-by-byte parsed SDT, CRC was different from what I calculated.


Solution

  • If you're talking about MPEG-2, then the CRC definition is:

    width=32 poly=0x04c11db7 init=0xffffffff refin=false refout=false xorout=0x00000000 check=0x0376e6e7 residue=0x00000000 name="CRC-32/MPEG-2"
    

    There is an example in RFC 4326:

    00 3f 86 dd 00 01 02 03 04 05 60 00 00 00 00 0d
    3a 40 20 01 0d b8 30 08 19 65 00 00 00 00 00 00
    00 01 20 01 0d b8 25 09 19 62 00 00 00 00 00 00
    00 02 80 00 9d 8c 06 38 00 04 00 00 00 00 00 7c
    17 17 63
    

    where the last four bytes of that is the CRC-32/MPEG-2 (in big-endian order) of all of the bytes that precede it.

    Here is example C code to calculate that CRC:

    #include <stddef.h>
    #include <stdint.h>
    
    uint32_t crc32mpeg2(uint32_t crc, void const *mem, size_t len) {
        unsigned char const *data = mem;
        if (data == NULL)
            return 0xffffffff;
        for (size_t i = 0; i < len; i++) {
            crc ^= (uint32_t)data[i] << 24;
            for (unsigned k = 0; k < 8; k++) {
                crc = crc & 0x80000000 ? (crc << 1) ^ 0x4c11db7 : crc << 1;
            }
        }
        return crc;
    }
    

    (When called with mem equal to NULL, the initial CRC value is returned.)