Refactorings to allow raw bytes to be passed back with reader result, where applicable
[zxing.git] / core / src / com / google / zxing / oned / Code39Reader.java
1 /*
2  * Copyright 2008 Google Inc.
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 supported "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, willa tetmpt 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     if (usingCheckDigit) {
126       int max = result.length() - 1;
127       int total = 0;
128       for (int i = 0; i < max; i++) {
129         total += ALPHABET_STRING.indexOf(result.charAt(i));
130       }
131       if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
132         throw new ReaderException("Checksum failed");
133       }
134       result.deleteCharAt(max);
135     }
136
137     String resultString = result.toString();
138     if (extendedMode) {
139       resultString = decodeExtended(resultString);
140     }
141     return new Result(
142         resultString,
143         null,
144         new ResultPoint[]{
145             new GenericResultPoint((float) (start[1] - start[0]) / 2.0f, (float) rowNumber),
146             new GenericResultPoint((float) (nextStart - lastStart) / 2.0f, (float) rowNumber)},
147         BarcodeFormat.CODE_39);
148
149   }
150
151   private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
152     int width = row.getSize();
153     int rowOffset = 0;
154     while (rowOffset < width) {
155       if (row.get(rowOffset)) {
156         break;
157       }
158       rowOffset++;
159     }
160
161     int counterPosition = 0;
162     int[] counters = new int[9];
163     int patternStart = rowOffset;
164     boolean isWhite = false;
165     int patternLength = counters.length;
166
167     for (int i = rowOffset; i < width; i++) {
168       boolean pixel = row.get(i);
169       if ((!pixel && isWhite) || (pixel && !isWhite)) {
170         counters[counterPosition]++;
171       } else {
172         if (counterPosition == patternLength - 1) {
173           try {
174             if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
175               return new int[]{patternStart, i};
176             }
177           } catch (ReaderException re) {
178             // no match, continue
179           }
180           patternStart += counters[0] + counters[1];
181           for (int y = 2; y < patternLength; y++) {
182             counters[y - 2] = counters[y];
183           }
184           counters[patternLength - 2] = 0;
185           counters[patternLength - 1] = 0;
186           counterPosition--;
187         } else {
188           counterPosition++;
189         }
190         counters[counterPosition] = 1;
191         isWhite = !isWhite;
192       }
193     }
194     throw new ReaderException("Can't find pattern");
195   }
196
197   private static int toNarrowWidePattern(int[] counters) throws ReaderException {
198     int numCounters = counters.length;
199     int maxNarrowCounter = 0;
200     int wideCounters;
201     do {
202       int minCounter = Integer.MAX_VALUE;
203       for (int i = 0; i < numCounters; i++) {
204         int counter = counters[i];
205         if (counter < minCounter && counter > maxNarrowCounter) {
206           minCounter = counter;
207         }
208       }
209       maxNarrowCounter = minCounter;
210       wideCounters = 0;
211       int pattern = 0;
212       for (int i = 0; i < numCounters; i++) {
213         if (counters[i] > maxNarrowCounter) {
214           pattern |= 1 << (numCounters - 1 - i);
215           wideCounters++;
216         }
217       }
218       if (wideCounters == 3) {
219         return pattern;
220       }
221     } while (wideCounters > 3);
222     throw new ReaderException("Can't find 3 wide bars/spaces out of 9");
223   }
224
225   private static char patternToChar(int pattern) throws ReaderException {
226     for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
227       if (CHARACTER_ENCODINGS[i] == pattern) {
228         return ALPHABET[i];
229       }
230     }
231     throw new ReaderException("Pattern did not match character encoding");
232   }
233
234   private static String decodeExtended(String encoded) throws ReaderException {
235     int length = encoded.length();
236     StringBuffer decoded = new StringBuffer(length);
237     for (int i = 0; i < length; i++) {
238       char c = encoded.charAt(i);
239       if (c == '+' || c == '$' || c == '%' || c == '/') {
240         char next = encoded.charAt(i + 1);
241         char decodedChar = '\0';
242         switch (c) {
243           case '+':
244             // +A to +Z map to a to z
245             if (next >= 'A' && next <= 'Z') {
246               decodedChar = (char) (next + 32);
247             } else {
248               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
249             }
250             break;
251           case '$':
252             // $A to $Z map to control codes SH to SB
253             if (next >= 'A' && next <= 'Z') {
254               decodedChar = (char) (next - 64);
255             } else {
256               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
257             }
258             break;
259           case '%':
260             // %A to %E map to control codes ESC to US
261             if (next >= 'A' && next <= 'E') {
262               decodedChar = (char) (next - 38);
263             } else if (next >= 'F' && next <= 'W') {
264               decodedChar = (char) (next - 11);
265             } else {
266               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
267             }
268             break;
269           case '/':
270             // /A to /O map to ! to , and /Z maps to :
271             if (next >= 'A' && next <= 'O') {
272               decodedChar = (char) (next - 32);
273             } else if (next == 'Z') {
274               decodedChar = ':';
275             } else {
276               throw new ReaderException("Invalid extended sequence: " + c + next);
277             }
278             break;
279         }
280         decoded.append(decodedChar);
281         // bump up i again since we read two characters
282         i++;
283       } else {
284         decoded.append(c);
285       }
286     }
287     return decoded.toString();
288   }
289
290 }