e73ccf00cc861ab825c396bd5c785f0ba256d18f
[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.ReaderException;
20 import com.google.zxing.Result;
21 import com.google.zxing.ResultPoint;
22 import com.google.zxing.common.BitArray;
23 import com.google.zxing.common.GenericResultPoint;
24
25 /**
26  * <p>Decodes Code 39 barcodes. This does not supported "Full ASCII Code 39" yet.</p>
27  *
28  * @author srowen@google.com (Sean Owen)
29  */
30 public final class Code39Reader extends AbstractOneDReader {
31
32   private static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
33   private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
34
35   /**
36    * These represent the encodings of characters, as patterns of wide and narrow bars.
37    * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
38    * with 1s representing "wide" and 0s representing narrow.
39    */
40   private static final int[] CHARACTER_ENCODINGS = {
41       0x038, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
42       0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
43       0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016,  // K-T
44       0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
45       0x0A8, 0x0A2, 0x08A, 0x02A // $-%
46   };
47
48   private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
49
50   private final boolean usingCheckDigit;
51   private final boolean extendedMode;
52
53   /**
54    * Creates a reader that assumes all encoded data is data, and does not treat the final
55    * character as a check digit. It will not decoded "extended Code 39" sequences.
56    */
57   public Code39Reader() {
58     usingCheckDigit = false;
59     extendedMode = false;
60   }
61
62   /**
63    * Creates a reader that can be configured to check the last character as a check digit.
64    * It will not decoded "extended Code 39" sequences.
65    *
66    * @param usingCheckDigit if true, treat the last data character as a check digit, not
67    * data, and verify that the checksum passes
68    */
69   public Code39Reader(boolean usingCheckDigit) {
70     this.usingCheckDigit = usingCheckDigit;
71     this.extendedMode = false;
72   }
73
74   /**
75    * Creates a reader that can be configured to check the last character as a check digit,
76    * or optionally attempt to decode "extended Code 39" sequences that are used to encode
77    * the full ASCII character set.
78    *
79    * @param usingCheckDigit if true, treat the last data character as a check digit, not
80    * data, and verify that the checksum passes
81    * @param extendedMode if true, willa tetmpt to decode extended Code 39 sequences in the
82    * text
83    */
84   public Code39Reader(boolean usingCheckDigit, boolean extendedMode) {
85     this.usingCheckDigit = usingCheckDigit;
86     this.extendedMode = extendedMode;
87   }
88
89   public Result decodeRow(final int rowNumber, final BitArray row) throws ReaderException {
90
91     int[] start = findAsteriskPattern(row);
92
93     int nextStart = start[1];
94
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     if (usingCheckDigit) {
123       int max = result.length() - 1;
124       int total = 0;
125       for (int i = 0; i < max; i++) {
126         total += ALPHABET_STRING.indexOf(result.charAt(i));
127       }
128       if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
129         throw new ReaderException("Checksum failed");
130       }
131       result.deleteCharAt(max);
132     }
133
134     String resultString = result.toString();
135     if (extendedMode) {
136       resultString = decodeExtended(resultString);
137     }
138     return new Result(resultString,
139         new ResultPoint[]{new GenericResultPoint((float) (start[1] - start[0]) / 2.0f, (float) rowNumber),
140             new GenericResultPoint((float) (nextStart - lastStart) / 2.0f, (float) rowNumber)});
141
142   }
143
144   private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
145     int width = row.getSize();
146     int rowOffset = 0;
147     while (rowOffset < width) {
148       if (row.get(rowOffset)) {
149         break;
150       }
151       rowOffset++;
152     }
153
154     int counterPosition = 0;
155     int[] counters = new int[9];
156     int patternStart = rowOffset;
157     boolean isWhite = false;
158     int patternLength = counters.length;
159
160     for (int i = rowOffset; i < width; i++) {
161       boolean pixel = row.get(i);
162       if ((!pixel && isWhite) || (pixel && !isWhite)) {
163         counters[counterPosition]++;
164       } else {
165         if (counterPosition == patternLength - 1) {
166           try {
167             if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
168               return new int[]{patternStart, i};
169             }
170           } catch (ReaderException re) {
171             // no match, continue
172           }
173           patternStart += counters[0] + counters[1];
174           for (int y = 2; y < patternLength; y++) {
175             counters[y - 2] = counters[y];
176           }
177           counterPosition--;
178         } else {
179           counterPosition++;
180         }
181         counters[counterPosition] = 1;
182         isWhite = !isWhite;
183       }
184     }
185     throw new ReaderException("Can't find pattern");
186   }
187
188   private static int toNarrowWidePattern(int[] counters) throws ReaderException {
189     int minCounter = Integer.MAX_VALUE;
190     for (int i = 0; i < counters.length; i++) {
191       if (counters[i] < minCounter) {
192         minCounter = counters[i];
193       }
194     }
195     int maxNarrowCounter = (int) (minCounter * 1.5f);
196     int wideCounters = 0;
197     int pattern = 0;
198     for (int i = 0; i < counters.length; i++) {
199       if (counters[i] > maxNarrowCounter) {
200         pattern |= 1 << (counters.length - 1 - i);
201         wideCounters++;
202       }
203     }
204     if (wideCounters != 3) {
205       throw new ReaderException("Can't find 3 wide bars/spaces out of 9");
206     }
207     return pattern;
208   }
209
210   private static char patternToChar(int pattern) throws ReaderException {
211     for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
212       if (CHARACTER_ENCODINGS[i] == pattern) {
213         return ALPHABET[i];
214       }
215     }
216     throw new ReaderException("Pattern did not match character encoding");
217   }
218
219   private static String decodeExtended(String encoded) throws ReaderException {
220     int length = encoded.length();
221     StringBuffer decoded = new StringBuffer(length);
222     for (int i = 0; i < length; i++) {
223       char c = encoded.charAt(i);
224       if (c == '+' || c == '$' || c == '%' || c == '/') {
225         char next = encoded.charAt(i + 1);
226         char decodedChar = '\0';
227         switch (c) {
228           case '+':
229             // +A to +Z map to a to z
230             if (next >= 'A' && next <= 'Z') {
231               decodedChar = (char) (next + 32);
232             } else {
233               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
234             }
235             break;
236           case '$':
237             // $A to $Z map to control codes SH to SB
238             if (next >= 'A' && next <= 'Z') {
239               decodedChar = (char) (next - 64);
240             } else {
241               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
242             }
243             break;
244           case '%':
245             // %A to %E map to control codes ESC to US
246             if (next >= 'A' && next <= 'E') {
247               decodedChar = (char) (next - 38);
248             } else if (next >= 'F' && next <= 'W') {
249               decodedChar = (char) (next - 11);
250             } else {
251               throw new ReaderException("Invalid extended code 39 sequence: " + c + next);
252             }
253             break;
254           case '/':
255             // /A to /O map to ! to , and /Z maps to :
256             if (next >= 'A' && next <= 'O') {
257               decodedChar = (char) (next - 32);
258             } else if (next == 'Z') {
259               decodedChar = ':';
260             } else {
261               throw new ReaderException("Invalid extended sequence: " + c + next);
262             }
263             break;
264         }
265         decoded.append(decodedChar);
266         // bump up i again since we read two characters
267         i++;
268       } else {
269         decoded.append(c);
270       }
271     }
272     return decoded.toString();
273   }
274
275 }