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