be74932d2d5e41a4b5726068a2953c75b3d57e83
[zxing.git] / core / src / com / google / zxing / oned / UPCEANReader.java
1 /*
2  * Copyright 2008 ZXing authors
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.ResultPointCallback;
22 import com.google.zxing.DecodeHintType;
23 import com.google.zxing.ResultPoint;
24 import com.google.zxing.BarcodeFormat;
25 import com.google.zxing.common.BitArray;
26
27 import java.util.Hashtable;
28
29 /**
30  * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
31  * of one-dimensional barcodes.</p>
32  *
33  * @author dswitkin@google.com (Daniel Switkin)
34  * @author Sean Owen
35  * @author alasdair@google.com (Alasdair Mackintosh)
36  */
37 public abstract class UPCEANReader extends OneDReader {
38
39   // These two values are critical for determining how permissive the decoding will be.
40   // We've arrived at these values through a lot of trial and error. Setting them any higher
41   // lets false positives creep in quickly.
42   private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
43   private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
44
45   /**
46    * Start/end guard pattern.
47    */
48   static final int[] START_END_PATTERN = {1, 1, 1,};
49
50   /**
51    * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
52    */
53   static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
54
55   /**
56    * "Odd", or "L" patterns used to encode UPC/EAN digits.
57    */
58   static final int[][] L_PATTERNS = {
59       {3, 2, 1, 1}, // 0
60       {2, 2, 2, 1}, // 1
61       {2, 1, 2, 2}, // 2
62       {1, 4, 1, 1}, // 3
63       {1, 1, 3, 2}, // 4
64       {1, 2, 3, 1}, // 5
65       {1, 1, 1, 4}, // 6
66       {1, 3, 1, 2}, // 7
67       {1, 2, 1, 3}, // 8
68       {3, 1, 1, 2}  // 9
69   };
70
71   /**
72    * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
73    */
74   static final int[][] L_AND_G_PATTERNS;
75
76   static {
77     L_AND_G_PATTERNS = new int[20][];
78     for (int i = 0; i < 10; i++) {
79       L_AND_G_PATTERNS[i] = L_PATTERNS[i];
80     }
81     for (int i = 10; i < 20; i++) {
82       int[] widths = L_PATTERNS[i - 10];
83       int[] reversedWidths = new int[widths.length];
84       for (int j = 0; j < widths.length; j++) {
85         reversedWidths[j] = widths[widths.length - j - 1];
86       }
87       L_AND_G_PATTERNS[i] = reversedWidths;
88     }
89   }
90
91   private final StringBuffer decodeRowStringBuffer;
92
93   protected UPCEANReader() {
94     decodeRowStringBuffer = new StringBuffer(20);
95   }
96
97   static int[] findStartGuardPattern(BitArray row) throws ReaderException {
98     boolean foundStart = false;
99     int[] startRange = null;
100     int nextStart = 0;
101     while (!foundStart) {
102       startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
103       int start = startRange[0];
104       nextStart = startRange[1];
105       // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
106       // If this check would run off the left edge of the image, do not accept this barcode,
107       // as it is very likely to be a false positive.
108       int quietStart = start - (nextStart - start);
109       if (quietStart >= 0) {
110         foundStart = row.isRange(quietStart, start, false);
111       }
112     }
113     return startRange;
114   }
115
116   public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {
117     return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
118   }
119
120   /**
121    * <p>Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but
122    * allows caller to inform method about where the UPC/EAN start pattern is
123    * found. This allows this to be computed once and reused across many implementations.</p>
124    */
125   public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
126       throws ReaderException {
127
128     ResultPointCallback resultPointCallback = hints == null ? null :
129         (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
130
131     if (resultPointCallback != null) {
132       resultPointCallback.foundPossibleResultPoint(new ResultPoint(
133           (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
134       ));
135     }
136
137     StringBuffer result = decodeRowStringBuffer;
138     result.setLength(0);
139     int endStart = decodeMiddle(row, startGuardRange, result);
140
141     if (resultPointCallback != null) {
142       resultPointCallback.foundPossibleResultPoint(new ResultPoint(
143           endStart, rowNumber
144       ));
145     }
146
147     int[] endRange = decodeEnd(row, endStart);
148
149     if (resultPointCallback != null) {
150       resultPointCallback.foundPossibleResultPoint(new ResultPoint(
151           (endRange[0] + endRange[1]) / 2.0f, rowNumber
152       ));
153     }
154
155
156     // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
157     // spec might want more whitespace, but in practice this is the maximum we can count on.
158     int end = endRange[1];
159     int quietEnd = end + (end - endRange[0]);
160     if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {
161       throw ReaderException.getInstance();
162     }
163
164     String resultString = result.toString();
165     if (!checkChecksum(resultString)) {
166       throw ReaderException.getInstance();
167     }
168
169     float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
170     float right = (float) (endRange[1] + endRange[0]) / 2.0f;
171     return new Result(resultString,
172         null, // no natural byte representation for these barcodes
173         new ResultPoint[]{
174             new ResultPoint(left, (float) rowNumber),
175             new ResultPoint(right, (float) rowNumber)},
176         getBarcodeFormat());
177   }
178
179   /**
180    * @return {@link #checkStandardUPCEANChecksum(String)}
181    */
182   boolean checkChecksum(String s) throws ReaderException {
183     return checkStandardUPCEANChecksum(s);
184   }
185
186   /**
187    * Computes the UPC/EAN checksum on a string of digits, and reports
188    * whether the checksum is correct or not.
189    *
190    * @param s string of digits to check
191    * @return true iff string of digits passes the UPC/EAN checksum algorithm
192    * @throws ReaderException if the string does not contain only digits
193    */
194   private static boolean checkStandardUPCEANChecksum(String s) throws ReaderException {
195     int length = s.length();
196     if (length == 0) {
197       return false;
198     }
199
200     int sum = 0;
201     for (int i = length - 2; i >= 0; i -= 2) {
202       int digit = (int) s.charAt(i) - (int) '0';
203       if (digit < 0 || digit > 9) {
204         throw ReaderException.getInstance();
205       }
206       sum += digit;
207     }
208     sum *= 3;
209     for (int i = length - 1; i >= 0; i -= 2) {
210       int digit = (int) s.charAt(i) - (int) '0';
211       if (digit < 0 || digit > 9) {
212         throw ReaderException.getInstance();
213       }
214       sum += digit;
215     }
216     return sum % 10 == 0;
217   }
218
219   int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
220     return findGuardPattern(row, endStart, false, START_END_PATTERN);
221   }
222
223   /**
224    * @param row row of black/white values to search
225    * @param rowOffset position to start search
226    * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
227    * pixel counts, otherwise, it is interpreted as black/white/black/...
228    * @param pattern pattern of counts of number of black and white pixels that are being
229    * searched for as a pattern
230    * @return start/end horizontal offset of guard pattern, as an array of two ints
231    * @throws ReaderException if pattern is not found
232    */
233   static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
234       throws ReaderException {
235     int patternLength = pattern.length;
236     int[] counters = new int[patternLength];
237     int width = row.getSize();
238     boolean isWhite = false;
239     while (rowOffset < width) {
240       isWhite = !row.get(rowOffset);
241       if (whiteFirst == isWhite) {
242         break;
243       }
244       rowOffset++;
245     }
246
247     int counterPosition = 0;
248     int patternStart = rowOffset;
249     for (int x = rowOffset; x < width; x++) {
250       boolean pixel = row.get(x);
251       if (pixel ^ isWhite) {
252         counters[counterPosition]++;
253       } else {
254         if (counterPosition == patternLength - 1) {
255           if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
256             return new int[]{patternStart, x};
257           }
258           patternStart += counters[0] + counters[1];
259           for (int y = 2; y < patternLength; y++) {
260             counters[y - 2] = counters[y];
261           }
262           counters[patternLength - 2] = 0;
263           counters[patternLength - 1] = 0;
264           counterPosition--;
265         } else {
266           counterPosition++;
267         }
268         counters[counterPosition] = 1;
269         isWhite ^= true; // isWhite = !isWhite;
270       }
271     }
272     throw ReaderException.getInstance();
273   }
274
275   /**
276    * Attempts to decode a single UPC/EAN-encoded digit.
277    *
278    * @param row row of black/white values to decode
279    * @param counters the counts of runs of observed black/white/black/... values
280    * @param rowOffset horizontal offset to start decoding from
281    * @param patterns the set of patterns to use to decode -- sometimes different encodings
282    * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
283    * be used
284    * @return horizontal offset of first pixel beyond the decoded digit
285    * @throws ReaderException if digit cannot be decoded
286    */
287   static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
288       throws ReaderException {
289     recordPattern(row, rowOffset, counters);
290     int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
291     int bestMatch = -1;
292     int max = patterns.length;
293     for (int i = 0; i < max; i++) {
294       int[] pattern = patterns[i];
295       int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
296       if (variance < bestVariance) {
297         bestVariance = variance;
298         bestMatch = i;
299       }
300     }
301     if (bestMatch >= 0) {
302       return bestMatch;
303     } else {
304       throw ReaderException.getInstance();
305     }
306   }
307
308   /**
309    * Get the format of this decoder.
310    *
311    * @return The 1D format.
312    */
313   abstract BarcodeFormat getBarcodeFormat();
314
315   /**
316    * Subclasses override this to decode the portion of a barcode between the start
317    * and end guard patterns.
318    *
319    * @param row row of black/white values to search
320    * @param startRange start/end offset of start guard pattern
321    * @param resultString {@link StringBuffer} to append decoded chars to
322    * @return horizontal offset of first pixel after the "middle" that was decoded
323    * @throws ReaderException if decoding could not complete successfully
324    */
325   protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
326       throws ReaderException;
327
328 }