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