9a2a82a10dcdc9567e58b65a69a4905aad99e1f8
[zxing.git] / cpp / core / src / zxing / oned / Code39Reader.cpp
1 /*
2  *  Code39Reader.cpp
3  *  ZXing
4  *
5  *  Copyright 2010 ZXing authors All rights reserved.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 #include "Code39Reader.h"
21 #include <zxing/oned/OneDResultPoint.h>
22 #include <zxing/common/Array.h>
23 #include <zxing/ReaderException.h>
24 #include <math.h>
25 #include <limits.h>
26
27 namespace zxing {
28 namespace oned {
29
30   static const char* ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
31
32
33   /**
34    * These represent the encodings of characters, as patterns of wide and narrow
35    * bars.
36    * The 9 least-significant bits of each int correspond to the pattern of wide
37    * and narrow, with 1s representing "wide" and 0s representing narrow.
38    */
39   const int CHARACTER_ENCODINGS_LEN = 44;
40   static int CHARACTER_ENCODINGS[CHARACTER_ENCODINGS_LEN] = {
41     0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
42     0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
43     0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
44     0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
45     0x0A8, 0x0A2, 0x08A, 0x02A // $-%
46   };
47
48   static int ASTERISK_ENCODING = 0x094;
49   static const char* ALPHABET_STRING =
50     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
51
52
53   /**
54    * Creates a reader that assumes all encoded data is data, and does not treat
55    * the final character as a check digit. It will not decoded "extended
56    * Code 39" sequences.
57    */
58   Code39Reader::Code39Reader() : alphabet_string(ALPHABET_STRING),
59                                  usingCheckDigit(false),
60                                  extendedMode(false) {
61   }
62
63   /**
64    * Creates a reader that can be configured to check the last character as a
65    * check digit. It will not decoded "extended Code 39" sequences.
66    *
67    * @param usingCheckDigit if true, treat the last data character as a check
68    * digit, not data, and verify that the checksum passes.
69    */
70   Code39Reader::Code39Reader(bool usingCheckDigit_) :
71     alphabet_string(ALPHABET_STRING),
72     usingCheckDigit(usingCheckDigit_),
73     extendedMode(false) {
74   }
75
76
77   Code39Reader::Code39Reader(bool usingCheckDigit_, bool extendedMode_) :
78     alphabet_string(ALPHABET_STRING),
79     usingCheckDigit(usingCheckDigit_),
80     extendedMode(extendedMode_) {
81   }
82
83   Ref<Result> Code39Reader::decodeRow(int rowNumber, Ref<BitArray> row) {
84     int* start = NULL;
85     try {
86       start = findAsteriskPattern(row);
87       int nextStart = start[1];
88       int end = row->getSize();
89
90       // Read off white space
91       while (nextStart < end && !row->get(nextStart)) {
92         nextStart++;
93       }
94
95       std::string tmpResultString;
96
97       const int countersLen = 9;
98       int counters[countersLen];
99       for (int i = 0; i < countersLen; i++) {
100         counters[i] = 0;
101       }
102       char decodedChar;
103       int lastStart;
104       do {
105         if (!recordPattern(row, nextStart, counters, countersLen)) {
106           throw ReaderException("");
107         }
108         int pattern = toNarrowWidePattern(counters, countersLen);
109         if (pattern < 0) {
110           throw ReaderException("pattern < 0");
111         }
112         decodedChar = patternToChar(pattern);
113         tmpResultString.append(1, decodedChar);
114         lastStart = nextStart;
115         for (int i = 0; i < countersLen; i++) {
116           nextStart += counters[i];
117         }
118         // Read off white space
119         while (nextStart < end && !row->get(nextStart)) {
120           nextStart++;
121         }
122       } while (decodedChar != '*');
123       tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk
124
125       // Look for whitespace after pattern:
126       int lastPatternSize = 0;
127       for (int i = 0; i < countersLen; i++) {
128         lastPatternSize += counters[i];
129       }
130       int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
131       // If 50% of last pattern size, following last pattern, is not whitespace,
132       // fail (but if it's whitespace to the very end of the image, that's OK)
133       if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
134         throw ReaderException("too short end white space");
135       }
136
137       if (usingCheckDigit) {
138         int max = tmpResultString.length() - 1;
139         unsigned int total = 0;
140         for (int i = 0; i < max; i++) {
141           total += alphabet_string.find_first_of(tmpResultString[i], 0);
142         }
143         if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
144           throw ReaderException("");
145         }
146         tmpResultString.erase(max, 1);
147       }
148
149       Ref<String> resultString(new String(tmpResultString));
150       if (extendedMode) {
151         resultString = decodeExtended(tmpResultString);
152       }
153
154       if (tmpResultString.length() == 0) {
155         // Almost surely a false positive
156         throw ReaderException("");
157       }
158
159       float left = (float) (start[1] + start[0]) / 2.0f;
160       float right = (float) (nextStart + lastStart) / 2.0f;
161
162       std::vector< Ref<ResultPoint> > resultPoints(2);
163       Ref<OneDResultPoint> resultPoint1(
164         new OneDResultPoint(left, (float) rowNumber));
165       Ref<OneDResultPoint> resultPoint2(
166         new OneDResultPoint(right, (float) rowNumber));
167       resultPoints[0] = resultPoint1;
168       resultPoints[1] = resultPoint2;
169
170       ArrayRef<unsigned char> resultBytes(1);
171
172       Ref<Result> res(new Result(
173                         resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
174
175       delete [] start;
176       return res;
177     } catch (ReaderException const& re) {
178       delete [] start;
179       return Ref<Result>();
180     }
181   }
182
183   int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
184     int width = row->getSize();
185     int rowOffset = 0;
186     while (rowOffset < width) {
187       if (row->get(rowOffset)) {
188         break;
189       }
190       rowOffset++;
191     }
192
193     int counterPosition = 0;
194     const int countersLen = 9;
195     int counters[countersLen];
196     for (int i = 0; i < countersLen; i++) {
197       counters[i] = 0;
198     }
199     int patternStart = rowOffset;
200     bool isWhite = false;
201     int patternLength = countersLen;
202
203     for (int i = rowOffset; i < width; i++) {
204       bool pixel = row->get(i);
205       if (pixel ^ isWhite) {
206         counters[counterPosition]++;
207       } else {
208         if (counterPosition == patternLength - 1) {
209           if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
210             // Look for whitespace before start pattern, >= 50% of width of
211             // start pattern.
212             long double longPatternOffset =
213               fmaxl(0, patternStart - (i - patternStart) / 2);
214             if (row->isRange(longPatternOffset, patternStart, false)) {
215               int* resultValue = new int[2];
216               resultValue[0] = patternStart;
217               resultValue[1] = i;
218               return resultValue;
219             }
220           }
221           patternStart += counters[0] + counters[1];
222           for (int y = 2; y < patternLength; y++) {
223             counters[y - 2] = counters[y];
224           }
225           counters[patternLength - 2] = 0;
226           counters[patternLength - 1] = 0;
227           counterPosition--;
228         } else {
229           counterPosition++;
230         }
231         counters[counterPosition] = 1;
232         isWhite = !isWhite;
233       }
234     }
235     throw ReaderException("");
236   }
237
238   // For efficiency, returns -1 on failure. Not throwing here saved as many as
239   // 700 exceptions per image when using some of our blackbox images.
240   int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
241     int numCounters = countersLen;
242     int maxNarrowCounter = 0;
243     int wideCounters;
244     do {
245       int minCounter = INT_MAX;
246       for (int i = 0; i < numCounters; i++) {
247         int counter = counters[i];
248         if (counter < minCounter && counter > maxNarrowCounter) {
249           minCounter = counter;
250         }
251       }
252       maxNarrowCounter = minCounter;
253       wideCounters = 0;
254       int totalWideCountersWidth = 0;
255       int pattern = 0;
256       for (int i = 0; i < numCounters; i++) {
257         int counter = counters[i];
258         if (counters[i] > maxNarrowCounter) {
259           pattern |= 1 << (numCounters - 1 - i);
260           wideCounters++;
261           totalWideCountersWidth += counter;
262         }
263       }
264       if (wideCounters == 3) {
265         // Found 3 wide counters, but are they close enough in width?
266         // We can perform a cheap, conservative check to see if any individual
267         // counter is more than 1.5 times the average:
268         for (int i = 0; i < numCounters && wideCounters > 0; i++) {
269           int counter = counters[i];
270           if (counters[i] > maxNarrowCounter) {
271             wideCounters--;
272             // totalWideCountersWidth = 3 * average, so this checks if
273             // counter >= 3/2 * average.
274             if ((counter << 1) >= totalWideCountersWidth) {
275               return -1;
276             }
277           }
278         }
279         return pattern;
280       }
281     } while (wideCounters > 3);
282     return -1;
283   }
284
285   char Code39Reader::patternToChar(int pattern){
286     for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
287       if (CHARACTER_ENCODINGS[i] == pattern) {
288         return ALPHABET[i];
289       }
290     }
291     throw ReaderException("");
292   }
293
294   Ref<String> Code39Reader::decodeExtended(std::string encoded){
295     int length = encoded.length();
296     std::string tmpDecoded;
297     for (int i = 0; i < length; i++) {
298       char c = encoded[i];
299       if (c == '+' || c == '$' || c == '%' || c == '/') {
300         char next = encoded[i + 1];
301         char decodedChar = '\0';
302         switch (c) {
303           case '+':
304             // +A to +Z map to a to z
305             if (next >= 'A' && next <= 'Z') {
306               decodedChar = (char) (next + 32);
307             } else {
308               throw ReaderException("");
309             }
310             break;
311           case '$':
312             // $A to $Z map to control codes SH to SB
313             if (next >= 'A' && next <= 'Z') {
314               decodedChar = (char) (next - 64);
315             } else {
316               throw ReaderException("");
317             }
318             break;
319           case '%':
320             // %A to %E map to control codes ESC to US
321             if (next >= 'A' && next <= 'E') {
322               decodedChar = (char) (next - 38);
323             } else if (next >= 'F' && next <= 'W') {
324               decodedChar = (char) (next - 11);
325             } else {
326               throw ReaderException("");
327             }
328             break;
329           case '/':
330             // /A to /O map to ! to , and /Z maps to :
331             if (next >= 'A' && next <= 'O') {
332               decodedChar = (char) (next - 32);
333             } else if (next == 'Z') {
334               decodedChar = ':';
335             } else {
336               throw ReaderException("");
337             }
338             break;
339         }
340         tmpDecoded.append(1, decodedChar);
341         // bump up i again since we read two characters
342         i++;
343       } else {
344         tmpDecoded.append(1, c);
345       }
346     }
347     Ref<String> decoded(new String(tmpDecoded));
348     return decoded;
349   }
350 } // namespace oned
351 } // namespace zxing
352