Removed as many exceptions as possible from the C++ product readers
[zxing.git] / cpp / core / src / zxing / oned / UPCEANReader.cpp
1 /*
2  *  UPCEANReader.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 "UPCEANReader.h"
21 #include <zxing/oned/OneDResultPoint.h>
22 #include <zxing/ReaderException.h>
23
24 namespace zxing {
25   namespace oned {
26
27     /**
28      * Start/end guard pattern.
29      */
30     static const int START_END_PATTERN[3] = {1, 1, 1};
31
32     /**
33      * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
34      */
35     static const int MIDDLE_PATTERN_LEN = 5;
36     static const int MIDDLE_PATTERN[MIDDLE_PATTERN_LEN] = {1, 1, 1, 1, 1};
37
38     /**
39      * "Odd", or "L" patterns used to encode UPC/EAN digits.
40      */
41     const int L_PATTERNS_LEN = 10;
42     const int L_PATTERNS_SUB_LEN = 4;
43     const int L_PATTERNS[10][4] = {
44       {3, 2, 1, 1}, // 0
45       {2, 2, 2, 1}, // 1
46       {2, 1, 2, 2}, // 2
47       {1, 4, 1, 1}, // 3
48       {1, 1, 3, 2}, // 4
49       {1, 2, 3, 1}, // 5
50       {1, 1, 1, 4}, // 6
51       {1, 3, 1, 2}, // 7
52       {1, 2, 1, 3}, // 8
53       {3, 1, 1, 2}  // 9
54     };
55
56     /**
57      * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
58      */
59     const int L_AND_G_PATTERNS_LEN = 20;
60     const int L_AND_G_PATTERNS_SUB_LEN = 4;
61     const int L_AND_G_PATTERNS[L_AND_G_PATTERNS_LEN][L_AND_G_PATTERNS_SUB_LEN] = {
62       {3, 2, 1, 1}, // 0
63       {2, 2, 2, 1}, // 1
64       {2, 1, 2, 2}, // 2
65       {1, 4, 1, 1}, // 3
66       {1, 1, 3, 2}, // 4
67       {1, 2, 3, 1}, // 5
68       {1, 1, 1, 4}, // 6
69       {1, 3, 1, 2}, // 7
70       {1, 2, 1, 3}, // 8
71       {3, 1, 1, 2}, // 9
72       {1, 1, 2, 3}, // 10 reversed 0
73       {1, 2, 2, 2}, // 11 reversed 1
74       {2, 2, 1, 2}, // 12 reversed 2
75       {1, 1, 4, 1}, // 13 reversed 3
76       {2, 3, 1, 1}, // 14 reversed 4
77       {1, 3, 2, 1}, // 15 reversed 5
78       {4, 1, 1, 1}, // 16 reversed 6
79       {2, 1, 3, 1}, // 17 reversed 7
80       {3, 1, 2, 1}, // 18 reversed 8
81       {2, 1, 1, 3}  // 19 reversed 9
82     };
83
84
85     const int UPCEANReader::getMIDDLE_PATTERN_LEN() {
86       return MIDDLE_PATTERN_LEN;
87     }
88
89     const int* UPCEANReader::getMIDDLE_PATTERN() {
90       return MIDDLE_PATTERN;
91     }
92
93     UPCEANReader::UPCEANReader() {
94     }
95
96
97     Ref<Result> UPCEANReader::decodeRow(int rowNumber, Ref<BitArray> row) {
98                         int* start = findStartGuardPattern(row);
99                         if (start != NULL) {
100         try {
101           Ref<Result> result = decodeRow(rowNumber, row, start);
102           delete [] start;
103           return result;
104         } catch (ReaderException const& re) {
105           delete [] start;
106         }
107                         }
108                         return Ref<Result>();
109     }
110
111     Ref<Result> UPCEANReader::decodeRow(int rowNumber, Ref<BitArray> row, int startGuardRange[]) {
112       std::string tmpResultString;
113       std::string& tmpResultStringRef = tmpResultString;
114       int endStart = decodeMiddle(row, startGuardRange, 2 /*reference findGuardPattern*/ ,
115           tmpResultStringRef);
116       if (endStart < 0) {
117         return Ref<Result>();
118       }
119       int* endRange = decodeEnd(row, endStart);
120       if (endRange == NULL) {
121         return Ref<Result>();
122       }
123
124       // Make sure there is a quiet zone at least as big as the end pattern after the barcode.
125       // The spec might want more whitespace, but in practice this is the maximum we can count on.
126       size_t end = endRange[1];
127       size_t quietEnd = end + (end - endRange[0]);
128       if (quietEnd >= row->getSize() || !row->isRange(end, quietEnd, false)) {
129         delete [] endRange;
130         return Ref<Result>();
131       }
132
133       if (!checkChecksum(tmpResultString)) {
134         delete [] endRange;
135         return Ref<Result>();
136       }
137
138       Ref<String> resultString(new String(tmpResultString));
139
140       float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
141       float right = (float) (endRange[1] + endRange[0]) / 2.0f;
142
143       std::vector< Ref<ResultPoint> > resultPoints(2);
144       Ref<OneDResultPoint> resultPoint1(new OneDResultPoint(left, (float) rowNumber));
145       Ref<OneDResultPoint> resultPoint2(new OneDResultPoint(right, (float) rowNumber));
146       resultPoints[0] = resultPoint1;
147       resultPoints[1] = resultPoint2;
148
149       ArrayRef<unsigned char> resultBytes(1);
150       Ref<Result> res(new Result(resultString, resultBytes, resultPoints, getBarcodeFormat()));
151       delete [] endRange;
152       return res;
153     }
154
155     int* UPCEANReader::findStartGuardPattern(Ref<BitArray> row) {
156       bool foundStart = false;
157       int* startRange = NULL;
158       int nextStart = 0;
159       while (!foundStart) {
160         delete [] startRange;
161         startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN,
162             sizeof(START_END_PATTERN) / sizeof(int));
163         if (startRange == NULL) {
164           return NULL;
165         }
166         int start = startRange[0];
167         nextStart = startRange[1];
168         // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
169         // If this check would run off the left edge of the image, do not accept this barcode,
170         // as it is very likely to be a false positive.
171         int quietStart = start - (nextStart - start);
172         if (quietStart >= 0) {
173           foundStart = row->isRange(quietStart, start, false);
174         }
175       }
176       return startRange;
177     }
178
179     // TODO(flyashi): Return a pair<int, int> for return value to avoid using the heap.
180     int* UPCEANReader::findGuardPattern(Ref<BitArray> row, int rowOffset, bool whiteFirst,
181         const int pattern[], int patternLen) {
182       int patternLength = patternLen;
183       int counters[patternLength];
184       int countersCount = sizeof(counters) / sizeof(int);
185       for (int i = 0; i < countersCount; i++) {
186         counters[i] = 0;
187       }
188       int width = row->getSize();
189       bool isWhite = false;
190       while (rowOffset < width) {
191         isWhite = !row->get(rowOffset);
192         if (whiteFirst == isWhite) {
193           break;
194         }
195         rowOffset++;
196       }
197
198       int counterPosition = 0;
199       int patternStart = rowOffset;
200       for (int x = rowOffset; x < width; x++) {
201         bool pixel = row->get(x);
202         if (pixel ^ isWhite) {
203           counters[counterPosition]++;
204         } else {
205           if (counterPosition == patternLength - 1) {
206             if (patternMatchVariance(counters, countersCount, pattern,
207                 MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
208               int* resultValue = new int[2];
209               resultValue[0] = patternStart;
210               resultValue[1] = x;
211               return resultValue;
212             }
213             patternStart += counters[0] + counters[1];
214             for (int y = 2; y < patternLength; y++) {
215               counters[y - 2] = counters[y];
216             }
217             counters[patternLength - 2] = 0;
218             counters[patternLength - 1] = 0;
219             counterPosition--;
220           } else {
221             counterPosition++;
222           }
223           counters[counterPosition] = 1;
224           isWhite = !isWhite;
225         }
226       }
227       return NULL;
228     }
229
230     int* UPCEANReader::decodeEnd(Ref<BitArray> row, int endStart) {
231       return findGuardPattern(row, endStart, false, START_END_PATTERN,
232           sizeof(START_END_PATTERN) / sizeof(int));
233     }
234
235     int UPCEANReader::decodeDigit(Ref<BitArray> row, int counters[], int countersLen, int rowOffset,
236         UPC_EAN_PATTERNS patternType) {
237       if (!recordPattern(row, rowOffset, counters, countersLen)) {
238         return -1;
239       }
240       unsigned int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
241       int bestMatch = -1;
242
243       int max = 0;
244       switch (patternType) {
245         case UPC_EAN_PATTERNS_L_PATTERNS:
246           max = L_PATTERNS_LEN;
247           for (int i = 0; i < max; i++) {
248             int pattern[countersLen];
249             for(int j = 0; j< countersLen; j++){
250               pattern[j] = L_PATTERNS[i][j];
251             }
252
253             unsigned int variance = patternMatchVariance(counters, countersLen, pattern,
254                 MAX_INDIVIDUAL_VARIANCE);
255             if (variance < bestVariance) {
256               bestVariance = variance;
257               bestMatch = i;
258             }
259           }
260           break;
261         case UPC_EAN_PATTERNS_L_AND_G_PATTERNS:
262           max = L_AND_G_PATTERNS_LEN;
263           for (int i = 0; i < max; i++) {
264             int pattern[countersLen];
265             for(int j = 0; j< countersLen; j++){
266               pattern[j] = L_AND_G_PATTERNS[i][j];
267             }
268
269             unsigned int variance = patternMatchVariance(counters, countersLen, pattern,
270                 MAX_INDIVIDUAL_VARIANCE);
271             if (variance < bestVariance) {
272               bestVariance = variance;
273               bestMatch = i;
274             }
275           }
276           break;
277         default:
278           break;
279       }
280       return bestMatch;
281     }
282
283     /**
284      * @return {@link #checkStandardUPCEANChecksum(String)}
285      */
286     bool UPCEANReader::checkChecksum(std::string s) {
287       return checkStandardUPCEANChecksum(s);
288     }
289
290     /**
291      * Computes the UPC/EAN checksum on a string of digits, and reports
292      * whether the checksum is correct or not.
293      *
294      * @param s string of digits to check
295      * @return true iff string of digits passes the UPC/EAN checksum algorithm
296      */
297     bool UPCEANReader::checkStandardUPCEANChecksum(std::string s) {
298       int length = s.length();
299       if (length == 0) {
300         return false;
301       }
302
303       int sum = 0;
304       for (int i = length - 2; i >= 0; i -= 2) {
305         int digit = (int) s[i] - (int) '0';
306         if (digit < 0 || digit > 9) {
307           return false;
308         }
309         sum += digit;
310       }
311       sum *= 3;
312       for (int i = length - 1; i >= 0; i -= 2) {
313         int digit = (int) s[i] - (int) '0';
314         if (digit < 0 || digit > 9) {
315           return false;
316         }
317         sum += digit;
318       }
319       return sum % 10 == 0;
320     }
321
322     UPCEANReader::~UPCEANReader() {
323     }
324   }
325 }