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