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