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_),
78 Code39Reader::Code39Reader(bool usingCheckDigit_, bool extendedMode_) :
79 alphabet_string(ALPHABET_STRING),
80 usingCheckDigit(usingCheckDigit_),
81 extendedMode(extendedMode_) {
84 Ref<Result> Code39Reader::decodeRow(int rowNumber, Ref<BitArray> row){
87 start = findAsteriskPattern(row);
88 int nextStart = start[1];
89 int end = row->getSize();
91 // Read off white space
92 while (nextStart < end && !row->get(nextStart)) {
96 std::string tmpResultString;
98 const int countersLen = 9;
99 int counters[countersLen];
100 for (int i = 0; i < countersLen; i++) {
106 recordPattern(row, nextStart, counters, countersLen);
107 int pattern = toNarrowWidePattern(counters, countersLen);
109 throw ReaderException("pattern < 0");
111 decodedChar = patternToChar(pattern);
112 tmpResultString.append(1, decodedChar);
113 lastStart = nextStart;
114 for (int i = 0; i < countersLen; i++) {
115 nextStart += counters[i];
117 // Read off white space
118 while (nextStart < end && !row->get(nextStart)) {
121 } while (decodedChar != '*');
122 tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk
124 // Look for whitespace after pattern:
125 int lastPatternSize = 0;
126 for (int i = 0; i < countersLen; i++) {
127 lastPatternSize += counters[i];
129 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
130 // If 50% of last pattern size, following last pattern, is not whitespace,
131 // fail (but if it's whitespace to the very end of the image, that's OK)
132 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
133 throw ReaderException("too short end white space");
136 if (usingCheckDigit) {
137 int max = tmpResultString.length() - 1;
138 unsigned int total = 0;
139 for (int i = 0; i < max; i++) {
140 total += alphabet_string.find_first_of(tmpResultString[i], 0);
142 if (total % 43 != alphabet_string.find_first_of(tmpResultString[max], 0)) {
143 throw ReaderException("");
145 tmpResultString.erase(max, 1);
148 Ref<String> resultString(new String(tmpResultString));
150 resultString = decodeExtended(tmpResultString);
153 if (tmpResultString.length() == 0) {
154 // Almost surely a false positive
155 throw ReaderException("");
158 float left = (float) (start[1] + start[0]) / 2.0f;
159 float right = (float) (nextStart + lastStart) / 2.0f;
161 std::vector< Ref<ResultPoint> > resultPoints(2);
162 Ref<OneDResultPoint> resultPoint1(
163 new OneDResultPoint(left, (float) rowNumber));
164 Ref<OneDResultPoint> resultPoint2(
165 new OneDResultPoint(right, (float) rowNumber));
166 resultPoints[0] = resultPoint1;
167 resultPoints[1] = resultPoint2;
169 ArrayRef<unsigned char> resultBytes(1);
171 Ref<Result> res(new Result(
172 resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
176 } catch (ReaderException const& re) {
182 int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
183 int width = row->getSize();
185 while (rowOffset < width) {
186 if (row->get(rowOffset)) {
192 int counterPosition = 0;
193 const int countersLen = 9;
194 int counters[countersLen];
195 for (int i = 0; i < countersLen; i++) {
198 int patternStart = rowOffset;
199 bool isWhite = false;
200 int patternLength = countersLen;
202 for (int i = rowOffset; i < width; i++) {
203 bool pixel = row->get(i);
204 if (pixel ^ isWhite) {
205 counters[counterPosition]++;
207 if (counterPosition == patternLength - 1) {
208 if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
209 // Look for whitespace before start pattern, >= 50% of width of
211 long double longPatternOffset =
212 fmaxl(0, patternStart - (i - patternStart) / 2);
213 if (row->isRange(longPatternOffset, patternStart, false)) {
214 int* resultValue = new int[2];
215 resultValue[0] = patternStart;
220 patternStart += counters[0] + counters[1];
221 for (int y = 2; y < patternLength; y++) {
222 counters[y - 2] = counters[y];
224 counters[patternLength - 2] = 0;
225 counters[patternLength - 1] = 0;
230 counters[counterPosition] = 1;
234 throw ReaderException("");
237 // For efficiency, returns -1 on failure. Not throwing here saved as many as
238 // 700 exceptions per image when using some of our blackbox images.
239 int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
240 int numCounters = countersLen;
241 int maxNarrowCounter = 0;
244 int minCounter = INT_MAX;
245 for (int i = 0; i < numCounters; i++) {
246 int counter = counters[i];
247 if (counter < minCounter && counter > maxNarrowCounter) {
248 minCounter = counter;
251 maxNarrowCounter = minCounter;
253 int totalWideCountersWidth = 0;
255 for (int i = 0; i < numCounters; i++) {
256 int counter = counters[i];
257 if (counters[i] > maxNarrowCounter) {
258 pattern |= 1 << (numCounters - 1 - i);
260 totalWideCountersWidth += counter;
263 if (wideCounters == 3) {
264 // Found 3 wide counters, but are they close enough in width?
265 // We can perform a cheap, conservative check to see if any individual
266 // counter is more than 1.5 times the average:
267 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
268 int counter = counters[i];
269 if (counters[i] > maxNarrowCounter) {
271 // totalWideCountersWidth = 3 * average, so this checks if
272 // counter >= 3/2 * average.
273 if ((counter << 1) >= totalWideCountersWidth) {
280 } while (wideCounters > 3);
284 char Code39Reader::patternToChar(int pattern){
285 for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
286 if (CHARACTER_ENCODINGS[i] == pattern) {
290 throw ReaderException("");
293 Ref<String> Code39Reader::decodeExtended(std::string encoded){
294 int length = encoded.length();
295 std::string tmpDecoded;
296 for (int i = 0; i < length; i++) {
298 if (c == '+' || c == '$' || c == '%' || c == '/') {
299 char next = encoded[i + 1];
300 char decodedChar = '\0';
303 // +A to +Z map to a to z
304 if (next >= 'A' && next <= 'Z') {
305 decodedChar = (char) (next + 32);
307 throw ReaderException("");
311 // $A to $Z map to control codes SH to SB
312 if (next >= 'A' && next <= 'Z') {
313 decodedChar = (char) (next - 64);
315 throw ReaderException("");
319 // %A to %E map to control codes ESC to US
320 if (next >= 'A' && next <= 'E') {
321 decodedChar = (char) (next - 38);
322 } else if (next >= 'F' && next <= 'W') {
323 decodedChar = (char) (next - 11);
325 throw ReaderException("");
329 // /A to /O map to ! to , and /Z maps to :
330 if (next >= 'A' && next <= 'O') {
331 decodedChar = (char) (next - 32);
332 } else if (next == 'Z') {
335 throw ReaderException("");
339 tmpDecoded.append(1, decodedChar);
340 // bump up i again since we read two characters
343 tmpDecoded.append(1, c);
346 Ref<String> decoded(new String(tmpDecoded));