668b0d83df5a9a38aea624e7babc7cf380aefa9b
[zxing.git] / core / src / com / google / zxing / qrcode / decoder / DecodedBitStreamParser.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.qrcode.decoder;
18
19 import com.google.zxing.ReaderException;
20 import com.google.zxing.common.BitSource;
21 import com.google.zxing.common.CharacterSetECI;
22
23 import java.io.UnsupportedEncodingException;
24
25 /**
26  * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
27  * in one QR Code. This class decodes the bits back into text.</p>
28  *
29  * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
30  *
31  * @author srowen@google.com (Sean Owen)
32  */
33 final class DecodedBitStreamParser {
34
35   /**
36    * See ISO 18004:2006, 6.4.4 Table 5
37    */
38   private static final char[] ALPHANUMERIC_CHARS = {
39       '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
40       'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
41       'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
42       ' ', '$', '%', '*', '+', '-', '.', '/', ':'
43   };
44   private static final String SHIFT_JIS = "SJIS";
45   private static final String EUC_JP = "EUC_JP";
46   private static final boolean ASSUME_SHIFT_JIS;
47   private static final String UTF8 = "UTF8";
48   private static final String ISO88591 = "ISO8859_1";
49
50   static {
51     String platformDefault = System.getProperty("file.encoding");
52     ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) || EUC_JP.equalsIgnoreCase(platformDefault);
53   }
54
55   private DecodedBitStreamParser() {
56   }
57
58   static String decode(byte[] bytes, Version version) throws ReaderException {
59     BitSource bits = new BitSource(bytes);
60     StringBuffer result = new StringBuffer();
61     CharacterSetECI currentCharacterSetECI = null;
62     boolean fc1InEffect = false;
63     Mode mode;
64     do {
65       // While still another segment to read...
66       if (bits.available() < 4) {
67         // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
68         mode = Mode.TERMINATOR;
69       } else {
70         mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
71       }
72       if (!mode.equals(Mode.TERMINATOR)) {
73         if (mode.equals(Mode.FNC1_FIRST_POSITION) || mode.equals(Mode.FNC1_SECOND_POSITION)) {
74           // We do little with FNC1 except alter the parsed result a bit according to the spec
75           fc1InEffect = true;
76         } else if (mode.equals(Mode.ECI)) {
77           // Count doesn't apply to ECI
78           int value = parseECIValue(bits);
79           try {
80             currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
81           } catch (IllegalArgumentException iae) {
82             // unsupported... just continue?
83           }
84         } else {
85           // How many characters will follow, encoded in this mode?
86           int count = bits.readBits(mode.getCharacterCountBits(version));
87           if (mode.equals(Mode.NUMERIC)) {
88             decodeNumericSegment(bits, result, count);
89           } else if (mode.equals(Mode.ALPHANUMERIC)) {
90             decodeAlphanumericSegment(bits, result, count, fc1InEffect);
91           } else if (mode.equals(Mode.BYTE)) {
92             decodeByteSegment(bits, result, count, currentCharacterSetECI);
93           } else if (mode.equals(Mode.KANJI)) {
94             decodeKanjiSegment(bits, result, count);
95           } else {
96             throw new ReaderException("Unsupported mode indicator");
97           }
98         }
99       }
100     } while (!mode.equals(Mode.TERMINATOR));
101
102     // I thought it wasn't allowed to leave extra bytes after the terminator but it happens
103     /*
104     int bitsLeft = bits.available();
105     if (bitsLeft > 0) {
106       if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {
107         throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");
108       }
109     }
110      */
111     return result.toString();
112   }
113
114   private static void decodeKanjiSegment(BitSource bits,
115                                          StringBuffer result,
116                                          int count) throws ReaderException {
117     // Each character will require 2 bytes. Read the characters as 2-byte pairs
118     // and decode as Shift_JIS afterwards
119     byte[] buffer = new byte[2 * count];
120     int offset = 0;
121     while (count > 0) {
122       // Each 13 bits encodes a 2-byte character
123       int twoBytes = bits.readBits(13);
124       int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
125       if (assembledTwoBytes < 0x01F00) {
126         // In the 0x8140 to 0x9FFC range
127         assembledTwoBytes += 0x08140;
128       } else {
129         // In the 0xE040 to 0xEBBF range
130         assembledTwoBytes += 0x0C140;
131       }
132       buffer[offset] = (byte) (assembledTwoBytes >> 8);
133       buffer[offset + 1] = (byte) assembledTwoBytes;
134       offset += 2;
135       count--;
136     }
137     // Shift_JIS may not be supported in some environments:
138     try {
139       result.append(new String(buffer, SHIFT_JIS));
140     } catch (UnsupportedEncodingException uee) {
141       throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device");
142     }
143   }
144
145   private static void decodeByteSegment(BitSource bits,
146                                         StringBuffer result,
147                                         int count,
148                                         CharacterSetECI currentCharacterSetECI) throws ReaderException {
149     byte[] readBytes = new byte[count];
150     if (count << 3 > bits.available()) {
151       throw new ReaderException("Count too large: " + count);
152     }
153     for (int i = 0; i < count; i++) {
154       readBytes[i] = (byte) bits.readBits(8);
155     }
156     String encoding;
157     if (currentCharacterSetECI == null) {
158     // The spec isn't clear on this mode; see
159     // section 6.4.5: t does not say which encoding to assuming
160     // upon decoding. I have seen ISO-8859-1 used as well as
161     // Shift_JIS -- without anything like an ECI designator to
162     // give a hint.
163       encoding = guessEncoding(readBytes);
164     } else {
165       encoding = currentCharacterSetECI.getEncodingName();
166     }
167     try {
168       result.append(new String(readBytes, encoding));
169     } catch (UnsupportedEncodingException uce) {
170       throw new ReaderException(uce.toString());
171     }
172   }
173
174   private static void decodeAlphanumericSegment(BitSource bits,
175                                                 StringBuffer result,
176                                                 int count,
177                                                 boolean fc1InEffect) {
178     // Read two characters at a time
179     int start = result.length();
180     while (count > 1) {
181       int nextTwoCharsBits = bits.readBits(11);
182       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
183       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
184       count -= 2;
185     }
186     if (count == 1) {
187       // special case: one character left
188       result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
189     }
190     // See section 6.4.8.1, 6.4.8.2
191     if (fc1InEffect) {
192       // We need to massage the result a bit if in an FNC1 mode:
193       for (int i = start; i < result.length(); i++) {
194         if (result.charAt(i) == '%') {
195           if (i < result.length() - 1 && result.charAt(i + 1) == '%') {
196             // %% is rendered as %
197             result.deleteCharAt(i + 1);
198           } else {
199             // In alpha mode, % should be converted to FNC1 separator 0x1D
200             result.setCharAt(i, (char) 0x1D);
201           }
202         }
203       }
204     }
205   }
206
207   private static void decodeNumericSegment(BitSource bits,
208                                            StringBuffer result,
209                                            int count) throws ReaderException {
210     // Read three digits at a time
211     while (count >= 3) {
212       // Each 10 bits encodes three digits
213       int threeDigitsBits = bits.readBits(10);
214       if (threeDigitsBits >= 1000) {
215         throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);
216       }
217       result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
218       result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
219       result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
220       count -= 3;
221     }
222     if (count == 2) {
223       // Two digits left over to read, encoded in 7 bits
224       int twoDigitsBits = bits.readBits(7);
225       if (twoDigitsBits >= 100) {
226         throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);
227       }
228       result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
229       result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
230     } else if (count == 1) {
231       // One digit left over to read
232       int digitBits = bits.readBits(4);
233       if (digitBits >= 10) {
234         throw new ReaderException("Illegal value for digit unit: " + digitBits);
235       }
236       result.append(ALPHANUMERIC_CHARS[digitBits]);
237     }
238   }
239
240   private static String guessEncoding(byte[] bytes) {
241     if (ASSUME_SHIFT_JIS) {
242       return SHIFT_JIS;
243     }
244     // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
245     if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
246       return UTF8;
247     }
248     // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
249     // which should be by far the most common encodings. ISO-8859-1
250     // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
251     // uses this as a first byte of a two-byte character. If we see this
252     // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
253     // If we see something else in that second byte, we'll make the risky guess
254     // that it's UTF-8.
255     int length = bytes.length;
256     boolean canBeISO88591 = true;
257     boolean canBeShiftJIS = true;
258     boolean sawDoubleByteStart = false;
259     int maybeSingleByteKatakanaCount = 0;
260     boolean lastWasPossibleDoubleByteStart = false;
261     for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) {
262       int value = bytes[i] & 0xFF;
263       if (value >= 0x7F && value <= 0x9F) {
264         canBeISO88591 = false;
265       }
266       if (value >= 0xA1 && value <= 0xDF) {
267         // count the number of characters that might be a Shift_JIS single-byte Katakana character
268         if (!lastWasPossibleDoubleByteStart) {
269           maybeSingleByteKatakanaCount++;
270         }
271       }
272       if (!lastWasPossibleDoubleByteStart && ((value >= 0xF0 && value <= 0xFF) || value == 0x80 || value == 0xA0)) {
273         canBeShiftJIS = false;
274       }
275       if (((value >= 0x81 && value <= 0x9F) || (value >= 0xE0 && value <= 0xEF)) && i < length - 1) {
276         // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid
277         // second byte.
278         sawDoubleByteStart = true;
279         if (lastWasPossibleDoubleByteStart) {
280           // If we just checked this and the last byte for being a valid double-byte
281           // char, don't check starting on this byte. If this and the last byte
282           // formed a valid pair, then this shouldn't be checked to see if it starts
283           // a double byte pair of course.
284           lastWasPossibleDoubleByteStart = false;
285         } else {
286           // ... otherwise do check to see if this plus the next byte form a valid
287           // double byte pair encoding a character.
288           lastWasPossibleDoubleByteStart = true;
289           int nextValue = bytes[i + 1] & 0xFF;
290           if (nextValue < 0x40 || nextValue > 0xFC) {
291             canBeShiftJIS = false;
292           }
293           // There is some conflicting information out there about which bytes can follow which in
294           // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice.
295         }
296       } else {
297         lastWasPossibleDoubleByteStart = false;
298       }
299     }
300     // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is:
301     // - If we saw
302     //   - at least one byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or
303     //   - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1),
304     // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS
305     if ((sawDoubleByteStart || 20 * maybeSingleByteKatakanaCount > length) && canBeShiftJIS) {
306       return SHIFT_JIS;
307     }
308     // Otherwise, we default to ISO-8859-1 unless we know it can't be
309     if (canBeISO88591) {
310       return ISO88591;
311     }
312     // Otherwise, we take a wild guess with UTF-8
313     return UTF8;
314   }
315   
316   private static int parseECIValue(BitSource bits) {
317     int firstByte = bits.readBits(8);
318     if ((firstByte & 0x80) == 0) {
319       // just one byte
320       return firstByte & 0x7F;
321     } else if ((firstByte & 0xC0) == 0x80) {
322       // two bytes
323       int secondByte = bits.readBits(8);
324       return ((firstByte & 0x3F) << 8) | secondByte;
325     } else if ((firstByte & 0xE0) == 0xC0) {
326       // three bytes
327       int secondThirdBytes = bits.readBits(16);
328       return ((firstByte & 0x1F) << 16) | secondThirdBytes;
329     }
330     throw new IllegalArgumentException("Bad ECI bits starting with byte " + firstByte);
331   }
332
333 }