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