Added some degree of support for Character Set ECIs
[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 = "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     CharacterSetECI currentCharacterSetECI = null;
61     Mode mode;
62     do {
63       // While still another segment to read...
64       if (bits.available() == 0) {
65         // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
66         mode = Mode.TERMINATOR;
67       } else {
68         mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
69       }
70       if (!mode.equals(Mode.TERMINATOR)) {
71         if (mode.equals(Mode.ECI)) {
72           // Count doesn't apply to ECI
73           int value = ECI.parseECI(bits);
74           try {
75             currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
76           } catch (IllegalArgumentException iae) {
77             // unsupported... just continue?
78           }
79         } else {
80           // How many characters will follow, encoded in this mode?
81          int count = bits.readBits(mode.getCharacterCountBits(version));
82           if (mode.equals(Mode.NUMERIC)) {
83             decodeNumericSegment(bits, result, count);
84           } else if (mode.equals(Mode.ALPHANUMERIC)) {
85             decodeAlphanumericSegment(bits, result, count);
86           } else if (mode.equals(Mode.BYTE)) {
87             decodeByteSegment(bits, result, count, currentCharacterSetECI);
88           } else if (mode.equals(Mode.KANJI)) {
89             decodeKanjiSegment(bits, result, count);
90           } else {
91             throw new ReaderException("Unsupported mode indicator");
92           }
93         }
94       }
95     } while (!mode.equals(Mode.TERMINATOR));
96
97     // I thought it wasn't allowed to leave extra bytes after the terminator but it happens
98     /*
99     int bitsLeft = bits.available();
100     if (bitsLeft > 0) {
101       if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {
102         throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");
103       }
104     }
105      */
106     return result.toString();
107   }
108
109   private static void decodeKanjiSegment(BitSource bits,
110                                          StringBuffer result,
111                                          int count) throws ReaderException {
112     // Each character will require 2 bytes. Read the characters as 2-byte pairs
113     // and decode as Shift_JIS afterwards
114     byte[] buffer = new byte[2 * count];
115     int offset = 0;
116     while (count > 0) {
117       // Each 13 bits encodes a 2-byte character
118       int twoBytes = bits.readBits(13);
119       int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
120       if (assembledTwoBytes < 0x01F00) {
121         // In the 0x8140 to 0x9FFC range
122         assembledTwoBytes += 0x08140;
123       } else {
124         // In the 0xE040 to 0xEBBF range
125         assembledTwoBytes += 0x0C140;
126       }
127       buffer[offset] = (byte) (assembledTwoBytes >> 8);
128       buffer[offset + 1] = (byte) assembledTwoBytes;
129       offset += 2;
130       count--;
131     }
132     // Shift_JIS may not be supported in some environments:
133     try {
134       result.append(new String(buffer, SHIFT_JIS));
135     } catch (UnsupportedEncodingException uee) {
136       throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device");
137     }
138   }
139
140   private static void decodeByteSegment(BitSource bits,
141                                         StringBuffer result,
142                                         int count,
143                                         CharacterSetECI currentCharacterSetECI) throws ReaderException {
144     byte[] readBytes = new byte[count];
145     if (count << 3 > bits.available()) {
146       throw new ReaderException("Count too large: " + count);
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 new ReaderException(uce.toString());
166     }
167   }
168
169   private static void decodeAlphanumericSegment(BitSource bits,
170                                                 StringBuffer result,
171                                                 int count) {
172     // Read two characters at a time
173     while (count > 1) {
174       int nextTwoCharsBits = bits.readBits(11);
175       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
176       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
177       count -= 2;
178     }
179     if (count == 1) {
180       // special case: one character left
181       result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
182     }
183   }
184
185   private static void decodeNumericSegment(BitSource bits,
186                                            StringBuffer result,
187                                            int count) throws ReaderException {
188     // Read three digits at a time
189     while (count >= 3) {
190       // Each 10 bits encodes three digits
191       int threeDigitsBits = bits.readBits(10);
192       if (threeDigitsBits >= 1000) {
193         throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);
194       }
195       result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
196       result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
197       result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
198       count -= 3;
199     }
200     if (count == 2) {
201       // Two digits left over to read, encoded in 7 bits
202       int twoDigitsBits = bits.readBits(7);
203       if (twoDigitsBits >= 100) {
204         throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);
205       }
206       result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
207       result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
208     } else if (count == 1) {
209       // One digit left over to read
210       int digitBits = bits.readBits(4);
211       if (digitBits >= 10) {
212         throw new ReaderException("Illegal value for digit unit: " + digitBits);
213       }
214       result.append(ALPHANUMERIC_CHARS[digitBits]);
215     }
216   }
217
218   private static String guessEncoding(byte[] bytes) {
219     if (ASSUME_SHIFT_JIS) {
220       return SHIFT_JIS;
221     }
222     // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
223     if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
224       return UTF8;
225     }
226     // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
227     // which should be by far the most common encodings. ISO-8859-1
228     // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
229     // uses this as a first byte of a two-byte character. If we see this
230     // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
231     // If we see something else in that second byte, we'll make the risky guess
232     // that it's UTF-8.
233     int length = bytes.length;
234     boolean canBeISO88591 = true;
235     boolean lastWasPossibleDoubleByteStart = false;
236     for (int i = 0; i < length; i++) {
237       int value = bytes[i] & 0xFF;
238       if (value >= 0x80 && value <= 0x9F && i < length - 1) {
239         canBeISO88591 = false;
240         // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
241         // just double check that it is followed by a byte that's valid in
242         // the Shift_JIS encoding
243         if (lastWasPossibleDoubleByteStart) {
244           // If we just checked this and the last byte for being a valid double-byte
245           // char, don't check starting on this byte. If the this and the last byte
246           // formed a valid pair, then this shouldn't be checked to see if it starts
247           // a double byte pair of course.
248           lastWasPossibleDoubleByteStart = false;
249         } else {
250           // ... otherwise do check to see if this plus the next byte form a valid
251           // double byte pair encoding a character.
252           lastWasPossibleDoubleByteStart = true;
253           int nextValue = bytes[i + 1] & 0xFF;
254           if ((value & 0x1) == 0) {
255             // if even, next value should be in [0x9F,0xFC]
256             // if not, we'll guess UTF-8
257             if (nextValue < 0x9F || nextValue > 0xFC) {
258               return UTF8;
259             }
260           } else {
261             // if odd, next value should be in [0x40,0x9E]
262             // if not, we'll guess UTF-8
263             if (nextValue < 0x40 || nextValue > 0x9E) {
264               return UTF8;
265             }
266           }
267         }
268       }
269     }
270     return canBeISO88591 ? ISO88591 : SHIFT_JIS;
271   }
272
273 }