Add check for minimal whitespace before/after Code 128, Code 39; a few code tweaks...
[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
96     int nextStart = start[1];
97
98     int end = row.getSize();
99
100     // Read off white space
101     while (nextStart < end && !row.get(nextStart)) {
102       nextStart++;
103     }
104
105     StringBuffer result = new StringBuffer();
106     int[] counters = new int[9];
107     char decodedChar;
108     int lastStart;
109     do {
110       recordPattern(row, nextStart, counters);
111       int pattern = toNarrowWidePattern(counters);
112       decodedChar = patternToChar(pattern);
113       result.append(decodedChar);
114       lastStart = nextStart;
115       for (int i = 0; i < counters.length; i++) {
116         nextStart += counters[i];
117       }
118       // Read off white space
119       while (nextStart < end && !row.get(nextStart)) {
120         nextStart++;
121       }
122     } while (decodedChar != '*');
123     result.deleteCharAt(result.length() - 1); // remove asterisk
124
125     // Look for whitespace after pattern:
126     int lastPatternSize = 0;
127     for (int i = 0; i < counters.length; i++) {
128       lastPatternSize += counters[i];
129     }
130     int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
131     // If 50% of last pattern size, following last pattern, is not whitespace, fail
132     // (but if it's whitespace to the very end of the image, that's OK)
133     if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
134       throw new ReaderException("Pattern not followed by whitespace");
135     }
136
137     if (usingCheckDigit) {
138       int max = result.length() - 1;
139       int total = 0;
140       for (int i = 0; i < max; i++) {
141         total += ALPHABET_STRING.indexOf(result.charAt(i));
142       }
143       if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
144         throw new ReaderException("Checksum failed");
145       }
146       result.deleteCharAt(max);
147     }
148
149     String resultString = result.toString();
150     if (extendedMode) {
151       resultString = decodeExtended(resultString);
152     }
153
154     if (resultString.length() == 0) {
155       // Almost surely a false positive
156       throw new ReaderException("Empty barcode found; assuming a false positive");
157     }
158
159     float left = (float) (start[1] + start[0]) / 2.0f;
160     float right = (float) (nextStart + lastStart) / 2.0f;
161     return new Result(
162         resultString,
163         null,
164         new ResultPoint[]{
165             new GenericResultPoint(left, (float) rowNumber),
166             new GenericResultPoint(right, (float) rowNumber)},
167         BarcodeFormat.CODE_39);
168
169   }
170
171   private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
172     int width = row.getSize();
173     int rowOffset = 0;
174     while (rowOffset < width) {
175       if (row.get(rowOffset)) {
176         break;
177       }
178       rowOffset++;
179     }
180
181     int counterPosition = 0;
182     int[] counters = new int[9];
183     int patternStart = rowOffset;
184     boolean isWhite = false;
185     int patternLength = counters.length;
186
187     for (int i = rowOffset; i < width; i++) {
188       boolean pixel = row.get(i);
189       if ((!pixel && isWhite) || (pixel && !isWhite)) {
190         counters[counterPosition]++;
191       } else {
192         if (counterPosition == patternLength - 1) {
193           try {
194             if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
195               // Look for whitespace before start pattern, >= 50% of width of start pattern
196               if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
197                 return new int[]{patternStart, i};
198               }
199             }
200           } catch (ReaderException re) {
201             // no match, continue
202           }
203           patternStart += counters[0] + counters[1];
204           for (int y = 2; y < patternLength; y++) {
205             counters[y - 2] = counters[y];
206           }
207           counters[patternLength - 2] = 0;
208           counters[patternLength - 1] = 0;
209           counterPosition--;
210         } else {
211           counterPosition++;
212         }
213         counters[counterPosition] = 1;
214         isWhite = !isWhite;
215       }
216     }
217     throw new ReaderException("Can't find pattern");
218   }
219
220   private static int toNarrowWidePattern(int[] counters) throws ReaderException {
221     int numCounters = counters.length;
222     int maxNarrowCounter = 0;
223     int wideCounters;
224     do {
225       int minCounter = Integer.MAX_VALUE;
226       for (int i = 0; i < numCounters; i++) {
227         int counter = counters[i];
228         if (counter < minCounter && counter > maxNarrowCounter) {
229           minCounter = counter;
230         }
231       }
232       maxNarrowCounter = minCounter;
233       wideCounters = 0;
234       int totalWideCountersWidth = 0;
235       int pattern = 0;
236       for (int i = 0; i < numCounters; i++) {
237         int counter = counters[i];
238         if (counters[i] > maxNarrowCounter) {
239           pattern |= 1 << (numCounters - 1 - i);
240           wideCounters++;
241           totalWideCountersWidth += counter;
242         }
243       }
244       if (wideCounters == 3) {
245         // Found 3 wide counters, but are they close enough in width?
246         // We can perform a cheap, conservative check to see if any individual
247         // counter is more than 1.5 times the average:
248         for (int i = 0; i < numCounters && wideCounters > 0; i++) {
249           int counter = counters[i];
250           if (counters[i] > maxNarrowCounter) {
251             wideCounters--;
252             // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
253             if ((counter << 1) >= totalWideCountersWidth) {
254               throw new ReaderException("Wide bars vary too much in width, rejecting");
255             }
256           }
257         }
258         return pattern;
259       }
260     } while (wideCounters > 3);
261     throw new ReaderException("Can't find 3 wide bars/spaces out of 9");
262   }
263
264   private static char patternToChar(int pattern) throws ReaderException {
265     for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
266       if (CHARACTER_ENCODINGS[i] == pattern) {
267         return ALPHABET[i];
268       }
269     }
270     throw new ReaderException("Pattern did not match character encoding");
271   }
272
273   private static String decodeExtended(String encoded) throws ReaderException {
274     int length = encoded.length();
275     StringBuffer decoded = new StringBuffer(length);
276     for (int i = 0; i < length; i++) {
277       char c = encoded.charAt(i);
278       if (c == '+' || c == '$' || c == '%' || c == '/') {
279         char next = encoded.charAt(i + 1);
280         char decodedChar = '\0';
281         switch (c) {
282           case '+':
283             // +A to +Z map to a to z
284             if (next >= 'A' && next <= 'Z') {
285               decodedChar = (char) (next + 32);
286             } else {
287               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
288             }
289             break;
290           case '$':
291             // $A to $Z map to control codes SH to SB
292             if (next >= 'A' && next <= 'Z') {
293               decodedChar = (char) (next - 64);
294             } else {
295               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
296             }
297             break;
298           case '%':
299             // %A to %E map to control codes ESC to US
300             if (next >= 'A' && next <= 'E') {
301               decodedChar = (char) (next - 38);
302             } else if (next >= 'F' && next <= 'W') {
303               decodedChar = (char) (next - 11);
304             } else {
305               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
306             }
307             break;
308           case '/':
309             // /A to /O map to ! to , and /Z maps to :
310             if (next >= 'A' && next <= 'O') {
311               decodedChar = (char) (next - 32);
312             } else if (next == 'Z') {
313               decodedChar = ':';
314             } else {
315               throw new ReaderException("Invalid extended sequence: " + c + next);
316             }
317             break;
318         }
319         decoded.append(decodedChar);
320         // bump up i again since we read two characters
321         i++;
322       } else {
323         decoded.append(c);
324       }
325     }
326     return decoded.toString();
327   }
328
329 }