Another round of optimization, focused on reusing arrays and small objects.
[zxing.git] / core / src / com / google / zxing / oned / Code39Reader.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.BarcodeFormat;
20 import com.google.zxing.ReaderException;
21 import com.google.zxing.Result;
22 import com.google.zxing.ResultPoint;
23 import com.google.zxing.common.BitArray;
24 import com.google.zxing.common.GenericResultPoint;
25
26 import java.util.Hashtable;
27
28 /**
29  * <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p>
30  *
31  * @author srowen@google.com (Sean Owen)
32  */
33 public final class Code39Reader extends AbstractOneDReader {
34
35   private static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
36   private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
37
38   /**
39    * These represent the encodings of characters, as patterns of wide and narrow bars.
40    * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
41    * with 1s representing "wide" and 0s representing narrow.
42    */
43   private static final int[] CHARACTER_ENCODINGS = {
44       0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
45       0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
46       0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
47       0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
48       0x0A8, 0x0A2, 0x08A, 0x02A // $-%
49   };
50
51   private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
52
53   private final boolean usingCheckDigit;
54   private final boolean extendedMode;
55
56   /**
57    * Creates a reader that assumes all encoded data is data, and does not treat the final
58    * character as a check digit. It will not decoded "extended Code 39" sequences.
59    */
60   public Code39Reader() {
61     usingCheckDigit = false;
62     extendedMode = false;
63   }
64
65   /**
66    * Creates a reader that can be configured to check the last character as a check digit.
67    * It will not decoded "extended Code 39" sequences.
68    *
69    * @param usingCheckDigit if true, treat the last data character as a check digit, not
70    * data, and verify that the checksum passes.
71    */
72   public Code39Reader(boolean usingCheckDigit) {
73     this.usingCheckDigit = usingCheckDigit;
74     this.extendedMode = false;
75   }
76
77   /**
78    * Creates a reader that can be configured to check the last character as a check digit,
79    * or optionally attempt to decode "extended Code 39" sequences that are used to encode
80    * the full ASCII character set.
81    *
82    * @param usingCheckDigit if true, treat the last data character as a check digit, not
83    * data, and verify that the checksum passes.
84    * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
85    * text.
86    */
87   public Code39Reader(boolean usingCheckDigit, boolean extendedMode) {
88     this.usingCheckDigit = usingCheckDigit;
89     this.extendedMode = extendedMode;
90   }
91
92   public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {
93
94     int[] start = findAsteriskPattern(row);
95     int nextStart = start[1];
96     int end = row.getSize();
97
98     // Read off white space
99     while (nextStart < end && !row.get(nextStart)) {
100       nextStart++;
101     }
102
103     StringBuffer result = new StringBuffer();
104     int[] counters = new int[9];
105     char decodedChar;
106     int lastStart;
107     do {
108       recordPattern(row, nextStart, counters);
109       int pattern = toNarrowWidePattern(counters);
110       decodedChar = patternToChar(pattern);
111       result.append(decodedChar);
112       lastStart = nextStart;
113       for (int i = 0; i < counters.length; i++) {
114         nextStart += counters[i];
115       }
116       // Read off white space
117       while (nextStart < end && !row.get(nextStart)) {
118         nextStart++;
119       }
120     } while (decodedChar != '*');
121     result.deleteCharAt(result.length() - 1); // remove asterisk
122
123     // Look for whitespace after pattern:
124     int lastPatternSize = 0;
125     for (int i = 0; i < counters.length; i++) {
126       lastPatternSize += counters[i];
127     }
128     int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
129     // If 50% of last pattern size, following last pattern, is not whitespace, fail
130     // (but if it's whitespace to the very end of the image, that's OK)
131     if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
132       throw new ReaderException("Pattern not followed by whitespace");
133     }
134
135     if (usingCheckDigit) {
136       int max = result.length() - 1;
137       int total = 0;
138       for (int i = 0; i < max; i++) {
139         total += ALPHABET_STRING.indexOf(result.charAt(i));
140       }
141       if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
142         throw new ReaderException("Checksum failed");
143       }
144       result.deleteCharAt(max);
145     }
146
147     String resultString = result.toString();
148     if (extendedMode) {
149       resultString = decodeExtended(resultString);
150     }
151
152     if (resultString.length() == 0) {
153       // Almost surely a false positive
154       throw new ReaderException("Empty barcode found; assuming a false positive");
155     }
156
157     float left = (float) (start[1] + start[0]) / 2.0f;
158     float right = (float) (nextStart + lastStart) / 2.0f;
159     return new Result(
160         resultString,
161         null,
162         new ResultPoint[]{
163             new GenericResultPoint(left, (float) rowNumber),
164             new GenericResultPoint(right, (float) rowNumber)},
165         BarcodeFormat.CODE_39);
166
167   }
168
169   private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
170     int width = row.getSize();
171     int rowOffset = 0;
172     while (rowOffset < width) {
173       if (row.get(rowOffset)) {
174         break;
175       }
176       rowOffset++;
177     }
178
179     int counterPosition = 0;
180     int[] counters = new int[9];
181     int patternStart = rowOffset;
182     boolean isWhite = false;
183     int patternLength = counters.length;
184
185     for (int i = rowOffset; i < width; i++) {
186       boolean pixel = row.get(i);
187       if ((!pixel && isWhite) || (pixel && !isWhite)) {
188         counters[counterPosition]++;
189       } else {
190         if (counterPosition == patternLength - 1) {
191           try {
192             if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
193               // Look for whitespace before start pattern, >= 50% of width of start pattern
194               if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
195                 return new int[]{patternStart, i};
196               }
197             }
198           } catch (ReaderException re) {
199             // no match, continue
200           }
201           patternStart += counters[0] + counters[1];
202           for (int y = 2; y < patternLength; y++) {
203             counters[y - 2] = counters[y];
204           }
205           counters[patternLength - 2] = 0;
206           counters[patternLength - 1] = 0;
207           counterPosition--;
208         } else {
209           counterPosition++;
210         }
211         counters[counterPosition] = 1;
212         isWhite = !isWhite;
213       }
214     }
215     throw new ReaderException("Can't find pattern");
216   }
217
218   private static int toNarrowWidePattern(int[] counters) throws ReaderException {
219     int numCounters = counters.length;
220     int maxNarrowCounter = 0;
221     int wideCounters;
222     do {
223       int minCounter = Integer.MAX_VALUE;
224       for (int i = 0; i < numCounters; i++) {
225         int counter = counters[i];
226         if (counter < minCounter && counter > maxNarrowCounter) {
227           minCounter = counter;
228         }
229       }
230       maxNarrowCounter = minCounter;
231       wideCounters = 0;
232       int totalWideCountersWidth = 0;
233       int pattern = 0;
234       for (int i = 0; i < numCounters; i++) {
235         int counter = counters[i];
236         if (counters[i] > maxNarrowCounter) {
237           pattern |= 1 << (numCounters - 1 - i);
238           wideCounters++;
239           totalWideCountersWidth += counter;
240         }
241       }
242       if (wideCounters == 3) {
243         // Found 3 wide counters, but are they close enough in width?
244         // We can perform a cheap, conservative check to see if any individual
245         // counter is more than 1.5 times the average:
246         for (int i = 0; i < numCounters && wideCounters > 0; i++) {
247           int counter = counters[i];
248           if (counters[i] > maxNarrowCounter) {
249             wideCounters--;
250             // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
251             if ((counter << 1) >= totalWideCountersWidth) {
252               throw new ReaderException("Wide bars vary too much in width, rejecting");
253             }
254           }
255         }
256         return pattern;
257       }
258     } while (wideCounters > 3);
259     throw new ReaderException("Can't find 3 wide bars/spaces out of 9");
260   }
261
262   private static char patternToChar(int pattern) throws ReaderException {
263     for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
264       if (CHARACTER_ENCODINGS[i] == pattern) {
265         return ALPHABET[i];
266       }
267     }
268     throw new ReaderException("Pattern did not match character encoding");
269   }
270
271   private static String decodeExtended(String encoded) throws ReaderException {
272     int length = encoded.length();
273     StringBuffer decoded = new StringBuffer(length);
274     for (int i = 0; i < length; i++) {
275       char c = encoded.charAt(i);
276       if (c == '+' || c == '$' || c == '%' || c == '/') {
277         char next = encoded.charAt(i + 1);
278         char decodedChar = '\0';
279         switch (c) {
280           case '+':
281             // +A to +Z map to a to z
282             if (next >= 'A' && next <= 'Z') {
283               decodedChar = (char) (next + 32);
284             } else {
285               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
286             }
287             break;
288           case '$':
289             // $A to $Z map to control codes SH to SB
290             if (next >= 'A' && next <= 'Z') {
291               decodedChar = (char) (next - 64);
292             } else {
293               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
294             }
295             break;
296           case '%':
297             // %A to %E map to control codes ESC to US
298             if (next >= 'A' && next <= 'E') {
299               decodedChar = (char) (next - 38);
300             } else if (next >= 'F' && next <= 'W') {
301               decodedChar = (char) (next - 11);
302             } else {
303               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
304             }
305             break;
306           case '/':
307             // /A to /O map to ! to , and /Z maps to :
308             if (next >= 'A' && next <= 'O') {
309               decodedChar = (char) (next - 32);
310             } else if (next == 'Z') {
311               decodedChar = ':';
312             } else {
313               throw new ReaderException("Invalid extended sequence: " + c + next);
314             }
315             break;
316         }
317         decoded.append(decodedChar);
318         // bump up i again since we read two characters
319         i++;
320       } else {
321         decoded.append(c);
322       }
323     }
324     return decoded.toString();
325   }
326
327 }