2 * Copyright 2007 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.qrcode.decoder;
19 import com.google.zxing.ReaderException;
20 import com.google.zxing.common.BitSource;
21 import com.google.zxing.common.CharacterSetECI;
22 import com.google.zxing.common.DecoderResult;
24 import java.io.UnsupportedEncodingException;
25 import java.util.Vector;
28 * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
29 * in one QR Code. This class decodes the bits back into text.</p>
31 * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
35 final class DecodedBitStreamParser {
38 * See ISO 18004:2006, 6.4.4 Table 5
40 private static final char[] ALPHANUMERIC_CHARS = {
41 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
42 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
43 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
44 ' ', '$', '%', '*', '+', '-', '.', '/', ':'
46 private static final String SHIFT_JIS = "SJIS";
47 private static final String EUC_JP = "EUC_JP";
48 private static final boolean ASSUME_SHIFT_JIS;
49 private static final String UTF8 = "UTF8";
50 private static final String ISO88591 = "ISO8859_1";
53 String platformDefault = System.getProperty("file.encoding");
54 ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) || EUC_JP.equalsIgnoreCase(platformDefault);
57 private DecodedBitStreamParser() {
60 static DecoderResult decode(byte[] bytes, Version version) throws ReaderException {
61 BitSource bits = new BitSource(bytes);
62 StringBuffer result = new StringBuffer();
63 CharacterSetECI currentCharacterSetECI = null;
64 boolean fc1InEffect = false;
65 Vector byteSegments = new Vector(1);
68 // While still another segment to read...
69 if (bits.available() < 4) {
70 // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
71 mode = Mode.TERMINATOR;
73 mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
75 if (!mode.equals(Mode.TERMINATOR)) {
76 if (mode.equals(Mode.FNC1_FIRST_POSITION) || mode.equals(Mode.FNC1_SECOND_POSITION)) {
77 // We do little with FNC1 except alter the parsed result a bit according to the spec
79 } else if (mode.equals(Mode.ECI)) {
80 // Count doesn't apply to ECI
81 int value = parseECIValue(bits);
83 currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
84 } catch (IllegalArgumentException iae) {
85 // unsupported... just continue?
88 // How many characters will follow, encoded in this mode?
89 int count = bits.readBits(mode.getCharacterCountBits(version));
90 if (mode.equals(Mode.NUMERIC)) {
91 decodeNumericSegment(bits, result, count);
92 } else if (mode.equals(Mode.ALPHANUMERIC)) {
93 decodeAlphanumericSegment(bits, result, count, fc1InEffect);
94 } else if (mode.equals(Mode.BYTE)) {
95 decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments);
96 } else if (mode.equals(Mode.KANJI)) {
97 decodeKanjiSegment(bits, result, count);
99 throw new ReaderException("Unsupported mode indicator");
103 } while (!mode.equals(Mode.TERMINATOR));
105 return new DecoderResult(bytes, result.toString(), byteSegments.isEmpty() ? null : byteSegments);
108 private static void decodeKanjiSegment(BitSource bits,
110 int count) throws ReaderException {
111 // Each character will require 2 bytes. Read the characters as 2-byte pairs
112 // and decode as Shift_JIS afterwards
113 byte[] buffer = new byte[2 * count];
116 // Each 13 bits encodes a 2-byte character
117 int twoBytes = bits.readBits(13);
118 int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
119 if (assembledTwoBytes < 0x01F00) {
120 // In the 0x8140 to 0x9FFC range
121 assembledTwoBytes += 0x08140;
123 // In the 0xE040 to 0xEBBF range
124 assembledTwoBytes += 0x0C140;
126 buffer[offset] = (byte) (assembledTwoBytes >> 8);
127 buffer[offset + 1] = (byte) assembledTwoBytes;
131 // Shift_JIS may not be supported in some environments:
133 result.append(new String(buffer, SHIFT_JIS));
134 } catch (UnsupportedEncodingException uee) {
135 throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device");
139 private static void decodeByteSegment(BitSource bits,
142 CharacterSetECI currentCharacterSetECI,
143 Vector byteSegments) throws ReaderException {
144 byte[] readBytes = new byte[count];
145 if (count << 3 > bits.available()) {
146 throw new ReaderException("Count too large: " + count);
148 for (int i = 0; i < count; i++) {
149 readBytes[i] = (byte) bits.readBits(8);
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
158 encoding = guessEncoding(readBytes);
160 encoding = currentCharacterSetECI.getEncodingName();
163 result.append(new String(readBytes, encoding));
164 } catch (UnsupportedEncodingException uce) {
165 throw new ReaderException(uce.toString());
167 byteSegments.addElement(readBytes);
170 private static void decodeAlphanumericSegment(BitSource bits,
173 boolean fc1InEffect) {
174 // Read two characters at a time
175 int start = result.length();
177 int nextTwoCharsBits = bits.readBits(11);
178 result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
179 result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
183 // special case: one character left
184 result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
186 // See section 6.4.8.1, 6.4.8.2
188 // We need to massage the result a bit if in an FNC1 mode:
189 for (int i = start; i < result.length(); i++) {
190 if (result.charAt(i) == '%') {
191 if (i < result.length() - 1 && result.charAt(i + 1) == '%') {
192 // %% is rendered as %
193 result.deleteCharAt(i + 1);
195 // In alpha mode, % should be converted to FNC1 separator 0x1D
196 result.setCharAt(i, (char) 0x1D);
203 private static void decodeNumericSegment(BitSource bits,
205 int count) throws ReaderException {
206 // Read three digits at a time
208 // Each 10 bits encodes three digits
209 int threeDigitsBits = bits.readBits(10);
210 if (threeDigitsBits >= 1000) {
211 throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);
213 result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
214 result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
215 result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
219 // Two digits left over to read, encoded in 7 bits
220 int twoDigitsBits = bits.readBits(7);
221 if (twoDigitsBits >= 100) {
222 throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);
224 result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
225 result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
226 } else if (count == 1) {
227 // One digit left over to read
228 int digitBits = bits.readBits(4);
229 if (digitBits >= 10) {
230 throw new ReaderException("Illegal value for digit unit: " + digitBits);
232 result.append(ALPHANUMERIC_CHARS[digitBits]);
236 private static String guessEncoding(byte[] bytes) {
237 if (ASSUME_SHIFT_JIS) {
240 // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
241 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
244 // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
245 // which should be by far the most common encodings. ISO-8859-1
246 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
247 // uses this as a first byte of a two-byte character. If we see this
248 // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
249 // If we see something else in that second byte, we'll make the risky guess
251 int length = bytes.length;
252 boolean canBeISO88591 = true;
253 boolean canBeShiftJIS = true;
254 boolean sawDoubleByteStart = false;
255 int maybeSingleByteKatakanaCount = 0;
256 boolean lastWasPossibleDoubleByteStart = false;
257 for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) {
258 int value = bytes[i] & 0xFF;
259 if (value >= 0x7F && value <= 0x9F) {
260 canBeISO88591 = false;
262 if (value >= 0xA1 && value <= 0xDF) {
263 // count the number of characters that might be a Shift_JIS single-byte Katakana character
264 if (!lastWasPossibleDoubleByteStart) {
265 maybeSingleByteKatakanaCount++;
268 if (!lastWasPossibleDoubleByteStart && ((value >= 0xF0 && value <= 0xFF) || value == 0x80 || value == 0xA0)) {
269 canBeShiftJIS = false;
271 if (((value >= 0x81 && value <= 0x9F) || (value >= 0xE0 && value <= 0xEF)) && i < length - 1) {
272 // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid
274 sawDoubleByteStart = true;
275 if (lastWasPossibleDoubleByteStart) {
276 // If we just checked this and the last byte for being a valid double-byte
277 // char, don't check starting on this byte. If this and the last byte
278 // formed a valid pair, then this shouldn't be checked to see if it starts
279 // a double byte pair of course.
280 lastWasPossibleDoubleByteStart = false;
282 // ... otherwise do check to see if this plus the next byte form a valid
283 // double byte pair encoding a character.
284 lastWasPossibleDoubleByteStart = true;
285 int nextValue = bytes[i + 1] & 0xFF;
286 if (nextValue < 0x40 || nextValue > 0xFC) {
287 canBeShiftJIS = false;
289 // There is some conflicting information out there about which bytes can follow which in
290 // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice.
293 lastWasPossibleDoubleByteStart = false;
296 // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is:
298 // - at least one byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or
299 // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1),
300 // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS
301 if ((sawDoubleByteStart || 20 * maybeSingleByteKatakanaCount > length) && canBeShiftJIS) {
304 // Otherwise, we default to ISO-8859-1 unless we know it can't be
308 // Otherwise, we take a wild guess with UTF-8
312 private static int parseECIValue(BitSource bits) {
313 int firstByte = bits.readBits(8);
314 if ((firstByte & 0x80) == 0) {
316 return firstByte & 0x7F;
317 } else if ((firstByte & 0xC0) == 0x80) {
319 int secondByte = bits.readBits(8);
320 return ((firstByte & 0x3F) << 8) | secondByte;
321 } else if ((firstByte & 0xE0) == 0xC0) {
323 int secondThirdBytes = bits.readBits(16);
324 return ((firstByte & 0x1F) << 16) | secondThirdBytes;
326 throw new IllegalArgumentException("Bad ECI bits starting with byte " + firstByte);