Small optimization to check ranges of bits set in BitArray in bulk
[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 = row.isRange(Math.max(0, start - 2 * (startRange[1] - start)), start, false);
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 (!row.isRange(end, Math.min(row.getSize(), end + 2 * (end - endRange[0])), false)) {
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    * Computes the UPC/EAN checksum on a string of digits, and reports
120    * whether the checksum is correct or not.
121    *
122    * @param s string of digits to check
123    * @return true iff string of digits passes the UPC/EAN checksum algorithm
124    * @throws ReaderException if the string does not contain only digits
125    */
126   protected boolean checkChecksum(String s) throws ReaderException {
127     int sum = 0;
128     int length = s.length();
129     for (int i = length - 2; i >= 0; i -= 2) {
130       int digit = (int) s.charAt(i) - (int) '0';
131       if (digit < 0 || digit > 9) {
132         throw new ReaderException("Illegal character during checksum");
133       }
134       sum += digit;
135     }
136     sum *= 3;
137     for (int i = length - 1; 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     return sum % 10 == 0;
145   }
146
147   /**
148    * Subclasses override this to decode the portion of a barcode between the start and end guard patterns.
149    *
150    * @param row row of black/white values to search
151    * @param startRange start/end offset of start guard pattern
152    * @param resultString {@link StringBuffer} to append decoded chars to
153    * @return horizontal offset of first pixel after the "middle" that was decoded
154    * @throws ReaderException if decoding could not complete successfully
155    */
156   protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
157       throws ReaderException;
158
159   protected int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
160     return findGuardPattern(row, endStart, false, START_END_PATTERN);
161   }
162
163   /**
164    * @param row row of black/white values to search
165    * @param rowOffset position to start search
166    * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
167    *  pixel counts, otherwise, it is interpreted as black/white/black/...
168    * @param pattern pattern of counts of number of black and white pixels that are being
169    *  searched for as a pattern
170    * @return start/end horizontal offset of guard pattern, as an array of two ints
171    * @throws ReaderException if pattern is not found
172    */
173   protected static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
174       throws ReaderException {
175     int patternLength = pattern.length;
176     int[] counters = new int[patternLength];
177     int width = row.getSize();
178     boolean isWhite = false;
179     while (rowOffset < width) {
180       isWhite = !row.get(rowOffset);
181       if (whiteFirst == isWhite) {
182         break;
183       }
184       rowOffset++;
185     }
186
187     int counterPosition = 0;
188     int patternStart = rowOffset;
189     for (int x = rowOffset; x < width; x++) {
190       boolean pixel = row.get(x);
191       if ((!pixel && isWhite) || (pixel && !isWhite)) {
192         counters[counterPosition]++;
193       } else {
194         if (counterPosition == patternLength - 1) {
195           if (patternMatchVariance(counters, pattern) < MAX_VARIANCE) {
196             return new int[] {patternStart, x};
197           }
198           patternStart += counters[0] + counters[1];
199           for (int y = 2; y < patternLength; y++) {
200             counters[y - 2] = counters[y];
201           }
202           counterPosition--;
203         } else {
204           counterPosition++;
205         }
206         counters[counterPosition] = 1;
207         isWhite = !isWhite;
208       }
209     }
210     throw new ReaderException("Can't find pattern");
211   }
212
213   /**
214    * Attempts to decode a single UPC/EAN-encoded digit.
215    *
216    * @param row row of black/white values to decode
217    * @param counters the counts of runs of observed black/white/black/... values
218    * @param rowOffset horizontal offset to start decoding from
219    * @param patterns the set of patterns to use to decode -- sometimes different encodings
220    *  for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
221    *  be used
222    * @return horizontal offset of first pixel beyond the decoded digit
223    * @throws ReaderException if digit cannot be decoded
224    */
225   protected static int decodeDigit(BitArray row,
226                                    int[] counters,
227                                    int rowOffset,
228                                    int[][] patterns) throws ReaderException {
229     recordPattern(row, rowOffset, counters);
230     float bestVariance = MAX_VARIANCE; // worst variance we'll accept
231     int bestMatch = -1;
232     for (int d = 0; d < patterns.length; d++) {
233       int[] pattern = patterns[d];
234       float variance = patternMatchVariance(counters, pattern);
235       if (variance < bestVariance) {
236         bestVariance = variance;
237         bestMatch = d;
238       }
239     }
240     if (bestMatch >= 0) {
241       return bestMatch;
242     } else {
243       throw new ReaderException("Could not match any digit in pattern");
244     }
245   }
246
247 }