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