]> git.sesse.net Git - nageru/blob - metacube2.cpp
Fix an issue where the mixer lagging too much behind CEF would cause us to display...
[nageru] / metacube2.cpp
1 /*
2  * Implementation of Metacube2 utility functions.
3  *
4  * Note: This file is meant to compile as both C and C++, for easier inclusion
5  * in other projects.
6  */
7
8 #include "metacube2.h"
9
10 #include <byteswap.h>
11 #include <netinet/in.h>
12
13 /*
14  * https://www.ece.cmu.edu/~koopman/pubs/KoopmanCRCWebinar9May2012.pdf
15  * recommends this for messages as short as ours (see table at page 34).
16  */
17 #define METACUBE2_CRC_POLYNOMIAL 0x8FDB
18
19 /* Semi-random starting value to make sure all-zero won't pass. */
20 #define METACUBE2_CRC_START 0x1234
21
22 /* This code is based on code generated by pycrc. */
23 uint16_t metacube2_compute_crc(const struct metacube2_block_header *hdr)
24 {
25         static const int data_len = sizeof(hdr->size) + sizeof(hdr->flags);
26         const uint8_t *data = (uint8_t *)&hdr->size;
27         uint16_t crc = METACUBE2_CRC_START;
28         int i, j;
29
30         for (i = 0; i < data_len; ++i) {
31                 uint8_t c = data[i];
32                 for (j = 0; j < 8; j++) {
33                         int bit = crc & 0x8000;
34                         crc = (crc << 1) | ((c >> (7 - j)) & 0x01);
35                         if (bit) {
36                                 crc ^= METACUBE2_CRC_POLYNOMIAL;
37                         }
38                 }
39         }
40
41         /* Finalize. */
42         for (i = 0; i < 16; i++) {
43                 int bit = crc & 0x8000;
44                 crc = crc << 1;
45                 if (bit) {
46                         crc ^= METACUBE2_CRC_POLYNOMIAL;
47                 }
48         }
49
50         /*
51          * Invert the checksum for metadata packets, so that clients that
52          * don't understand metadata will ignore it as broken. There will
53          * probably be logging, but apart from that, it's harmless.
54          */
55         if (ntohs(hdr->flags) & METACUBE_FLAGS_METADATA) {
56                 crc ^= 0xffff;
57         }
58
59         return crc;
60 }