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