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