41d589e0c8a5fcbe9a8f51eac611c34bf3a7e9e3
[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
22 import java.io.UnsupportedEncodingException;
23
24 /**
25  * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
26  * in one QR Code. This class decodes the bits back into text.</p>
27  *
28  * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
29  *
30  * @author srowen@google.com (Sean Owen)
31  */
32 final class DecodedBitStreamParser {
33
34   /**
35    * See ISO 18004:2006, 6.4.4 Table 5
36    */
37   private static final char[] ALPHANUMERIC_CHARS = {
38       '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
39       'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
40       'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
41       ' ', '$', '%', '*', '+', '-', '.', '/', ':'
42   };
43   private static final String SHIFT_JIS = "SJIS";
44   private static final String EUC_JP = "EUC_JP";
45   private static final boolean ASSUME_SHIFT_JIS;
46   private static final String UTF8 = "UTF8";
47   private static final String ISO88591 = "ISO8859_1";
48
49   static {
50     String platformDefault = System.getProperty("file.encoding");
51     ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) || EUC_JP.equalsIgnoreCase(platformDefault);
52   }
53
54   private DecodedBitStreamParser() {
55   }
56
57   static String decode(byte[] bytes, Version version) throws ReaderException {
58     BitSource bits = new BitSource(bytes);
59     StringBuffer result = new StringBuffer();
60     CharacterSetECI currentCharacterSetECI = null;
61     boolean fc1InEffect = false;
62     Mode mode;
63     do {
64       // While still another segment to read...
65       if (bits.available() == 0) {
66         // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
67         mode = Mode.TERMINATOR;
68       } else {
69         mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
70       }
71       if (!mode.equals(Mode.TERMINATOR)) {
72         if (mode.equals(Mode.FNC1_FIRST_POSITION) || mode.equals(Mode.FNC1_SECOND_POSITION)) {
73           // We do little with FNC1 except alter the parsed result a bit according to the spec
74           fc1InEffect = true;
75         } else if (mode.equals(Mode.ECI)) {
76           // Count doesn't apply to ECI
77           int value = ECI.parseECI(bits);
78           try {
79             currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
80           } catch (IllegalArgumentException iae) {
81             // unsupported... just continue?
82           }
83         } else {
84           // How many characters will follow, encoded in this mode?
85          int count = bits.readBits(mode.getCharacterCountBits(version));
86           if (mode.equals(Mode.NUMERIC)) {
87             decodeNumericSegment(bits, result, count);
88           } else if (mode.equals(Mode.ALPHANUMERIC)) {
89             decodeAlphanumericSegment(bits, result, count, fc1InEffect);
90           } else if (mode.equals(Mode.BYTE)) {
91             decodeByteSegment(bits, result, count, currentCharacterSetECI);
92           } else if (mode.equals(Mode.KANJI)) {
93             decodeKanjiSegment(bits, result, count);
94           } else {
95             throw new ReaderException("Unsupported mode indicator");
96           }
97         }
98       }
99     } while (!mode.equals(Mode.TERMINATOR));
100
101     // I thought it wasn't allowed to leave extra bytes after the terminator but it happens
102     /*
103     int bitsLeft = bits.available();
104     if (bitsLeft > 0) {
105       if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {
106         throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");
107       }
108     }
109      */
110     return result.toString();
111   }
112
113   private static void decodeKanjiSegment(BitSource bits,
114                                          StringBuffer result,
115                                          int count) throws ReaderException {
116     // Each character will require 2 bytes. Read the characters as 2-byte pairs
117     // and decode as Shift_JIS afterwards
118     byte[] buffer = new byte[2 * count];
119     int offset = 0;
120     while (count > 0) {
121       // Each 13 bits encodes a 2-byte character
122       int twoBytes = bits.readBits(13);
123       int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
124       if (assembledTwoBytes < 0x01F00) {
125         // In the 0x8140 to 0x9FFC range
126         assembledTwoBytes += 0x08140;
127       } else {
128         // In the 0xE040 to 0xEBBF range
129         assembledTwoBytes += 0x0C140;
130       }
131       buffer[offset] = (byte) (assembledTwoBytes >> 8);
132       buffer[offset + 1] = (byte) assembledTwoBytes;
133       offset += 2;
134       count--;
135     }
136     // Shift_JIS may not be supported in some environments:
137     try {
138       result.append(new String(buffer, SHIFT_JIS));
139     } catch (UnsupportedEncodingException uee) {
140       throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device");
141     }
142   }
143
144   private static void decodeByteSegment(BitSource bits,
145                                         StringBuffer result,
146                                         int count,
147                                         CharacterSetECI currentCharacterSetECI) throws ReaderException {
148     byte[] readBytes = new byte[count];
149     if (count << 3 > bits.available()) {
150       throw new ReaderException("Count too large: " + count);
151     }
152     for (int i = 0; i < count; i++) {
153       readBytes[i] = (byte) bits.readBits(8);
154     }
155     String encoding;
156     if (currentCharacterSetECI == null) {
157     // The spec isn't clear on this mode; see
158     // section 6.4.5: t does not say which encoding to assuming
159     // upon decoding. I have seen ISO-8859-1 used as well as
160     // Shift_JIS -- without anything like an ECI designator to
161     // give a hint.
162       encoding = guessEncoding(readBytes);
163     } else {
164       encoding = currentCharacterSetECI.getEncodingName();
165     }
166     try {
167       result.append(new String(readBytes, encoding));
168     } catch (UnsupportedEncodingException uce) {
169       throw new ReaderException(uce.toString());
170     }
171   }
172
173   private static void decodeAlphanumericSegment(BitSource bits,
174                                                 StringBuffer result,
175                                                 int count,
176                                                 boolean fc1InEffect) {
177     // Read two characters at a time
178     int start = result.length();
179     while (count > 1) {
180       int nextTwoCharsBits = bits.readBits(11);
181       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
182       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
183       count -= 2;
184     }
185     if (count == 1) {
186       // special case: one character left
187       result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
188     }
189     // See section 6.4.8.1, 6.4.8.2
190     if (fc1InEffect) {
191       // We need to massage the result a bit if in an FNC1 mode:
192       for (int i = start; i < result.length(); i++) {
193         if (result.charAt(i) == '%') {
194           if (i < result.length() - 1 && result.charAt(i + 1) == '%') {
195             // %% is rendered as %
196             result.deleteCharAt(i + 1);
197           } else {
198             // In alpha mode, % should be converted to FNC1 separator 0x1D
199             result.setCharAt(i, (char) 0x1D);
200           }
201         }
202       }
203     }
204   }
205
206   private static void decodeNumericSegment(BitSource bits,
207                                            StringBuffer result,
208                                            int count) throws ReaderException {
209     // Read three digits at a time
210     while (count >= 3) {
211       // Each 10 bits encodes three digits
212       int threeDigitsBits = bits.readBits(10);
213       if (threeDigitsBits >= 1000) {
214         throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);
215       }
216       result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
217       result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
218       result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
219       count -= 3;
220     }
221     if (count == 2) {
222       // Two digits left over to read, encoded in 7 bits
223       int twoDigitsBits = bits.readBits(7);
224       if (twoDigitsBits >= 100) {
225         throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);
226       }
227       result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
228       result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
229     } else if (count == 1) {
230       // One digit left over to read
231       int digitBits = bits.readBits(4);
232       if (digitBits >= 10) {
233         throw new ReaderException("Illegal value for digit unit: " + digitBits);
234       }
235       result.append(ALPHANUMERIC_CHARS[digitBits]);
236     }
237   }
238
239   private static String guessEncoding(byte[] bytes) {
240     if (ASSUME_SHIFT_JIS) {
241       return SHIFT_JIS;
242     }
243     // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
244     if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
245       return UTF8;
246     }
247     // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
248     // which should be by far the most common encodings. ISO-8859-1
249     // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
250     // uses this as a first byte of a two-byte character. If we see this
251     // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
252     // If we see something else in that second byte, we'll make the risky guess
253     // that it's UTF-8.
254     int length = bytes.length;
255     boolean canBeISO88591 = true;
256     boolean lastWasPossibleDoubleByteStart = false;
257     for (int i = 0; i < length; i++) {
258       int value = bytes[i] & 0xFF;
259       if (value >= 0x80 && value <= 0x9F && i < length - 1) {
260         canBeISO88591 = false;
261         // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
262         // just double check that it is followed by a byte that's valid in
263         // the Shift_JIS encoding
264         if (lastWasPossibleDoubleByteStart) {
265           // If we just checked this and the last byte for being a valid double-byte
266           // char, don't check starting on this byte. If the this and the last byte
267           // formed a valid pair, then this shouldn't be checked to see if it starts
268           // a double byte pair of course.
269           lastWasPossibleDoubleByteStart = false;
270         } else {
271           // ... otherwise do check to see if this plus the next byte form a valid
272           // double byte pair encoding a character.
273           lastWasPossibleDoubleByteStart = true;
274           int nextValue = bytes[i + 1] & 0xFF;
275           if ((value & 0x1) == 0) {
276             // if even, next value should be in [0x9F,0xFC]
277             // if not, we'll guess UTF-8
278             if (nextValue < 0x9F || nextValue > 0xFC) {
279               return UTF8;
280             }
281           } else {
282             // if odd, next value should be in [0x40,0x9E]
283             // if not, we'll guess UTF-8
284             if (nextValue < 0x40 || nextValue > 0x9E) {
285               return UTF8;
286             }
287           }
288         }
289       }
290     }
291     return canBeISO88591 ? ISO88591 : SHIFT_JIS;
292   }
293
294 }