Debian Codegraph @

libtwolame/crc.c

raw
1 /*
2 * TwoLAME: an optimized MPEG Audio Layer Two encoder
3 *
4 * Copyright (C) 2001-2004 Michael Cheng
5 * Copyright (C) 2004-2018 The TwoLAME Project
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 *
21 */
22
23
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "twolame.h"
28 #include "common.h"
29 #include "bitbuffer.h"
30 #include "encode.h"
31 #include "crc.h"
32
33
34
35 static unsigned int crc_update(unsigned int value, unsigned int crc, unsigned int nbBit)
36 {
37 int i;
38 value <<= 8;
39 for (i = 0; i < nbBit; i++) {
40 value <<= 1;
41 crc <<= 1;
42
43 if (((crc ^ value) & 0x10000))
44 crc ^= CRC16_POLYNOMIAL;
45 }
46 return crc;
47 }
48
49
50
51 /*
52 * The CRC is based on the second two bytes of the MPEG audio header
53 * and then the bits up and until the scale-factor bits.
54 */
55
56 void twolame_crc_writeheader(unsigned char *bitstream, int bit_count)
57 {
58 unsigned int crc = 0xffff; /* (jo) init crc16 for error_protection */
59 int whole_bytes = (bit_count >> 3);
60 int byte;
61
62 // Calculate the CRC on the second two bytes of the header
63 crc = crc_update(bitstream[2], crc, 8);
64 crc = crc_update(bitstream[3], crc, 8);
65
66 // Calculate CRC on whole bytes after CRC
67 for (byte = 6; byte < (whole_bytes + 6); byte++) {
68 crc = crc_update(bitstream[byte], crc, 8);
69 }
70
71 // Calculate CRC on remaining bits
72 if (bit_count & 7) {
73 crc = crc_update(bitstream[byte], crc, bit_count & 7);
74 }
75 // Insert the CRC into the 16-bits after the header
76 bitstream[4] = crc >> 8;
77 bitstream[5] = crc & 0xFF;
78 }
79
80
81
82 // vim:ts=4:sw=4:nowrap: