Issue 537, don't return UPC-A for EAN-13 starting with 0 when UPC-A isn't allowed
[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(rowNumber, row, endRange[1]);
190       decodeResult.putAllMetadata(extensionResult.getResultMetadata());
191       decodeResult.addResultPoints(extensionResult.getResultPoints());
192     } catch (ReaderException re) {
193       // continue
194     }
195
196     if (BarcodeFormat.EAN_13.equals(format) || BarcodeFormat.UPC_A.equals(format)) {
197       String countryID = eanManSupport.lookupCountryIdentifier(resultString);
198       if (countryID != null) {
199         decodeResult.putMetadata(ResultMetadataType.POSSIBLE_COUNTRY, countryID);
200       }
201     }
202
203     return decodeResult;
204   }
205
206   /**
207    * @return {@link #checkStandardUPCEANChecksum(String)}
208    */
209   boolean checkChecksum(String s) throws ChecksumException, FormatException {
210     return checkStandardUPCEANChecksum(s);
211   }
212
213   /**
214    * Computes the UPC/EAN checksum on a string of digits, and reports
215    * whether the checksum is correct or not.
216    *
217    * @param s string of digits to check
218    * @return true iff string of digits passes the UPC/EAN checksum algorithm
219    * @throws FormatException if the string does not contain only digits
220    */
221   private static boolean checkStandardUPCEANChecksum(String s) throws FormatException {
222     int length = s.length();
223     if (length == 0) {
224       return false;
225     }
226
227     int sum = 0;
228     for (int i = length - 2; i >= 0; i -= 2) {
229       int digit = (int) s.charAt(i) - (int) '0';
230       if (digit < 0 || digit > 9) {
231         throw FormatException.getFormatInstance();
232       }
233       sum += digit;
234     }
235     sum *= 3;
236     for (int i = length - 1; i >= 0; i -= 2) {
237       int digit = (int) s.charAt(i) - (int) '0';
238       if (digit < 0 || digit > 9) {
239         throw FormatException.getFormatInstance();
240       }
241       sum += digit;
242     }
243     return sum % 10 == 0;
244   }
245
246   int[] decodeEnd(BitArray row, int endStart) throws NotFoundException {
247     return findGuardPattern(row, endStart, false, START_END_PATTERN);
248   }
249
250   /**
251    * @param row row of black/white values to search
252    * @param rowOffset position to start search
253    * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
254    * pixel counts, otherwise, it is interpreted as black/white/black/...
255    * @param pattern pattern of counts of number of black and white pixels that are being
256    * searched for as a pattern
257    * @return start/end horizontal offset of guard pattern, as an array of two ints
258    * @throws NotFoundException if pattern is not found
259    */
260   static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
261       throws NotFoundException {
262     int patternLength = pattern.length;
263     int[] counters = new int[patternLength];
264     int width = row.getSize();
265     boolean isWhite = false;
266     while (rowOffset < width) {
267       isWhite = !row.get(rowOffset);
268       if (whiteFirst == isWhite) {
269         break;
270       }
271       rowOffset++;
272     }
273
274     int counterPosition = 0;
275     int patternStart = rowOffset;
276     for (int x = rowOffset; x < width; x++) {
277       boolean pixel = row.get(x);
278       if (pixel ^ isWhite) {
279         counters[counterPosition]++;
280       } else {
281         if (counterPosition == patternLength - 1) {
282           if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
283             return new int[]{patternStart, x};
284           }
285           patternStart += counters[0] + counters[1];
286           for (int y = 2; y < patternLength; y++) {
287             counters[y - 2] = counters[y];
288           }
289           counters[patternLength - 2] = 0;
290           counters[patternLength - 1] = 0;
291           counterPosition--;
292         } else {
293           counterPosition++;
294         }
295         counters[counterPosition] = 1;
296         isWhite = !isWhite;
297       }
298     }
299     throw NotFoundException.getNotFoundInstance();
300   }
301
302   /**
303    * Attempts to decode a single UPC/EAN-encoded digit.
304    *
305    * @param row row of black/white values to decode
306    * @param counters the counts of runs of observed black/white/black/... values
307    * @param rowOffset horizontal offset to start decoding from
308    * @param patterns the set of patterns to use to decode -- sometimes different encodings
309    * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
310    * be used
311    * @return horizontal offset of first pixel beyond the decoded digit
312    * @throws NotFoundException if digit cannot be decoded
313    */
314   static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
315       throws NotFoundException {
316     recordPattern(row, rowOffset, counters);
317     int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
318     int bestMatch = -1;
319     int max = patterns.length;
320     for (int i = 0; i < max; i++) {
321       int[] pattern = patterns[i];
322       int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
323       if (variance < bestVariance) {
324         bestVariance = variance;
325         bestMatch = i;
326       }
327     }
328     if (bestMatch >= 0) {
329       return bestMatch;
330     } else {
331       throw NotFoundException.getNotFoundInstance();
332     }
333   }
334
335   /**
336    * Get the format of this decoder.
337    *
338    * @return The 1D format.
339    */
340   abstract BarcodeFormat getBarcodeFormat();
341
342   /**
343    * Subclasses override this to decode the portion of a barcode between the start
344    * and end guard patterns.
345    *
346    * @param row row of black/white values to search
347    * @param startRange start/end offset of start guard pattern
348    * @param resultString {@link StringBuffer} to append decoded chars to
349    * @return horizontal offset of first pixel after the "middle" that was decoded
350    * @throws NotFoundException if decoding could not complete successfully
351    */
352   protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
353       throws NotFoundException;
354
355 }