Added, at least, parsing of ECI mode in QR Code
[zxing.git] / core / src / com / google / zxing / qrcode / decoder / DecodedBitStreamParser.java
1 /*
2  * Copyright 2007 Google Inc.
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 = "Shift_JIS";
44   private static final String EUC_JP = "EUC-JP";
45   private static final boolean ASSUME_SHIFT_JIS;
46   private static final String UTF8 = "UTF-8";
47   private static final String ISO88591 = "ISO-8859-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     Mode mode;
61     do {
62       // While still another segment to read...
63       if (bits.available() == 0) {
64         // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
65         mode = Mode.TERMINATOR;
66       } else {
67         mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
68       }
69       if (!mode.equals(Mode.TERMINATOR)) {
70         if (mode.equals(Mode.ECI)) {
71           // Count doesn't apply to ECI
72           parseECI(bits);
73           // We don't currently do anything with ECI, since there seems to be no reference
74           // defining what each value means. AIM's "Extended Channel Interpretations" does
75           // not define it. I have never observed a QR Code using it. So for now, we at least
76           // parse it but don't know how to take action on it.
77         } else {
78           // How many characters will follow, encoded in this mode?
79          int count = bits.readBits(mode.getCharacterCountBits(version));
80           if (mode.equals(Mode.NUMERIC)) {
81             decodeNumericSegment(bits, result, count);
82           } else if (mode.equals(Mode.ALPHANUMERIC)) {
83             decodeAlphanumericSegment(bits, result, count);
84           } else if (mode.equals(Mode.BYTE)) {
85             decodeByteSegment(bits, result, count);
86           } else if (mode.equals(Mode.KANJI)) {
87             decodeKanjiSegment(bits, result, count);
88           } else {
89             throw new ReaderException("Unsupported mode indicator");
90           }
91         }
92       }
93     } while (!mode.equals(Mode.TERMINATOR));
94
95     // I thought it wasn't allowed to leave extra bytes after the terminator but it happens
96     /*
97     int bitsLeft = bits.available();
98     if (bitsLeft > 0) {
99       if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {
100         throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");
101       }
102     }
103      */
104     return result.toString();
105   }
106
107   private static int parseECI(BitSource bits) {
108     int firstByte = bits.readBits(8);
109     if (firstByte & 0x80 == 0) {
110       // just one byte
111       return firstByte & 0x7F;
112     } else if (firstByte & 0xC0 == 0x80) {
113       // two bytes
114       int secondByte = bits.readBits(8);
115       return ((firstByte & 0x3F) << 8) | secondByte;
116     } else if (firstByte & 0xE0 == 0xC0) {
117       // three bytes
118       int secondByte = bits.readBits(8);
119       int thirdByte = bits.readBits(8);
120       return ((firstByte & 0x1F) << 16) | (secondByte << 8) | thirdByte;
121     }
122   }
123
124   private static void decodeKanjiSegment(BitSource bits,
125                                          StringBuffer result,
126                                          int count) throws ReaderException {
127     // Each character will require 2 bytes. Read the characters as 2-byte pairs
128     // and decode as Shift_JIS afterwards
129     byte[] buffer = new byte[2 * count];
130     int offset = 0;
131     while (count > 0) {
132       // Each 13 bits encodes a 2-byte character
133       int twoBytes = bits.readBits(13);
134       int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
135       if (assembledTwoBytes < 0x01F00) {
136         // In the 0x8140 to 0x9FFC range
137         assembledTwoBytes += 0x08140;
138       } else {
139         // In the 0xE040 to 0xEBBF range
140         assembledTwoBytes += 0x0C140;
141       }
142       buffer[offset] = (byte) (assembledTwoBytes >> 8);
143       buffer[offset + 1] = (byte) assembledTwoBytes;
144       offset += 2;
145       count--;
146     }
147     // Shift_JIS may not be supported in some environments:
148     try {
149       result.append(new String(buffer, SHIFT_JIS));
150     } catch (UnsupportedEncodingException uee) {
151       throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device");
152     }
153   }
154
155   private static void decodeByteSegment(BitSource bits,
156                                         StringBuffer result,
157                                         int count) throws ReaderException {
158     byte[] readBytes = new byte[count];
159     if (count << 3 > bits.available()) {
160       throw new ReaderException("Count too large: " + count);
161     }
162     for (int i = 0; i < count; i++) {
163       readBytes[i] = (byte) bits.readBits(8);
164     }
165     // The spec isn't clear on this mode; see
166     // section 6.4.5: t does not say which encoding to assuming
167     // upon decoding. I have seen ISO-8859-1 used as well as
168     // Shift_JIS -- without anything like an ECI designator to
169     // give a hint.
170     String encoding = guessEncoding(readBytes);
171     try {
172       result.append(new String(readBytes, encoding));
173     } catch (UnsupportedEncodingException uce) {
174       throw new ReaderException(uce.toString());
175     }
176   }
177
178   private static void decodeAlphanumericSegment(BitSource bits,
179                                                 StringBuffer result,
180                                                 int count) {
181     // Read two characters at a time
182     while (count > 1) {
183       int nextTwoCharsBits = bits.readBits(11);
184       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
185       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
186       count -= 2;
187     }
188     if (count == 1) {
189       // special case: one character left
190       result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
191     }
192   }
193
194   private static void decodeNumericSegment(BitSource bits,
195                                            StringBuffer result,
196                                            int count) throws ReaderException {
197     // Read three digits at a time
198     while (count >= 3) {
199       // Each 10 bits encodes three digits
200       int threeDigitsBits = bits.readBits(10);
201       if (threeDigitsBits >= 1000) {
202         throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);
203       }
204       result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
205       result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
206       result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
207       count -= 3;
208     }
209     if (count == 2) {
210       // Two digits left over to read, encoded in 7 bits
211       int twoDigitsBits = bits.readBits(7);
212       if (twoDigitsBits >= 100) {
213         throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);
214       }
215       result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
216       result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
217     } else if (count == 1) {
218       // One digit left over to read
219       int digitBits = bits.readBits(4);
220       if (digitBits >= 10) {
221         throw new ReaderException("Illegal value for digit unit: " + digitBits);
222       }
223       result.append(ALPHANUMERIC_CHARS[digitBits]);
224     }
225   }
226
227   private static String guessEncoding(byte[] bytes) {
228     if (ASSUME_SHIFT_JIS) {
229       return SHIFT_JIS;
230     }
231     // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
232     if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
233       return UTF8;
234     }
235     // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
236     // which should be by far the most common encodings. ISO-8859-1
237     // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
238     // uses this as a first byte of a two-byte character. If we see this
239     // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
240     // If we see something else in that second byte, we'll make the risky guess
241     // that it's UTF-8.
242     int length = bytes.length;
243     boolean canBeISO88591 = true;
244     boolean lastWasPossibleDoubleByteStart = false;
245     for (int i = 0; i < length; i++) {
246       int value = bytes[i] & 0xFF;
247       if (value >= 0x80 && value <= 0x9F && i < length - 1) {
248         canBeISO88591 = false;
249         // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
250         // just double check that it is followed by a byte that's valid in
251         // the Shift_JIS encoding
252         if (lastWasPossibleDoubleByteStart) {
253           // If we just checked this and the last byte for being a valid double-byte
254           // char, don't check starting on this byte. If the this and the last byte
255           // formed a valid pair, then this shouldn't be checked to see if it starts
256           // a double byte pair of course.
257           lastWasPossibleDoubleByteStart = false;
258         } else {
259           // ... otherwise do check to see if this plus the next byte form a valid
260           // double byte pair encoding a character.
261           lastWasPossibleDoubleByteStart = true;
262           int nextValue = bytes[i + 1] & 0xFF;
263           if ((value & 0x1) == 0) {
264             // if even, next value should be in [0x9F,0xFC]
265             // if not, we'll guess UTF-8
266             if (nextValue < 0x9F || nextValue > 0xFC) {
267               return UTF8;
268             }
269           } else {
270             // if odd, next value should be in [0x40,0x9E]
271             // if not, we'll guess UTF-8
272             if (nextValue < 0x40 || nextValue > 0x9E) {
273               return UTF8;
274             }
275           }
276         }
277       }
278     }
279     return canBeISO88591 ? ISO88591 : SHIFT_JIS;
280   }
281
282 }