2 * Copyright 2007 ZXing authors
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
17 using ReaderException = com.google.zxing.ReaderException;
\r
18 using BitSource = com.google.zxing.common.BitSource;
\r
19 using CharacterSetECI = com.google.zxing.common.CharacterSetECI;
\r
20 using DecoderResult = com.google.zxing.common.DecoderResult;
\r
21 namespace com.google.zxing.qrcode.decoder
\r
24 /// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
\r
25 /// in one QR Code. This class decodes the bits back into text.</p>
\r
27 /// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
\r
30 /// <author> Sean Owen
\r
32 /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
\r
34 sealed class DecodedBitStreamParser
\r
37 /// <summary> See ISO 18004:2006, 6.4.4 Table 5</summary>
\r
38 //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
\r
39 private static readonly char[] ALPHANUMERIC_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'};
\r
40 private const System.String SHIFT_JIS = "SJIS";
\r
41 private const System.String EUC_JP = "EUC_JP";
\r
42 private static bool ASSUME_SHIFT_JIS;
\r
43 private const System.String UTF8 = "UTF8";
\r
44 // Redivivus.in Java to c# Porting update
\r
46 // Commented & Added
\r
47 private const System.String ISO88591 = "ISO-8859-1";
\r
49 private DecodedBitStreamParser()
\r
53 internal static DecoderResult decode(sbyte[] bytes, Version version, ErrorCorrectionLevel ecLevel)
\r
55 BitSource bits = new BitSource(bytes);
\r
56 System.Text.StringBuilder result = new System.Text.StringBuilder(50);
\r
57 CharacterSetECI currentCharacterSetECI = null;
\r
58 bool fc1InEffect = false;
\r
59 System.Collections.ArrayList byteSegments = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(1));
\r
63 // While still another segment to read...
\r
64 if (bits.available() < 4)
\r
66 // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
\r
67 mode = Mode.TERMINATOR;
\r
73 mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
\r
75 catch (System.ArgumentException iae)
\r
77 throw ReaderException.Instance;
\r
80 if (!mode.Equals(Mode.TERMINATOR))
\r
82 if (mode.Equals(Mode.FNC1_FIRST_POSITION) || mode.Equals(Mode.FNC1_SECOND_POSITION))
\r
84 // We do little with FNC1 except alter the parsed result a bit according to the spec
\r
87 else if (mode.Equals(Mode.STRUCTURED_APPEND))
\r
89 // not really supported; all we do is ignore it
\r
90 // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
\r
93 else if (mode.Equals(Mode.ECI))
\r
95 // Count doesn't apply to ECI
\r
96 int value_Renamed = parseECIValue(bits);
\r
97 currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value_Renamed);
\r
98 if (currentCharacterSetECI == null)
\r
100 throw ReaderException.Instance;
\r
105 // How many characters will follow, encoded in this mode?
\r
106 int count = bits.readBits(mode.getCharacterCountBits(version));
\r
107 if (mode.Equals(Mode.NUMERIC))
\r
109 decodeNumericSegment(bits, result, count);
\r
111 else if (mode.Equals(Mode.ALPHANUMERIC))
\r
113 decodeAlphanumericSegment(bits, result, count, fc1InEffect);
\r
115 else if (mode.Equals(Mode.BYTE))
\r
117 decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments);
\r
119 else if (mode.Equals(Mode.KANJI))
\r
121 decodeKanjiSegment(bits, result, count);
\r
125 throw ReaderException.Instance;
\r
130 while (!mode.Equals(Mode.TERMINATOR));
\r
132 return new DecoderResult(bytes, result.ToString(), (byteSegments.Count == 0)?null:byteSegments, ecLevel);
\r
135 private static void decodeKanjiSegment(BitSource bits, System.Text.StringBuilder result, int count)
\r
137 // Each character will require 2 bytes. Read the characters as 2-byte pairs
\r
138 // and decode as Shift_JIS afterwards
\r
139 sbyte[] buffer = new sbyte[2 * count];
\r
143 // Each 13 bits encodes a 2-byte character
\r
144 int twoBytes = bits.readBits(13);
\r
145 int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
\r
146 if (assembledTwoBytes < 0x01F00)
\r
148 // In the 0x8140 to 0x9FFC range
\r
149 assembledTwoBytes += 0x08140;
\r
153 // In the 0xE040 to 0xEBBF range
\r
154 assembledTwoBytes += 0x0C140;
\r
156 buffer[offset] = (sbyte) (assembledTwoBytes >> 8);
\r
157 buffer[offset + 1] = (sbyte) assembledTwoBytes;
\r
161 // Shift_JIS may not be supported in some environments:
\r
164 //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
\r
165 result.Append(System.Text.Encoding.GetEncoding(SHIFT_JIS).GetString(SupportClass.ToByteArray(buffer)));
\r
167 catch (System.IO.IOException uee)
\r
169 throw ReaderException.Instance;
\r
173 private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count, CharacterSetECI currentCharacterSetECI, System.Collections.ArrayList byteSegments)
\r
175 sbyte[] readBytes = new sbyte[count];
\r
176 if (count << 3 > bits.available())
\r
178 throw ReaderException.Instance;
\r
180 for (int i = 0; i < count; i++)
\r
182 readBytes[i] = (sbyte) bits.readBits(8);
\r
184 System.String encoding;
\r
185 if (currentCharacterSetECI == null)
\r
187 // The spec isn't clear on this mode; see
\r
188 // section 6.4.5: t does not say which encoding to assuming
\r
189 // upon decoding. I have seen ISO-8859-1 used as well as
\r
190 // Shift_JIS -- without anything like an ECI designator to
\r
192 encoding = guessEncoding(readBytes);
\r
196 encoding = currentCharacterSetECI.EncodingName;
\r
200 //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
\r
201 result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(SupportClass.ToByteArray(readBytes)));
\r
203 catch (System.IO.IOException uce)
\r
205 throw ReaderException.Instance;
\r
207 byteSegments.Add(SupportClass.ToByteArray(readBytes));
\r
210 private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count, bool fc1InEffect)
\r
212 // Read two characters at a time
\r
213 int start = result.Length;
\r
216 int nextTwoCharsBits = bits.readBits(11);
\r
217 result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
\r
218 result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
\r
223 // special case: one character left
\r
224 result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
\r
226 // See section 6.4.8.1, 6.4.8.2
\r
229 // We need to massage the result a bit if in an FNC1 mode:
\r
230 for (int i = start; i < result.Length; i++)
\r
232 if (result[i] == '%')
\r
234 if (i < result.Length - 1 && result[i + 1] == '%')
\r
236 // %% is rendered as %
\r
237 result.Remove(i + 1, 1);
\r
241 // In alpha mode, % should be converted to FNC1 separator 0x1D
\r
242 result[i] = (char) 0x1D;
\r
249 private static void decodeNumericSegment(BitSource bits, System.Text.StringBuilder result, int count)
\r
251 // Read three digits at a time
\r
254 // Each 10 bits encodes three digits
\r
255 int threeDigitsBits = bits.readBits(10);
\r
256 if (threeDigitsBits >= 1000)
\r
258 throw ReaderException.Instance;
\r
260 result.Append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
\r
261 result.Append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
\r
262 result.Append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
\r
267 // Two digits left over to read, encoded in 7 bits
\r
268 int twoDigitsBits = bits.readBits(7);
\r
269 if (twoDigitsBits >= 100)
\r
271 throw ReaderException.Instance;
\r
273 result.Append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
\r
274 result.Append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
\r
276 else if (count == 1)
\r
278 // One digit left over to read
\r
279 int digitBits = bits.readBits(4);
\r
280 if (digitBits >= 10)
\r
282 throw ReaderException.Instance;
\r
284 result.Append(ALPHANUMERIC_CHARS[digitBits]);
\r
288 private static System.String guessEncoding(sbyte[] bytes)
\r
290 if (ASSUME_SHIFT_JIS)
\r
294 // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
\r
295 if (bytes.Length > 3 && bytes[0] == (sbyte) SupportClass.Identity(0xEF) && bytes[1] == (sbyte) SupportClass.Identity(0xBB) && bytes[2] == (sbyte) SupportClass.Identity(0xBF))
\r
299 // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
\r
300 // which should be by far the most common encodings. ISO-8859-1
\r
301 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
\r
302 // uses this as a first byte of a two-byte character. If we see this
\r
303 // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
\r
304 // If we see something else in that second byte, we'll make the risky guess
\r
305 // that it's UTF-8.
\r
306 int length = bytes.Length;
\r
307 bool canBeISO88591 = true;
\r
308 bool canBeShiftJIS = true;
\r
309 int maybeDoubleByteCount = 0;
\r
310 int maybeSingleByteKatakanaCount = 0;
\r
311 bool sawLatin1Supplement = false;
\r
312 bool lastWasPossibleDoubleByteStart = false;
\r
313 for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++)
\r
315 int value_Renamed = bytes[i] & 0xFF;
\r
316 if ((value_Renamed == 0xC2 || value_Renamed == 0xC3) && i < length - 1)
\r
318 // This is really a poor hack. The slightly more exotic characters people might want to put in
\r
319 // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings
\r
320 // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF].
\r
321 int nextValue = bytes[i + 1] & 0xFF;
\r
322 if (nextValue <= 0xBF && ((value_Renamed == 0xC2 && nextValue >= 0xA0) || (value_Renamed == 0xC3 && nextValue >= 0x80)))
\r
324 sawLatin1Supplement = true;
\r
327 if (value_Renamed >= 0x7F && value_Renamed <= 0x9F)
\r
329 canBeISO88591 = false;
\r
331 if (value_Renamed >= 0xA1 && value_Renamed <= 0xDF)
\r
333 // count the number of characters that might be a Shift_JIS single-byte Katakana character
\r
334 if (!lastWasPossibleDoubleByteStart)
\r
336 maybeSingleByteKatakanaCount++;
\r
339 if (!lastWasPossibleDoubleByteStart && ((value_Renamed >= 0xF0 && value_Renamed <= 0xFF) || value_Renamed == 0x80 || value_Renamed == 0xA0))
\r
341 canBeShiftJIS = false;
\r
343 if (((value_Renamed >= 0x81 && value_Renamed <= 0x9F) || (value_Renamed >= 0xE0 && value_Renamed <= 0xEF)))
\r
345 // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid
\r
347 if (lastWasPossibleDoubleByteStart)
\r
349 // If we just checked this and the last byte for being a valid double-byte
\r
350 // char, don't check starting on this byte. If this and the last byte
\r
351 // formed a valid pair, then this shouldn't be checked to see if it starts
\r
352 // a double byte pair of course.
\r
353 lastWasPossibleDoubleByteStart = false;
\r
357 // ... otherwise do check to see if this plus the next byte form a valid
\r
358 // double byte pair encoding a character.
\r
359 lastWasPossibleDoubleByteStart = true;
\r
360 if (i >= bytes.Length - 1)
\r
362 canBeShiftJIS = false;
\r
366 int nextValue = bytes[i + 1] & 0xFF;
\r
367 if (nextValue < 0x40 || nextValue > 0xFC)
\r
369 canBeShiftJIS = false;
\r
373 maybeDoubleByteCount++;
\r
375 // There is some conflicting information out there about which bytes can follow which in
\r
376 // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice.
\r
382 lastWasPossibleDoubleByteStart = false;
\r
385 // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is:
\r
387 // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or
\r
388 // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1),
\r
389 // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS
\r
390 if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length))
\r
394 // Otherwise, we default to ISO-8859-1 unless we know it can't be
\r
395 if (!sawLatin1Supplement && canBeISO88591)
\r
399 // Otherwise, we take a wild guess with UTF-8
\r
403 private static int parseECIValue(BitSource bits)
\r
405 int firstByte = bits.readBits(8);
\r
406 if ((firstByte & 0x80) == 0)
\r
409 return firstByte & 0x7F;
\r
411 else if ((firstByte & 0xC0) == 0x80)
\r
414 int secondByte = bits.readBits(8);
\r
415 return ((firstByte & 0x3F) << 8) | secondByte;
\r
417 else if ((firstByte & 0xE0) == 0xC0)
\r
420 int secondThirdBytes = bits.readBits(16);
\r
421 return ((firstByte & 0x1F) << 16) | secondThirdBytes;
\r
423 throw new System.ArgumentException("Bad ECI bits starting with byte " + firstByte);
\r
425 static DecodedBitStreamParser()
\r
428 // Redivivus.in Java to c# Porting update
\r
430 // Commented & Added
\r
431 //System.String platformDefault = System_Renamed.getProperty("file.encoding");
\r
432 //ASSUME_SHIFT_JIS = SHIFT_JIS.ToUpper().Equals(platformDefault.ToUpper()) || EUC_JP.ToUpper().Equals(platformDefault.ToUpper());
\r
433 ASSUME_SHIFT_JIS = false;
\r