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