Added rendering fix from beyonddeath
[zxing.git] / csharp / oned / AbstractUPCEANReader.cs
1 /*\r
2 * Licensed under the Apache License, Version 2.0 (the "License");\r
3 * you may not use this file except in compliance with the License.\r
4 * You may obtain a copy of the License at\r
5 *\r
6 *      http://www.apache.org/licenses/LICENSE-2.0\r
7 *\r
8 * Unless required by applicable law or agreed to in writing, software\r
9 * distributed under the License is distributed on an "AS IS" BASIS,\r
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
11 * See the License for the specific language governing permissions and\r
12 * limitations under the License.\r
13 */\r
14 namespace com.google.zxing.oned\r
15 {\r
16     using System;\r
17     using System.Text;\r
18     using com.google.zxing.common;\r
19 \r
20     /**\r
21      * <p>Encapsulates functionality and implementation that is common to UPC and EAN families\r
22      * of one-dimensional barcodes.</p>\r
23      *\r
24      * @author dswitkin@google.com (Daniel Switkin)\r
25      * @author Sean Owen\r
26      * @author alasdair@google.com (Alasdair Mackintosh)\r
27      */\r
28 \r
29     public abstract class AbstractUPCEANReader : AbstractOneDReader,UPCEANReader\r
30     { \r
31           private static  int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);\r
32           private static  int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);\r
33 \r
34           /**\r
35            * Start/end guard pattern.\r
36            */\r
37           private static  int[] START_END_PATTERN = {1, 1, 1,};\r
38 \r
39           /**\r
40            * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.\r
41            */\r
42           public static  int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};\r
43 \r
44           /**\r
45            * "Odd", or "L" patterns used to encode UPC/EAN digits.\r
46            */\r
47           public static  int[][] L_PATTERNS = new int[][]{\r
48               new int[]{3, 2, 1, 1}, // 0\r
49               new int[]{2, 2, 2, 1}, // 1\r
50               new int[]{2, 1, 2, 2}, // 2\r
51               new int[]{1, 4, 1, 1}, // 3\r
52               new int[]{1, 1, 3, 2}, // 4\r
53               new int[]{1, 2, 3, 1}, // 5\r
54               new int[]{1, 1, 1, 4}, // 6\r
55               new int[]{1, 3, 1, 2}, // 7\r
56               new int[]{1, 2, 1, 3}, // 8\r
57               new int[]{3, 1, 1, 2}  // 9\r
58           };\r
59 \r
60           /**\r
61            * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.\r
62            */\r
63           public static  int[][] L_AND_G_PATTERNS=new int[20][];\r
64 \r
65           //static {\r
66           //  L_AND_G_PATTERNS = new int[20][];\r
67           //  for (int i = 0; i < 10; i++) {\r
68           //    L_AND_G_PATTERNS[i] = L_PATTERNS[i];\r
69           //  }\r
70           //  for (int i = 10; i < 20; i++) {\r
71           //    int[] widths = L_PATTERNS[i - 10];\r
72           //    int[] reversedWidths = new int[widths.length];\r
73           //    for (int j = 0; j < widths.length; j++) {\r
74           //      reversedWidths[j] = widths[widths.length - j - 1];\r
75           //    }\r
76           //    L_AND_G_PATTERNS[i] = reversedWidths;\r
77           //  }\r
78           //}\r
79 \r
80           private  StringBuilder decodeRowStringBuffer;\r
81 \r
82           protected AbstractUPCEANReader() {\r
83             for (int i = 0; i < 10; i++) {\r
84               L_AND_G_PATTERNS[i] = L_PATTERNS[i];\r
85             }\r
86             for (int i = 10; i < 20; i++) {\r
87               int[] widths = L_PATTERNS[i - 10];\r
88               int[] reversedWidths = new int[widths.Length];\r
89               for (int j = 0; j < widths.Length; j++) {\r
90                 reversedWidths[j] = widths[widths.Length - j - 1];\r
91               }\r
92               L_AND_G_PATTERNS[i] = reversedWidths;\r
93             }\r
94             decodeRowStringBuffer = new StringBuilder(20);\r
95           }\r
96 \r
97           public static int[] findStartGuardPattern(BitArray row) {\r
98             bool foundStart = false;\r
99             int[] startRange = null;\r
100             int nextStart = 0;\r
101             while (!foundStart) {\r
102               startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);\r
103               int start = startRange[0];\r
104               nextStart = startRange[1];\r
105               // Make sure there is a quiet zone at least as big as the start pattern before the barcode. If\r
106               // this check would run off the left edge of the image, do not accept this barcode, as it is\r
107               // very likely to be a false positive.\r
108               int quietStart = start - (nextStart - start);\r
109               if (quietStart >= 0) {\r
110                 foundStart = row.isRange(quietStart, start, false);\r
111               }\r
112             }\r
113             return startRange;\r
114           }\r
115 \r
116           public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) {\r
117             return decodeRow(rowNumber, row, findStartGuardPattern(row));\r
118           }\r
119 \r
120           public  Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) {\r
121             StringBuilder result = decodeRowStringBuffer;\r
122             result.Length = 0;\r
123             int endStart = decodeMiddle(row, startGuardRange, result);\r
124             int[] endRange = decodeEnd(row, endStart);\r
125 \r
126             // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The\r
127             // spec might want more whitespace, but in practice this is the maximum we can count on.\r
128             int end = endRange[1];\r
129             int quietEnd = end + (end - endRange[0]);\r
130             if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {\r
131               throw new ReaderException();\r
132             }\r
133 \r
134             String resultString = result.ToString();\r
135             if (!checkChecksum(resultString)) {\r
136               throw new ReaderException();\r
137             }\r
138 \r
139             float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;\r
140             float right = (float) (endRange[1] + endRange[0]) / 2.0f;\r
141             return new Result(resultString,\r
142                 null, // no natural byte representation for these barcodes\r
143                 new ResultPoint[]{\r
144                     new GenericResultPoint(left, (float) rowNumber),\r
145                     new GenericResultPoint(right, (float) rowNumber)},\r
146                 getBarcodeFormat());\r
147           }\r
148 \r
149           public abstract BarcodeFormat getBarcodeFormat();\r
150 \r
151           /**\r
152            * @return {@link #checkStandardUPCEANChecksum(String)} \r
153            */\r
154           public bool checkChecksum(String s) {\r
155             return checkStandardUPCEANChecksum(s);\r
156           }\r
157 \r
158           /**\r
159            * Computes the UPC/EAN checksum on a string of digits, and reports\r
160            * whether the checksum is correct or not.\r
161            *\r
162            * @param s string of digits to check\r
163            * @return true iff string of digits passes the UPC/EAN checksum algorithm\r
164            * @throws ReaderException if the string does not contain only digits\r
165            */\r
166           public static bool checkStandardUPCEANChecksum(String s) {\r
167             int length = s.Length;\r
168             if (length == 0) {\r
169               return false;\r
170             }\r
171 \r
172             int sum = 0;\r
173             for (int i = length - 2; i >= 0; i -= 2) {\r
174               int digit = (int) s[i] - (int) '0';\r
175               if (digit < 0 || digit > 9) {\r
176                 throw new ReaderException();\r
177               }\r
178               sum += digit;\r
179             }\r
180             sum *= 3;\r
181             for (int i = length - 1; i >= 0; i -= 2) {\r
182               int digit = (int) s[i] - (int) '0';\r
183               if (digit < 0 || digit > 9) {\r
184                 throw new ReaderException();\r
185               }\r
186               sum += digit;\r
187             }\r
188             return sum % 10 == 0;\r
189           }\r
190 \r
191           /**\r
192            * Subclasses override this to decode the portion of a barcode between the start and end guard patterns.\r
193            *\r
194            * @param row row of black/white values to search\r
195            * @param startRange start/end offset of start guard pattern\r
196            * @param resultString {@link StringBuffer} to append decoded chars to\r
197            * @return horizontal offset of first pixel after the "middle" that was decoded\r
198            * @throws ReaderException if decoding could not complete successfully\r
199            */\r
200           protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString);\r
201 \r
202           int[] decodeEnd(BitArray row, int endStart) {\r
203             return findGuardPattern(row, endStart, false, START_END_PATTERN);\r
204           }\r
205 \r
206           /**\r
207            * @param row row of black/white values to search\r
208            * @param rowOffset position to start search\r
209            * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...\r
210            * pixel counts, otherwise, it is interpreted as black/white/black/...\r
211            * @param pattern pattern of counts of number of black and white pixels that are being\r
212            * searched for as a pattern\r
213            * @return start/end horizontal offset of guard pattern, as an array of two ints\r
214            * @throws ReaderException if pattern is not found\r
215            */\r
216           public static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern)\r
217               {\r
218             int patternLength = pattern.Length;\r
219             int[] counters = new int[patternLength];\r
220             int width = row.getSize();\r
221             bool isWhite = false;\r
222             while (rowOffset < width) {\r
223               isWhite = !row.get(rowOffset);\r
224               if (whiteFirst == isWhite) {\r
225                 break;\r
226               }\r
227               rowOffset++;\r
228             }\r
229 \r
230             int counterPosition = 0;\r
231             int patternStart = rowOffset;\r
232             for (int x = rowOffset; x < width; x++) {\r
233               bool pixel = row.get(x);\r
234               if ((!pixel && isWhite) || (pixel && !isWhite)) {\r
235                 counters[counterPosition]++;\r
236               } else {\r
237                 if (counterPosition == patternLength - 1) {\r
238                   if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {\r
239                     return new int[]{patternStart, x};\r
240                   }\r
241                   patternStart += counters[0] + counters[1];\r
242                   for (int y = 2; y < patternLength; y++) {\r
243                     counters[y - 2] = counters[y];\r
244                   }\r
245                   counters[patternLength - 2] = 0;\r
246                   counters[patternLength - 1] = 0;\r
247                   counterPosition--;\r
248                 } else {\r
249                   counterPosition++;\r
250                 }\r
251                 counters[counterPosition] = 1;\r
252                 isWhite = !isWhite;\r
253               }\r
254             }\r
255             throw new ReaderException();\r
256           }\r
257 \r
258           /**\r
259            * Attempts to decode a single UPC/EAN-encoded digit.\r
260            *\r
261            * @param row row of black/white values to decode\r
262            * @param counters the counts of runs of observed black/white/black/... values\r
263            * @param rowOffset horizontal offset to start decoding from\r
264            * @param patterns the set of patterns to use to decode -- sometimes different encodings\r
265            * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should\r
266            * be used\r
267            * @return horizontal offset of first pixel beyond the decoded digit\r
268            * @throws ReaderException if digit cannot be decoded\r
269            */\r
270           public static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)\r
271               {\r
272             recordPattern(row, rowOffset, counters);\r
273             int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept\r
274             int bestMatch = -1;\r
275             int max = patterns.Length;\r
276             for (int i = 0; i < max; i++) {\r
277               int[] pattern = patterns[i];\r
278               int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);\r
279               if (variance < bestVariance) {\r
280                 bestVariance = variance;\r
281                 bestMatch = i;\r
282               }\r
283             }\r
284             if (bestMatch >= 0) {\r
285               return bestMatch;\r
286             } else {\r
287               throw new ReaderException();\r
288             }\r
289           }\r
290 \r
291     \r
292     }\r
293 \r
294 \r
295 }