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