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