Issue 537, don't return UPC-A for EAN-13 starting with 0 when UPC-A isn't allowed
[zxing.git] / core / src / com / google / zxing / oned / CodaBarReader.java
1 /*\r
2  * Copyright 2008 ZXing authors\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *      http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package com.google.zxing.oned;\r
18 \r
19 import java.util.Hashtable;\r
20 \r
21 import com.google.zxing.BarcodeFormat;\r
22 import com.google.zxing.NotFoundException;\r
23 import com.google.zxing.Result;\r
24 import com.google.zxing.ResultPoint;\r
25 import com.google.zxing.common.BitArray;\r
26 \r
27 /**\r
28  * <p>Decodes Codabar barcodes.</p>\r
29  *\r
30  * @author Bas Vijfwinkel\r
31  */\r
32 public final class CodaBarReader extends OneDReader {\r
33 \r
34   private static final String ALPHABET_STRING = "0123456789-$:/.+ABCDTN";\r
35   private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();\r
36 \r
37   /**\r
38    * These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of\r
39    * each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. NOTE\r
40    * : c is equal to the  * pattern NOTE : d is equal to the e pattern\r
41    */\r
42   private static final int[] CHARACTER_ENCODINGS = {\r
43       0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9\r
44       0x00c, 0x018, 0x025, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD\r
45       0x01A, 0x029 //TN\r
46   };\r
47 \r
48   // minimal number of characters that should be present (inclusing start and stop characters)\r
49   // this check has been added to reduce the number of false positive on other formats\r
50   // until the cause for this behaviour has been determined\r
51   // under normal circumstances this should be set to 3\r
52   private static final int minCharacterLength = 6; \r
53   \r
54   // multiple start/end patterns\r
55   // official start and end patterns\r
56   private static final char[] STARTEND_ENCODING = {'E', '*', 'A', 'B', 'C', 'D', 'T', 'N'};\r
57   // some codabar generator allow the codabar string to be closed by every character\r
58   //private static final char[] STARTEND_ENCODING = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};\r
59   \r
60   // some industries use a checksum standard but this is not part of the original codabar standard\r
61   // for more information see : http://www.mecsw.com/specs/codabar.html\r
62 \r
63   public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException {\r
64     int[] start = findAsteriskPattern(row);\r
65     start[1] = 0; // BAS: settings this to 0 improves the recognition rate somehow?\r
66     int nextStart = start[1];\r
67     int end = row.getSize();\r
68 \r
69     // Read off white space\r
70     while (nextStart < end && !row.get(nextStart)) {\r
71       nextStart++;\r
72     }\r
73 \r
74     StringBuffer result = new StringBuffer();\r
75     //int[] counters = new int[7];\r
76     int[] counters;\r
77     int lastStart;\r
78 \r
79     do {\r
80       counters = new int[]{0, 0, 0, 0, 0, 0, 0}; // reset counters\r
81       recordPattern(row, nextStart, counters);\r
82 \r
83       char decodedChar = toNarrowWidePattern(counters);\r
84       if (decodedChar == '!') {\r
85         throw NotFoundException.getNotFoundInstance();\r
86       }\r
87       result.append(decodedChar);\r
88       lastStart = nextStart;\r
89       for (int i = 0; i < counters.length; i++) {\r
90         nextStart += counters[i];\r
91       }\r
92 \r
93       // Read off white space\r
94       while (nextStart < end && !row.get(nextStart)) {\r
95         nextStart++;\r
96       }\r
97     } while (nextStart < end); // no fixed end pattern so keep on reading while data is available\r
98 \r
99     // Look for whitespace after pattern:\r
100     int lastPatternSize = 0;\r
101     for (int i = 0; i < counters.length; i++) {\r
102       lastPatternSize += counters[i];\r
103     }\r
104 \r
105     int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;\r
106     // If 50% of last pattern size, following last pattern, is not whitespace, fail\r
107     // (but if it's whitespace to the very end of the image, that's OK)\r
108     if ((nextStart) != end && (whiteSpaceAfterEnd / 2 < lastPatternSize)) {\r
109       throw NotFoundException.getNotFoundInstance();\r
110     }\r
111 \r
112         // valid result?\r
113         if (result.length() < 2)\r
114         {\r
115                 throw NotFoundException.getNotFoundInstance();\r
116         }\r
117         \r
118         char startchar = result.charAt(0);\r
119         if (!arrayContains(STARTEND_ENCODING, startchar))\r
120         {\r
121                 //invalid start character\r
122                 throw NotFoundException.getNotFoundInstance();\r
123         }\r
124     \r
125         // find stop character\r
126     for (int k = 1;k < result.length() ;k++) \r
127         {\r
128       if (result.charAt(k) == startchar) \r
129           {\r
130         // found stop character -> discard rest of the string\r
131                 if ((k+1) != result.length())\r
132                 {\r
133                         result.delete(k+1,result.length()-1);\r
134                         k = result.length();// break out of loop\r
135                 } \r
136           }\r
137     }\r
138 \r
139     // remove stop/start characters character and check if a string longer than 5 characters is contained\r
140     if (result.length() > minCharacterLength) \r
141         { \r
142                 result.deleteCharAt(result.length()-1); \r
143                 result.deleteCharAt(0); \r
144         }\r
145         else\r
146         {\r
147                 // Almost surely a false positive ( start + stop + at least 1 character)\r
148                 throw NotFoundException.getNotFoundInstance();\r
149         }\r
150 \r
151     float left = (float) (start[1] + start[0]) / 2.0f;\r
152     float right = (float) (nextStart + lastStart) / 2.0f;\r
153     return new Result(\r
154         result.toString(),\r
155         null,\r
156         new ResultPoint[]{\r
157             new ResultPoint(left, (float) rowNumber),\r
158             new ResultPoint(right, (float) rowNumber)},\r
159         BarcodeFormat.CODABAR);\r
160   }\r
161 \r
162   private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {\r
163     int width = row.getSize();\r
164     int rowOffset = 0;\r
165     while (rowOffset < width) {\r
166       if (row.get(rowOffset)) {\r
167         break;\r
168       }\r
169       rowOffset++;\r
170     }\r
171 \r
172     int counterPosition = 0;\r
173     int[] counters = new int[7];\r
174     int patternStart = rowOffset;\r
175     boolean isWhite = false;\r
176     int patternLength = counters.length;\r
177 \r
178     for (int i = rowOffset; i < width; i++) {\r
179       boolean pixel = row.get(i);\r
180       if (pixel ^ isWhite) {\r
181         counters[counterPosition]++;\r
182       } else {\r
183         if (counterPosition == patternLength - 1) {\r
184           try {\r
185             if (arrayContains(STARTEND_ENCODING, toNarrowWidePattern(counters))) {\r
186               // Look for whitespace before start pattern, >= 50% of width of start pattern\r
187               if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {\r
188                 return new int[]{patternStart, i};\r
189               }\r
190             }\r
191           } catch (IllegalArgumentException re) {\r
192             // no match, continue\r
193           }\r
194           patternStart += counters[0] + counters[1];\r
195           for (int y = 2; y < patternLength; y++) {\r
196             counters[y - 2] = counters[y];\r
197           }\r
198           counters[patternLength - 2] = 0;\r
199           counters[patternLength - 1] = 0;\r
200           counterPosition--;\r
201         } else {\r
202           counterPosition++;\r
203         }\r
204         counters[counterPosition] = 1;\r
205         isWhite ^= true; // isWhite = !isWhite;\r
206       }\r
207     }\r
208     throw NotFoundException.getNotFoundInstance();\r
209   }\r
210 \r
211   private static boolean arrayContains(char[] array, char key) {\r
212     if (array != null) {\r
213       for (int i = 0; i < array.length; i++) {\r
214         if (array[i] == key) {\r
215           return true;\r
216         }\r
217       }\r
218     }\r
219     return false;\r
220   }\r
221 \r
222   private static char toNarrowWidePattern(int[] counters) {\r
223     // BAS : I have changed the following part because some codabar images would fail with the original routine\r
224     //        I took from the Code39Reader.java file\r
225     // ----------- change start\r
226     int numCounters = counters.length;\r
227     int maxNarrowCounter = 0;\r
228 \r
229     int minCounter = Integer.MAX_VALUE;\r
230     for (int i = 0; i < numCounters; i++) {\r
231       if (counters[i] < minCounter) {\r
232         minCounter = counters[i];\r
233       }\r
234       if (counters[i] > maxNarrowCounter) {\r
235         maxNarrowCounter = counters[i];\r
236       }\r
237     }\r
238     // ---------- change end\r
239 \r
240 \r
241     do {\r
242       int wideCounters = 0;\r
243       int pattern = 0;\r
244       for (int i = 0; i < numCounters; i++) {\r
245         if (counters[i] > maxNarrowCounter) {\r
246           pattern |= 1 << (numCounters - 1 - i);\r
247           wideCounters++;\r
248         }\r
249       }\r
250 \r
251       if ((wideCounters == 2) || (wideCounters == 3)) {\r
252         for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {\r
253           if (CHARACTER_ENCODINGS[i] == pattern) {\r
254             return ALPHABET[i];\r
255           }\r
256         }\r
257       }\r
258       maxNarrowCounter--;\r
259     } while (maxNarrowCounter > minCounter);\r
260     return '!';\r
261   }\r
262 \r
263 }\r