Removed three interfaces which weren't doing any good and were making the 1D class...
[zxing.git] / core / src / com / google / zxing / oned / OneDReader.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.BinaryBitmap;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.Reader;
22 import com.google.zxing.ReaderException;
23 import com.google.zxing.Result;
24 import com.google.zxing.ResultMetadataType;
25 import com.google.zxing.ResultPoint;
26 import com.google.zxing.common.BitArray;
27
28 import java.util.Hashtable;
29
30 /**
31  * Encapsulates functionality and implementation that is common to all families
32  * of one-dimensional barcodes.
33  *
34  * @author dswitkin@google.com (Daniel Switkin)
35  * @author Sean Owen
36  */
37 public abstract class OneDReader implements Reader {
38
39   private static final int INTEGER_MATH_SHIFT = 8;
40   static final int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
41
42   public Result decode(BinaryBitmap image) throws ReaderException {
43     return decode(image, null);
44   }
45
46   // Note that we don't try rotation without the try harder flag, even if rotation was supported.
47   public Result decode(BinaryBitmap image, Hashtable hints) throws ReaderException {
48     try {
49       return doDecode(image, hints);
50     } catch (ReaderException re) {
51       boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
52       if (tryHarder && image.isRotateSupported()) {
53         BinaryBitmap rotatedImage = image.rotateCounterClockwise();
54         Result result = doDecode(rotatedImage, hints);
55         // Record that we found it rotated 90 degrees CCW / 270 degrees CW
56         Hashtable metadata = result.getResultMetadata();
57         int orientation = 270;
58         if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) {
59           // But if we found it reversed in doDecode(), add in that result here:
60           orientation = (orientation +
61               ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
62         }
63         result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
64         return result;
65       } else {
66         throw re;
67       }
68     }
69   }
70
71   /**
72    * We're going to examine rows from the middle outward, searching alternately above and below the
73    * middle, and farther out each time. rowStep is the number of rows between each successive
74    * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
75    * middle + rowStep, then middle - (2 * rowStep), etc.
76    * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
77    * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
78    * image if "trying harder".
79    *
80    * @param image The image to decode
81    * @param hints Any hints that were requested
82    * @return The contents of the decoded barcode
83    * @throws ReaderException Any spontaneous errors which occur
84    */
85   private Result doDecode(BinaryBitmap image, Hashtable hints) throws ReaderException {
86     int width = image.getWidth();
87     int height = image.getHeight();
88     BitArray row = new BitArray(width);
89
90     int middle = height >> 1;
91     boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
92     int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
93     int maxLines;
94     if (tryHarder) {
95       maxLines = height; // Look at the whole image, not just the center
96     } else {
97       maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
98     }
99
100     for (int x = 0; x < maxLines; x++) {
101
102       // Scanning from the middle out. Determine which row we're looking at next:
103       int rowStepsAboveOrBelow = (x + 1) >> 1;
104       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
105       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
106       if (rowNumber < 0 || rowNumber >= height) {
107         // Oops, if we run off the top or bottom, stop
108         break;
109       }
110
111       // Estimate black point for this row and load it:
112       try {
113         row = image.getBlackRow(rowNumber, row);
114       } catch (ReaderException re) {
115         continue;
116       }
117
118       // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
119       // handle decoding upside down barcodes.
120       for (int attempt = 0; attempt < 2; attempt++) {
121         if (attempt == 1) { // trying again?
122           row.reverse(); // reverse the row and continue
123           // This means we will only ever draw result points *once* in the life of this method
124           // since we want to avoid drawing the wrong points after flipping the row, and,
125           // don't want to clutter with noise from every single row scan -- just the scans
126           // that start on the center line.
127           if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
128             hints = (Hashtable) hints.clone();
129             hints.remove(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
130           }
131         }
132         try {
133           // Look for a barcode
134           Result result = decodeRow(rowNumber, row, hints);
135           // We found our barcode
136           if (attempt == 1) {
137             // But it was upside down, so note that
138             result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
139             // And remember to flip the result points horizontally.
140             ResultPoint[] points = result.getResultPoints();
141             points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());
142             points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());
143           }
144           return result;
145         } catch (ReaderException re) {
146           // continue -- just couldn't decode this row
147         }
148       }
149     }
150
151     throw ReaderException.getInstance();
152   }
153
154   /**
155    * Records the size of successive runs of white and black pixels in a row, starting at a given point.
156    * The values are recorded in the given array, and the number of runs recorded is equal to the size
157    * of the array. If the row starts on a white pixel at the given start point, then the first count
158    * recorded is the run of white pixels starting from that point; likewise it is the count of a run
159    * of black pixels if the row begin on a black pixels at that point.
160    *
161    * @param row row to count from
162    * @param start offset into row to start at
163    * @param counters array into which to record counts
164    * @throws ReaderException if counters cannot be filled entirely from row before running out
165    *  of pixels
166    */
167   static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
168     int numCounters = counters.length;
169     for (int i = 0; i < numCounters; i++) {
170       counters[i] = 0;
171     }
172     int end = row.getSize();
173     if (start >= end) {
174       throw ReaderException.getInstance();
175     }
176     boolean isWhite = !row.get(start);
177     int counterPosition = 0;
178     int i = start;
179     while (i < end) {
180       boolean pixel = row.get(i);
181       if (pixel ^ isWhite) { // that is, exactly one is true
182         counters[counterPosition]++;
183       } else {
184         counterPosition++;
185         if (counterPosition == numCounters) {
186           break;
187         } else {
188           counters[counterPosition] = 1;
189           isWhite = !isWhite;
190         }
191       }
192       i++;
193     }
194     // If we read fully the last section of pixels and filled up our counters -- or filled
195     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
196     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
197       throw ReaderException.getInstance();
198     }
199   }
200
201   /**
202    * Determines how closely a set of observed counts of runs of black/white values matches a given
203    * target pattern. This is reported as the ratio of the total variance from the expected pattern
204    * proportions across all pattern elements, to the length of the pattern.
205    *
206    * @param counters observed counters
207    * @param pattern expected pattern
208    * @param maxIndividualVariance The most any counter can differ before we give up
209    * @return ratio of total variance between counters and pattern compared to total pattern size,
210    *  where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
211    *  the total variance between counters and patterns equals the pattern length, higher values mean
212    *  even more variance
213    */
214   static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
215     int numCounters = counters.length;
216     int total = 0;
217     int patternLength = 0;
218     for (int i = 0; i < numCounters; i++) {
219       total += counters[i];
220       patternLength += pattern[i];
221     }
222     if (total < patternLength) {
223       // If we don't even have one pixel per unit of bar width, assume this is too small
224       // to reliably match, so fail:
225       return Integer.MAX_VALUE;
226     }
227     // We're going to fake floating-point math in integers. We just need to use more bits.
228     // Scale up patternLength so that intermediate values below like scaledCounter will have
229     // more "significant digits"
230     int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
231     maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
232
233     int totalVariance = 0;
234     for (int x = 0; x < numCounters; x++) {
235       int counter = counters[x] << INTEGER_MATH_SHIFT;
236       int scaledPattern = pattern[x] * unitBarWidth;
237       int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
238       if (variance > maxIndividualVariance) {
239         return Integer.MAX_VALUE;
240       }
241       totalVariance += variance;
242     }
243     return totalVariance / total;
244   }
245
246   /**
247    * <p>Attempts to decode a one-dimensional barcode format given a single row of
248    * an image.</p>
249    *
250    * @param rowNumber row number from top of the row
251    * @param row the black/white pixel data of the row
252    * @param hints decode hints
253    * @return {@link Result} containing encoded string and start/end of barcode
254    * @throws ReaderException if an error occurs or barcode cannot be found
255    */
256   public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
257       throws ReaderException;
258
259 }