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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 "ZXBitArray.h"
  17. #import "ZXCodaBarReader.h"
  18. #import "ZXDecodeHints.h"
  19. #import "ZXErrors.h"
  20. #import "ZXIntArray.h"
  21. #import "ZXResult.h"
  22. #import "ZXResultPoint.h"
  23. // These values are critical for determining how permissive the decoding
  24. // will be. All stripe sizes must be within the window these define, as
  25. // compared to the average stripe size.
  26. static float ZX_CODA_MAX_ACCEPTABLE = 2.0f;
  27. static float ZX_CODA_PADDING = 1.5f;
  28. const unichar ZX_CODA_ALPHABET[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  29. '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};
  30. const int ZX_CODA_ALPHABET_LEN = sizeof(ZX_CODA_ALPHABET) / sizeof(unichar);
  31. /**
  32. * These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
  33. * each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow.
  34. */
  35. const int ZX_CODA_CHARACTER_ENCODINGS[] = {
  36. 0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
  37. 0x00c, 0x018, 0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
  38. };
  39. // minimal number of characters that should be present (inclusing start and stop characters)
  40. // under normal circumstances this should be set to 3, but can be set higher
  41. // as a last-ditch attempt to reduce false positives.
  42. const int ZX_CODA_MIN_CHARACTER_LENGTH = 3;
  43. // official start and end patterns
  44. const unichar ZX_CODA_STARTEND_ENCODING[] = {'A', 'B', 'C', 'D'};
  45. // some codabar generator allow the codabar string to be closed by every
  46. // character. This will cause lots of false positives!
  47. // some industries use a checksum standard but this is not part of the original codabar standard
  48. // for more information see : http://www.mecsw.com/specs/codabar.html
  49. @interface ZXCodaBarReader ()
  50. @property (nonatomic, strong) NSMutableString *decodeRowResult;
  51. @property (nonatomic, strong) ZXIntArray *counters;
  52. @property (nonatomic, assign) int counterLength;
  53. @end
  54. @implementation ZXCodaBarReader
  55. - (id)init {
  56. if (self = [super init]) {
  57. _decodeRowResult = [NSMutableString stringWithCapacity:20];
  58. _counters = [[ZXIntArray alloc] initWithLength:80];
  59. _counterLength = 0;
  60. }
  61. return self;
  62. }
  63. - (ZXResult *)decodeRow:(int)rowNumber row:(ZXBitArray *)row hints:(ZXDecodeHints *)hints error:(NSError **)error {
  64. [self.counters clear];
  65. if (![self setCountersWithRow:row]) {
  66. if (error) *error = ZXNotFoundErrorInstance();
  67. return nil;
  68. }
  69. int startOffset = [self findStartPattern];
  70. if (startOffset == -1) {
  71. if (error) *error = ZXNotFoundErrorInstance();
  72. return nil;
  73. }
  74. int nextStart = startOffset;
  75. self.decodeRowResult = [NSMutableString string];
  76. do {
  77. int charOffset = [self toNarrowWidePattern:nextStart];
  78. if (charOffset == -1) {
  79. if (error) *error = ZXNotFoundErrorInstance();
  80. return nil;
  81. }
  82. // Hack: We store the position in the alphabet table into a
  83. // NSMutableString, so that we can access the decoded patterns in
  84. // validatePattern. We'll translate to the actual characters later.
  85. [self.decodeRowResult appendFormat:@"%C", (unichar)charOffset];
  86. nextStart += 8;
  87. // Stop as soon as we see the end character.
  88. if (self.decodeRowResult.length > 1 &&
  89. [ZXCodaBarReader arrayContains:ZX_CODA_STARTEND_ENCODING
  90. length:sizeof(ZX_CODA_STARTEND_ENCODING) / sizeof(unichar)
  91. key:ZX_CODA_ALPHABET[charOffset]]) {
  92. break;
  93. }
  94. } while (nextStart < self.counterLength); // no fixed end pattern so keep on reading while data is available
  95. // Look for whitespace after pattern:
  96. int trailingWhitespace = self.counters.array[nextStart - 1];
  97. int lastPatternSize = 0;
  98. for (int i = -8; i < -1; i++) {
  99. lastPatternSize += self.counters.array[nextStart + i];
  100. }
  101. // We need to see whitespace equal to 50% of the last pattern size,
  102. // otherwise this is probably a false positive. The exception is if we are
  103. // at the end of the row. (I.e. the barcode barely fits.)
  104. if (nextStart < self.counterLength && trailingWhitespace < lastPatternSize / 2) {
  105. if (error) *error = ZXNotFoundErrorInstance();
  106. return nil;
  107. }
  108. if (![self validatePattern:startOffset]) {
  109. if (error) *error = ZXNotFoundErrorInstance();
  110. return nil;
  111. }
  112. // Translate character table offsets to actual characters.
  113. for (int i = 0; i < self.decodeRowResult.length; i++) {
  114. [self.decodeRowResult replaceCharactersInRange:NSMakeRange(i, 1) withString:[NSString stringWithFormat:@"%c", ZX_CODA_ALPHABET[[self.decodeRowResult characterAtIndex:i]]]];
  115. }
  116. // Ensure a valid start and end character
  117. unichar startchar = [self.decodeRowResult characterAtIndex:0];
  118. if (![ZXCodaBarReader arrayContains:ZX_CODA_STARTEND_ENCODING
  119. length:sizeof(ZX_CODA_STARTEND_ENCODING) / sizeof(unichar)
  120. key:startchar]) {
  121. if (error) *error = ZXNotFoundErrorInstance();
  122. return nil;
  123. }
  124. unichar endchar = [self.decodeRowResult characterAtIndex:self.decodeRowResult.length - 1];
  125. if (![ZXCodaBarReader arrayContains:ZX_CODA_STARTEND_ENCODING
  126. length:sizeof(ZX_CODA_STARTEND_ENCODING) / sizeof(unichar)
  127. key:endchar]) {
  128. if (error) *error = ZXNotFoundErrorInstance();
  129. return nil;
  130. }
  131. // remove stop/start characters character and check if a long enough string is contained
  132. if (self.decodeRowResult.length <= ZX_CODA_MIN_CHARACTER_LENGTH) {
  133. if (error) *error = ZXNotFoundErrorInstance();
  134. return nil;
  135. }
  136. if (!hints.returnCodaBarStartEnd) {
  137. [self.decodeRowResult deleteCharactersInRange:NSMakeRange(self.decodeRowResult.length - 1, 1)];
  138. [self.decodeRowResult deleteCharactersInRange:NSMakeRange(0, 1)];
  139. }
  140. int runningCount = 0;
  141. for (int i = 0; i < startOffset; i++) {
  142. runningCount += self.counters.array[i];
  143. }
  144. float left = (float) runningCount;
  145. for (int i = startOffset; i < nextStart - 1; i++) {
  146. runningCount += self.counters.array[i];
  147. }
  148. float right = (float) runningCount;
  149. return [ZXResult resultWithText:self.decodeRowResult
  150. rawBytes:nil
  151. resultPoints:@[[[ZXResultPoint alloc] initWithX:left y:(float)rowNumber],
  152. [[ZXResultPoint alloc] initWithX:right y:(float)rowNumber]]
  153. format:kBarcodeFormatCodabar];
  154. }
  155. - (BOOL)validatePattern:(int)start {
  156. // First, sum up the total size of our four categories of stripe sizes;
  157. int sizes[4] = {0, 0, 0, 0};
  158. int counts[4] = {0, 0, 0, 0};
  159. int end = (int)self.decodeRowResult.length - 1;
  160. // We break out of this loop in the middle, in order to handle
  161. // inter-character spaces properly.
  162. int pos = start;
  163. for (int i = 0; true; i++) {
  164. int pattern = ZX_CODA_CHARACTER_ENCODINGS[[self.decodeRowResult characterAtIndex:i]];
  165. for (int j = 6; j >= 0; j--) {
  166. // Even j = bars, while odd j = spaces. Categories 2 and 3 are for
  167. // long stripes, while 0 and 1 are for short stripes.
  168. int category = (j & 1) + (pattern & 1) * 2;
  169. sizes[category] += self.counters.array[pos + j];
  170. counts[category]++;
  171. pattern >>= 1;
  172. }
  173. if (i >= end) {
  174. break;
  175. }
  176. // We ignore the inter-character space - it could be of any size.
  177. pos += 8;
  178. }
  179. // Calculate our allowable size thresholds using fixed-point math.
  180. float maxes[4] = {0.0f, 0.0f, 0.0f, 0.0f};
  181. float mins[4] = {0.0f, 0.0f, 0.0f, 0.0f};
  182. // Define the threshold of acceptability to be the midpoint between the
  183. // average small stripe and the average large stripe. No stripe lengths
  184. // should be on the "wrong" side of that line.
  185. for (int i = 0; i < 2; i++) {
  186. mins[i] = 0.0f; // Accept arbitrarily small "short" stripes.
  187. mins[i + 2] = ((float) sizes[i] / counts[i] + (float) sizes[i + 2] / counts[i + 2]) / 2.0f;
  188. maxes[i] = mins[i + 2];
  189. maxes[i + 2] = (sizes[i + 2] * ZX_CODA_MAX_ACCEPTABLE + ZX_CODA_PADDING) / counts[i + 2];
  190. }
  191. // Now verify that all of the stripes are within the thresholds.
  192. pos = start;
  193. for (int i = 0; true; i++) {
  194. int pattern = ZX_CODA_CHARACTER_ENCODINGS[[self.decodeRowResult characterAtIndex:i]];
  195. for (int j = 6; j >= 0; j--) {
  196. // Even j = bars, while odd j = spaces. Categories 2 and 3 are for
  197. // long stripes, while 0 and 1 are for short stripes.
  198. int category = (j & 1) + (pattern & 1) * 2;
  199. int size = self.counters.array[pos + j];
  200. if (size < mins[category] || size > maxes[category]) {
  201. return NO;
  202. }
  203. pattern >>= 1;
  204. }
  205. if (i >= end) {
  206. break;
  207. }
  208. pos += 8;
  209. }
  210. return YES;
  211. }
  212. /**
  213. * Records the size of all runs of white and black pixels, starting with white.
  214. * This is just like recordPattern, except it records all the counters, and
  215. * uses our builtin "counters" member for storage.
  216. */
  217. - (BOOL)setCountersWithRow:(ZXBitArray *)row {
  218. self.counterLength = 0;
  219. // Start from the first white bit.
  220. int i = [row nextUnset:0];
  221. int end = row.size;
  222. if (i >= end) {
  223. return NO;
  224. }
  225. BOOL isWhite = YES;
  226. int count = 0;
  227. while (i < end) {
  228. if ([row get:i] ^ isWhite) { // that is, exactly one is true
  229. count++;
  230. } else {
  231. [self counterAppend:count];
  232. count = 1;
  233. isWhite = !isWhite;
  234. }
  235. i++;
  236. }
  237. [self counterAppend:count];
  238. return YES;
  239. }
  240. - (void)counterAppend:(int)e {
  241. self.counters.array[self.counterLength] = e;
  242. self.counterLength++;
  243. if (self.counterLength >= self.counters.length) {
  244. ZXIntArray *temp = [[ZXIntArray alloc] initWithLength:self.counterLength * 2];
  245. memcpy(temp.array, self.counters.array, self.counters.length * sizeof(int32_t));
  246. self.counters = temp;
  247. }
  248. }
  249. - (int)findStartPattern {
  250. for (int i = 1; i < self.counterLength; i += 2) {
  251. int charOffset = [self toNarrowWidePattern:i];
  252. if (charOffset != -1 && [[self class] arrayContains:ZX_CODA_STARTEND_ENCODING
  253. length:sizeof(ZX_CODA_STARTEND_ENCODING) / sizeof(unichar)
  254. key:ZX_CODA_ALPHABET[charOffset]]) {
  255. // Look for whitespace before start pattern, >= 50% of width of start pattern
  256. // We make an exception if the whitespace is the first element.
  257. int patternSize = 0;
  258. for (int j = i; j < i + 7; j++) {
  259. patternSize += self.counters.array[j];
  260. }
  261. if (i == 1 || self.counters.array[i-1] >= patternSize / 2) {
  262. return i;
  263. }
  264. }
  265. }
  266. return -1;
  267. }
  268. + (BOOL)arrayContains:(const unichar *)array length:(unsigned int)length key:(unichar)key {
  269. if (array != nil) {
  270. for (int i = 0; i < length; i++) {
  271. if (array[i] == key) {
  272. return YES;
  273. }
  274. }
  275. }
  276. return NO;
  277. }
  278. // Assumes that counters[position] is a bar.
  279. - (int)toNarrowWidePattern:(int)position {
  280. int32_t *array = self.counters.array;
  281. int end = position + 7;
  282. if (end >= self.counterLength) {
  283. return -1;
  284. }
  285. int maxBar = 0;
  286. int minBar = INT_MAX;
  287. for (int j = position; j < end; j += 2) {
  288. int currentCounter = array[j];
  289. if (currentCounter < minBar) {
  290. minBar = currentCounter;
  291. }
  292. if (currentCounter > maxBar) {
  293. maxBar = currentCounter;
  294. }
  295. }
  296. int thresholdBar = (minBar + maxBar) / 2;
  297. int maxSpace = 0;
  298. int minSpace = INT_MAX;
  299. for (int j = position + 1; j < end; j += 2) {
  300. int currentCounter = array[j];
  301. if (currentCounter < minSpace) {
  302. minSpace = currentCounter;
  303. }
  304. if (currentCounter > maxSpace) {
  305. maxSpace = currentCounter;
  306. }
  307. }
  308. int thresholdSpace = (minSpace + maxSpace) / 2;
  309. int bitmask = 1 << 7;
  310. int pattern = 0;
  311. for (int i = 0; i < 7; i++) {
  312. int threshold = (i & 1) == 0 ? thresholdBar : thresholdSpace;
  313. bitmask >>= 1;
  314. if (array[position + i] > threshold) {
  315. pattern |= bitmask;
  316. }
  317. }
  318. for (int i = 0; i < sizeof(ZX_CODA_CHARACTER_ENCODINGS) / sizeof(int); i++) {
  319. if (ZX_CODA_CHARACTER_ENCODINGS[i] == pattern) {
  320. return i;
  321. }
  322. }
  323. return -1;
  324. }
  325. @end