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 bars.
36 * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
37 * 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;
53 * Creates a reader that assumes all encoded data is data, and does not treat the final
54 * character as a check digit. It will not decoded "extended Code 39" sequences.
56 Code39Reader::Code39Reader(){
57 ALPHABET_STRING = new std::string("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%");
58 usingCheckDigit = false;
63 * Creates a reader that can be configured to check the last character as a check digit.
64 * It will not decoded "extended Code 39" sequences.
66 * @param usingCheckDigit if true, treat the last data character as a check digit, not
67 * data, and verify that the checksum passes.
69 Code39Reader::Code39Reader(bool usingCheckDigit_){
70 ALPHABET_STRING = new std::string("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%");
71 usingCheckDigit = usingCheckDigit_;
77 Ref<Result> Code39Reader::decodeRow(int rowNumber, Ref<BitArray> row){
78 int* start = findAsteriskPattern(row);
79 int nextStart = start[1];
80 int end = row->getSize();
82 // Read off white space
83 while (nextStart < end && !row->get(nextStart)) {
87 std::string tmpResultString;
90 int* counters = new int[countersLen];
91 for (int i=0; i<countersLen; i++) {
97 recordPattern(row, nextStart, counters, countersLen);
98 int pattern = toNarrowWidePattern(counters, countersLen);
100 throw ReaderException("pattern < 0");
102 decodedChar = patternToChar(pattern);
103 tmpResultString.append(1, decodedChar);
104 lastStart = nextStart;
105 for (int i = 0; i < countersLen; i++) {
106 nextStart += counters[i];
108 // Read off white space
109 while (nextStart < end && !row->get(nextStart)) {
112 } while (decodedChar != '*');
113 tmpResultString.erase(tmpResultString.length()-1, 1);// remove asterisk
115 // Look for whitespace after pattern:
116 int lastPatternSize = 0;
117 for (int i = 0; i < countersLen; i++) {
118 lastPatternSize += counters[i];
120 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
121 // If 50% of last pattern size, following last pattern, is not whitespace, fail
122 // (but if it's whitespace to the very end of the image, that's OK)
123 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
124 throw ReaderException("too short end white space");
127 if (usingCheckDigit) {
128 int max = tmpResultString.length() - 1;
130 for (int i = 0; i < max; i++) {
131 total += ALPHABET_STRING->find_first_of(tmpResultString[i], 0);
133 if (total % 43 != ALPHABET_STRING->find_first_of(tmpResultString[max], 0)) {
134 throw ReaderException("");
136 tmpResultString.erase(max, 1);
142 Ref<String> resultString(new String(tmpResultString));
145 resultString = decodeExtended(tmpResultString);
148 if (tmpResultString.length() == 0) {
149 // Almost surely a false positive
150 throw ReaderException("");
153 float left = (float) (start[1] + start[0]) / 2.0f;
154 float right = (float) (nextStart + lastStart) / 2.0f;
156 std::vector< Ref<ResultPoint> > resultPoints(2);
157 Ref<OneDResultPoint> resultPoint1(new OneDResultPoint(left, (float) rowNumber));
158 Ref<OneDResultPoint> resultPoint2(new OneDResultPoint(right, (float) rowNumber));
159 resultPoints[0] = resultPoint1;
160 resultPoints[1] = resultPoint2;
162 ArrayRef<unsigned char> resultBytes(1);
166 Ref<Result> res(new Result(resultString, resultBytes, resultPoints, BarcodeFormat_CODE_39));
170 int* Code39Reader::findAsteriskPattern(Ref<BitArray> row){
171 int width = row->getSize();
173 while (rowOffset < width) {
174 if (row->get(rowOffset)) {
180 int counterPosition = 0;
182 int* counters = new int[countersLen];
183 for (int i=0; i<countersLen; i++) {
186 int patternStart = rowOffset;
187 bool isWhite = false;
188 int patternLength = countersLen;
190 for (int i = rowOffset; i < width; i++) {
191 bool pixel = row->get(i);
192 if (pixel ^ isWhite) {
193 counters[counterPosition]++;
195 if (counterPosition == patternLength - 1) {
196 if (toNarrowWidePattern(counters, countersLen) == ASTERISK_ENCODING) {
197 // Look for whitespace before start pattern, >= 50% of width of start pattern
198 if (row->isRange(fmaxl(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
199 int* resultValue = new int[2];
200 resultValue[0] = patternStart;
205 patternStart += counters[0] + counters[1];
206 for (int y = 2; y < patternLength; y++) {
207 counters[y - 2] = counters[y];
209 counters[patternLength - 2] = 0;
210 counters[patternLength - 1] = 0;
215 counters[counterPosition] = 1;
219 throw ReaderException("");
222 // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
223 // per image when using some of our blackbox images.
224 int Code39Reader::toNarrowWidePattern(int counters[], int countersLen){
225 int numCounters = countersLen;
226 int maxNarrowCounter = 0;
229 int minCounter = INT_MAX;
230 for (int i = 0; i < numCounters; i++) {
231 int counter = counters[i];
232 if (counter < minCounter && counter > maxNarrowCounter) {
233 minCounter = counter;
236 maxNarrowCounter = minCounter;
238 int totalWideCountersWidth = 0;
240 for (int i = 0; i < numCounters; i++) {
241 int counter = counters[i];
242 if (counters[i] > maxNarrowCounter) {
243 pattern |= 1 << (numCounters - 1 - i);
245 totalWideCountersWidth += counter;
248 if (wideCounters == 3) {
249 // Found 3 wide counters, but are they close enough in width?
250 // We can perform a cheap, conservative check to see if any individual
251 // counter is more than 1.5 times the average:
252 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
253 int counter = counters[i];
254 if (counters[i] > maxNarrowCounter) {
256 // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
257 if ((counter << 1) >= totalWideCountersWidth) {
264 } while (wideCounters > 3);
268 char Code39Reader::patternToChar(int pattern){
269 for (int i = 0; i < CHARACTER_ENCODINGS_LEN; i++) {
270 if (CHARACTER_ENCODINGS[i] == pattern) {
274 throw ReaderException("");
277 Ref<String> Code39Reader::decodeExtended(std::string encoded){
278 int length = encoded.length();
279 std::string tmpDecoded;
280 for (int i = 0; i < length; i++) {
282 if (c == '+' || c == '$' || c == '%' || c == '/') {
283 char next = encoded[i + 1];
284 char decodedChar = '\0';
287 // +A to +Z map to a to z
288 if (next >= 'A' && next <= 'Z') {
289 decodedChar = (char) (next + 32);
291 throw ReaderException("");
295 // $A to $Z map to control codes SH to SB
296 if (next >= 'A' && next <= 'Z') {
297 decodedChar = (char) (next - 64);
299 throw ReaderException("");
303 // %A to %E map to control codes ESC to US
304 if (next >= 'A' && next <= 'E') {
305 decodedChar = (char) (next - 38);
306 } else if (next >= 'F' && next <= 'W') {
307 decodedChar = (char) (next - 11);
309 throw ReaderException("");
313 // /A to /O map to ! to , and /Z maps to :
314 if (next >= 'A' && next <= 'O') {
315 decodedChar = (char) (next - 32);
316 } else if (next == 'Z') {
319 throw ReaderException("");
323 tmpDecoded.append(1, decodedChar);
324 // bump up i again since we read two characters
327 tmpDecoded.append(1, c);
330 Ref<String> decoded(new String(tmpDecoded));
335 Code39Reader::~Code39Reader(){
336 delete ALPHABET_STRING;