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