PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/silverlight/qrcode/decoder/DecodedBitStreamParser.cs

https://bitbucket.org/jrasanen/silverlightzxing
C# | 447 lines | 331 code | 14 blank | 102 comment | 100 complexity | 4c7863b1cc346cf88bbece4a8e096532 MD5 | raw file
  1. /*
  2. * Copyright 2007 ZXing authors
  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. using System;
  17. using ReaderException = com.google.zxing.ReaderException;
  18. using BitSource = com.google.zxing.common.BitSource;
  19. using CharacterSetECI = com.google.zxing.common.CharacterSetECI;
  20. using DecoderResult = com.google.zxing.common.DecoderResult;
  21. namespace com.google.zxing.qrcode.decoder
  22. {
  23. /// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
  24. /// in one QR Code. This class decodes the bits back into text.</p>
  25. ///
  26. /// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
  27. ///
  28. /// </summary>
  29. /// <author> Sean Owen
  30. /// </author>
  31. /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
  32. /// </author>
  33. sealed class DecodedBitStreamParser
  34. {
  35. /// <summary> See ISO 18004:2006, 6.4.4 Table 5</summary>
  36. //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'"
  37. 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', ' ', '$', '%', '*', '+', '-', '.', '/', ':'};
  38. private const System.String SHIFT_JIS = "SJIS";
  39. private const System.String EUC_JP = "EUC_JP";
  40. private static bool ASSUME_SHIFT_JIS;
  41. private const System.String UTF8 = "UTF8";
  42. // Redivivus.in Java to c# Porting update
  43. // 30/01/2010
  44. // Commented & Added
  45. private const System.String ISO88591 = "ISO-8859-1";
  46. private DecodedBitStreamParser()
  47. {
  48. }
  49. internal static DecoderResult decode(sbyte[] bytes, Version version, ErrorCorrectionLevel ecLevel)
  50. {
  51. BitSource bits = new BitSource(bytes);
  52. System.Text.StringBuilder result = new System.Text.StringBuilder(50);
  53. CharacterSetECI currentCharacterSetECI = null;
  54. bool fc1InEffect = false;
  55. System.Collections.Generic.List<Object> byteSegments = new System.Collections.Generic.List<Object>(1);
  56. Mode mode;
  57. do
  58. {
  59. // While still another segment to read...
  60. if (bits.available() < 4)
  61. {
  62. // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
  63. mode = Mode.TERMINATOR;
  64. }
  65. else
  66. {
  67. try
  68. {
  69. mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
  70. }
  71. catch (System.ArgumentException iae)
  72. {
  73. throw ReaderException.Instance;
  74. }
  75. }
  76. if (!mode.Equals(Mode.TERMINATOR))
  77. {
  78. if (mode.Equals(Mode.FNC1_FIRST_POSITION) || mode.Equals(Mode.FNC1_SECOND_POSITION))
  79. {
  80. // We do little with FNC1 except alter the parsed result a bit according to the spec
  81. fc1InEffect = true;
  82. }
  83. else if (mode.Equals(Mode.STRUCTURED_APPEND))
  84. {
  85. // not really supported; all we do is ignore it
  86. // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
  87. bits.readBits(16);
  88. }
  89. else if (mode.Equals(Mode.ECI))
  90. {
  91. // Count doesn't apply to ECI
  92. int value_Renamed = parseECIValue(bits);
  93. currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value_Renamed);
  94. if (currentCharacterSetECI == null)
  95. {
  96. throw ReaderException.Instance;
  97. }
  98. }
  99. else
  100. {
  101. // How many characters will follow, encoded in this mode?
  102. int count = bits.readBits(mode.getCharacterCountBits(version));
  103. if (mode.Equals(Mode.NUMERIC))
  104. {
  105. decodeNumericSegment(bits, result, count);
  106. }
  107. else if (mode.Equals(Mode.ALPHANUMERIC))
  108. {
  109. decodeAlphanumericSegment(bits, result, count, fc1InEffect);
  110. }
  111. else if (mode.Equals(Mode.BYTE))
  112. {
  113. decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments);
  114. }
  115. else if (mode.Equals(Mode.KANJI))
  116. {
  117. decodeKanjiSegment(bits, result, count);
  118. }
  119. else
  120. {
  121. throw ReaderException.Instance;
  122. }
  123. }
  124. }
  125. }
  126. while (!mode.Equals(Mode.TERMINATOR));
  127. return new DecoderResult(bytes, result.ToString(), (byteSegments.Count == 0)?null:byteSegments, ecLevel);
  128. }
  129. private static void decodeKanjiSegment(BitSource bits, System.Text.StringBuilder result, int count)
  130. {
  131. // Each character will require 2 bytes. Read the characters as 2-byte pairs
  132. // and decode as Shift_JIS afterwards
  133. sbyte[] buffer = new sbyte[2 * count];
  134. int offset = 0;
  135. while (count > 0)
  136. {
  137. // Each 13 bits encodes a 2-byte character
  138. int twoBytes = bits.readBits(13);
  139. int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
  140. if (assembledTwoBytes < 0x01F00)
  141. {
  142. // In the 0x8140 to 0x9FFC range
  143. assembledTwoBytes += 0x08140;
  144. }
  145. else
  146. {
  147. // In the 0xE040 to 0xEBBF range
  148. assembledTwoBytes += 0x0C140;
  149. }
  150. buffer[offset] = (sbyte) (assembledTwoBytes >> 8);
  151. buffer[offset + 1] = (sbyte) assembledTwoBytes;
  152. offset += 2;
  153. count--;
  154. }
  155. // Shift_JIS may not be supported in some environments:
  156. try
  157. {
  158. //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'"
  159. //result.Append(System.Text.Encoding.GetEncoding(SHIFT_JIS).GetString(SupportClass.ToByteArray(buffer)));
  160. byte[] inputBytes =SupportClass.ToByteArray(buffer);
  161. //Marauderz : Errrr... what if this thing isn't Null terminated?
  162. result.Append(System.Text.Encoding.UTF8.GetString(inputBytes,0,inputBytes.Length));
  163. }
  164. catch (System.IO.IOException uee)
  165. {
  166. throw ReaderException.Instance;
  167. }
  168. }
  169. private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count, CharacterSetECI currentCharacterSetECI, System.Collections.Generic.List<Object> byteSegments)
  170. {
  171. sbyte[] readBytes = new sbyte[count];
  172. if (count << 3 > bits.available())
  173. {
  174. throw ReaderException.Instance;
  175. }
  176. for (int i = 0; i < count; i++)
  177. {
  178. readBytes[i] = (sbyte) bits.readBits(8);
  179. }
  180. System.String encoding;
  181. if (currentCharacterSetECI == null)
  182. {
  183. // The spec isn't clear on this mode; see
  184. // section 6.4.5: t does not say which encoding to assuming
  185. // upon decoding. I have seen ISO-8859-1 used as well as
  186. // Shift_JIS -- without anything like an ECI designator to
  187. // give a hint.
  188. encoding = guessEncoding(readBytes);
  189. }
  190. else
  191. {
  192. encoding = currentCharacterSetECI.EncodingName;
  193. }
  194. try
  195. {
  196. //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'"
  197. //Marauderz : Switching to UTF 8 encoding
  198. //result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(SupportClass.ToByteArray(readBytes)));
  199. byte[] inputBytes =SupportClass.ToByteArray(readBytes);
  200. //Marauderz : Errrr... what if this thing isn't Null terminated?
  201. result.Append(System.Text.Encoding.UTF8.GetString(inputBytes,0,inputBytes.Length));
  202. }
  203. catch (System.IO.IOException uce)
  204. {
  205. throw ReaderException.Instance;
  206. }
  207. byteSegments.Add(SupportClass.ToByteArray(readBytes));
  208. }
  209. private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count, bool fc1InEffect)
  210. {
  211. // Read two characters at a time
  212. int start = result.Length;
  213. while (count > 1)
  214. {
  215. int nextTwoCharsBits = bits.readBits(11);
  216. result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
  217. result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
  218. count -= 2;
  219. }
  220. if (count == 1)
  221. {
  222. // special case: one character left
  223. result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
  224. }
  225. // See section 6.4.8.1, 6.4.8.2
  226. if (fc1InEffect)
  227. {
  228. // We need to massage the result a bit if in an FNC1 mode:
  229. for (int i = start; i < result.Length; i++)
  230. {
  231. if (result[i] == '%')
  232. {
  233. if (i < result.Length - 1 && result[i + 1] == '%')
  234. {
  235. // %% is rendered as %
  236. result.Remove(i + 1, 1);
  237. }
  238. else
  239. {
  240. // In alpha mode, % should be converted to FNC1 separator 0x1D
  241. result[i] = (char) 0x1D;
  242. }
  243. }
  244. }
  245. }
  246. }
  247. private static void decodeNumericSegment(BitSource bits, System.Text.StringBuilder result, int count)
  248. {
  249. // Read three digits at a time
  250. while (count >= 3)
  251. {
  252. // Each 10 bits encodes three digits
  253. int threeDigitsBits = bits.readBits(10);
  254. if (threeDigitsBits >= 1000)
  255. {
  256. throw ReaderException.Instance;
  257. }
  258. result.Append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
  259. result.Append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
  260. result.Append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
  261. count -= 3;
  262. }
  263. if (count == 2)
  264. {
  265. // Two digits left over to read, encoded in 7 bits
  266. int twoDigitsBits = bits.readBits(7);
  267. if (twoDigitsBits >= 100)
  268. {
  269. throw ReaderException.Instance;
  270. }
  271. result.Append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
  272. result.Append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
  273. }
  274. else if (count == 1)
  275. {
  276. // One digit left over to read
  277. int digitBits = bits.readBits(4);
  278. if (digitBits >= 10)
  279. {
  280. throw ReaderException.Instance;
  281. }
  282. result.Append(ALPHANUMERIC_CHARS[digitBits]);
  283. }
  284. }
  285. private static System.String guessEncoding(sbyte[] bytes)
  286. {
  287. if (ASSUME_SHIFT_JIS)
  288. {
  289. return SHIFT_JIS;
  290. }
  291. // Does it start with the UTF-8 byte order mark? then guess it's UTF-8
  292. if (bytes.Length > 3 && bytes[0] == (sbyte) SupportClass.Identity(0xEF) && bytes[1] == (sbyte) SupportClass.Identity(0xBB) && bytes[2] == (sbyte) SupportClass.Identity(0xBF))
  293. {
  294. return UTF8;
  295. }
  296. // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
  297. // which should be by far the most common encodings. ISO-8859-1
  298. // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
  299. // uses this as a first byte of a two-byte character. If we see this
  300. // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
  301. // If we see something else in that second byte, we'll make the risky guess
  302. // that it's UTF-8.
  303. int length = bytes.Length;
  304. bool canBeISO88591 = true;
  305. bool canBeShiftJIS = true;
  306. int maybeDoubleByteCount = 0;
  307. int maybeSingleByteKatakanaCount = 0;
  308. bool sawLatin1Supplement = false;
  309. bool lastWasPossibleDoubleByteStart = false;
  310. for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++)
  311. {
  312. int value_Renamed = bytes[i] & 0xFF;
  313. if ((value_Renamed == 0xC2 || value_Renamed == 0xC3) && i < length - 1)
  314. {
  315. // This is really a poor hack. The slightly more exotic characters people might want to put in
  316. // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings
  317. // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF].
  318. int nextValue = bytes[i + 1] & 0xFF;
  319. if (nextValue <= 0xBF && ((value_Renamed == 0xC2 && nextValue >= 0xA0) || (value_Renamed == 0xC3 && nextValue >= 0x80)))
  320. {
  321. sawLatin1Supplement = true;
  322. }
  323. }
  324. if (value_Renamed >= 0x7F && value_Renamed <= 0x9F)
  325. {
  326. canBeISO88591 = false;
  327. }
  328. if (value_Renamed >= 0xA1 && value_Renamed <= 0xDF)
  329. {
  330. // count the number of characters that might be a Shift_JIS single-byte Katakana character
  331. if (!lastWasPossibleDoubleByteStart)
  332. {
  333. maybeSingleByteKatakanaCount++;
  334. }
  335. }
  336. if (!lastWasPossibleDoubleByteStart && ((value_Renamed >= 0xF0 && value_Renamed <= 0xFF) || value_Renamed == 0x80 || value_Renamed == 0xA0))
  337. {
  338. canBeShiftJIS = false;
  339. }
  340. if (((value_Renamed >= 0x81 && value_Renamed <= 0x9F) || (value_Renamed >= 0xE0 && value_Renamed <= 0xEF)))
  341. {
  342. // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid
  343. // second byte.
  344. if (lastWasPossibleDoubleByteStart)
  345. {
  346. // If we just checked this and the last byte for being a valid double-byte
  347. // char, don't check starting on this byte. If this and the last byte
  348. // formed a valid pair, then this shouldn't be checked to see if it starts
  349. // a double byte pair of course.
  350. lastWasPossibleDoubleByteStart = false;
  351. }
  352. else
  353. {
  354. // ... otherwise do check to see if this plus the next byte form a valid
  355. // double byte pair encoding a character.
  356. lastWasPossibleDoubleByteStart = true;
  357. if (i >= bytes.Length - 1)
  358. {
  359. canBeShiftJIS = false;
  360. }
  361. else
  362. {
  363. int nextValue = bytes[i + 1] & 0xFF;
  364. if (nextValue < 0x40 || nextValue > 0xFC)
  365. {
  366. canBeShiftJIS = false;
  367. }
  368. else
  369. {
  370. maybeDoubleByteCount++;
  371. }
  372. // There is some conflicting information out there about which bytes can follow which in
  373. // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice.
  374. }
  375. }
  376. }
  377. else
  378. {
  379. lastWasPossibleDoubleByteStart = false;
  380. }
  381. }
  382. // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is:
  383. // - If we saw
  384. // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or
  385. // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1),
  386. // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS
  387. if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length))
  388. {
  389. return SHIFT_JIS;
  390. }
  391. // Otherwise, we default to ISO-8859-1 unless we know it can't be
  392. if (!sawLatin1Supplement && canBeISO88591)
  393. {
  394. return ISO88591;
  395. }
  396. // Otherwise, we take a wild guess with UTF-8
  397. return UTF8;
  398. }
  399. private static int parseECIValue(BitSource bits)
  400. {
  401. int firstByte = bits.readBits(8);
  402. if ((firstByte & 0x80) == 0)
  403. {
  404. // just one byte
  405. return firstByte & 0x7F;
  406. }
  407. else if ((firstByte & 0xC0) == 0x80)
  408. {
  409. // two bytes
  410. int secondByte = bits.readBits(8);
  411. return ((firstByte & 0x3F) << 8) | secondByte;
  412. }
  413. else if ((firstByte & 0xE0) == 0xC0)
  414. {
  415. // three bytes
  416. int secondThirdBytes = bits.readBits(16);
  417. return ((firstByte & 0x1F) << 16) | secondThirdBytes;
  418. }
  419. throw new System.ArgumentException("Bad ECI bits starting with byte " + firstByte);
  420. }
  421. static DecodedBitStreamParser()
  422. {
  423. {
  424. // Redivivus.in Java to c# Porting update
  425. // 30/01/2010
  426. // Commented & Added
  427. //System.String platformDefault = System_Renamed.getProperty("file.encoding");
  428. //ASSUME_SHIFT_JIS = SHIFT_JIS.ToUpper().Equals(platformDefault.ToUpper()) || EUC_JP.ToUpper().Equals(platformDefault.ToUpper());
  429. ASSUME_SHIFT_JIS = false;
  430. }
  431. }
  432. }
  433. }