Added a project written on Qt framework for Symbian and added tutorials for both...
[zxing.git] / symbian / QQrDecoder / 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 bars.
36                  * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
37                  * 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                 
50         
51                 
52                 /**
53                  * Creates a reader that assumes all encoded data is data, and does not treat the final
54                  * character as a check digit. It will not decoded "extended Code 39" sequences.
55                  */
56                 Code39Reader::Code39Reader(){
57                         ALPHABET_STRING = new std::string("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%");
58                         usingCheckDigit = false;
59                         extendedMode = false;
60                 }
61                 
62                 /**
63                  * Creates a reader that can be configured to check the last character as a check digit.
64                  * It will not decoded "extended Code 39" sequences.
65                  *
66                  * @param usingCheckDigit if true, treat the last data character as a check digit, not
67                  * data, and verify that the checksum passes.
68                  */
69                 Code39Reader::Code39Reader(bool usingCheckDigit_){
70                         ALPHABET_STRING = new std::string("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%");
71                         usingCheckDigit = usingCheckDigit_;
72                         extendedMode = false;
73                 }
74  
75
76                 
77                 Ref<Result> Code39Reader::decodeRow(int rowNumber, Ref<BitArray> row){
78                         int* start = findAsteriskPattern(row);
79                         int nextStart = start[1];
80                         int end = row->getSize();
81                         
82                         // Read off white space
83                         while (nextStart < end && !row->get(nextStart)) {
84                                 nextStart++;
85                         }
86                         
87                         std::string tmpResultString;
88                         
89                         int countersLen = 9;
90                         int* counters = new int[countersLen];
91                         for (int i=0; i<countersLen; i++) {
92                                 counters[i] = 0;
93                         }
94                         char decodedChar;
95                         int lastStart;
96                         do {
97                                 recordPattern(row, nextStart, counters, countersLen);
98                                 int pattern = toNarrowWidePattern(counters, countersLen);
99                                 if (pattern < 0) {
100                                         throw ReaderException("pattern < 0");
101                                 }
102                                 decodedChar = patternToChar(pattern);
103                                 tmpResultString.append(1, decodedChar);
104                                 lastStart = nextStart;
105                                 for (int i = 0; i < countersLen; i++) {
106                                         nextStart += counters[i];
107                                 }
108                                 // Read off white space
109                                 while (nextStart < end && !row->get(nextStart)) {
110                                         nextStart++;
111                                 }
112                         } while (decodedChar != '*');
113                         tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk
114                         
115                         // Look for whitespace after pattern:
116                         int lastPatternSize = 0;
117                         for (int i = 0; i < countersLen; i++) {
118                                 lastPatternSize += counters[i];
119                         }
120                         int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
121                         // If 50% of last pattern size, following last pattern, is not whitespace, fail
122                         // (but if it's whitespace to the very end of the image, that's OK)
123                         if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
124                                 throw ReaderException("too short end white space");
125                         }
126                         
127                         if (usingCheckDigit) {
128                                 int max = tmpResultString.length() - 1;
129                                 int total = 0;
130                                 for (int i = 0; i < max; i++) {
131                                         total += ALPHABET_STRING->find_first_of(tmpResultString[i], 0);
132                                 }
133                                 if (total % 43 != ALPHABET_STRING->find_first_of(tmpResultString[max], 0)) {
134                                         throw ReaderException("");
135                                 }
136                                 tmpResultString.erase(max, 1);
137                         }
138                         
139                         
140                         
141                         
142                         Ref<String> resultString(new String(tmpResultString));
143                         if (extendedMode) {
144                                 delete resultString;
145                                 resultString = decodeExtended(tmpResultString);
146                         }
147                         
148                         if (tmpResultString.length() == 0) {
149                                 // Almost surely a false positive
150                                 throw ReaderException("");
151                         }
152                         
153                         float left = (float) (start[1] + start[0]) / 2.0f;
154                         float right = (float) (nextStart + lastStart) / 2.0f;
155                         
156                         std::vector< Ref<ResultPoint> > resultPoints(2);
157                         Ref<OneDResultPoint> resultPoint1(new OneDResultPoint(left, (float) rowNumber));
158                         Ref<OneDResultPoint> resultPoint2(new OneDResultPoint(right, (float) rowNumber));
159                         resultPoints[0] = resultPoint1;
160                         resultPoints[1] = resultPoint2;
161                         
162                         ArrayRef<unsigned char> resultBytes(1);
163                         
164                         delete [] start;
165                         
166                         Ref<Result> res(new Result(resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
167                         return res;
168                 }
169                 
170                 int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
171                         int width = row->getSize();
172                         int rowOffset = 0;
173                         while (rowOffset < width) {
174                                 if (row->get(rowOffset)) {
175                                         break;
176                                 }
177                                 rowOffset++;
178                         }
179                         
180                         int counterPosition = 0;
181                         int countersLen = 9;
182                         int* counters = new int[countersLen];
183                         for (int i=0; i<countersLen; i++) {
184                                 counters[i] = 0;
185                         }
186                         int patternStart = rowOffset;
187                         bool isWhite = false;
188                         int patternLength = countersLen;
189                         
190                         for (int i = rowOffset; i < width; i++) {
191                                 bool pixel = row->get(i);
192                                 if (pixel ^ isWhite) {
193                                         counters[counterPosition]++;
194                                 } else {
195                                         if (counterPosition == patternLength - 1) {
196                                                 if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
197                                                         // Look for whitespace before start pattern, >= 50% of width of start pattern
198                                                         if (row->isRange(fmaxl(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
199                                                                 int* resultValue = new int[2];
200                                                                 resultValue[0] = patternStart;
201                                                                 resultValue[1] = i;
202                                                                 return resultValue;
203                                                         }
204                                                 }
205                                                 patternStart += counters[0] + counters[1];
206                                                 for (int y = 2; y < patternLength; y++) {
207                                                         counters[y - 2] = counters[y];
208                                                 }
209                                                 counters[patternLength - 2] = 0;
210                                                 counters[patternLength - 1] = 0;
211                                                 counterPosition--;
212                                         } else {
213                                                 counterPosition++;
214                                         }
215                                         counters[counterPosition] = 1;
216                                         isWhite = !isWhite;
217                                 }
218                         }
219                         throw ReaderException("");
220                 }
221                 
222                 // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
223                 // per image when using some of our blackbox images.
224                 int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
225                         int numCounters = countersLen;
226                         int maxNarrowCounter = 0;
227                         int wideCounters;
228                         do {
229                                 int minCounter = INT_MAX;
230                                 for (int i = 0; i < numCounters; i++) {
231                                         int counter = counters[i];
232                                         if (counter < minCounter && counter > maxNarrowCounter) {
233                                                 minCounter = counter;
234                                         }
235                                 }
236                                 maxNarrowCounter = minCounter;
237                                 wideCounters = 0;
238                                 int totalWideCountersWidth = 0;
239                                 int pattern = 0;
240                                 for (int i = 0; i < numCounters; i++) {
241                                         int counter = counters[i];
242                                         if (counters[i] > maxNarrowCounter) {
243                                                 pattern |= 1 << (numCounters - 1 - i);
244                                                 wideCounters++;
245                                                 totalWideCountersWidth += counter;
246                                         }
247                                 }
248                                 if (wideCounters == 3) {
249                                         // Found 3 wide counters, but are they close enough in width?
250                                         // We can perform a cheap, conservative check to see if any individual
251                                         // counter is more than 1.5 times the average:
252                                         for (int i = 0; i < numCounters && wideCounters > 0; i++) {
253                                                 int counter = counters[i];
254                                                 if (counters[i] > maxNarrowCounter) {
255                                                         wideCounters--;
256                                                         // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
257                                                         if ((counter << 1) >= totalWideCountersWidth) {
258                                                                 return -1;
259                                                         }
260                                                 }
261                                         }
262                                         return pattern;
263                                 }
264                         } while (wideCounters > 3);
265                         return -1;
266                 }
267                 
268                 char Code39Reader::patternToChar(int pattern){
269                         for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
270                                 if (CHARACTER_ENCODINGS[i] == pattern) {
271                                         return ALPHABET[i];
272                                 }
273                         }
274                         throw ReaderException("");
275                 }
276                 
277                 Ref<String> Code39Reader::decodeExtended(std::string encoded){
278                         int length = encoded.length();
279                         std::string tmpDecoded;
280                         for (int i = 0; i < length; i++) {
281                                 char c = encoded[i];
282                                 if (c == '+' || c == '$' || c == '%' || c == '/') {
283                                         char next = encoded[i + 1];
284                                         char decodedChar = '\0';
285                                         switch (c) {
286                                                 case '+':
287                                                         // +A to +Z map to a to z
288                                                         if (next >= 'A' && next <= 'Z') {
289                                                                 decodedChar = (char) (next + 32);
290                                                         } else {
291                                                                 throw ReaderException("");
292                                                         }
293                                                         break;
294                                                 case '$':
295                                                         // $A to $Z map to control codes SH to SB
296                                                         if (next >= 'A' && next <= 'Z') {
297                                                                 decodedChar = (char) (next - 64);
298                                                         } else {
299                                                                 throw ReaderException("");
300                                                         }
301                                                         break;
302                                                 case '%':
303                                                         // %A to %E map to control codes ESC to US
304                                                         if (next >= 'A' && next <= 'E') {
305                                                                 decodedChar = (char) (next - 38);
306                                                         } else if (next >= 'F' && next <= 'W') {
307                                                                 decodedChar = (char) (next - 11);
308                                                         } else {
309                                                                 throw ReaderException("");
310                                                         }
311                                                         break;
312                                                 case '/':
313                                                         // /A to /O map to ! to , and /Z maps to :
314                                                         if (next >= 'A' && next <= 'O') {
315                                                                 decodedChar = (char) (next - 32);
316                                                         } else if (next == 'Z') {
317                                                                 decodedChar = ':';
318                                                         } else {
319                                                                 throw ReaderException("");
320                                                         }
321                                                         break;
322                                         }
323                                         tmpDecoded.append(1, decodedChar);
324                                         // bump up i again since we read two characters
325                                         i++;
326                                 } else {
327                                         tmpDecoded.append(1, c);
328                                 }
329                         }
330                         Ref<String> decoded(new String(tmpDecoded));
331                         return decoded;
332                 }
333                 
334
335                 Code39Reader::~Code39Reader(){
336                         delete ALPHABET_STRING;
337                 }
338
339         }
340 }