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