Many changes to the C++ port.
[zxing.git] / cpp / core / src / zxing / qrcode / decoder / DecodedBitStreamParser.cpp
1 /*
2  *  DecodedBitStreamParser.cpp
3  *  zxing
4  *
5  *  Created by Christian Brunschen on 20/05/2008.
6  *  Copyright 2008 ZXing authors All rights reserved.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20
21 #include <zxing/qrcode/decoder/DecodedBitStreamParser.h>
22 #include <iostream>
23 #include <iconv.h>
24
25 // Required for compatibility. TODO: test on Symbian
26 #ifndef ICONV_CONST
27 #define ICONV_CONST /**/
28 #endif
29
30 using namespace zxing;
31
32 namespace zxing {
33 namespace qrcode {
34
35 using namespace std;
36
37 const char DecodedBitStreamParser::ALPHANUMERIC_CHARS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
38     'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
39     'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'
40                                                           };
41
42 const char *DecodedBitStreamParser::ASCII = "ASCII";
43 const char *DecodedBitStreamParser::ISO88591 = "ISO-8859-1";
44 const char *DecodedBitStreamParser::UTF8 = "UTF-8";
45 const char *DecodedBitStreamParser::SHIFT_JIS = "SHIFT_JIS";
46 const char *DecodedBitStreamParser::EUC_JP = "EUC-JP";
47
48 void DecodedBitStreamParser::append(ostream &ost, const unsigned char *bufIn, size_t nIn, const char *src) {
49   if (nIn == 0) {
50     return;
51   }
52
53   iconv_t cd = iconv_open(UTF8, src);
54   int maxOut = 4 * nIn + 1;
55   unsigned char bufOut[maxOut];
56
57   ICONV_CONST char *fromPtr = (ICONV_CONST char *)bufIn;
58   size_t nFrom = nIn;
59   char *toPtr = (char *)bufOut;
60   size_t nTo = maxOut;
61
62   while (nFrom > 0) {
63     size_t oneway = iconv(cd, &fromPtr, &nFrom, &toPtr, &nTo);
64     if (oneway == (size_t)(-1)) {
65       iconv_close(cd);
66       throw ReaderException("error converting characters");
67     }
68   }
69   iconv_close(cd);
70
71   int nResult = maxOut - nTo;
72   bufOut[nResult] = '\0';
73
74   ost << bufOut;
75 }
76
77 void DecodedBitStreamParser::decodeKanjiSegment(Ref<BitSource> bits, ostringstream &result, int count) {
78   // Each character will require 2 bytes. Read the characters as 2-byte pairs
79   // and decode as Shift_JIS afterwards
80   size_t nBytes = 2 * count;
81   unsigned char buffer[nBytes];
82   int offset = 0;
83   while (count > 0) {
84     // Each 13 bits encodes a 2-byte character
85
86     int twoBytes = bits->readBits(13);
87     int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
88     if (assembledTwoBytes < 0x01F00) {
89       // In the 0x8140 to 0x9FFC range
90       assembledTwoBytes += 0x08140;
91     } else {
92       // In the 0xE040 to 0xEBBF range
93       assembledTwoBytes += 0x0C140;
94     }
95     buffer[offset] = (unsigned char)(assembledTwoBytes >> 8);
96     buffer[offset + 1] = (unsigned char)assembledTwoBytes;
97     offset += 2;
98     count--;
99   }
100
101   append(result, buffer, nBytes, SHIFT_JIS);
102 }
103
104 void DecodedBitStreamParser::decodeByteSegment(Ref<BitSource> bits, ostringstream &result, int count) {
105   int nBytes = count;
106   unsigned char readBytes[nBytes];
107   if (count << 3 > bits->available()) {
108     ostringstream s;
109     s << "Count too large: " << count;
110     throw ReaderException(s.str().c_str());
111   }
112   for (int i = 0; i < count; i++) {
113     readBytes[i] = (unsigned char)bits->readBits(8);
114   }
115   // The spec isn't clear on this mode; see
116   // section 6.4.5: t does not say which encoding to assuming
117   // upon decoding. I have seen ISO-8859-1 used as well as
118   // Shift_JIS -- without anything like an ECI designator to
119   // give a hint.
120   const char *encoding = guessEncoding(readBytes, nBytes);
121   append(result, readBytes, nBytes, encoding);
122 }
123
124 void DecodedBitStreamParser::decodeNumericSegment(Ref<BitSource> bits, ostringstream &result, int count) {
125   int nBytes = count;
126   unsigned char bytes[nBytes];
127   int i = 0;
128   // Read three digits at a time
129   while (count >= 3) {
130     // Each 10 bits encodes three digits
131     int threeDigitsBits = bits->readBits(10);
132     if (threeDigitsBits >= 1000) {
133       ostringstream s;
134       s << "Illegal value for 3-digit unit: " << threeDigitsBits;
135       throw ReaderException(s.str().c_str());
136     }
137     bytes[i++] = ALPHANUMERIC_CHARS[threeDigitsBits / 100];
138     bytes[i++] = ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10];
139     bytes[i++] = ALPHANUMERIC_CHARS[threeDigitsBits % 10];
140     count -= 3;
141   }
142   if (count == 2) {
143     // Two digits left over to read, encoded in 7 bits
144     int twoDigitsBits = bits->readBits(7);
145     if (twoDigitsBits >= 100) {
146       ostringstream s;
147       s << "Illegal value for 2-digit unit: " << twoDigitsBits;
148       throw ReaderException(s.str().c_str());
149     }
150     bytes[i++] = ALPHANUMERIC_CHARS[twoDigitsBits / 10];
151     bytes[i++] = ALPHANUMERIC_CHARS[twoDigitsBits % 10];
152   } else if (count == 1) {
153     // One digit left over to read
154     int digitBits = bits->readBits(4);
155     if (digitBits >= 10) {
156       ostringstream s;
157       s << "Illegal value for digit unit: " << digitBits;
158       throw ReaderException(s.str().c_str());
159     }
160     bytes[i++] = ALPHANUMERIC_CHARS[digitBits];
161   }
162   append(result, bytes, nBytes, ASCII);
163 }
164
165 void DecodedBitStreamParser::decodeAlphanumericSegment(Ref<BitSource> bits, ostringstream &result, int count) {
166   int nBytes = count;
167   unsigned char bytes[nBytes];
168   int i = 0;
169   // Read two characters at a time
170   while (count > 1) {
171     int nextTwoCharsBits = bits->readBits(11);
172     bytes[i++] = ALPHANUMERIC_CHARS[nextTwoCharsBits / 45];
173     bytes[i++] = ALPHANUMERIC_CHARS[nextTwoCharsBits % 45];
174     count -= 2;
175   }
176   if (count == 1) {
177     bytes[i++] = ALPHANUMERIC_CHARS[bits->readBits(6)];
178   }
179   append(result, bytes, nBytes, ASCII);
180 }
181
182 const char *
183 DecodedBitStreamParser::guessEncoding(unsigned char *bytes, int length) {
184   // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
185   if (length > 3 && bytes[0] == (unsigned char)0xEF && bytes[1] == (unsigned char)0xBB && bytes[2]
186       == (unsigned char)0xBF) {
187     return UTF8;
188   }
189   // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
190   // which should be by far the most common encodings. ISO-8859-1
191   // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
192   // uses this as a first byte of a two-byte character. If we see this
193   // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
194   // If we see something else in that second byte, we'll make the risky guess
195   // that it's UTF-8.
196   bool canBeISO88591 = true;
197   bool lastWasPossibleDoubleByteStart = false;
198   for (int i = 0; i < length; i++) {
199     int value = bytes[i] & 0xFF;
200     if (value >= 0x80 && value <= 0x9F && i < length - 1) {
201       canBeISO88591 = false;
202       // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
203       // just double check that it is followed by a byte that's valid in
204       // the Shift_JIS encoding
205       if (lastWasPossibleDoubleByteStart) {
206         // If we just checked this and the last byte for being a valid double-byte
207         // char, don't check starting on this byte. If the this and the last byte
208         // formed a valid pair, then this shouldn't be checked to see if it starts
209         // a double byte pair of course.
210         lastWasPossibleDoubleByteStart = false;
211       } else {
212         // ... otherwise do check to see if this plus the next byte form a valid
213         // double byte pair encoding a character.
214         lastWasPossibleDoubleByteStart = true;
215         int nextValue = bytes[i + 1] & 0xFF;
216         if ((value & 0x1) == 0) {
217           // if even, next value should be in [0x9F,0xFC]
218           // if not, we'll guess UTF-8
219           if (nextValue < 0x9F || nextValue > 0xFC) {
220             return UTF8;
221           }
222         } else {
223           // if odd, next value should be in [0x40,0x9E]
224           // if not, we'll guess UTF-8
225           if (nextValue < 0x40 || nextValue > 0x9E) {
226             return UTF8;
227           }
228         }
229       }
230     }
231   }
232   return canBeISO88591 ? ISO88591 : SHIFT_JIS;
233 }
234
235 string DecodedBitStreamParser::decode(ArrayRef<unsigned char> bytes, Version *version) {
236   ostringstream result;
237   Ref<BitSource> bits(new BitSource(bytes));
238   Mode *mode = &Mode::TERMINATOR;
239   do {
240     // While still another segment to read...
241     if (bits->available() < 4) {
242       // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
243       mode = &Mode::TERMINATOR;
244     } else {
245       mode = &Mode::forBits(bits->readBits(4)); // mode is encoded by 4 bits
246     }
247     if (mode != &Mode::TERMINATOR) {
248       // How many characters will follow, encoded in this mode?
249       int count = bits->readBits(mode->getCharacterCountBits(version));
250       if (mode == &Mode::NUMERIC) {
251         decodeNumericSegment(bits, result, count);
252       } else if (mode == &Mode::ALPHANUMERIC) {
253         decodeAlphanumericSegment(bits, result, count);
254       } else if (mode == &Mode::BYTE) {
255         decodeByteSegment(bits, result, count);
256       } else if (mode == &Mode::KANJI) {
257         decodeKanjiSegment(bits, result, count);
258       } else {
259         throw ReaderException("Unsupported mode indicator");
260       }
261     }
262   } while (mode != &Mode::TERMINATOR);
263   return result.str();
264 }
265
266 }
267 }