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