bcf1b68fdc83bdc2b4cf09d02dffbeafb756ea0e
[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         recordPattern(row, nextStart, counters, countersLen);
106         int pattern = toNarrowWidePattern(counters, countersLen);
107         if (pattern < 0) {
108           throw ReaderException("pattern < 0");
109         }
110         decodedChar = patternToChar(pattern);
111         tmpResultString.append(1, decodedChar);
112         lastStart = nextStart;
113         for (int i = 0; i < countersLen; i++) {
114           nextStart += counters[i];
115         }
116         // Read off white space
117         while (nextStart < end && !row->get(nextStart)) {
118           nextStart++;
119         }
120       } while (decodedChar != '*');
121       tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk
122
123       // Look for whitespace after pattern:
124       int lastPatternSize = 0;
125       for (int i = 0; i < countersLen; i++) {
126         lastPatternSize += counters[i];
127       }
128       int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
129       // If 50% of last pattern size, following last pattern, is not whitespace,
130       // fail (but if it's whitespace to the very end of the image, that's OK)
131       if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
132         throw ReaderException("too short end white space");
133       }
134
135       if (usingCheckDigit) {
136         int max = tmpResultString.length() - 1;
137         unsigned int total = 0;
138         for (int i = 0; i < max; i++) {
139           total += alphabet_string.find_first_of(tmpResultString[i], 0);
140         }
141         if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
142           throw ReaderException("");
143         }
144         tmpResultString.erase(max, 1);
145       }
146
147       Ref<String> resultString(new String(tmpResultString));
148       if (extendedMode) {
149         resultString = decodeExtended(tmpResultString);
150       }
151
152       if (tmpResultString.length() == 0) {
153         // Almost surely a false positive
154         throw ReaderException("");
155       }
156
157       float left = (float) (start[1] + start[0]) / 2.0f;
158       float right = (float) (nextStart + lastStart) / 2.0f;
159
160       std::vector< Ref<ResultPoint> > resultPoints(2);
161       Ref<OneDResultPoint> resultPoint1(
162         new OneDResultPoint(left, (float) rowNumber));
163       Ref<OneDResultPoint> resultPoint2(
164         new OneDResultPoint(right, (float) rowNumber));
165       resultPoints[0] = resultPoint1;
166       resultPoints[1] = resultPoint2;
167
168       ArrayRef<unsigned char> resultBytes(1);
169
170       Ref<Result> res(new Result(
171                         resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
172
173       delete [] start;
174       return res;
175     } catch (ReaderException const& re) {
176       delete [] start;
177       return Ref<Result>();
178     }
179   }
180
181   int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
182     int width = row->getSize();
183     int rowOffset = 0;
184     while (rowOffset < width) {
185       if (row->get(rowOffset)) {
186         break;
187       }
188       rowOffset++;
189     }
190
191     int counterPosition = 0;
192     const int countersLen = 9;
193     int counters[countersLen];
194     for (int i = 0; i < countersLen; i++) {
195       counters[i] = 0;
196     }
197     int patternStart = rowOffset;
198     bool isWhite = false;
199     int patternLength = countersLen;
200
201     for (int i = rowOffset; i < width; i++) {
202       bool pixel = row->get(i);
203       if (pixel ^ isWhite) {
204         counters[counterPosition]++;
205       } else {
206         if (counterPosition == patternLength - 1) {
207           if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
208             // Look for whitespace before start pattern, >= 50% of width of
209             // start pattern.
210             long double longPatternOffset =
211               fmaxl(0, patternStart - (i - patternStart) / 2);
212             if (row->isRange(longPatternOffset, patternStart, false)) {
213               int* resultValue = new int[2];
214               resultValue[0] = patternStart;
215               resultValue[1] = i;
216               return resultValue;
217             }
218           }
219           patternStart += counters[0] + counters[1];
220           for (int y = 2; y < patternLength; y++) {
221             counters[y - 2] = counters[y];
222           }
223           counters[patternLength - 2] = 0;
224           counters[patternLength - 1] = 0;
225           counterPosition--;
226         } else {
227           counterPosition++;
228         }
229         counters[counterPosition] = 1;
230         isWhite = !isWhite;
231       }
232     }
233     throw ReaderException("");
234   }
235
236   // For efficiency, returns -1 on failure. Not throwing here saved as many as
237   // 700 exceptions per image when using some of our blackbox images.
238   int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
239     int numCounters = countersLen;
240     int maxNarrowCounter = 0;
241     int wideCounters;
242     do {
243       int minCounter = INT_MAX;
244       for (int i = 0; i < numCounters; i++) {
245         int counter = counters[i];
246         if (counter < minCounter && counter > maxNarrowCounter) {
247           minCounter = counter;
248         }
249       }
250       maxNarrowCounter = minCounter;
251       wideCounters = 0;
252       int totalWideCountersWidth = 0;
253       int pattern = 0;
254       for (int i = 0; i < numCounters; i++) {
255         int counter = counters[i];
256         if (counters[i] > maxNarrowCounter) {
257           pattern |= 1 << (numCounters - 1 - i);
258           wideCounters++;
259           totalWideCountersWidth += counter;
260         }
261       }
262       if (wideCounters == 3) {
263         // Found 3 wide counters, but are they close enough in width?
264         // We can perform a cheap, conservative check to see if any individual
265         // counter is more than 1.5 times the average:
266         for (int i = 0; i < numCounters && wideCounters > 0; i++) {
267           int counter = counters[i];
268           if (counters[i] > maxNarrowCounter) {
269             wideCounters--;
270             // totalWideCountersWidth = 3 * average, so this checks if
271             // counter >= 3/2 * average.
272             if ((counter << 1) >= totalWideCountersWidth) {
273               return -1;
274             }
275           }
276         }
277         return pattern;
278       }
279     } while (wideCounters > 3);
280     return -1;
281   }
282
283   char Code39Reader::patternToChar(int pattern){
284     for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
285       if (CHARACTER_ENCODINGS[i] == pattern) {
286         return ALPHABET[i];
287       }
288     }
289     throw ReaderException("");
290   }
291
292   Ref<String> Code39Reader::decodeExtended(std::string encoded){
293     int length = encoded.length();
294     std::string tmpDecoded;
295     for (int i = 0; i < length; i++) {
296       char c = encoded[i];
297       if (c == '+' || c == '$' || c == '%' || c == '/') {
298         char next = encoded[i + 1];
299         char decodedChar = '\0';
300         switch (c) {
301           case '+':
302             // +A to +Z map to a to z
303             if (next >= 'A' && next <= 'Z') {
304               decodedChar = (char) (next + 32);
305             } else {
306               throw ReaderException("");
307             }
308             break;
309           case '$':
310             // $A to $Z map to control codes SH to SB
311             if (next >= 'A' && next <= 'Z') {
312               decodedChar = (char) (next - 64);
313             } else {
314               throw ReaderException("");
315             }
316             break;
317           case '%':
318             // %A to %E map to control codes ESC to US
319             if (next >= 'A' && next <= 'E') {
320               decodedChar = (char) (next - 38);
321             } else if (next >= 'F' && next <= 'W') {
322               decodedChar = (char) (next - 11);
323             } else {
324               throw ReaderException("");
325             }
326             break;
327           case '/':
328             // /A to /O map to ! to , and /Z maps to :
329             if (next >= 'A' && next <= 'O') {
330               decodedChar = (char) (next - 32);
331             } else if (next == 'Z') {
332               decodedChar = ':';
333             } else {
334               throw ReaderException("");
335             }
336             break;
337         }
338         tmpDecoded.append(1, decodedChar);
339         // bump up i again since we read two characters
340         i++;
341       } else {
342         tmpDecoded.append(1, c);
343       }
344     }
345     Ref<String> decoded(new String(tmpDecoded));
346     return decoded;
347   }
348 } // namespace oned
349 } // namespace zxing
350