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