You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Copyright 2012 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. #import "ZXBitSource.h"
  17. #import "ZXByteArray.h"
  18. #import "ZXCharacterSetECI.h"
  19. #import "ZXDecoderResult.h"
  20. #import "ZXErrors.h"
  21. #import "ZXQRCodeDecodedBitStreamParser.h"
  22. #import "ZXQRCodeErrorCorrectionLevel.h"
  23. #import "ZXQRCodeMode.h"
  24. #import "ZXQRCodeVersion.h"
  25. #import "ZXStringUtils.h"
  26. /**
  27. * See ISO 18004:2006, 6.4.4 Table 5
  28. */
  29. const unichar ZX_ALPHANUMERIC_CHARS[45] = {
  30. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
  31. 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
  32. 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  33. ' ', '$', '%', '*', '+', '-', '.', '/', ':'
  34. };
  35. const int ZX_GB2312_SUBSET = 1;
  36. @implementation ZXQRCodeDecodedBitStreamParser
  37. + (ZXDecoderResult *)decode:(ZXByteArray *)bytes
  38. version:(ZXQRCodeVersion *)version
  39. ecLevel:(ZXQRCodeErrorCorrectionLevel *)ecLevel
  40. hints:(ZXDecodeHints *)hints
  41. error:(NSError **)error {
  42. ZXBitSource *bits = [[ZXBitSource alloc] initWithBytes:bytes];
  43. NSMutableString *result = [NSMutableString stringWithCapacity:50];
  44. NSMutableArray *byteSegments = [NSMutableArray arrayWithCapacity:1];
  45. int symbolSequence = -1;
  46. int parityData = -1;
  47. ZXCharacterSetECI *currentCharacterSetECI = nil;
  48. ZXQRCodeMode *mode;
  49. BOOL fc1InEffect = NO;
  50. do {
  51. // While still another segment to read...
  52. if ([bits available] < 4) {
  53. // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
  54. mode = [ZXQRCodeMode terminatorMode];
  55. } else {
  56. mode = [ZXQRCodeMode forBits:[bits readBits:4]]; // mode is encoded by 4 bits
  57. if (!mode) {
  58. if (error) *error = ZXFormatErrorInstance();
  59. return nil;
  60. }
  61. }
  62. if (![mode isEqual:[ZXQRCodeMode terminatorMode]]) {
  63. if ([mode isEqual:[ZXQRCodeMode fnc1FirstPositionMode]] || [mode isEqual:[ZXQRCodeMode fnc1SecondPositionMode]]) {
  64. // We do little with FNC1 except alter the parsed result a bit according to the spec
  65. fc1InEffect = YES;
  66. } else if ([mode isEqual:[ZXQRCodeMode structuredAppendMode]]) {
  67. if (bits.available < 16) {
  68. if (error) *error = ZXFormatErrorInstance();
  69. return nil;
  70. }
  71. // sequence number and parity is added later to the result metadata
  72. // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
  73. symbolSequence = [bits readBits:8];
  74. parityData = [bits readBits:8];
  75. } else if ([mode isEqual:[ZXQRCodeMode eciMode]]) {
  76. // Count doesn't apply to ECI
  77. int value = [self parseECIValue:bits];
  78. currentCharacterSetECI = [ZXCharacterSetECI characterSetECIByValue:value];
  79. if (currentCharacterSetECI == nil) {
  80. if (error) *error = ZXFormatErrorInstance();
  81. return nil;
  82. }
  83. } else {
  84. // First handle Hanzi mode which does not start with character count
  85. if ([mode isEqual:[ZXQRCodeMode hanziMode]]) {
  86. //chinese mode contains a sub set indicator right after mode indicator
  87. int subset = [bits readBits:4];
  88. int countHanzi = [bits readBits:[mode characterCountBits:version]];
  89. if (subset == ZX_GB2312_SUBSET) {
  90. if (![self decodeHanziSegment:bits result:result count:countHanzi]) {
  91. if (error) *error = ZXFormatErrorInstance();
  92. return nil;
  93. }
  94. }
  95. } else {
  96. // "Normal" QR code modes:
  97. // How many characters will follow, encoded in this mode?
  98. int count = [bits readBits:[mode characterCountBits:version]];
  99. if ([mode isEqual:[ZXQRCodeMode numericMode]]) {
  100. if (![self decodeNumericSegment:bits result:result count:count]) {
  101. if (error) *error = ZXFormatErrorInstance();
  102. return nil;
  103. }
  104. } else if ([mode isEqual:[ZXQRCodeMode alphanumericMode]]) {
  105. if (![self decodeAlphanumericSegment:bits result:result count:count fc1InEffect:fc1InEffect]) {
  106. if (error) *error = ZXFormatErrorInstance();
  107. return nil;
  108. }
  109. } else if ([mode isEqual:[ZXQRCodeMode byteMode]]) {
  110. if (![self decodeByteSegment:bits result:result count:count currentCharacterSetECI:currentCharacterSetECI byteSegments:byteSegments hints:hints]) {
  111. if (error) *error = ZXFormatErrorInstance();
  112. return nil;
  113. }
  114. } else if ([mode isEqual:[ZXQRCodeMode kanjiMode]]) {
  115. if (![self decodeKanjiSegment:bits result:result count:count]) {
  116. if (error) *error = ZXFormatErrorInstance();
  117. return nil;
  118. }
  119. } else {
  120. if (error) *error = ZXFormatErrorInstance();
  121. return nil;
  122. }
  123. }
  124. }
  125. }
  126. } while (![mode isEqual:[ZXQRCodeMode terminatorMode]]);
  127. return [[ZXDecoderResult alloc] initWithRawBytes:bytes
  128. text:result.description
  129. byteSegments:byteSegments.count == 0 ? nil : byteSegments
  130. ecLevel:ecLevel == nil ? nil : ecLevel.description
  131. saSequence:symbolSequence
  132. saParity:parityData];
  133. }
  134. /**
  135. * See specification GBT 18284-2000
  136. */
  137. + (BOOL)decodeHanziSegment:(ZXBitSource *)bits result:(NSMutableString *)result count:(int)count {
  138. if (count * 13 > bits.available) {
  139. return NO;
  140. }
  141. NSMutableData *buffer = [NSMutableData dataWithCapacity:2 * count];
  142. while (count > 0) {
  143. int twoBytes = [bits readBits:13];
  144. int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
  145. if (assembledTwoBytes < 0x003BF) {
  146. assembledTwoBytes += 0x0A1A1;
  147. } else {
  148. assembledTwoBytes += 0x0A6A1;
  149. }
  150. int8_t bytes[2];
  151. bytes[0] = (int8_t)((assembledTwoBytes >> 8) & 0xFF);
  152. bytes[1] = (int8_t)(assembledTwoBytes & 0xFF);
  153. [buffer appendBytes:bytes length:2];
  154. count--;
  155. }
  156. NSString *string = [[NSString alloc] initWithData:buffer encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
  157. if (string) {
  158. [result appendString:string];
  159. }
  160. return YES;
  161. }
  162. + (BOOL)decodeKanjiSegment:(ZXBitSource *)bits result:(NSMutableString *)result count:(int)count {
  163. if (count * 13 > bits.available) {
  164. return NO;
  165. }
  166. NSMutableData *buffer = [NSMutableData dataWithCapacity:2 * count];
  167. while (count > 0) {
  168. int twoBytes = [bits readBits:13];
  169. int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
  170. if (assembledTwoBytes < 0x01F00) {
  171. assembledTwoBytes += 0x08140;
  172. } else {
  173. assembledTwoBytes += 0x0C140;
  174. }
  175. int8_t bytes[2];
  176. bytes[0] = (int8_t)(assembledTwoBytes >> 8);
  177. bytes[1] = (int8_t)assembledTwoBytes;
  178. [buffer appendBytes:bytes length:2];
  179. count--;
  180. }
  181. NSString *string = [[NSString alloc] initWithData:buffer encoding:NSShiftJISStringEncoding];
  182. if (string) {
  183. [result appendString:string];
  184. }
  185. return YES;
  186. }
  187. + (BOOL)decodeByteSegment:(ZXBitSource *)bits result:(NSMutableString *)result count:(int)count currentCharacterSetECI:(ZXCharacterSetECI *)currentCharacterSetECI byteSegments:(NSMutableArray *)byteSegments hints:(ZXDecodeHints *)hints {
  188. if (8 * count > bits.available) {
  189. return NO;
  190. }
  191. ZXByteArray *readBytes = [[ZXByteArray alloc] initWithLength:count];
  192. for (int i = 0; i < count; i++) {
  193. readBytes.array[i] = (int8_t)[bits readBits:8];
  194. }
  195. NSStringEncoding encoding;
  196. if (currentCharacterSetECI == nil) {
  197. encoding = [ZXStringUtils guessEncoding:readBytes hints:hints];
  198. } else {
  199. encoding = [currentCharacterSetECI encoding];
  200. }
  201. NSString *string = [[NSString alloc] initWithBytes:readBytes.array length:readBytes.length encoding:encoding];
  202. if (string) {
  203. [result appendString:string];
  204. }
  205. [byteSegments addObject:readBytes];
  206. return YES;
  207. }
  208. + (unichar)toAlphaNumericChar:(int)value {
  209. if (value >= 45) {
  210. return -1;
  211. }
  212. return ZX_ALPHANUMERIC_CHARS[value];
  213. }
  214. + (BOOL)decodeAlphanumericSegment:(ZXBitSource *)bits result:(NSMutableString *)result count:(int)count fc1InEffect:(BOOL)fc1InEffect {
  215. int start = (int)result.length;
  216. while (count > 1) {
  217. if ([bits available] < 11) {
  218. return NO;
  219. }
  220. int nextTwoCharsBits = [bits readBits:11];
  221. unichar next1 = [self toAlphaNumericChar:nextTwoCharsBits / 45];
  222. unichar next2 = [self toAlphaNumericChar:nextTwoCharsBits % 45];
  223. [result appendFormat:@"%C%C", next1, next2];
  224. count -= 2;
  225. }
  226. if (count == 1) {
  227. if ([bits available] < 6) {
  228. return NO;
  229. }
  230. unichar next1 = [self toAlphaNumericChar:[bits readBits:6]];
  231. [result appendFormat:@"%C", next1];
  232. }
  233. if (fc1InEffect) {
  234. for (int i = start; i < [result length]; i++) {
  235. if ([result characterAtIndex:i] == '%') {
  236. if (i < [result length] - 1 && [result characterAtIndex:i + 1] == '%') {
  237. [result deleteCharactersInRange:NSMakeRange(i + 1, 1)];
  238. } else {
  239. [result insertString:[NSString stringWithFormat:@"%C", (unichar)0x1D]
  240. atIndex:i];
  241. }
  242. }
  243. }
  244. }
  245. return YES;
  246. }
  247. + (BOOL)decodeNumericSegment:(ZXBitSource *)bits result:(NSMutableString *)result count:(int)count {
  248. // Read three digits at a time
  249. while (count >= 3) {
  250. // Each 10 bits encodes three digits
  251. if (bits.available < 10) {
  252. return NO;
  253. }
  254. int threeDigitsBits = [bits readBits:10];
  255. if (threeDigitsBits >= 1000) {
  256. return NO;
  257. }
  258. unichar next1 = [self toAlphaNumericChar:threeDigitsBits / 100];
  259. unichar next2 = [self toAlphaNumericChar:(threeDigitsBits / 10) % 10];
  260. unichar next3 = [self toAlphaNumericChar:threeDigitsBits % 10];
  261. [result appendFormat:@"%C%C%C", next1, next2, next3];
  262. count -= 3;
  263. }
  264. if (count == 2) {
  265. // Two digits left over to read, encoded in 7 bits
  266. if (bits.available < 7) {
  267. return NO;
  268. }
  269. int twoDigitsBits = [bits readBits:7];
  270. if (twoDigitsBits >= 100) {
  271. return NO;
  272. }
  273. unichar next1 = [self toAlphaNumericChar:twoDigitsBits / 10];
  274. unichar next2 = [self toAlphaNumericChar:twoDigitsBits % 10];
  275. [result appendFormat:@"%C%C", next1, next2];
  276. } else if (count == 1) {
  277. // One digit left over to read
  278. if (bits.available < 4) {
  279. return NO;
  280. }
  281. int digitBits = [bits readBits:4];
  282. if (digitBits >= 10) {
  283. return NO;
  284. }
  285. unichar next1 = [self toAlphaNumericChar:digitBits];
  286. [result appendFormat:@"%C", next1];
  287. }
  288. return YES;
  289. }
  290. + (int)parseECIValue:(ZXBitSource *)bits {
  291. int firstByte = [bits readBits:8];
  292. if ((firstByte & 0x80) == 0) {
  293. return firstByte & 0x7F;
  294. }
  295. if ((firstByte & 0xC0) == 0x80) {
  296. int secondByte = [bits readBits:8];
  297. return ((firstByte & 0x3F) << 8) | secondByte;
  298. }
  299. if ((firstByte & 0xE0) == 0xC0) {
  300. int secondThirdBytes = [bits readBits:16];
  301. return ((firstByte & 0x1F) << 16) | secondThirdBytes;
  302. }
  303. return -1;
  304. }
  305. @end