Improved approach to 1D decoding -- better use of integer math by scaling pattern...
[zxing.git] / core / src / com / google / zxing / oned / AbstractUPCEANReader.java
1 /*
2  * Copyright 2008 Google Inc.
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.ReaderException;
21 import com.google.zxing.Result;
22 import com.google.zxing.ResultPoint;
23 import com.google.zxing.common.BitArray;
24 import com.google.zxing.common.GenericResultPoint;
25
26 import java.util.Hashtable;
27
28 /**
29  * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
30  * of one-dimensional barcodes.</p>
31  *
32  * @author dswitkin@google.com (Daniel Switkin)
33  * @author srowen@google.com (Sean Owen)
34  * @author alasdair@google.com (Alasdair Mackintosh)
35  */
36 public abstract class AbstractUPCEANReader extends AbstractOneDReader implements UPCEANReader {
37
38   private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.40625f);
39   private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.5f);
40
41   /**
42    * Start/end guard pattern.
43    */
44   private static final int[] START_END_PATTERN = {1, 1, 1,};
45
46   /**
47    * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
48    */
49   static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
50
51   /**
52    * "Odd", or "L" patterns used to encode UPC/EAN digits.
53    */
54   static final int[][] L_PATTERNS = {
55       {3, 2, 1, 1}, // 0
56       {2, 2, 2, 1}, // 1
57       {2, 1, 2, 2}, // 2
58       {1, 4, 1, 1}, // 3
59       {1, 1, 3, 2}, // 4
60       {1, 2, 3, 1}, // 5
61       {1, 1, 1, 4}, // 6
62       {1, 3, 1, 2}, // 7
63       {1, 2, 1, 3}, // 8
64       {3, 1, 1, 2}  // 9
65   };
66
67   /**
68    * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
69    */
70   static final int[][] L_AND_G_PATTERNS;
71
72   static {
73     L_AND_G_PATTERNS = new int[20][];
74     for (int i = 0; i < 10; i++) {
75       L_AND_G_PATTERNS[i] = L_PATTERNS[i];
76     }
77     for (int i = 10; i < 20; i++) {
78       int[] widths = L_PATTERNS[i - 10];
79       int[] reversedWidths = new int[widths.length];
80       for (int j = 0; j < widths.length; j++) {
81         reversedWidths[j] = widths[widths.length - j - 1];
82       }
83       L_AND_G_PATTERNS[i] = reversedWidths;
84     }
85   }
86
87   static int[] findStartGuardPattern(BitArray row) throws ReaderException {
88     boolean foundStart = false;
89     int[] startRange = null;
90     int nextStart = 0;
91     while (!foundStart) {
92       startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
93       int start = startRange[0];
94       nextStart = startRange[1];
95       // As a check, we want to see some white in front of this "start pattern",
96       // maybe as wide as the start pattern itself?
97       foundStart = row.isRange(Math.max(0, start - 2 * (startRange[1] - start)), start, false);
98     }
99     return startRange;
100   }
101
102   public final Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {
103     return decodeRow(rowNumber, row, findStartGuardPattern(row));
104   }
105
106   public final Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) throws ReaderException {
107     StringBuffer result = new StringBuffer(20);
108     int endStart = decodeMiddle(row, startGuardRange, result);
109     int[] endRange = decodeEnd(row, endStart);
110
111     // Check for whitespace after the pattern
112     int end = endRange[1];
113     if (!row.isRange(end, Math.min(row.getSize(), end + 2 * (end - endRange[0])), false)) {
114       throw new ReaderException("Pattern not followed by whitespace");
115     }
116
117     String resultString = result.toString();
118     if (!checkChecksum(resultString)) {
119       throw new ReaderException("Checksum failed");
120     }
121
122     float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
123     float right = (float) (endRange[1] + endRange[0]) / 2.0f;
124     return new Result(resultString,
125         null, // no natural byte representation for these barcodes
126         new ResultPoint[]{
127             new GenericResultPoint(left, (float) rowNumber),
128             new GenericResultPoint(right, (float) rowNumber)},
129         getBarcodeFormat());
130   }
131
132   abstract BarcodeFormat getBarcodeFormat();
133
134   /**
135    * Computes the UPC/EAN checksum on a string of digits, and reports
136    * whether the checksum is correct or not.
137    *
138    * @param s string of digits to check
139    * @return true iff string of digits passes the UPC/EAN checksum algorithm
140    * @throws ReaderException if the string does not contain only digits
141    */
142   boolean checkChecksum(String s) throws ReaderException {
143     int sum = 0;
144     int length = s.length();
145     for (int i = length - 2; i >= 0; i -= 2) {
146       int digit = (int) s.charAt(i) - (int) '0';
147       if (digit < 0 || digit > 9) {
148         throw new ReaderException("Illegal character during checksum");
149       }
150       sum += digit;
151     }
152     sum *= 3;
153     for (int i = length - 1; i >= 0; i -= 2) {
154       int digit = (int) s.charAt(i) - (int) '0';
155       if (digit < 0 || digit > 9) {
156         throw new ReaderException("Illegal character during checksum");
157       }
158       sum += digit;
159     }
160     return sum % 10 == 0;
161   }
162
163   /**
164    * Subclasses override this to decode the portion of a barcode between the start and end guard patterns.
165    *
166    * @param row row of black/white values to search
167    * @param startRange start/end offset of start guard pattern
168    * @param resultString {@link StringBuffer} to append decoded chars to
169    * @return horizontal offset of first pixel after the "middle" that was decoded
170    * @throws ReaderException if decoding could not complete successfully
171    */
172   protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
173       throws ReaderException;
174
175   int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
176     return findGuardPattern(row, endStart, false, START_END_PATTERN);
177   }
178
179   /**
180    * @param row row of black/white values to search
181    * @param rowOffset position to start search
182    * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
183    * pixel counts, otherwise, it is interpreted as black/white/black/...
184    * @param pattern pattern of counts of number of black and white pixels that are being
185    * searched for as a pattern
186    * @return start/end horizontal offset of guard pattern, as an array of two ints
187    * @throws ReaderException if pattern is not found
188    */
189   static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
190       throws ReaderException {
191     int patternLength = pattern.length;
192     int[] counters = new int[patternLength];
193     int width = row.getSize();
194     boolean isWhite = false;
195     while (rowOffset < width) {
196       isWhite = !row.get(rowOffset);
197       if (whiteFirst == isWhite) {
198         break;
199       }
200       rowOffset++;
201     }
202
203     int counterPosition = 0;
204     int patternStart = rowOffset;
205     for (int x = rowOffset; x < width; x++) {
206       boolean pixel = row.get(x);
207       if ((!pixel && isWhite) || (pixel && !isWhite)) {
208         counters[counterPosition]++;
209       } else {
210         if (counterPosition == patternLength - 1) {
211           if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
212             return new int[]{patternStart, x};
213           }
214           patternStart += counters[0] + counters[1];
215           for (int y = 2; y < patternLength; y++) {
216             counters[y - 2] = counters[y];
217           }
218           counters[patternLength - 2] = 0;
219           counters[patternLength - 1] = 0;
220           counterPosition--;
221         } else {
222           counterPosition++;
223         }
224         counters[counterPosition] = 1;
225         isWhite = !isWhite;
226       }
227     }
228     throw new ReaderException("Can't find pattern");
229   }
230
231   /**
232    * Attempts to decode a single UPC/EAN-encoded digit.
233    *
234    * @param row row of black/white values to decode
235    * @param counters the counts of runs of observed black/white/black/... values
236    * @param rowOffset horizontal offset to start decoding from
237    * @param patterns the set of patterns to use to decode -- sometimes different encodings
238    * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
239    * be used
240    * @return horizontal offset of first pixel beyond the decoded digit
241    * @throws ReaderException if digit cannot be decoded
242    */
243   static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
244       throws ReaderException {
245     recordPattern(row, rowOffset, counters);
246     int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
247     int bestMatch = -1;
248     int max = patterns.length;
249     for (int i = 0; i < max; i++) {
250       int[] pattern = patterns[i];
251       int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
252       if (variance < bestVariance) {
253         bestVariance = variance;
254         bestMatch = i;
255       }
256     }
257     if (bestMatch >= 0) {
258       return bestMatch;
259     } else {
260       throw new ReaderException("Could not match any digit in pattern");
261     }
262   }
263
264 }