5 * Copyright 2010 ZXing authors All rights reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 #include "Code39Reader.h"
21 #include <zxing/oned/OneDResultPoint.h>
22 #include <zxing/common/Array.h>
23 #include <zxing/ReaderException.h>
30 static const char* ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
34 * These represent the encodings of characters, as patterns of wide and narrow
36 * The 9 least-significant bits of each int correspond to the pattern of wide
37 * and narrow, with 1s representing "wide" and 0s representing narrow.
39 const int CHARACTER_ENCODINGS_LEN = 44;
40 static int CHARACTER_ENCODINGS[CHARACTER_ENCODINGS_LEN] = {
41 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
42 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
43 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
44 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
45 0x0A8, 0x0A2, 0x08A, 0x02A // $-%
48 static int ASTERISK_ENCODING = 0x094;
49 static const char* ALPHABET_STRING =
50 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
54 * Creates a reader that assumes all encoded data is data, and does not treat
55 * the final character as a check digit. It will not decoded "extended
58 Code39Reader::Code39Reader() : alphabet_string(ALPHABET_STRING),
59 usingCheckDigit(false),
64 * Creates a reader that can be configured to check the last character as a
65 * check digit. It will not decoded "extended Code 39" sequences.
67 * @param usingCheckDigit if true, treat the last data character as a check
68 * digit, not data, and verify that the checksum passes.
70 Code39Reader::Code39Reader(bool usingCheckDigit_) :
71 alphabet_string(ALPHABET_STRING),
72 usingCheckDigit(usingCheckDigit_),
77 Code39Reader::Code39Reader(bool usingCheckDigit_, bool extendedMode_) :
78 alphabet_string(ALPHABET_STRING),
79 usingCheckDigit(usingCheckDigit_),
80 extendedMode(extendedMode_) {
83 Ref<Result> Code39Reader::decodeRow(int rowNumber, Ref<BitArray> row) {
86 start = findAsteriskPattern(row);
87 int nextStart = start[1];
88 int end = row->getSize();
90 // Read off white space
91 while (nextStart < end && !row->get(nextStart)) {
95 std::string tmpResultString;
97 const int countersLen = 9;
98 int counters[countersLen];
99 for (int i = 0; i < countersLen; i++) {
105 recordPattern(row, nextStart, counters, countersLen);
106 int pattern = toNarrowWidePattern(counters, countersLen);
108 throw ReaderException("pattern < 0");
110 decodedChar = patternToChar(pattern);
111 tmpResultString.append(1, decodedChar);
112 lastStart = nextStart;
113 for (int i = 0; i < countersLen; i++) {
114 nextStart += counters[i];
116 // Read off white space
117 while (nextStart < end && !row->get(nextStart)) {
120 } while (decodedChar != '*');
121 tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk
123 // Look for whitespace after pattern:
124 int lastPatternSize = 0;
125 for (int i = 0; i < countersLen; i++) {
126 lastPatternSize += counters[i];
128 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
129 // If 50% of last pattern size, following last pattern, is not whitespace,
130 // fail (but if it's whitespace to the very end of the image, that's OK)
131 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
132 throw ReaderException("too short end white space");
135 if (usingCheckDigit) {
136 int max = tmpResultString.length() - 1;
137 unsigned int total = 0;
138 for (int i = 0; i < max; i++) {
139 total += alphabet_string.find_first_of(tmpResultString[i], 0);
141 if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
142 throw ReaderException("");
144 tmpResultString.erase(max, 1);
147 Ref<String> resultString(new String(tmpResultString));
149 resultString = decodeExtended(tmpResultString);
152 if (tmpResultString.length() == 0) {
153 // Almost surely a false positive
154 throw ReaderException("");
157 float left = (float) (start[1] + start[0]) / 2.0f;
158 float right = (float) (nextStart + lastStart) / 2.0f;
160 std::vector< Ref<ResultPoint> > resultPoints(2);
161 Ref<OneDResultPoint> resultPoint1(
162 new OneDResultPoint(left, (float) rowNumber));
163 Ref<OneDResultPoint> resultPoint2(
164 new OneDResultPoint(right, (float) rowNumber));
165 resultPoints[0] = resultPoint1;
166 resultPoints[1] = resultPoint2;
168 ArrayRef<unsigned char> resultBytes(1);
170 Ref<Result> res(new Result(
171 resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
175 } catch (ReaderException const& re) {
177 return Ref<Result>();
181 int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
182 int width = row->getSize();
184 while (rowOffset < width) {
185 if (row->get(rowOffset)) {
191 int counterPosition = 0;
192 const int countersLen = 9;
193 int counters[countersLen];
194 for (int i = 0; i < countersLen; i++) {
197 int patternStart = rowOffset;
198 bool isWhite = false;
199 int patternLength = countersLen;
201 for (int i = rowOffset; i < width; i++) {
202 bool pixel = row->get(i);
203 if (pixel ^ isWhite) {
204 counters[counterPosition]++;
206 if (counterPosition == patternLength - 1) {
207 if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
208 // Look for whitespace before start pattern, >= 50% of width of
210 long double longPatternOffset =
211 fmaxl(0, patternStart - (i - patternStart) / 2);
212 if (row->isRange(longPatternOffset, patternStart, false)) {
213 int* resultValue = new int[2];
214 resultValue[0] = patternStart;
219 patternStart += counters[0] + counters[1];
220 for (int y = 2; y < patternLength; y++) {
221 counters[y - 2] = counters[y];
223 counters[patternLength - 2] = 0;
224 counters[patternLength - 1] = 0;
229 counters[counterPosition] = 1;
233 throw ReaderException("");
236 // For efficiency, returns -1 on failure. Not throwing here saved as many as
237 // 700 exceptions per image when using some of our blackbox images.
238 int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
239 int numCounters = countersLen;
240 int maxNarrowCounter = 0;
243 int minCounter = INT_MAX;
244 for (int i = 0; i < numCounters; i++) {
245 int counter = counters[i];
246 if (counter < minCounter && counter > maxNarrowCounter) {
247 minCounter = counter;
250 maxNarrowCounter = minCounter;
252 int totalWideCountersWidth = 0;
254 for (int i = 0; i < numCounters; i++) {
255 int counter = counters[i];
256 if (counters[i] > maxNarrowCounter) {
257 pattern |= 1 << (numCounters - 1 - i);
259 totalWideCountersWidth += counter;
262 if (wideCounters == 3) {
263 // Found 3 wide counters, but are they close enough in width?
264 // We can perform a cheap, conservative check to see if any individual
265 // counter is more than 1.5 times the average:
266 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
267 int counter = counters[i];
268 if (counters[i] > maxNarrowCounter) {
270 // totalWideCountersWidth = 3 * average, so this checks if
271 // counter >= 3/2 * average.
272 if ((counter << 1) >= totalWideCountersWidth) {
279 } while (wideCounters > 3);
283 char Code39Reader::patternToChar(int pattern){
284 for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
285 if (CHARACTER_ENCODINGS[i] == pattern) {
289 throw ReaderException("");
292 Ref<String> Code39Reader::decodeExtended(std::string encoded){
293 int length = encoded.length();
294 std::string tmpDecoded;
295 for (int i = 0; i < length; i++) {
297 if (c == '+' || c == '$' || c == '%' || c == '/') {
298 char next = encoded[i + 1];
299 char decodedChar = '\0';
302 // +A to +Z map to a to z
303 if (next >= 'A' && next <= 'Z') {
304 decodedChar = (char) (next + 32);
306 throw ReaderException("");
310 // $A to $Z map to control codes SH to SB
311 if (next >= 'A' && next <= 'Z') {
312 decodedChar = (char) (next - 64);
314 throw ReaderException("");
318 // %A to %E map to control codes ESC to US
319 if (next >= 'A' && next <= 'E') {
320 decodedChar = (char) (next - 38);
321 } else if (next >= 'F' && next <= 'W') {
322 decodedChar = (char) (next - 11);
324 throw ReaderException("");
328 // /A to /O map to ! to , and /Z maps to :
329 if (next >= 'A' && next <= 'O') {
330 decodedChar = (char) (next - 32);
331 } else if (next == 'Z') {
334 throw ReaderException("");
338 tmpDecoded.append(1, decodedChar);
339 // bump up i again since we read two characters
342 tmpDecoded.append(1, c);
345 Ref<String> decoded(new String(tmpDecoded));