More javadoc
[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 boolean ASSUME_SHIFT_JIS;
44
45   static {
46     String platformDefault = System.getProperty("file.encoding");
47     ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) ||
48         "EUC-JP".equalsIgnoreCase(platformDefault);
49   }
50
51   private DecodedBitStreamParser() {
52   }
53
54   static String decode(byte[] bytes, Version version) throws ReaderException {
55     BitSource bits = new BitSource(bytes);
56     StringBuffer result = new StringBuffer();
57     Mode mode;
58     do {
59       // While still another segment to read...
60       mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
61       if (!mode.equals(Mode.TERMINATOR)) {
62         // How many characters will follow, encoded in this mode?
63         int count = bits.readBits(mode.getCharacterCountBits(version));
64         if (mode.equals(Mode.NUMERIC)) {
65           decodeNumericSegment(bits, result, count);
66         } else if (mode.equals(Mode.ALPHANUMERIC)) {
67           decodeAlphanumericSegment(bits, result, count);
68         } else if (mode.equals(Mode.BYTE)) {
69           decodeByteSegment(bits, result, count);
70         } else if (mode.equals(Mode.KANJI)) {
71           decodeKanjiSegment(bits, result, count);
72         } else {
73           throw new ReaderException("Unsupported mode indicator");
74         }
75       }
76     } while (!mode.equals(Mode.TERMINATOR));
77
78     // I thought it wasn't allowed to leave extra bytes after the terminator but it happens
79     /*
80     int bitsLeft = bits.available();
81     if (bitsLeft > 0) {
82       if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {
83         throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");
84       }
85     }
86      */
87     return result.toString();
88   }
89
90   private static void decodeKanjiSegment(BitSource bits,
91                                          StringBuffer result,
92                                          int count) throws ReaderException {
93     // Each character will require 2 bytes. Read the characters as 2-byte pairs
94     // and decode as Shift_JIS afterwards
95     byte[] buffer = new byte[2 * count];
96     int offset = 0;
97     while (count > 0) {
98       // Each 13 bits encodes a 2-byte character
99       int twoBytes = bits.readBits(13);
100       int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
101       if (assembledTwoBytes < 0x01F00) {
102         // In the 0x8140 to 0x9FFC range
103         assembledTwoBytes += 0x08140;
104       } else {
105         // In the 0xE040 to 0xEBBF range
106         assembledTwoBytes += 0x0C140;
107       }
108       buffer[offset] = (byte) (assembledTwoBytes >> 8);
109       buffer[offset + 1] = (byte) assembledTwoBytes;
110       offset += 2;
111       count--;
112     }
113     // Shift_JIS may not be supported in some environments:
114     try {
115       result.append(new String(buffer, "Shift_JIS"));
116     } catch (UnsupportedEncodingException uee) {
117       throw new ReaderException("Can't decode SHIFT_JIS string: " + uee);
118     }
119   }
120
121   private static void decodeByteSegment(BitSource bits,
122                                         StringBuffer result,
123                                         int count) throws ReaderException {
124     byte[] readBytes = new byte[count];
125     if (count << 3 > bits.available()) {
126       throw new ReaderException("Count too large: " + count);
127     }
128     for (int i = 0; i < count; i++) {
129       readBytes[i] = (byte) bits.readBits(8);
130     }
131     // The spec isn't clear on this mode; see
132     // section 6.4.5: t does not say which encoding to assuming
133     // upon decoding. I have seen ISO-8859-1 used as well as
134     // Shift_JIS -- without anything like an ECI designator to
135     // give a hint.
136     String encoding = guessEncoding(readBytes);
137     try {
138       result.append(new String(readBytes, encoding));
139     } catch (UnsupportedEncodingException uce) {
140       throw new ReaderException(uce.toString());
141     }
142   }
143
144   private static void decodeAlphanumericSegment(BitSource bits,
145                                                 StringBuffer result,
146                                                 int count) {
147     // Read two characters at a time
148     while (count > 1) {
149       int nextTwoCharsBits = bits.readBits(11);
150       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
151       result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
152       count -= 2;
153     }
154     if (count == 1) {
155       // special case: one character left
156       result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
157     }
158   }
159
160   private static void decodeNumericSegment(BitSource bits,
161                                            StringBuffer result,
162                                            int count) throws ReaderException {
163     // Read three digits at a time
164     while (count >= 3) {
165       // Each 10 bits encodes three digits
166       int threeDigitsBits = bits.readBits(10);
167       if (threeDigitsBits >= 1000) {
168         throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);
169       }
170       result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
171       result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
172       result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
173       count -= 3;
174     }
175     if (count == 2) {
176       // Two digits left over to read, encoded in 7 bits
177       int twoDigitsBits = bits.readBits(7);
178       if (twoDigitsBits >= 100) {
179         throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);
180       }
181       result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
182       result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
183     } else if (count == 1) {
184       // One digit left over to read
185       int digitBits = bits.readBits(4);
186       if (digitBits >= 10) {
187         throw new ReaderException("Illegal value for digit unit: " + digitBits);
188       }
189       result.append(ALPHANUMERIC_CHARS[digitBits]);
190     }
191   }
192
193   private static String guessEncoding(byte[] bytes) {
194     if (ASSUME_SHIFT_JIS) {
195       return SHIFT_JIS;
196     }
197     // For now, merely tries to distinguish ISO-8859-1 and Shift_JIS,
198     // which should be by far the most common encodings. ISO-8859-1
199     // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
200     // uses this as a first byte of a two-byte character. If we see this
201     // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
202     int length = bytes.length;
203     for (int i = 0; i < length; i++) {
204       int value = bytes[i] & 0xFF;
205       if (value >= 0x80 && value <= 0x9F && i < length - 1) {
206         // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
207         // just double check that it is followed by a byte that's valid in
208         // the Shift_JIS encoding
209         int nextValue = bytes[i + 1] & 0xFF;
210         if ((value & 0x1) == 0) {
211           // if even,
212           if (nextValue >= 0x40 && nextValue <= 0x9E) {
213             return SHIFT_JIS;
214           }
215         } else {
216           if (nextValue >= 0x9F && nextValue <= 0x7C) {
217             return SHIFT_JIS;
218           }
219         }
220       }
221     }
222     return "ISO-8859-1";
223   }
224
225 }