Draft of 'thinking' visualization for barcode scanning. Works for 1D and QR codes.
[zxing.git] / core / src / com / google / zxing / oned / AbstractUPCEANReader.java
1 /*
2  * Copyright 2008 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.oned;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.Result;
23 import com.google.zxing.ResultPoint;
24 import com.google.zxing.ResultPointCallback;
25 import com.google.zxing.common.BitArray;
26
27 import java.util.Hashtable;
28
29 /**
30  * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
31  * of one-dimensional barcodes.</p>
32  *
33  * @author dswitkin@google.com (Daniel Switkin)
34  * @author Sean Owen
35  * @author alasdair@google.com (Alasdair Mackintosh)
36  */
37 public abstract class AbstractUPCEANReader extends AbstractOneDReader implements UPCEANReader {
38
39   private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
40   private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
41
42   /**
43    * Start/end guard pattern.
44    */
45   static final int[] START_END_PATTERN = {1, 1, 1,};
46
47   /**
48    * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
49    */
50   static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
51
52   /**
53    * "Odd", or "L" patterns used to encode UPC/EAN digits.
54    */
55   static final int[][] L_PATTERNS = {
56       {3, 2, 1, 1}, // 0
57       {2, 2, 2, 1}, // 1
58       {2, 1, 2, 2}, // 2
59       {1, 4, 1, 1}, // 3
60       {1, 1, 3, 2}, // 4
61       {1, 2, 3, 1}, // 5
62       {1, 1, 1, 4}, // 6
63       {1, 3, 1, 2}, // 7
64       {1, 2, 1, 3}, // 8
65       {3, 1, 1, 2}  // 9
66   };
67
68   /**
69    * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
70    */
71   static final int[][] L_AND_G_PATTERNS;
72
73   static {
74     L_AND_G_PATTERNS = new int[20][];
75     for (int i = 0; i < 10; i++) {
76       L_AND_G_PATTERNS[i] = L_PATTERNS[i];
77     }
78     for (int i = 10; i < 20; i++) {
79       int[] widths = L_PATTERNS[i - 10];
80       int[] reversedWidths = new int[widths.length];
81       for (int j = 0; j < widths.length; j++) {
82         reversedWidths[j] = widths[widths.length - j - 1];
83       }
84       L_AND_G_PATTERNS[i] = reversedWidths;
85     }
86   }
87
88   private final StringBuffer decodeRowStringBuffer;
89
90   protected AbstractUPCEANReader() {
91     decodeRowStringBuffer = new StringBuffer(20);
92   }
93
94   static int[] findStartGuardPattern(BitArray row) throws ReaderException {
95     boolean foundStart = false;
96     int[] startRange = null;
97     int nextStart = 0;
98     while (!foundStart) {
99       startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
100       int start = startRange[0];
101       nextStart = startRange[1];
102       // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
103       // If this check would run off the left edge of the image, do not accept this barcode,
104       // as it is very likely to be a false positive.
105       int quietStart = start - (nextStart - start);
106       if (quietStart >= 0) {
107         foundStart = row.isRange(quietStart, start, false);
108       }
109     }
110     return startRange;
111   }
112
113   public final Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
114       throws ReaderException {
115     return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
116   }
117
118   public final Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
119       throws ReaderException {
120
121     ResultPointCallback resultPointCallback = hints == null ? null :
122         (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
123
124     if (resultPointCallback != null) {
125       resultPointCallback.foundPossibleResultPoint(new ResultPoint(
126           (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
127       ));
128     }
129
130     StringBuffer result = decodeRowStringBuffer;
131     result.setLength(0);
132     int endStart = decodeMiddle(row, startGuardRange, result);
133
134     if (resultPointCallback != null) {
135       resultPointCallback.foundPossibleResultPoint(new ResultPoint(
136           endStart, rowNumber
137       ));
138     }
139
140     int[] endRange = decodeEnd(row, endStart);
141
142     if (resultPointCallback != null) {
143       resultPointCallback.foundPossibleResultPoint(new ResultPoint(
144           (endRange[0] + endRange[1]) / 2.0f, rowNumber
145       ));
146     }
147
148
149     // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
150     // spec might want more whitespace, but in practice this is the maximum we can count on.
151     int end = endRange[1];
152     int quietEnd = end + (end - endRange[0]);
153     if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {
154       throw ReaderException.getInstance();
155     }
156
157     String resultString = result.toString();
158     if (!checkChecksum(resultString)) {
159       throw ReaderException.getInstance();
160     }
161
162     float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
163     float right = (float) (endRange[1] + endRange[0]) / 2.0f;
164     return new Result(resultString,
165         null, // no natural byte representation for these barcodes
166         new ResultPoint[]{
167             new ResultPoint(left, (float) rowNumber),
168             new ResultPoint(right, (float) rowNumber)},
169         getBarcodeFormat());
170   }
171
172   abstract BarcodeFormat getBarcodeFormat();
173
174   /**
175    * @return {@link #checkStandardUPCEANChecksum(String)} 
176    */
177   boolean checkChecksum(String s) throws ReaderException {
178     return checkStandardUPCEANChecksum(s);
179   }
180
181   /**
182    * Computes the UPC/EAN checksum on a string of digits, and reports
183    * whether the checksum is correct or not.
184    *
185    * @param s string of digits to check
186    * @return true iff string of digits passes the UPC/EAN checksum algorithm
187    * @throws ReaderException if the string does not contain only digits
188    */
189   private static boolean checkStandardUPCEANChecksum(String s) throws ReaderException {
190     int length = s.length();
191     if (length == 0) {
192       return false;
193     }
194
195     int sum = 0;
196     for (int i = length - 2; i >= 0; i -= 2) {
197       int digit = (int) s.charAt(i) - (int) '0';
198       if (digit < 0 || digit > 9) {
199         throw ReaderException.getInstance();
200       }
201       sum += digit;
202     }
203     sum *= 3;
204     for (int i = length - 1; i >= 0; i -= 2) {
205       int digit = (int) s.charAt(i) - (int) '0';
206       if (digit < 0 || digit > 9) {
207         throw ReaderException.getInstance();
208       }
209       sum += digit;
210     }
211     return sum % 10 == 0;
212   }
213
214   /**
215    * Subclasses override this to decode the portion of a barcode between the start
216    * and end guard patterns.
217    *
218    * @param row row of black/white values to search
219    * @param startRange start/end offset of start guard pattern
220    * @param resultString {@link StringBuffer} to append decoded chars to
221    * @return horizontal offset of first pixel after the "middle" that was decoded
222    * @throws ReaderException if decoding could not complete successfully
223    */
224   protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
225       throws ReaderException;
226
227   int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
228     return findGuardPattern(row, endStart, false, START_END_PATTERN);
229   }
230
231   /**
232    * @param row row of black/white values to search
233    * @param rowOffset position to start search
234    * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
235    * pixel counts, otherwise, it is interpreted as black/white/black/...
236    * @param pattern pattern of counts of number of black and white pixels that are being
237    * searched for as a pattern
238    * @return start/end horizontal offset of guard pattern, as an array of two ints
239    * @throws ReaderException if pattern is not found
240    */
241   static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
242       throws ReaderException {
243     int patternLength = pattern.length;
244     int[] counters = new int[patternLength];
245     int width = row.getSize();
246     boolean isWhite = false;
247     while (rowOffset < width) {
248       isWhite = !row.get(rowOffset);
249       if (whiteFirst == isWhite) {
250         break;
251       }
252       rowOffset++;
253     }
254
255     int counterPosition = 0;
256     int patternStart = rowOffset;
257     for (int x = rowOffset; x < width; x++) {
258       boolean pixel = row.get(x);
259       if (pixel ^ isWhite) {
260         counters[counterPosition]++;
261       } else {
262         if (counterPosition == patternLength - 1) {
263           if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
264             return new int[]{patternStart, x};
265           }
266           patternStart += counters[0] + counters[1];
267           for (int y = 2; y < patternLength; y++) {
268             counters[y - 2] = counters[y];
269           }
270           counters[patternLength - 2] = 0;
271           counters[patternLength - 1] = 0;
272           counterPosition--;
273         } else {
274           counterPosition++;
275         }
276         counters[counterPosition] = 1;
277         isWhite ^= true; // isWhite = !isWhite;
278       }
279     }
280     throw ReaderException.getInstance();
281   }
282
283   /**
284    * Attempts to decode a single UPC/EAN-encoded digit.
285    *
286    * @param row row of black/white values to decode
287    * @param counters the counts of runs of observed black/white/black/... values
288    * @param rowOffset horizontal offset to start decoding from
289    * @param patterns the set of patterns to use to decode -- sometimes different encodings
290    * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
291    * be used
292    * @return horizontal offset of first pixel beyond the decoded digit
293    * @throws ReaderException if digit cannot be decoded
294    */
295   static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
296       throws ReaderException {
297     recordPattern(row, rowOffset, counters);
298     int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
299     int bestMatch = -1;
300     int max = patterns.length;
301     for (int i = 0; i < max; i++) {
302       int[] pattern = patterns[i];
303       int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
304       if (variance < bestVariance) {
305         bestVariance = variance;
306         bestMatch = i;
307       }
308     }
309     if (bestMatch >= 0) {
310       return bestMatch;
311     } else {
312       throw ReaderException.getInstance();
313     }
314   }
315
316 }