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