Fixed or removed a bunch of TODOs, and enforced the 100 columns limit in a bunch...
[zxing.git] / core / src / com / google / zxing / oned / Code128Reader.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 import com.google.zxing.common.GenericResultPoint;
25
26 import java.util.Hashtable;
27
28 /**
29  * <p>Decodes Code 128 barcodes.</p>
30  *
31  * @author Sean Owen
32  */
33 public final class Code128Reader extends AbstractOneDReader {
34
35   private static final int[][] CODE_PATTERNS = {
36       {2, 1, 2, 2, 2, 2}, // 0
37       {2, 2, 2, 1, 2, 2},
38       {2, 2, 2, 2, 2, 1},
39       {1, 2, 1, 2, 2, 3},
40       {1, 2, 1, 3, 2, 2},
41       {1, 3, 1, 2, 2, 2}, // 5
42       {1, 2, 2, 2, 1, 3},
43       {1, 2, 2, 3, 1, 2},
44       {1, 3, 2, 2, 1, 2},
45       {2, 2, 1, 2, 1, 3},
46       {2, 2, 1, 3, 1, 2}, // 10
47       {2, 3, 1, 2, 1, 2},
48       {1, 1, 2, 2, 3, 2},
49       {1, 2, 2, 1, 3, 2},
50       {1, 2, 2, 2, 3, 1},
51       {1, 1, 3, 2, 2, 2}, // 15
52       {1, 2, 3, 1, 2, 2},
53       {1, 2, 3, 2, 2, 1},
54       {2, 2, 3, 2, 1, 1},
55       {2, 2, 1, 1, 3, 2},
56       {2, 2, 1, 2, 3, 1}, // 20
57       {2, 1, 3, 2, 1, 2},
58       {2, 2, 3, 1, 1, 2},
59       {3, 1, 2, 1, 3, 1},
60       {3, 1, 1, 2, 2, 2},
61       {3, 2, 1, 1, 2, 2}, // 25
62       {3, 2, 1, 2, 2, 1},
63       {3, 1, 2, 2, 1, 2},
64       {3, 2, 2, 1, 1, 2},
65       {3, 2, 2, 2, 1, 1},
66       {2, 1, 2, 1, 2, 3}, // 30
67       {2, 1, 2, 3, 2, 1},
68       {2, 3, 2, 1, 2, 1},
69       {1, 1, 1, 3, 2, 3},
70       {1, 3, 1, 1, 2, 3},
71       {1, 3, 1, 3, 2, 1}, // 35
72       {1, 1, 2, 3, 1, 3},
73       {1, 3, 2, 1, 1, 3},
74       {1, 3, 2, 3, 1, 1},
75       {2, 1, 1, 3, 1, 3},
76       {2, 3, 1, 1, 1, 3}, // 40
77       {2, 3, 1, 3, 1, 1},
78       {1, 1, 2, 1, 3, 3},
79       {1, 1, 2, 3, 3, 1},
80       {1, 3, 2, 1, 3, 1},
81       {1, 1, 3, 1, 2, 3}, // 45
82       {1, 1, 3, 3, 2, 1},
83       {1, 3, 3, 1, 2, 1},
84       {3, 1, 3, 1, 2, 1},
85       {2, 1, 1, 3, 3, 1},
86       {2, 3, 1, 1, 3, 1}, // 50
87       {2, 1, 3, 1, 1, 3},
88       {2, 1, 3, 3, 1, 1},
89       {2, 1, 3, 1, 3, 1},
90       {3, 1, 1, 1, 2, 3},
91       {3, 1, 1, 3, 2, 1}, // 55
92       {3, 3, 1, 1, 2, 1},
93       {3, 1, 2, 1, 1, 3},
94       {3, 1, 2, 3, 1, 1},
95       {3, 3, 2, 1, 1, 1},
96       {3, 1, 4, 1, 1, 1}, // 60
97       {2, 2, 1, 4, 1, 1},
98       {4, 3, 1, 1, 1, 1},
99       {1, 1, 1, 2, 2, 4},
100       {1, 1, 1, 4, 2, 2},
101       {1, 2, 1, 1, 2, 4}, // 65
102       {1, 2, 1, 4, 2, 1},
103       {1, 4, 1, 1, 2, 2},
104       {1, 4, 1, 2, 2, 1},
105       {1, 1, 2, 2, 1, 4},
106       {1, 1, 2, 4, 1, 2}, // 70
107       {1, 2, 2, 1, 1, 4},
108       {1, 2, 2, 4, 1, 1},
109       {1, 4, 2, 1, 1, 2},
110       {1, 4, 2, 2, 1, 1},
111       {2, 4, 1, 2, 1, 1}, // 75
112       {2, 2, 1, 1, 1, 4},
113       {4, 1, 3, 1, 1, 1},
114       {2, 4, 1, 1, 1, 2},
115       {1, 3, 4, 1, 1, 1},
116       {1, 1, 1, 2, 4, 2}, // 80
117       {1, 2, 1, 1, 4, 2},
118       {1, 2, 1, 2, 4, 1},
119       {1, 1, 4, 2, 1, 2},
120       {1, 2, 4, 1, 1, 2},
121       {1, 2, 4, 2, 1, 1}, // 85
122       {4, 1, 1, 2, 1, 2},
123       {4, 2, 1, 1, 1, 2},
124       {4, 2, 1, 2, 1, 1},
125       {2, 1, 2, 1, 4, 1},
126       {2, 1, 4, 1, 2, 1}, // 90
127       {4, 1, 2, 1, 2, 1},
128       {1, 1, 1, 1, 4, 3},
129       {1, 1, 1, 3, 4, 1},
130       {1, 3, 1, 1, 4, 1},
131       {1, 1, 4, 1, 1, 3}, // 95
132       {1, 1, 4, 3, 1, 1},
133       {4, 1, 1, 1, 1, 3},
134       {4, 1, 1, 3, 1, 1},
135       {1, 1, 3, 1, 4, 1},
136       {1, 1, 4, 1, 3, 1}, // 100
137       {3, 1, 1, 1, 4, 1},
138       {4, 1, 1, 1, 3, 1},
139       {2, 1, 1, 4, 1, 2},
140       {2, 1, 1, 2, 1, 4},
141       {2, 1, 1, 2, 3, 2}, // 105
142       {2, 3, 3, 1, 1, 1, 2}
143   };
144
145   private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f);
146   private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
147
148   private static final int CODE_SHIFT = 98;
149
150   private static final int CODE_CODE_C = 99;
151   private static final int CODE_CODE_B = 100;
152   private static final int CODE_CODE_A = 101;
153
154   private static final int CODE_FNC_1 = 102;
155   private static final int CODE_FNC_2 = 97;
156   private static final int CODE_FNC_3 = 96;
157   private static final int CODE_FNC_4_A = 101;
158   private static final int CODE_FNC_4_B = 100;
159
160   private static final int CODE_START_A = 103;
161   private static final int CODE_START_B = 104;
162   private static final int CODE_START_C = 105;
163   private static final int CODE_STOP = 106;
164
165   private static int[] findStartPattern(BitArray row) throws ReaderException {
166     int width = row.getSize();
167     int rowOffset = 0;
168     while (rowOffset < width) {
169       if (row.get(rowOffset)) {
170         break;
171       }
172       rowOffset++;
173     }
174
175     int counterPosition = 0;
176     int[] counters = new int[6];
177     int patternStart = rowOffset;
178     boolean isWhite = false;
179     int patternLength = counters.length;
180
181     for (int i = rowOffset; i < width; i++) {
182       boolean pixel = row.get(i);
183       if (pixel ^ isWhite) {
184         counters[counterPosition]++;
185       } else {
186         if (counterPosition == patternLength - 1) {
187           int bestVariance = MAX_AVG_VARIANCE;
188           int bestMatch = -1;
189           for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) {
190             int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode],
191                 MAX_INDIVIDUAL_VARIANCE);
192             if (variance < bestVariance) {
193               bestVariance = variance;
194               bestMatch = startCode;
195             }
196           }
197           if (bestMatch >= 0) {
198             // Look for whitespace before start pattern, >= 50% of width of start pattern            
199             if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart,
200                 false)) {
201               return new int[]{patternStart, i, bestMatch};
202             }
203           }
204           patternStart += counters[0] + counters[1];
205           for (int y = 2; y < patternLength; y++) {
206             counters[y - 2] = counters[y];
207           }
208           counters[patternLength - 2] = 0;
209           counters[patternLength - 1] = 0;
210           counterPosition--;
211         } else {
212           counterPosition++;
213         }
214         counters[counterPosition] = 1;
215         isWhite ^= true; // isWhite = !isWhite;
216       }
217     }
218     throw ReaderException.getInstance();
219   }
220
221   private static int decodeCode(BitArray row, int[] counters, int rowOffset) throws ReaderException {
222     recordPattern(row, rowOffset, counters);
223     int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
224     int bestMatch = -1;
225     for (int d = 0; d < CODE_PATTERNS.length; d++) {
226       int[] pattern = CODE_PATTERNS[d];
227       int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
228       if (variance < bestVariance) {
229         bestVariance = variance;
230         bestMatch = d;
231       }
232     }
233     // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6.
234     if (bestMatch >= 0) {
235       return bestMatch;
236     } else {
237       throw ReaderException.getInstance();
238     }
239   }
240
241   public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {
242
243     int[] startPatternInfo = findStartPattern(row);
244     int startCode = startPatternInfo[2];
245     int codeSet;
246     switch (startCode) {
247       case CODE_START_A:
248         codeSet = CODE_CODE_A;
249         break;
250       case CODE_START_B:
251         codeSet = CODE_CODE_B;
252         break;
253       case CODE_START_C:
254         codeSet = CODE_CODE_C;
255         break;
256       default:
257         throw ReaderException.getInstance();
258     }
259
260     boolean done = false;
261     boolean isNextShifted = false;
262
263     StringBuffer result = new StringBuffer();
264     int lastStart = startPatternInfo[0];
265     int nextStart = startPatternInfo[1];
266     int[] counters = new int[6];
267
268     int lastCode = 0;
269     int code = 0;
270     int checksumTotal = startCode;
271     int multiplier = 0;
272     boolean lastCharacterWasPrintable = true;
273
274     while (!done) {
275
276       boolean unshift = isNextShifted;
277       isNextShifted = false;
278
279       // Save off last code
280       lastCode = code;
281
282       // Decode another code from image
283       code = decodeCode(row, counters, nextStart);
284
285       // Remember whether the last code was printable or not (excluding CODE_STOP)
286       if (code != CODE_STOP) {
287         lastCharacterWasPrintable = true;
288       }
289
290       // Add to checksum computation (if not CODE_STOP of course)
291       if (code != CODE_STOP) {
292         multiplier++;
293         checksumTotal += multiplier * code;
294       }
295
296       // Advance to where the next code will to start
297       lastStart = nextStart;
298       for (int i = 0; i < counters.length; i++) {
299         nextStart += counters[i];
300       }
301
302       // Take care of illegal start codes
303       switch (code) {
304         case CODE_START_A:
305         case CODE_START_B:
306         case CODE_START_C:
307           throw ReaderException.getInstance();
308       }
309
310       switch (codeSet) {
311
312         case CODE_CODE_A:
313           if (code < 64) {
314             result.append((char) (' ' + code));
315           } else if (code < 96) {
316             result.append((char) (code - 64));
317           } else {
318             // Don't let CODE_STOP, which always appears, affect whether whether we think the last
319             // code was printable or not.
320             if (code != CODE_STOP) {
321               lastCharacterWasPrintable = false;
322             }
323             switch (code) {
324               case CODE_FNC_1:
325               case CODE_FNC_2:
326               case CODE_FNC_3:
327               case CODE_FNC_4_A:
328                 // do nothing?
329                 break;
330               case CODE_SHIFT:
331                 isNextShifted = true;
332                 codeSet = CODE_CODE_B;
333                 break;
334               case CODE_CODE_B:
335                 codeSet = CODE_CODE_B;
336                 break;
337               case CODE_CODE_C:
338                 codeSet = CODE_CODE_C;
339                 break;
340               case CODE_STOP:
341                 done = true;
342                 break;
343             }
344           }
345           break;
346         case CODE_CODE_B:
347           if (code < 96) {
348             result.append((char) (' ' + code));
349           } else {
350             if (code != CODE_STOP) {
351               lastCharacterWasPrintable = false;
352             }
353             switch (code) {
354               case CODE_FNC_1:
355               case CODE_FNC_2:
356               case CODE_FNC_3:
357               case CODE_FNC_4_B:
358                 // do nothing?
359                 break;
360               case CODE_SHIFT:
361                 isNextShifted = true;
362                 codeSet = CODE_CODE_C;
363                 break;
364               case CODE_CODE_A:
365                 codeSet = CODE_CODE_A;
366                 break;
367               case CODE_CODE_C:
368                 codeSet = CODE_CODE_C;
369                 break;
370               case CODE_STOP:
371                 done = true;
372                 break;
373             }
374           }
375           break;
376         case CODE_CODE_C:
377           if (code < 100) {
378             if (code < 10) {
379               result.append('0');
380             }
381             result.append(code);
382           } else {
383             if (code != CODE_STOP) {
384               lastCharacterWasPrintable = false;
385             }
386             switch (code) {
387               case CODE_FNC_1:
388                 // do nothing?
389                 break;
390               case CODE_CODE_A:
391                 codeSet = CODE_CODE_A;
392                 break;
393               case CODE_CODE_B:
394                 codeSet = CODE_CODE_B;
395                 break;
396               case CODE_STOP:
397                 done = true;
398                 break;
399             }
400           }
401           break;
402       }
403
404       // Unshift back to another code set if we were shifted
405       if (unshift) {
406         switch (codeSet) {
407           case CODE_CODE_A:
408             codeSet = CODE_CODE_C;
409             break;
410           case CODE_CODE_B:
411             codeSet = CODE_CODE_A;
412             break;
413           case CODE_CODE_C:
414             codeSet = CODE_CODE_B;
415             break;
416         }
417       }
418
419     }
420
421     // Check for ample whitespice following pattern, but, to do this we first need to remember that
422     // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left
423     // to read off. Would be slightly better to properly read. Here we just skip it:
424     while (row.get(nextStart)) {
425       nextStart++;
426     }
427     if (!row.isRange(nextStart, Math.min(row.getSize(), nextStart + (nextStart - lastStart) / 2),
428         false)) {
429       throw ReaderException.getInstance();
430     }
431
432     // Pull out from sum the value of the penultimate check code
433     checksumTotal -= multiplier * lastCode;
434     // lastCode is the checksum then:
435     if (checksumTotal % 103 != lastCode) {
436       throw ReaderException.getInstance();
437     }
438
439     // Need to pull out the check digits from string
440     int resultLength = result.length();
441     // Only bother if the result had at least one character, and if the checksum digit happened to
442     // be a printable character. If it was just interpreted as a control code, nothing to remove.
443     if (resultLength > 0 && lastCharacterWasPrintable) {
444       if (codeSet == CODE_CODE_C) {
445         result.delete(resultLength - 2, resultLength);
446       } else {
447         result.delete(resultLength - 1, resultLength);
448       }
449     }
450
451     String resultString = result.toString();
452
453     if (resultString.length() == 0) {
454       // Almost surely a false positive
455       throw ReaderException.getInstance();
456     }
457
458     float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f;
459     float right = (float) (nextStart + lastStart) / 2.0f;
460     return new Result(
461         resultString,
462         null,
463         new ResultPoint[]{
464             new GenericResultPoint(left, (float) rowNumber),
465             new GenericResultPoint(right, (float) rowNumber)},
466         BarcodeFormat.CODE_128);
467
468   }
469
470 }