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