- Fixed a crash when parsing a particular VCard with a blank entry.
[zxing.git] / core / src / com / google / zxing / oned / AbstractOneDReader.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.BlackPointEstimationMethod;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.MonochromeBitmapSource;
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 import com.google.zxing.common.GenericResultPoint;
28
29 import java.util.Hashtable;
30
31 /**
32  * <p>Encapsulates functionality and implementation that is common to all families
33  * of one-dimensional barcodes.</p>
34  *
35  * @author dswitkin@google.com (Daniel Switkin)
36  * @author srowen@google.com (Sean Owen)
37  */
38 public abstract class AbstractOneDReader implements OneDReader {
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 final Result decode(MonochromeBitmapSource image) throws ReaderException {
44     return decode(image, null);
45   }
46
47   public final Result decode(MonochromeBitmapSource 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         MonochromeBitmapSource 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 + ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
61         }
62         result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
63         return result;
64       } else {
65         throw re;
66       }
67     }
68   }
69
70   /**
71    * We're going to examine rows from the middle outward, searching alternately above and below the
72    * middle, and farther out each time. rowStep is the number of rows between each successive
73    * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
74    * middle + rowStep, then middle - (2 * rowStep), etc.
75    * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
76    * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
77    * image if "trying harder".
78    *
79    * @param image The image to decode
80    * @param hints Any hints that were requested
81    * @return The contents of the decoded barcode
82    * @throws ReaderException Any spontaneous errors which occur
83    */
84   private Result doDecode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException {
85     int width = image.getWidth();
86     int height = image.getHeight();
87     BitArray row = new BitArray(width);
88
89     int middle = height >> 1;
90     boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
91     int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
92     int maxLines;
93     if (tryHarder) {
94       maxLines = height; // Look at the whole image, not just the center
95     } else {
96       maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
97     }
98
99     for (int x = 0; x < maxLines; x++) {
100
101       // Scanning from the middle out. Determine which row we're looking at next:
102       int rowStepsAboveOrBelow = (x + 1) >> 1;
103       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
104       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
105       if (rowNumber < 0 || rowNumber >= height) {
106         // Oops, if we run off the top or bottom, stop
107         break;
108       }
109
110       // Estimate black point for this row and load it:
111       try {
112         image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
113       } catch (ReaderException re) {
114         continue;
115       }
116       image.getBlackRow(rowNumber, row, 0, width);
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         }
124         try {
125           // Look for a barcode
126           Result result = decodeRow(rowNumber, row, hints);
127           // We found our barcode
128           if (attempt == 1) {
129             // But it was upside down, so note that
130             result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
131             // And remember to flip the result points horizontally.
132             ResultPoint[] points = result.getResultPoints();
133             points[0] = new GenericResultPoint(width - points[0].getX() - 1, points[0].getY());
134             points[1] = new GenericResultPoint(width - points[1].getX() - 1, points[1].getY());
135           }
136           return result;
137         } catch (ReaderException re) {
138           // continue -- just couldn't decode this row
139         }
140       }
141     }
142
143     throw new ReaderException("No barcode found");
144   }
145
146   /**
147    * Records the size of successive runs of white and black pixels in a row, starting at a given point.
148    * The values are recorded in the given array, and the number of runs recorded is equal to the size
149    * of the array. If the row starts on a white pixel at the given start point, then the first count
150    * recorded is the run of white pixels starting from that point; likewise it is the count of a run
151    * of black pixels if the row begin on a black pixels at that point.
152    *
153    * @param row row to count from
154    * @param start offset into row to start at
155    * @param counters array into which to record counts
156    * @throws ReaderException if counters cannot be filled entirely from row before running out of pixels
157    */
158   static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
159     int numCounters = counters.length;
160     for (int i = 0; i < numCounters; i++) {
161       counters[i] = 0;
162     }
163     int end = row.getSize();
164     if (start >= end) {
165       throw new ReaderException("Couldn't fully read a pattern");
166     }
167     boolean isWhite = !row.get(start);
168     int counterPosition = 0;
169     int i = start;
170     while (i < end) {
171       boolean pixel = row.get(i);
172       if ((!pixel && isWhite) || (pixel && !isWhite)) {
173         counters[counterPosition]++;
174       } else {
175         counterPosition++;
176         if (counterPosition == numCounters) {
177           break;
178         } else {
179           counters[counterPosition] = 1;
180           isWhite = !isWhite;
181         }
182       }
183       i++;
184     }
185     // If we read fully the last section of pixels and filled up our counters -- or filled
186     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
187     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
188       throw new ReaderException("Couldn't fully read a pattern");
189     }
190   }
191
192   /**
193    * Determines how closely a set of observed counts of runs of black/white values matches a given
194    * target pattern. This is reported as the ratio of the total variance from the expected pattern
195    * proportions across all pattern elements, to the length of the pattern.
196    *
197    * @param counters observed counters
198    * @param pattern expected pattern
199    * @param maxIndividualVariance The most any counter can differ before we give up
200    * @return ratio of total variance between counters and pattern compared to total pattern size,
201    *  where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
202    *  the total variance between counters and patterns equals the pattern length, higher values mean
203    *  even more variance
204    */
205   static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
206     int numCounters = counters.length;
207     int total = 0;
208     int patternLength = 0;
209     for (int i = 0; i < numCounters; i++) {
210       total += counters[i];
211       patternLength += pattern[i];
212     }
213     if (total < patternLength) {
214       // If we don't even have one pixel per unit of bar width, assume this is too small
215       // to reliably match, so fail:
216       return Integer.MAX_VALUE;
217     }
218     // We're going to fake floating-point math in integers. We just need to use more bits.
219     // Scale up patternLength so that intermediate values below like scaledCounter will have
220     // more "significant digits"
221     int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
222     maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
223
224     int totalVariance = 0;
225     for (int x = 0; x < numCounters; x++) {
226       int counter = counters[x] << INTEGER_MATH_SHIFT;
227       int scaledPattern = pattern[x] * unitBarWidth;
228       int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
229       if (variance > maxIndividualVariance) {
230         return Integer.MAX_VALUE;
231       }
232       totalVariance += variance; 
233     }
234     return totalVariance / total;
235   }
236
237   // This declaration should not be necessary, since this class is
238   // abstract and so does not have to provide an implementation for every
239   // method of an interface it implements, but it is causing NoSuchMethodError
240   // issues on some Nokia JVMs. So we add this superfluous declaration:
241
242   public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException;
243
244 }