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 if (!recordPattern(row, nextStart, counters, countersLen)) {
106 throw ReaderException("");
108 int pattern = toNarrowWidePattern(counters, countersLen);
110 throw ReaderException("pattern < 0");
112 decodedChar = patternToChar(pattern);
113 tmpResultString.append(1, decodedChar);
114 lastStart = nextStart;
115 for (int i = 0; i < countersLen; i++) {
116 nextStart += counters[i];
118 // Read off white space
119 while (nextStart < end && !row->get(nextStart)) {
122 } while (decodedChar != '*');
123 tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk
125 // Look for whitespace after pattern:
126 int lastPatternSize = 0;
127 for (int i = 0; i < countersLen; i++) {
128 lastPatternSize += counters[i];
130 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
131 // If 50% of last pattern size, following last pattern, is not whitespace,
132 // fail (but if it's whitespace to the very end of the image, that's OK)
133 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
134 throw ReaderException("too short end white space");
137 if (usingCheckDigit) {
138 int max = tmpResultString.length() - 1;
139 unsigned int total = 0;
140 for (int i = 0; i < max; i++) {
141 total += alphabet_string.find_first_of(tmpResultString[i], 0);
143 if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
144 throw ReaderException("");
146 tmpResultString.erase(max, 1);
149 Ref<String> resultString(new String(tmpResultString));
151 resultString = decodeExtended(tmpResultString);
154 if (tmpResultString.length() == 0) {
155 // Almost surely a false positive
156 throw ReaderException("");
159 float left = (float) (start[1] + start[0]) / 2.0f;
160 float right = (float) (nextStart + lastStart) / 2.0f;
162 std::vector< Ref<ResultPoint> > resultPoints(2);
163 Ref<OneDResultPoint> resultPoint1(
164 new OneDResultPoint(left, (float) rowNumber));
165 Ref<OneDResultPoint> resultPoint2(
166 new OneDResultPoint(right, (float) rowNumber));
167 resultPoints[0] = resultPoint1;
168 resultPoints[1] = resultPoint2;
170 ArrayRef<unsigned char> resultBytes(1);
172 Ref<Result> res(new Result(
173 resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
177 } catch (ReaderException const& re) {
179 return Ref<Result>();
183 int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
184 int width = row->getSize();
186 while (rowOffset < width) {
187 if (row->get(rowOffset)) {
193 int counterPosition = 0;
194 const int countersLen = 9;
195 int counters[countersLen];
196 for (int i = 0; i < countersLen; i++) {
199 int patternStart = rowOffset;
200 bool isWhite = false;
201 int patternLength = countersLen;
203 for (int i = rowOffset; i < width; i++) {
204 bool pixel = row->get(i);
205 if (pixel ^ isWhite) {
206 counters[counterPosition]++;
208 if (counterPosition == patternLength - 1) {
209 if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
210 // Look for whitespace before start pattern, >= 50% of width of
212 long double longPatternOffset =
213 fmaxl(0, patternStart - (i - patternStart) / 2);
214 if (row->isRange(longPatternOffset, patternStart, false)) {
215 int* resultValue = new int[2];
216 resultValue[0] = patternStart;
221 patternStart += counters[0] + counters[1];
222 for (int y = 2; y < patternLength; y++) {
223 counters[y - 2] = counters[y];
225 counters[patternLength - 2] = 0;
226 counters[patternLength - 1] = 0;
231 counters[counterPosition] = 1;
235 throw ReaderException("");
238 // For efficiency, returns -1 on failure. Not throwing here saved as many as
239 // 700 exceptions per image when using some of our blackbox images.
240 int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
241 int numCounters = countersLen;
242 int maxNarrowCounter = 0;
245 int minCounter = INT_MAX;
246 for (int i = 0; i < numCounters; i++) {
247 int counter = counters[i];
248 if (counter < minCounter && counter > maxNarrowCounter) {
249 minCounter = counter;
252 maxNarrowCounter = minCounter;
254 int totalWideCountersWidth = 0;
256 for (int i = 0; i < numCounters; i++) {
257 int counter = counters[i];
258 if (counters[i] > maxNarrowCounter) {
259 pattern |= 1 << (numCounters - 1 - i);
261 totalWideCountersWidth += counter;
264 if (wideCounters == 3) {
265 // Found 3 wide counters, but are they close enough in width?
266 // We can perform a cheap, conservative check to see if any individual
267 // counter is more than 1.5 times the average:
268 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
269 int counter = counters[i];
270 if (counters[i] > maxNarrowCounter) {
272 // totalWideCountersWidth = 3 * average, so this checks if
273 // counter >= 3/2 * average.
274 if ((counter << 1) >= totalWideCountersWidth) {
281 } while (wideCounters > 3);
285 char Code39Reader::patternToChar(int pattern){
286 for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
287 if (CHARACTER_ENCODINGS[i] == pattern) {
291 throw ReaderException("");
294 Ref<String> Code39Reader::decodeExtended(std::string encoded){
295 int length = encoded.length();
296 std::string tmpDecoded;
297 for (int i = 0; i < length; i++) {
299 if (c == '+' || c == '$' || c == '%' || c == '/') {
300 char next = encoded[i + 1];
301 char decodedChar = '\0';
304 // +A to +Z map to a to z
305 if (next >= 'A' && next <= 'Z') {
306 decodedChar = (char) (next + 32);
308 throw ReaderException("");
312 // $A to $Z map to control codes SH to SB
313 if (next >= 'A' && next <= 'Z') {
314 decodedChar = (char) (next - 64);
316 throw ReaderException("");
320 // %A to %E map to control codes ESC to US
321 if (next >= 'A' && next <= 'E') {
322 decodedChar = (char) (next - 38);
323 } else if (next >= 'F' && next <= 'W') {
324 decodedChar = (char) (next - 11);
326 throw ReaderException("");
330 // /A to /O map to ! to , and /Z maps to :
331 if (next >= 'A' && next <= 'O') {
332 decodedChar = (char) (next - 32);
333 } else if (next == 'Z') {
336 throw ReaderException("");
340 tmpDecoded.append(1, decodedChar);
341 // bump up i again since we read two characters
344 tmpDecoded.append(1, c);
347 Ref<String> decoded(new String(tmpDecoded));