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