2 * Copyright 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.oned;
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;
31 import java.util.Hashtable;
34 * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
35 * of one-dimensional barcodes.</p>
37 * @author dswitkin@google.com (Daniel Switkin)
39 * @author alasdair@google.com (Alasdair Mackintosh)
41 public abstract class UPCEANReader extends OneDReader {
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);
50 * Start/end guard pattern.
52 static final int[] START_END_PATTERN = {1, 1, 1,};
55 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
57 static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
60 * "Odd", or "L" patterns used to encode UPC/EAN digits.
62 static final int[][] L_PATTERNS = {
76 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
78 static final int[][] L_AND_G_PATTERNS;
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];
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];
91 L_AND_G_PATTERNS[i] = reversedWidths;
95 private final StringBuffer decodeRowStringBuffer;
96 private final UPCEANExtensionSupport extensionReader;
97 private final EANManufacturerOrgSupport eanManSupport;
99 protected UPCEANReader() {
100 decodeRowStringBuffer = new StringBuffer(20);
101 extensionReader = new UPCEANExtensionSupport();
102 eanManSupport = new EANManufacturerOrgSupport();
105 static int[] findStartGuardPattern(BitArray row) throws NotFoundException {
106 boolean foundStart = false;
107 int[] startRange = null;
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);
124 public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
125 throws NotFoundException, ChecksumException, FormatException {
126 return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
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>
134 public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
135 throws NotFoundException, ChecksumException, FormatException {
137 ResultPointCallback resultPointCallback = hints == null ? null :
138 (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
140 if (resultPointCallback != null) {
141 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
142 (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
146 StringBuffer result = decodeRowStringBuffer;
148 int endStart = decodeMiddle(row, startGuardRange, result);
150 if (resultPointCallback != null) {
151 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
156 int[] endRange = decodeEnd(row, endStart);
158 if (resultPointCallback != null) {
159 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
160 (endRange[0] + endRange[1]) / 2.0f, rowNumber
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();
173 String resultString = result.toString();
174 if (!checkChecksum(resultString)) {
175 throw ChecksumException.getChecksumInstance();
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
184 new ResultPoint(left, (float) rowNumber),
185 new ResultPoint(right, (float) rowNumber)},
189 Result extensionResult = extensionReader.decodeRow(row, endRange[1]);
190 decodeResult.putAllMetadata(extensionResult.getResultMetadata());
191 } catch (ReaderException re) {
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);
206 * @return {@link #checkStandardUPCEANChecksum(String)}
208 boolean checkChecksum(String s) throws ChecksumException, FormatException {
209 return checkStandardUPCEANChecksum(s);
213 * Computes the UPC/EAN checksum on a string of digits, and reports
214 * whether the checksum is correct or not.
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
220 private static boolean checkStandardUPCEANChecksum(String s) throws FormatException {
221 int length = s.length();
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();
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();
242 return sum % 10 == 0;
245 int[] decodeEnd(BitArray row, int endStart) throws NotFoundException {
246 return findGuardPattern(row, endStart, false, START_END_PATTERN);
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
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) {
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]++;
280 if (counterPosition == patternLength - 1) {
281 if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
282 return new int[]{patternStart, x};
284 patternStart += counters[0] + counters[1];
285 for (int y = 2; y < patternLength; y++) {
286 counters[y - 2] = counters[y];
288 counters[patternLength - 2] = 0;
289 counters[patternLength - 1] = 0;
294 counters[counterPosition] = 1;
298 throw NotFoundException.getNotFoundInstance();
302 * Attempts to decode a single UPC/EAN-encoded digit.
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
310 * @return horizontal offset of first pixel beyond the decoded digit
311 * @throws NotFoundException if digit cannot be decoded
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
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;
327 if (bestMatch >= 0) {
330 throw NotFoundException.getNotFoundInstance();
335 * Get the format of this decoder.
337 * @return The 1D format.
339 abstract BarcodeFormat getBarcodeFormat();
342 * Subclasses override this to decode the portion of a barcode between the start
343 * and end guard patterns.
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
351 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
352 throws NotFoundException;