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