Add Code 93 support. Update tests to reflect new (better) number of successes.
[zxing.git] / core / src / com / google / zxing / oned / Code93Reader.java
1 /*
2  * Copyright 2010 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 java.util.Hashtable;
20
21 import com.google.zxing.BarcodeFormat;
22 import com.google.zxing.ChecksumException;
23 import com.google.zxing.FormatException;
24 import com.google.zxing.NotFoundException;
25 import com.google.zxing.Result;
26 import com.google.zxing.ResultPoint;
27 import com.google.zxing.common.BitArray;
28
29 /**
30  * <p>Decodes Code 93 barcodes.</p>
31  *
32  * @author Sean Owen
33  * @see Code39Reader
34  */
35 public final class Code93Reader extends OneDReader {
36
37   // Note that 'abcd' are dummy characters in place of control characters.
38   private static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
39   private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
40
41   /**
42    * These represent the encodings of characters, as patterns of wide and narrow bars.
43    * The 9 least-significant bits of each int correspond to the pattern of wide and narrow.
44    */
45   private static final int[] CHARACTER_ENCODINGS = {
46       0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A, // 0-9
47       0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134, // A-J
48       0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6, // K-T
49       0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, // U-Z
50       0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE, // - - %
51       0x126, 0x1DA, 0x1D6, 0x132, 0x15E, // Control chars? $-*
52   };
53   private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[47];
54
55   public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
56       throws NotFoundException, ChecksumException, FormatException {
57
58     int[] start = findAsteriskPattern(row);
59     int nextStart = start[1];
60     int end = row.getSize();
61
62     // Read off white space
63     while (nextStart < end && !row.get(nextStart)) {
64       nextStart++;
65     }
66
67     StringBuffer result = new StringBuffer(20);
68     int[] counters = new int[6];
69     char decodedChar;
70     int lastStart;
71     do {
72       recordPattern(row, nextStart, counters);
73       int pattern = toPattern(counters);
74       if (pattern < 0) {
75         throw NotFoundException.getNotFoundInstance();
76       }
77       decodedChar = patternToChar(pattern);
78       result.append(decodedChar);
79       lastStart = nextStart;
80       for (int i = 0; i < counters.length; i++) {
81         nextStart += counters[i];
82       }
83       // Read off white space
84       while (nextStart < end && !row.get(nextStart)) {
85         nextStart++;
86       }
87     } while (decodedChar != '*');
88     result.deleteCharAt(result.length() - 1); // remove asterisk
89
90     // Should be at least one more black module
91     if (nextStart == end || !row.get(nextStart)) {
92       throw NotFoundException.getNotFoundInstance();
93     }
94
95     if (result.length() < 2) {
96       // Almost surely a false positive
97       throw NotFoundException.getNotFoundInstance();
98     }
99
100     checkChecksums(result);
101     // Remove checksum digits
102     result.setLength(result.length() - 2);
103
104     String resultString = decodeExtended(result);
105
106     float left = (float) (start[1] + start[0]) / 2.0f;
107     float right = (float) (nextStart + lastStart) / 2.0f;
108     return new Result(
109         resultString,
110         null,
111         new ResultPoint[]{
112             new ResultPoint(left, (float) rowNumber),
113             new ResultPoint(right, (float) rowNumber)},
114         BarcodeFormat.CODE_93);
115
116   }
117
118   private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
119     int width = row.getSize();
120     int rowOffset = 0;
121     while (rowOffset < width) {
122       if (row.get(rowOffset)) {
123         break;
124       }
125       rowOffset++;
126     }
127
128     int counterPosition = 0;
129     int[] counters = new int[6];
130     int patternStart = rowOffset;
131     boolean isWhite = false;
132     int patternLength = counters.length;
133
134     for (int i = rowOffset; i < width; i++) {
135       boolean pixel = row.get(i);
136       if (pixel ^ isWhite) {
137         counters[counterPosition]++;
138       } else {
139         if (counterPosition == patternLength - 1) {
140           if (toPattern(counters) == ASTERISK_ENCODING) {
141             return new int[]{patternStart, i};
142           }
143           patternStart += counters[0] + counters[1];
144           for (int y = 2; y < patternLength; y++) {
145             counters[y - 2] = counters[y];
146           }
147           counters[patternLength - 2] = 0;
148           counters[patternLength - 1] = 0;
149           counterPosition--;
150         } else {
151           counterPosition++;
152         }
153         counters[counterPosition] = 1;
154         isWhite = !isWhite;
155       }
156     }
157     throw NotFoundException.getNotFoundInstance();
158   }
159
160   private static int toPattern(int[] counters) {
161     int max = counters.length;
162     int sum = 0;
163     for (int i = 0; i < max; i++) {
164       sum += counters[i];
165     }
166     int pattern = 0;
167     for (int i = 0; i < max; i++) {
168       int scaledShifted = (counters[i] << INTEGER_MATH_SHIFT) * 9 / sum;
169       int scaledUnshifted = scaledShifted >> INTEGER_MATH_SHIFT;
170       if ((scaledShifted & 0xFF) > 0x7F) {
171         scaledUnshifted++;
172       }
173       if (scaledUnshifted < 1 || scaledUnshifted > 4) {
174         return -1;
175       }
176       if ((i & 0x01) == 0) {
177         for (int j = 0; j < scaledUnshifted; j++) {
178           pattern = (pattern << 1) | 0x01;
179         }
180       } else {
181         pattern <<= scaledUnshifted;
182       }
183     }
184     return pattern;
185   }
186
187   private static char patternToChar(int pattern) throws NotFoundException {
188     for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
189       if (CHARACTER_ENCODINGS[i] == pattern) {
190         return ALPHABET[i];
191       }
192     }
193     throw NotFoundException.getNotFoundInstance();
194   }
195
196   private static String decodeExtended(StringBuffer encoded) throws FormatException {
197     int length = encoded.length();
198     StringBuffer decoded = new StringBuffer(length);
199     for (int i = 0; i < length; i++) {
200       char c = encoded.charAt(i);
201       if (c >= 'a' && c <= 'd') {
202         char next = encoded.charAt(i + 1);
203         char decodedChar = '\0';
204         switch (c) {
205           case 'd':
206             // +A to +Z map to a to z
207             if (next >= 'A' && next <= 'Z') {
208               decodedChar = (char) (next + 32);
209             } else {
210               throw FormatException.getFormatInstance();
211             }
212             break;
213           case 'a':
214             // $A to $Z map to control codes SH to SB
215             if (next >= 'A' && next <= 'Z') {
216               decodedChar = (char) (next - 64);
217             } else {
218               throw FormatException.getFormatInstance();
219             }
220             break;
221           case 'b':
222             // %A to %E map to control codes ESC to US
223             if (next >= 'A' && next <= 'E') {
224               decodedChar = (char) (next - 38);
225             } else if (next >= 'F' && next <= 'W') {
226               decodedChar = (char) (next - 11);
227             } else {
228               throw FormatException.getFormatInstance();
229             }
230             break;
231           case 'c':
232             // /A to /O map to ! to , and /Z maps to :
233             if (next >= 'A' && next <= 'O') {
234               decodedChar = (char) (next - 32);
235             } else if (next == 'Z') {
236               decodedChar = ':';
237             } else {
238               throw FormatException.getFormatInstance();
239             }
240             break;
241         }
242         decoded.append(decodedChar);
243         // bump up i again since we read two characters
244         i++;
245       } else {
246         decoded.append(c);
247       }
248     }
249     return decoded.toString();
250   }
251
252   private static void checkChecksums(StringBuffer result) throws ChecksumException {
253     int length = result.length();
254     checkOneChecksum(result, length - 2, 20);
255     checkOneChecksum(result, length - 1, 15);
256   }
257
258   private static void checkOneChecksum(StringBuffer result, int checkPosition, int weightMax)
259       throws ChecksumException {
260     int weight = 1;
261     int total = 0;
262     for (int i = checkPosition - 1; i >= 0; i--) {
263       total += weight * ALPHABET_STRING.indexOf(result.charAt(i));
264       if (++weight > weightMax) {
265         weight = 1;
266       }
267     }
268     if (result.charAt(checkPosition) != ALPHABET[total % 47]) {
269       throw ChecksumException.getChecksumInstance();
270     }
271   }
272
273 }