Issue 439: be more lax and don't look for END
[zxing.git] / csharp / oned / UPCEANReader.cs
index c4af834..b0a031e 100755 (executable)
@@ -1,4 +1,6 @@
-/*\r
+/*\r
+* Copyright 2008 ZXing authors\r
+*\r
 * Licensed under the Apache License, Version 2.0 (the "License");\r
 * you may not use this file except in compliance with the License.\r
 * You may obtain a copy of the License at\r
 * See the License for the specific language governing permissions and\r
 * limitations under the License.\r
 */\r
+using System;\r
+using ReaderException = com.google.zxing.ReaderException;\r
+using Result = com.google.zxing.Result;\r
+using ResultPointCallback = com.google.zxing.ResultPointCallback;\r
+using DecodeHintType = com.google.zxing.DecodeHintType;\r
+using ResultPoint = com.google.zxing.ResultPoint;\r
+using BarcodeFormat = com.google.zxing.BarcodeFormat;\r
+using BitArray = com.google.zxing.common.BitArray;\r
 namespace com.google.zxing.oned\r
 {\r
-    using com.google.zxing.common;  \r
-    /**\r
-     * <p>This interfaces captures addtional functionality that readers of\r
-     * UPC/EAN family of barcodes should expose.</p>\r
-     *\r
-     * @author Sean Owen\r
-     */\r
-\r
-    public interface UPCEANReader : OneDReader \r
-    {\r
-           /**\r
-           * <p>Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but\r
-           * allows caller to inform method about where the UPC/EAN start pattern is\r
-           * found. This allows this to be computed once and reused across many implementations.</p>\r
-           */\r
-          Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange);\r
-    }\r
-\r
+       \r
+       /// <summary> <p>Encapsulates functionality and implementation that is common to UPC and EAN families\r
+       /// of one-dimensional barcodes.</p>\r
+       /// \r
+       /// </summary>\r
+       /// <author>  dswitkin@google.com (Daniel Switkin)\r
+       /// </author>\r
+       /// <author>  Sean Owen\r
+       /// </author>\r
+       /// <author>  alasdair@google.com (Alasdair Mackintosh)\r
+       /// </author>\r
+       /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source \r
+       /// </author>\r
+       public abstract class UPCEANReader:OneDReader\r
+       {\r
+               /// <summary> Get the format of this decoder.\r
+               /// \r
+               /// </summary>\r
+               /// <returns> The 1D format.\r
+               /// </returns>\r
+               internal abstract BarcodeFormat BarcodeFormat{get;}\r
+               \r
+               // These two values are critical for determining how permissive the decoding will be.\r
+               // We've arrived at these values through a lot of trial and error. Setting them any higher\r
+               // lets false positives creep in quickly.\r
+               //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_AVG_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"\r
+               //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"\r
+               private static readonly int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);\r
+               //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_INDIVIDUAL_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"\r
+               //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"\r
+               private static readonly int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);\r
+               \r
+               /// <summary> Start/end guard pattern.</summary>\r
+               //UPGRADE_NOTE: Final was removed from the declaration of 'START_END_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"\r
+               internal static readonly int[] START_END_PATTERN = new int[]{1, 1, 1};\r
+               \r
+               /// <summary> Pattern marking the middle of a UPC/EAN pattern, separating the two halves.</summary>\r
+               //UPGRADE_NOTE: Final was removed from the declaration of 'MIDDLE_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"\r
+               internal static readonly int[] MIDDLE_PATTERN = new int[]{1, 1, 1, 1, 1};\r
+               \r
+               /// <summary> "Odd", or "L" patterns used to encode UPC/EAN digits.</summary>\r
+               //UPGRADE_NOTE: Final was removed from the declaration of 'L_PATTERNS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"\r
+               internal static readonly int[][] L_PATTERNS = new int[][]{new int[]{3, 2, 1, 1}, new int[]{2, 2, 2, 1}, new int[]{2, 1, 2, 2}, new int[]{1, 4, 1, 1}, new int[]{1, 1, 3, 2}, new int[]{1, 2, 3, 1}, new int[]{1, 1, 1, 4}, new int[]{1, 3, 1, 2}, new int[]{1, 2, 1, 3}, new int[]{3, 1, 1, 2}};\r
+               \r
+               /// <summary> As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.</summary>\r
+               internal static int[][] L_AND_G_PATTERNS;\r
+               \r
+               //UPGRADE_NOTE: Final was removed from the declaration of 'decodeRowStringBuffer '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"\r
+               private System.Text.StringBuilder decodeRowStringBuffer;\r
+               \r
+               protected internal UPCEANReader()\r
+               {\r
+                       decodeRowStringBuffer = new System.Text.StringBuilder(20);\r
+               }\r
+               \r
+               internal static int[] findStartGuardPattern(BitArray row)\r
+               {\r
+                       bool foundStart = false;\r
+                       int[] startRange = null;\r
+                       int nextStart = 0;\r
+                       while (!foundStart)\r
+                       {\r
+                               startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);\r
+                               int start = startRange[0];\r
+                               nextStart = startRange[1];\r
+                               // Make sure there is a quiet zone at least as big as the start pattern before the barcode.\r
+                               // If this check would run off the left edge of the image, do not accept this barcode,\r
+                               // as it is very likely to be a false positive.\r
+                               int quietStart = start - (nextStart - start);\r
+                               if (quietStart >= 0)\r
+                               {\r
+                                       foundStart = row.isRange(quietStart, start, false);\r
+                               }\r
+                       }\r
+                       return startRange;\r
+               }\r
+               \r
+               public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints)\r
+               {\r
+                       return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);\r
+               }\r
+               \r
+               /// <summary> <p>Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but\r
+               /// allows caller to inform method about where the UPC/EAN start pattern is\r
+               /// found. This allows this to be computed once and reused across many implementations.</p>\r
+               /// </summary>\r
+               public virtual Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, System.Collections.Hashtable hints)\r
+               {\r
+                       \r
+                       ResultPointCallback resultPointCallback = hints == null?null:(ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];\r
+                       \r
+                       if (resultPointCallback != null)\r
+                       {\r
+                               resultPointCallback.foundPossibleResultPoint(new ResultPoint((startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber));\r
+                       }\r
+                       \r
+                       System.Text.StringBuilder result = decodeRowStringBuffer;\r
+                       result.Length = 0;\r
+                       int endStart = decodeMiddle(row, startGuardRange, result);\r
+                       \r
+                       if (resultPointCallback != null)\r
+                       {\r
+                               resultPointCallback.foundPossibleResultPoint(new ResultPoint(endStart, rowNumber));\r
+                       }\r
+                       \r
+                       int[] endRange = decodeEnd(row, endStart);\r
+                       \r
+                       if (resultPointCallback != null)\r
+                       {\r
+                               resultPointCallback.foundPossibleResultPoint(new ResultPoint((endRange[0] + endRange[1]) / 2.0f, rowNumber));\r
+                       }\r
+                       \r
+                       \r
+                       // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The\r
+                       // spec might want more whitespace, but in practice this is the maximum we can count on.\r
+                       int end = endRange[1];\r
+                       int quietEnd = end + (end - endRange[0]);\r
+                       if (quietEnd >= row.Size || !row.isRange(end, quietEnd, false))\r
+                       {\r
+                               throw ReaderException.Instance;\r
+                       }\r
+                       \r
+                       System.String resultString = result.ToString();\r
+                       if (!checkChecksum(resultString))\r
+                       {\r
+                               throw ReaderException.Instance;\r
+                       }\r
+                       \r
+                       //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"\r
+                       float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;\r
+                       //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"\r
+                       float right = (float) (endRange[1] + endRange[0]) / 2.0f;\r
+                       //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"\r
+                       return new Result(resultString, null, new ResultPoint[]{new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat);\r
+               }\r
+               \r
+               /// <returns> {@link #checkStandardUPCEANChecksum(String)}\r
+               /// </returns>\r
+               //UPGRADE_NOTE: Access modifiers of method 'checkChecksum' were changed to 'protected'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1204'"\r
+               protected internal virtual bool checkChecksum(System.String s)\r
+               {\r
+                       return checkStandardUPCEANChecksum(s);\r
+               }\r
+               \r
+               /// <summary> Computes the UPC/EAN checksum on a string of digits, and reports\r
+               /// whether the checksum is correct or not.\r
+               /// \r
+               /// </summary>\r
+               /// <param name="s">string of digits to check\r
+               /// </param>\r
+               /// <returns> true iff string of digits passes the UPC/EAN checksum algorithm\r
+               /// </returns>\r
+               /// <throws>  ReaderException if the string does not contain only digits </throws>\r
+               private static bool checkStandardUPCEANChecksum(System.String s)\r
+               {\r
+                       int length = s.Length;\r
+                       if (length == 0)\r
+                       {\r
+                               return false;\r
+                       }\r
+                       \r
+                       int sum = 0;\r
+                       for (int i = length - 2; i >= 0; i -= 2)\r
+                       {\r
+                               int digit = (int) s[i] - (int) '0';\r
+                               if (digit < 0 || digit > 9)\r
+                               {\r
+                                       throw ReaderException.Instance;\r
+                               }\r
+                               sum += digit;\r
+                       }\r
+                       sum *= 3;\r
+                       for (int i = length - 1; i >= 0; i -= 2)\r
+                       {\r
+                               int digit = (int) s[i] - (int) '0';\r
+                               if (digit < 0 || digit > 9)\r
+                               {\r
+                                       throw ReaderException.Instance;\r
+                               }\r
+                               sum += digit;\r
+                       }\r
+                       return sum % 10 == 0;\r
+               }\r
+               \r
+               //UPGRADE_NOTE: Access modifiers of method 'decodeEnd' were changed to 'protected'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1204'"\r
+               protected internal virtual int[] decodeEnd(BitArray row, int endStart)\r
+               {\r
+                       return findGuardPattern(row, endStart, false, START_END_PATTERN);\r
+               }\r
+               \r
+               /// <param name="row">row of black/white values to search\r
+               /// </param>\r
+               /// <param name="rowOffset">position to start search\r
+               /// </param>\r
+               /// <param name="whiteFirst">if true, indicates that the pattern specifies white/black/white/...\r
+               /// pixel counts, otherwise, it is interpreted as black/white/black/...\r
+               /// </param>\r
+               /// <param name="pattern">pattern of counts of number of black and white pixels that are being\r
+               /// searched for as a pattern\r
+               /// </param>\r
+               /// <returns> start/end horizontal offset of guard pattern, as an array of two ints\r
+               /// </returns>\r
+               /// <throws>  ReaderException if pattern is not found </throws>\r
+               internal static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern)\r
+               {\r
+                       int patternLength = pattern.Length;\r
+                       int[] counters = new int[patternLength];\r
+                       int width = row.Size;\r
+                       bool isWhite = false;\r
+                       while (rowOffset < width)\r
+                       {\r
+                               isWhite = !row.get_Renamed(rowOffset);\r
+                               if (whiteFirst == isWhite)\r
+                               {\r
+                                       break;\r
+                               }\r
+                               rowOffset++;\r
+                       }\r
+                       \r
+                       int counterPosition = 0;\r
+                       int patternStart = rowOffset;\r
+                       for (int x = rowOffset; x < width; x++)\r
+                       {\r
+                               bool pixel = row.get_Renamed(x);\r
+                               if (pixel ^ isWhite)\r
+                               {\r
+                                       counters[counterPosition]++;\r
+                               }\r
+                               else\r
+                               {\r
+                                       if (counterPosition == patternLength - 1)\r
+                                       {\r
+                                               if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE)\r
+                                               {\r
+                                                       return new int[]{patternStart, x};\r
+                                               }\r
+                                               patternStart += counters[0] + counters[1];\r
+                                               for (int y = 2; y < patternLength; y++)\r
+                                               {\r
+                                                       counters[y - 2] = counters[y];\r
+                                               }\r
+                                               counters[patternLength - 2] = 0;\r
+                                               counters[patternLength - 1] = 0;\r
+                                               counterPosition--;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               counterPosition++;\r
+                                       }\r
+                                       counters[counterPosition] = 1;\r
+                                       isWhite = !isWhite;\r
+                               }\r
+                       }\r
+                       throw ReaderException.Instance;\r
+               }\r
+               \r
+               /// <summary> Attempts to decode a single UPC/EAN-encoded digit.\r
+               /// \r
+               /// </summary>\r
+               /// <param name="row">row of black/white values to decode\r
+               /// </param>\r
+               /// <param name="counters">the counts of runs of observed black/white/black/... values\r
+               /// </param>\r
+               /// <param name="rowOffset">horizontal offset to start decoding from\r
+               /// </param>\r
+               /// <param name="patterns">the set of patterns to use to decode -- sometimes different encodings\r
+               /// for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should\r
+               /// be used\r
+               /// </param>\r
+               /// <returns> horizontal offset of first pixel beyond the decoded digit\r
+               /// </returns>\r
+               /// <throws>  ReaderException if digit cannot be decoded </throws>\r
+               internal static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)\r
+               {\r
+                       recordPattern(row, rowOffset, counters);\r
+                       int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept\r
+                       int bestMatch = - 1;\r
+                       int max = patterns.Length;\r
+                       for (int i = 0; i < max; i++)\r
+                       {\r
+                               int[] pattern = patterns[i];\r
+                               int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);\r
+                               if (variance < bestVariance)\r
+                               {\r
+                                       bestVariance = variance;\r
+                                       bestMatch = i;\r
+                               }\r
+                       }\r
+                       if (bestMatch >= 0)\r
+                       {\r
+                               return bestMatch;\r
+                       }\r
+                       else\r
+                       {\r
+                               throw ReaderException.Instance;\r
+                       }\r
+               }\r
+               \r
+               /// <summary> Subclasses override this to decode the portion of a barcode between the start\r
+               /// and end guard patterns.\r
+               /// \r
+               /// </summary>\r
+               /// <param name="row">row of black/white values to search\r
+               /// </param>\r
+               /// <param name="startRange">start/end offset of start guard pattern\r
+               /// </param>\r
+               /// <param name="resultString">{@link StringBuffer} to append decoded chars to\r
+               /// </param>\r
+               /// <returns> horizontal offset of first pixel after the "middle" that was decoded\r
+               /// </returns>\r
+               /// <throws>  ReaderException if decoding could not complete successfully </throws>\r
+               protected internal abstract int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder resultString);\r
+               static UPCEANReader()\r
+               {\r
+                       {\r
+                               L_AND_G_PATTERNS = new int[20][];\r
+                               for (int i = 0; i < 10; i++)\r
+                               {\r
+                                       L_AND_G_PATTERNS[i] = L_PATTERNS[i];\r
+                               }\r
+                               for (int i = 10; i < 20; i++)\r
+                               {\r
+                                       int[] widths = L_PATTERNS[i - 10];\r
+                                       int[] reversedWidths = new int[widths.Length];\r
+                                       for (int j = 0; j < widths.Length; j++)\r
+                                       {\r
+                                               reversedWidths[j] = widths[widths.Length - j - 1];\r
+                                       }\r
+                                       L_AND_G_PATTERNS[i] = reversedWidths;\r
+                               }\r
+                       }\r
+               }\r
+       }\r
 }
\ No newline at end of file