5 * Created by Lukasz Warchol on 10-01-26.
6 * Copyright 2010 ZXing authors All rights reserved.
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
21 #include "Code39Reader.h"
22 #include <zxing/oned/OneDResultPoint.h>
23 #include <zxing/common/Array.h>
24 #include <zxing/ReaderException.h>
31 static const char* ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
35 * These represent the encodings of characters, as patterns of wide and narrow
37 * The 9 least-significant bits of each int correspond to the pattern of wide
38 * and narrow, with 1s representing "wide" and 0s representing narrow.
40 const int CHARACTER_ENCODINGS_LEN = 44;
41 static int CHARACTER_ENCODINGS[CHARACTER_ENCODINGS_LEN] = {
42 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
43 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
44 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
45 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
46 0x0A8, 0x0A2, 0x08A, 0x02A // $-%
49 static int ASTERISK_ENCODING = 0x094;
50 static const char* ALPHABET_STRING =
51 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
55 * Creates a reader that assumes all encoded data is data, and does not treat
56 * the final character as a check digit. It will not decoded "extended
59 Code39Reader::Code39Reader() : alphabet_string(ALPHABET_STRING),
60 usingCheckDigit(false),
65 * Creates a reader that can be configured to check the last character as a
66 * check digit. It will not decoded "extended Code 39" sequences.
68 * @param usingCheckDigit if true, treat the last data character as a check
69 * digit, not data, and verify that the checksum passes.
71 Code39Reader::Code39Reader(bool usingCheckDigit_) :
72 alphabet_string(ALPHABET_STRING),
73 usingCheckDigit(usingCheckDigit_),
79 Ref<Result> Code39Reader::decodeRow(int rowNumber, Ref<BitArray> row){
80 int* start = findAsteriskPattern(row);
81 int nextStart = start[1];
82 int end = row->getSize();
84 // Read off white space
85 while (nextStart < end && !row->get(nextStart)) {
89 std::string tmpResultString;
92 int* counters = new int[countersLen];
93 for (int i=0; i<countersLen; i++) {
100 recordPattern(row, nextStart, counters, countersLen);
101 } catch (ReaderException re) {
105 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];
131 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
132 // If 50% of last pattern size, following last pattern, is not whitespace,
133 // fail (but if it's whitespace to the very end of the image, that's OK)
134 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
136 throw ReaderException("too short end white space");
139 if (usingCheckDigit) {
140 int max = tmpResultString.length() - 1;
141 unsigned int total = 0;
142 for (int i = 0; i < max; i++) {
143 total += alphabet_string.find_first_of(tmpResultString[i], 0);
145 if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
146 throw ReaderException("");
148 tmpResultString.erase(max, 1);
154 Ref<String> resultString(new String(tmpResultString));
157 resultString = decodeExtended(tmpResultString);
160 if (tmpResultString.length() == 0) {
162 // Almost surely a false positive
163 throw ReaderException("");
166 float left = (float) (start[1] + start[0]) / 2.0f;
167 float right = (float) (nextStart + lastStart) / 2.0f;
169 std::vector< Ref<ResultPoint> > resultPoints(2);
170 Ref<OneDResultPoint> resultPoint1(
171 new OneDResultPoint(left, (float) rowNumber));
172 Ref<OneDResultPoint> resultPoint2(
173 new OneDResultPoint(right, (float) rowNumber));
174 resultPoints[0] = resultPoint1;
175 resultPoints[1] = resultPoint2;
177 ArrayRef<unsigned char> resultBytes(1);
181 Ref<Result> res(new Result(
182 resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
186 int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
187 int width = row->getSize();
189 while (rowOffset < width) {
190 if (row->get(rowOffset)) {
196 int counterPosition = 0;
198 int* counters = new int[countersLen];
199 for (int i=0; i<countersLen; i++) {
202 int patternStart = rowOffset;
203 bool isWhite = false;
204 int patternLength = countersLen;
206 for (int i = rowOffset; i < width; i++) {
207 bool pixel = row->get(i);
208 if (pixel ^ isWhite) {
209 counters[counterPosition]++;
211 if (counterPosition == patternLength - 1) {
212 if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
213 // Look for whitespace before start pattern, >= 50% of width of
215 long double longPatternOffset =
216 fmaxl(0, patternStart - (i - patternStart) / 2);
217 if (row->isRange(longPatternOffset, patternStart, false)) {
218 int* resultValue = new int[2];
219 resultValue[0] = patternStart;
224 patternStart += counters[0] + counters[1];
225 for (int y = 2; y < patternLength; y++) {
226 counters[y - 2] = counters[y];
228 counters[patternLength - 2] = 0;
229 counters[patternLength - 1] = 0;
234 counters[counterPosition] = 1;
241 throw ReaderException("");
244 // For efficiency, returns -1 on failure. Not throwing here saved as many as
245 // 700 exceptions per image when using some of our blackbox images.
246 int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
247 int numCounters = countersLen;
248 int maxNarrowCounter = 0;
251 int minCounter = INT_MAX;
252 for (int i = 0; i < numCounters; i++) {
253 int counter = counters[i];
254 if (counter < minCounter && counter > maxNarrowCounter) {
255 minCounter = counter;
258 maxNarrowCounter = minCounter;
260 int totalWideCountersWidth = 0;
262 for (int i = 0; i < numCounters; i++) {
263 int counter = counters[i];
264 if (counters[i] > maxNarrowCounter) {
265 pattern |= 1 << (numCounters - 1 - i);
267 totalWideCountersWidth += counter;
270 if (wideCounters == 3) {
271 // Found 3 wide counters, but are they close enough in width?
272 // We can perform a cheap, conservative check to see if any individual
273 // counter is more than 1.5 times the average:
274 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
275 int counter = counters[i];
276 if (counters[i] > maxNarrowCounter) {
278 // totalWideCountersWidth = 3 * average, so this checks if
279 // counter >= 3/2 * average.
280 if ((counter << 1) >= totalWideCountersWidth) {
287 } while (wideCounters > 3);
291 char Code39Reader::patternToChar(int pattern){
292 for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
293 if (CHARACTER_ENCODINGS[i] == pattern) {
297 throw ReaderException("");
300 Ref<String> Code39Reader::decodeExtended(std::string encoded){
301 int length = encoded.length();
302 std::string tmpDecoded;
303 for (int i = 0; i < length; i++) {
305 if (c == '+' || c == '$' || c == '%' || c == '/') {
306 char next = encoded[i + 1];
307 char decodedChar = '\0';
310 // +A to +Z map to a to z
311 if (next >= 'A' && next <= 'Z') {
312 decodedChar = (char) (next + 32);
314 throw ReaderException("");
318 // $A to $Z map to control codes SH to SB
319 if (next >= 'A' && next <= 'Z') {
320 decodedChar = (char) (next - 64);
322 throw ReaderException("");
326 // %A to %E map to control codes ESC to US
327 if (next >= 'A' && next <= 'E') {
328 decodedChar = (char) (next - 38);
329 } else if (next >= 'F' && next <= 'W') {
330 decodedChar = (char) (next - 11);
332 throw ReaderException("");
336 // /A to /O map to ! to , and /Z maps to :
337 if (next >= 'A' && next <= 'O') {
338 decodedChar = (char) (next - 32);
339 } else if (next == 'Z') {
342 throw ReaderException("");
346 tmpDecoded.append(1, decodedChar);
347 // bump up i again since we read two characters
350 tmpDecoded.append(1, c);
353 Ref<String> decoded(new String(tmpDecoded));