text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitArray; namespace OneD::DataBar { std::string DecodeExpandedBits(const BitArray& bits); } // namespace OneD::DataBar } // namespace ZXing ```
/content/code_sandbox/core/src/oned/ODDataBarExpandedBitDecoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
52
```objective-c /* */ #pragma once #include "ODRowReader.h" namespace ZXing::OneD { /** * <p>Implements decoding of the DX Edge Film code format, a type or barcode found on 35mm films.</p> * * <p>See <a href="path_to_url">path_to_url */ class DXFilmEdgeReader : public RowReader { public: using RowReader::RowReader; Barcode decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>&) const override; }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODDXFilmEdgeReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
124
```objective-c /* */ #pragma once #include <array> namespace ZXing::OneD::Code128 { extern const std::array<std::array<int, 6>, 107> CODE_PATTERNS; } // namespace ZXing::OneD::Code128 ```
/content/code_sandbox/core/src/oned/ODCode128Patterns.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
53
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitMatrix; namespace OneD { /** * This object renders a CODE39 code as a {@link BitMatrix}. * * @author erik.barbara@gmail.com (Erik Barbara) */ class Code39Writer { public: Code39Writer& setMargin(int sidesMargin) { _sidesMargin = sidesMargin; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _sidesMargin = -1; }; } // OneD } // ZXing ```
/content/code_sandbox/core/src/oned/ODCode39Writer.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
147
```objective-c /* */ #pragma once #include "GTIN.h" #include <array> #include <cstddef> #include <stdexcept> #include <string> namespace ZXing::OneD::UPCEANCommon { using Digit = std::array<int, 4>; /** * Start/end guard pattern. */ extern const std::array<int, 3> START_END_PATTERN; /** * "Odd", or "L" patterns used to encode UPC/EAN digits. */ extern const std::array<Digit, 10> L_PATTERNS; /** * Pattern marking the middle of a UPC/EAN pattern, separating the two halves. */ extern const std::array<int, 5> MIDDLE_PATTERN; /** * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits. */ extern const std::array<Digit, 20> L_AND_G_PATTERNS; /** * UPCE end guard pattern (== MIDDLE_PATTERN + single module black bar) */ extern const std::array<int, 6> UPCE_END_PATTERN; /** * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of * even-odd parity encodings of digits that imply both the number system (0 or 1) * used (index / 10), and the check digit (index % 10). */ extern const std::array<int, 20> NUMSYS_AND_CHECK_DIGIT_PATTERNS; template <size_t N, typename T> std::array<int, N> DigitString2IntArray(const std::basic_string<T>& in, int checkDigit = -1) { static_assert(N == 8 || N == 13, "invalid UPC/EAN length"); if (in.size() != N && in.size() != N - 1) throw std::invalid_argument("Invalid input string length"); std::array<int, N> out = {}; for (size_t i = 0; i < in.size(); ++i) { out[i] = in[i] - '0'; if (out[i] < 0 || out[i] > 9) throw std::invalid_argument("Contents must contain only digits: 0-9"); } if (checkDigit == -1) checkDigit = GTIN::ComputeCheckDigit(in, N == in.size()); if (in.size() == N - 1) out.back() = checkDigit - '0'; else if (in.back() != checkDigit) throw std::invalid_argument("Checksum error"); return out; } /** * Expands a UPC-E value back into its full, equivalent UPC-A code value. * * @param upce UPC-E code as string of digits * @return equivalent UPC-A code as string of digits */ template <typename StringT> StringT ConvertUPCEtoUPCA(const StringT& upce) { if (upce.length() < 7) return upce; auto upceChars = upce.substr(1, 6); StringT result; result.reserve(12); result += upce[0]; auto lastChar = upceChars[5]; switch (lastChar) { case '0': case '1': case '2': result += upceChars.substr(0, 2); result += lastChar; result += StringT(4, '0'); result += upceChars.substr(2, 3); break; case '3': result += upceChars.substr(0, 3); result += StringT(5, '0'); result += upceChars.substr(3, 2); break; case '4': result += upceChars.substr(0, 4); result += StringT(5, '0'); ; result += upceChars[4]; break; default: result += upceChars.substr(0, 5); result += StringT(4, '0'); result += lastChar; break; } // Only append check digit in conversion if supplied if (upce.length() >= 8) { result += upce[7]; } return result; } } // namespace ZXing::OneD::UPCEANCommon ```
/content/code_sandbox/core/src/oned/ODUPCEANCommon.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
893
```c++ /* */ #include "ODUPCEWriter.h" #include "ODUPCEANCommon.h" #include "ODWriterHelper.h" #include "Utf.h" #include <stdexcept> #include <vector> namespace ZXing::OneD { static const int CODE_WIDTH = 3 + // start guard (7 * 6) + // bars 6; // end guard BitMatrix UPCEWriter::encode(const std::wstring& contents, int width, int height) const { auto digits = UPCEANCommon::DigitString2IntArray<8>( contents, GTIN::ComputeCheckDigit(UPCEANCommon::ConvertUPCEtoUPCA(contents), contents.size() == 8)); int firstDigit = digits[0]; if (firstDigit != 0 && firstDigit != 1) { throw std::invalid_argument("Number system must be 0 or 1"); } int parities = UPCEANCommon::NUMSYS_AND_CHECK_DIGIT_PATTERNS[firstDigit * 10 + digits[7]]; std::vector<bool> result(CODE_WIDTH, false); int pos = 0; pos += WriterHelper::AppendPattern(result, pos, UPCEANCommon::START_END_PATTERN, true); for (int i = 1; i <= 6; i++) { int digit = digits[i]; if ((parities >> (6 - i) & 1) == 1) { digit += 10; } pos += WriterHelper::AppendPattern(result, pos, UPCEANCommon::L_AND_G_PATTERNS[digit], false); } WriterHelper::AppendPattern(result, pos, UPCEANCommon::UPCE_END_PATTERN, false); return WriterHelper::RenderResult(result, width, height, _sidesMargin >= 0 ? _sidesMargin : 9); } BitMatrix UPCEWriter::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODUPCEWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
438
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitMatrix; namespace OneD { /** * This object renders a CODE128 code as a {@link BitMatrix}. * * @author erik.barbara@gmail.com (Erik Barbara) */ class Code128Writer { public: Code128Writer& setMargin(int sidesMargin) { _sidesMargin = sidesMargin; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _sidesMargin = -1; }; } // OneD } // ZXing ```
/content/code_sandbox/core/src/oned/ODCode128Writer.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
146
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitMatrix; namespace OneD { /** * This object renders a ITF code as a {@link BitMatrix}. * * @author erik.barbara@gmail.com (Erik Barbara) */ class ITFWriter { public: ITFWriter& setMargin(int sidesMargin) { _sidesMargin = sidesMargin; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _sidesMargin = -1; }; } // OneD } // ZXing ```
/content/code_sandbox/core/src/oned/ODITFWriter.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
147
```objective-c /* */ #pragma once #include "ODRowReader.h" namespace ZXing::OneD { /** * Decodes DataBarExpandedReader (formerly known as RSS) sybmols, including truncated and stacked variants. See ISO/IEC 24724:2006. */ class DataBarExpandedReader : public RowReader { public: using RowReader::RowReader; Barcode decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>& state) const override; }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODDataBarExpandedReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
114
```objective-c /* */ #pragma once #include "ODRowReader.h" namespace ZXing::OneD { /** * @brief A reader that can read all available UPC/EAN formats. */ class MultiUPCEANReader : public RowReader { public: using RowReader::RowReader; Barcode decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>&) const override; }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODMultiUPCEANReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
94
```objective-c /* */ #pragma once #include "ODRowReader.h" namespace ZXing::OneD { class Code93Reader : public RowReader { public: using RowReader::RowReader; Barcode decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>&) const override; }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODCode93Reader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
75
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitMatrix; namespace OneD { /** * This object renders a CODE93 code as a BitMatrix */ class Code93Writer { public: Code93Writer& setMargin(int sidesMargin) { _sidesMargin = sidesMargin; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _sidesMargin = -1; }; } // OneD } // ZXing ```
/content/code_sandbox/core/src/oned/ODCode93Writer.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
129
```c++ /* */ #include "ODCodabarWriter.h" #include "ODWriterHelper.h" #include "Utf.h" #include "ZXAlgorithms.h" #include <stdexcept> #include <vector> namespace ZXing::OneD { static constexpr wchar_t START_END_CHARS[] = L"ABCD"; static constexpr wchar_t ALT_START_END_CHARS[] = L"TN*E"; static constexpr wchar_t CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED[] = L"/:+."; static constexpr wchar_t DEFAULT_GUARD = START_END_CHARS[0]; static constexpr wchar_t ALPHABET[] = L"0123456789-$:/.+ABCD"; static constexpr int WIDE_TO_NARROW_BAR_RATIO = 2; //TODO: spec says 2.25 to 3 is the valid range. So this is technically illformed. /** * These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of * each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. */ static const int CHARACTER_ENCODINGS[] = { 0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9 0x00c, 0x018, 0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD }; static_assert(Size(ALPHABET) - 1 == Size(CHARACTER_ENCODINGS), "table size mismatch"); BitMatrix CodabarWriter::encode(const std::wstring& contents_, int width, int height) const { std::wstring contents = contents_; if (contents.empty()) { throw std::invalid_argument("Found empty contents"); } if (contents.length() < 2) { // Can't have a start/end guard, so tentatively add default guards contents = DEFAULT_GUARD + contents + DEFAULT_GUARD; } else { // Verify input and calculate decoded length. bool startsNormal = Contains(START_END_CHARS, contents.front()); bool endsNormal = Contains(START_END_CHARS, contents.back()); bool startsAlt = Contains(ALT_START_END_CHARS, contents.front()); bool endsAlt = Contains(ALT_START_END_CHARS, contents.back()); if (startsNormal) { if (!endsNormal) { throw std::invalid_argument("Invalid start/end guards"); } // else already has valid start/end } else if (startsAlt) { if (!endsAlt) { throw std::invalid_argument("Invalid start/end guards"); } // else already has valid start/end // map alt characters to normal once so they are found in the ALPHABET auto map_alt_guard_char = [](wchar_t& c) { switch (c) { case 'T': c = 'A'; break; case 'N': c = 'B'; break; case '*': c = 'C'; break; case 'E': c = 'D'; break; } }; map_alt_guard_char(contents.front()); map_alt_guard_char(contents.back()); } else { // Doesn't start with a guard if (endsNormal || endsAlt) { throw std::invalid_argument("Invalid start/end guards"); } // else doesn't end with guard either, so add a default contents = DEFAULT_GUARD + contents + DEFAULT_GUARD; } } // The start character and the end character are decoded to 10 length each. size_t resultLength = 20; for (size_t i = 1; i + 1 < contents.length(); ++i) { auto c = contents[i]; if ((c >= '0' && c <= '9') || c == '-' || c == '$') { resultLength += 9; } else if (Contains(CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED, c)) { resultLength += 10; } else { throw std::invalid_argument(std::string("Cannot encode : '") + static_cast<char>(c) + std::string("'")); } } // A blank is placed between each character. resultLength += contents.length() - 1; std::vector<bool> result(resultLength, false); auto position = result.begin(); for (wchar_t c : contents) { int code = CHARACTER_ENCODINGS[IndexOf(ALPHABET, c)]; // c is checked above to be in ALPHABET bool isBlack = true; int counter = 0; // count the width of the current bar int bit = 0; while (bit < 7) { // A character consists of 7 digit. *position++ = isBlack; ++counter; if (((code >> (6 - bit)) & 1) == 0 || counter == WIDE_TO_NARROW_BAR_RATIO) { // if current bar is short or we isBlack = !isBlack; // Flip the color. bit++; counter = 0; } } if (position != result.end()) { *position++ = false; // inter character whitespace } } return WriterHelper::RenderResult(result, width, height, _sidesMargin >= 0 ? _sidesMargin : 10); } BitMatrix CodabarWriter::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODCodabarWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,278
```objective-c /* */ #pragma once #include "BitMatrix.h" #include <cstddef> #include <vector> namespace ZXing::OneD { /** * <p>Encapsulates functionality and implementation that is common to one-dimensional barcodes.</p> * * @author dsbnatut@gmail.com (Kazuki Nishiura) */ class WriterHelper { static int AppendPattern(std::vector<bool>& target, int pos, const int* pattern, size_t patternCount, bool startColor); public: /** * @return a byte array of horizontal pixels (0 = white, 1 = black) */ static BitMatrix RenderResult(const std::vector<bool>& code, int width, int height, int sidesMargin); /** * @param target encode black/white pattern into this array * @param pos position to start encoding at in {@code target} * @param pattern lengths of black/white runs to encode * @param startColor starting color - false for white, true for black * @return the number of elements added to target. */ template <typename Container> static int AppendPattern(std::vector<bool>& target, int pos, const Container& pattern, bool startColor) { return AppendPattern(target, pos, pattern.data(), pattern.size(), startColor); } }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODWriterHelper.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
285
```c++ /* */ #include "ODMultiUPCEANReader.h" #include "BarcodeFormat.h" #include "BitArray.h" #include "ReaderOptions.h" #include "GTIN.h" #include "ODUPCEANCommon.h" #include "Barcode.h" #include <cmath> namespace ZXing::OneD { constexpr int CHAR_LEN = 4; constexpr auto END_PATTERN = FixedPattern<3, 3>{1, 1, 1}; constexpr auto MID_PATTERN = FixedPattern<5, 5>{1, 1, 1, 1, 1}; constexpr auto UPCE_END_PATTERN = FixedPattern<6, 6>{1, 1, 1, 1, 1, 1}; constexpr auto EXT_START_PATTERN = FixedPattern<3, 4>{1, 1, 2}; constexpr auto EXT_SEPARATOR_PATTERN = FixedPattern<2, 2>{1, 1}; static const int FIRST_DIGIT_ENCODINGS[] = {0x00, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A}; // The GS1 specification has the following to say about quiet zones // Type: EAN-13 | EAN-8 | UPC-A | UPC-E | EAN Add-on | UPC Add-on // QZ L: 11 | 7 | 9 | 9 | 7-12 | 9-12 // QZ R: 7 | 7 | 9 | 7 | 5 | 5 constexpr float QUIET_ZONE_LEFT = 6; constexpr float QUIET_ZONE_RIGHT_EAN = 3; // used to be 6, see #526 and #558 constexpr float QUIET_ZONE_RIGHT_UPC = 6; constexpr float QUIET_ZONE_ADDON = 3; // There is a single sample (ean13-1/12.png) that fails to decode with these (new) settings because // it has a right-side quiet zone of only about 4.5 modules, which is clearly out of spec. static bool DecodeDigit(const PatternView& view, std::string& txt, int* lgPattern = nullptr) { #if 1 // These two values are critical for determining how permissive the decoding will be. // We've arrived at these values through a lot of trial and error. Setting them any higher // lets false positives creep in quickly. static constexpr float MAX_AVG_VARIANCE = 0.48f; static constexpr float MAX_INDIVIDUAL_VARIANCE = 0.7f; int bestMatch = lgPattern ? RowReader::DecodeDigit(view, UPCEANCommon::L_AND_G_PATTERNS, MAX_AVG_VARIANCE, MAX_INDIVIDUAL_VARIANCE, false) : RowReader::DecodeDigit(view, UPCEANCommon::L_PATTERNS, MAX_AVG_VARIANCE, MAX_INDIVIDUAL_VARIANCE, false); if (bestMatch == -1) return false; txt += ToDigit(bestMatch % 10); if (lgPattern) AppendBit(*lgPattern, bestMatch >= 10); return true; #else constexpr int CHAR_SUM = 7; auto pattern = RowReader::OneToFourBitPattern<CHAR_LEN, CHAR_SUM>(view); // remove first and last bit pattern = (~pattern >> 1) & 0b11111; // clang-format off /* pattern now contains the central 5 bits of the L/G/R code * L/G-codes always start with 1 and end with 0, R-codes are simply * inverted L-codes. L-Code G-Code R-Code ___________________________________ 0 00110 10011 11001 1 01100 11001 10011 2 01001 01101 10110 3 11110 10000 00001 4 10001 01110 01110 5 11000 11100 00111 6 10111 00010 01000 7 11101 01000 00010 8 11011 00100 00100 9 00101 01011 11010 */ constexpr char I = 0xf0; // invalid pattern const char digit[] = {I, I, 0x16, I, 0x18, 0x09, 0x00, I, 0x17, 0x02, I, 0x19, 0x01, 0x12, 0x14, I, 0x13, 0x04, I, 0x10, I, I, I, 0x06, 0x05, 0x11, I, 0x08, 0x15, 0x07, 0x03, I}; // clang-format on char d = digit[pattern]; txt += ToDigit(d & 0xf); if (lgPattern) AppendBit(*lgPattern, (d >> 4) & 1); return d != I; #endif } static bool DecodeDigits(int digitCount, PatternView& next, std::string& txt, int* lgPattern = nullptr) { for (int j = 0; j < digitCount; ++j, next.skipSymbol()) if (!DecodeDigit(next, txt, lgPattern)) return false; return true; } struct PartialResult { std::string txt; PatternView end; BarcodeFormat format = BarcodeFormat::None; PartialResult() { txt.reserve(14); } bool isValid() const { return format != BarcodeFormat::None; } }; bool _ret_false_debug_helper() { return false; } #define CHECK(A) if(!(A)) return _ret_false_debug_helper(); static bool EAN13(PartialResult& res, PatternView begin) { auto mid = begin.subView(27, MID_PATTERN.size()); auto end = begin.subView(56, END_PATTERN.size()); CHECK(end.isValid() && IsRightGuard(end, END_PATTERN, QUIET_ZONE_RIGHT_EAN) && IsPattern(mid, MID_PATTERN)); auto next = begin.subView(END_PATTERN.size(), CHAR_LEN); res.txt = " "; // make space for lgPattern character int lgPattern = 0; CHECK(DecodeDigits(6, next, res.txt, &lgPattern)); next = next.subView(MID_PATTERN.size(), CHAR_LEN); CHECK(DecodeDigits(6, next, res.txt)); int i = IndexOf(FIRST_DIGIT_ENCODINGS, lgPattern); CHECK(i != -1); res.txt[0] = ToDigit(i); res.end = end; res.format = BarcodeFormat::EAN13; return true; } static bool PlausibleDigitModuleSize(PatternView begin, int start, int i, float moduleSizeRef) { float moduleSizeData = begin.subView(start + i * 4, 4).sum() / 7.f; return std::abs(moduleSizeData / moduleSizeRef - 1) < 0.2f; } static bool EAN8(PartialResult& res, PatternView begin) { auto mid = begin.subView(19, MID_PATTERN.size()); auto end = begin.subView(40, END_PATTERN.size()); CHECK(end.isValid() && IsRightGuard(end, END_PATTERN, QUIET_ZONE_RIGHT_EAN) && IsPattern(mid, MID_PATTERN)); // additional plausibility check for the module size: it has to be about the same for both // the guard patterns and the payload/data part. float moduleSizeGuard = (begin.sum() + mid.sum() + end.sum()) / 11.f; for (auto start : {3, 24}) for (int i = 0; i < 4; ++i) CHECK(PlausibleDigitModuleSize(begin, start, i, moduleSizeGuard)); auto next = begin.subView(END_PATTERN.size(), CHAR_LEN); res.txt.clear(); CHECK(DecodeDigits(4, next, res.txt)); next = next.subView(MID_PATTERN.size(), CHAR_LEN); CHECK(DecodeDigits(4, next, res.txt)); res.end = end; res.format = BarcodeFormat::EAN8; return true; } static bool UPCE(PartialResult& res, PatternView begin) { auto end = begin.subView(27, UPCE_END_PATTERN.size()); CHECK(end.isValid() && IsRightGuard(end, UPCE_END_PATTERN, QUIET_ZONE_RIGHT_UPC)); // additional plausibility check for the module size: it has to be about the same for both // the guard patterns and the payload/data part. This speeds up the falsepositives use case // about 2x and brings the misread count down to 0 float moduleSizeGuard = (begin.sum() + end.sum()) / 9.f; for (int i = 0; i < 6; ++i) CHECK(PlausibleDigitModuleSize(begin, 3, i, moduleSizeGuard)); auto next = begin.subView(END_PATTERN.size(), CHAR_LEN); int lgPattern = 0; res.txt = " "; // make space for lgPattern character CHECK(DecodeDigits(6, next, res.txt, &lgPattern)); int i = IndexOf(UPCEANCommon::NUMSYS_AND_CHECK_DIGIT_PATTERNS, lgPattern); CHECK(i != -1); res.txt[0] = ToDigit(i / 10); res.txt += ToDigit(i % 10); res.end = end; res.format = BarcodeFormat::UPCE; return true; } static int Ean5Checksum(const std::string& s) { int sum = 0, N = Size(s); for (int i = N - 2; i >= 0; i -= 2) sum += s[i] - '0'; sum *= 3; for (int i = N - 1; i >= 0; i -= 2) sum += s[i] - '0'; sum *= 3; return sum % 10; } static bool AddOn(PartialResult& res, PatternView begin, int digitCount) { auto ext = begin.subView(0, 3 + digitCount * 4 + (digitCount - 1) * 2); CHECK(ext.isValid()); auto moduleSize = IsPattern(ext, EXT_START_PATTERN); CHECK(moduleSize); CHECK(ext.isAtLastBar() || *ext.end() > QUIET_ZONE_ADDON * moduleSize - 1); res.end = ext; ext = ext.subView(EXT_START_PATTERN.size(), CHAR_LEN); int lgPattern = 0; res.txt.clear(); for (int i = 0; i < digitCount; ++i) { CHECK(DecodeDigit(ext, res.txt, &lgPattern)); ext.skipSymbol(); if (i < digitCount - 1) { CHECK(IsPattern(ext, EXT_SEPARATOR_PATTERN, 0, 0, moduleSize)); ext.skipPair(); } } if (digitCount == 2) { CHECK(std::stoi(res.txt) % 4 == lgPattern); } else { constexpr int CHECK_DIGIT_ENCODINGS[] = {0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05}; CHECK(Ean5Checksum(res.txt) == IndexOf(CHECK_DIGIT_ENCODINGS, lgPattern)); } res.format = BarcodeFormat::Any; // make sure res.format is valid, see below return true; } Barcode MultiUPCEANReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<RowReader::DecodingState>&) const { const int minSize = 3 + 6*4 + 6; // UPC-E next = FindLeftGuard(next, minSize, END_PATTERN, QUIET_ZONE_LEFT); if (!next.isValid()) return {}; PartialResult res; auto begin = next; if (!(((_opts.hasFormat(BarcodeFormat::EAN13 | BarcodeFormat::UPCA)) && EAN13(res, begin)) || (_opts.hasFormat(BarcodeFormat::EAN8) && EAN8(res, begin)) || (_opts.hasFormat(BarcodeFormat::UPCE) && UPCE(res, begin)))) return {}; Error error; if (!GTIN::IsCheckDigitValid(res.format == BarcodeFormat::UPCE ? UPCEANCommon::ConvertUPCEtoUPCA(res.txt) : res.txt)) error = ChecksumError(); // If UPC-A was a requested format and we detected a EAN-13 code with a leading '0', then we drop the '0' and call it // a UPC-A code. // TODO: this is questionable if (_opts.hasFormat(BarcodeFormat::UPCA) && res.format == BarcodeFormat::EAN13 && res.txt.front() == '0') { res.txt = res.txt.substr(1); res.format = BarcodeFormat::UPCA; } // if we explicitly requested UPCA but not EAN13, don't return an EAN13 symbol if (res.format == BarcodeFormat::EAN13 && ! _opts.hasFormat(BarcodeFormat::EAN13)) return {}; // Symbology identifier modifiers ISO/IEC 15420:2009 Annex B Table B.1 // ISO/IEC 15420:2009 (& GS1 General Specifications 5.1.3) states that the content for "]E0" should be 13 digits, // i.e. converted to EAN-13 if UPC-A/E, but not doing this here to maintain backward compatibility SymbologyIdentifier symbologyIdentifier = {'E', res.format == BarcodeFormat::EAN8 ? '4' : '0'}; next = res.end; auto ext = res.end; PartialResult addOnRes; if (_opts.eanAddOnSymbol() != EanAddOnSymbol::Ignore && ext.skipSymbol() && ext.skipSingle(static_cast<int>(begin.sum() * 3.5)) && (AddOn(addOnRes, ext, 5) || AddOn(addOnRes, ext, 2))) { // ISO/IEC 15420:2009 states that the content for "]E3" should be 15 or 18 digits, i.e. converted to EAN-13 // and extended with no separator, and that the content for "]E4" should be 8 digits, i.e. no add-on res.txt += " " + addOnRes.txt; next = addOnRes.end; if (res.format != BarcodeFormat::EAN8) // Keeping EAN-8 with add-on as "]E4" symbologyIdentifier.modifier = '3'; // Combined packet, EAN-13, UPC-A, UPC-E, with add-on } if (_opts.eanAddOnSymbol() == EanAddOnSymbol::Require && !addOnRes.isValid()) return {}; return Barcode(res.txt, rowNumber, begin.pixelsInFront(), next.pixelsTillEnd(), res.format, symbologyIdentifier, error); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODMultiUPCEANReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,366
```c++ /* */ #include "ODUPCAWriter.h" #include "BitMatrix.h" #include "ODEAN13Writer.h" #include "Utf.h" #include <stdexcept> namespace ZXing::OneD { BitMatrix UPCAWriter::encode(const std::wstring& contents, int width, int height) const { // Transform a UPC-A code into the equivalent EAN-13 code, and add a check digit if it is not already present. size_t length = contents.length(); if (length != 11 && length != 12) { throw std::invalid_argument("Requested contents should be 11 or 12 digits long"); } return EAN13Writer().setMargin(_sidesMargin).encode(L'0' + contents, width, height); } BitMatrix UPCAWriter::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODUPCAWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
205
```c++ /* */ #include "ODEAN13Writer.h" #include "ODUPCEANCommon.h" #include "ODWriterHelper.h" #include "Utf.h" #include <array> #include <vector> namespace ZXing::OneD { static const int FIRST_DIGIT_ENCODINGS[] = { 0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A }; static const int CODE_WIDTH = 3 + // start guard (7 * 6) + // left bars 5 + // middle guard (7 * 6) + // right bars 3; // end guard BitMatrix EAN13Writer::encode(const std::wstring& contents, int width, int height) const { auto digits = UPCEANCommon::DigitString2IntArray<13>(contents); int parities = FIRST_DIGIT_ENCODINGS[digits[0]]; std::vector<bool> result(CODE_WIDTH, false); int pos = 0; pos += WriterHelper::AppendPattern(result, pos, UPCEANCommon::START_END_PATTERN, true); // See {@link #EAN13Reader} for a description of how the first digit & left bars are encoded for (int i = 1; i <= 6; i++) { int digit = digits[i]; if ((parities >> (6 - i) & 1) == 1) { digit += 10; } pos += WriterHelper::AppendPattern(result, pos, UPCEANCommon::L_AND_G_PATTERNS[digit], false); } pos += WriterHelper::AppendPattern(result, pos, UPCEANCommon::MIDDLE_PATTERN, false); for (int i = 7; i <= 12; i++) { pos += WriterHelper::AppendPattern(result, pos, UPCEANCommon::L_PATTERNS[digits[i]], true); } WriterHelper::AppendPattern(result, pos, UPCEANCommon::START_END_PATTERN, true); return WriterHelper::RenderResult(result, width, height, _sidesMargin >= 0 ? _sidesMargin : 9); } BitMatrix EAN13Writer::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODEAN13Writer.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
532
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitMatrix; namespace OneD { /** * This object renders an EAN8 code as a {@link BitMatrix}. * * @author aripollak@gmail.com (Ari Pollak) */ class EAN13Writer { public: EAN13Writer& setMargin(int sidesMargin) { _sidesMargin = sidesMargin; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _sidesMargin = -1; }; } // OneD } // ZXing ```
/content/code_sandbox/core/src/oned/ODEAN13Writer.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
150
```objective-c /* */ #pragma once #include "ODRowReader.h" namespace ZXing::OneD { /** * <p>Implements decoding of the ITF format, or Interleaved Two of Five.</p> * * <p>This Reader will scan ITF barcodes of certain lengths only. * At the moment it reads length >= 6. Not all lengths are scanned, especially shorter ones, to avoid false positives. * This in turn is due to a lack of required checksum function.</p> * * <p>According to the specification, the modifier (3rd char) of the symbologyIdentifier is '1' iff the symbol has a valid checksum</p> * * <p><a href="path_to_url">path_to_url * is a great reference for Interleaved 2 of 5 information.</p> */ class ITFReader : public RowReader { public: using RowReader::RowReader; Barcode decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>&) const override; }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODITFReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
229
```c++ /* */ #include "ODITFReader.h" #include "ReaderOptions.h" #include "GTIN.h" #include "Barcode.h" #include "ZXAlgorithms.h" namespace ZXing::OneD { Barcode ITFReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>&) const { const int minCharCount = 6; const int minQuietZone = 6; // spec requires 10 next = FindLeftGuard(next, 4 + minCharCount/2 + 3, FixedPattern<4, 4>{1, 1, 1, 1}, minQuietZone); if (!next.isValid()) return {}; // get threshold of first character pair auto threshold = NarrowWideThreshold(next.subView(4, 10)); if (!threshold.isValid()) return {}; // check that each bar/space in the start pattern is < threshold for (int i = 0; i < 4; ++i) if (next[i] > threshold[i]) return {}; constexpr int weights[] = {1, 2, 4, 7, 0}; int xStart = next.pixelsInFront(); next = next.subView(4, 10); std::string txt; txt.reserve(20); while (next.isValid()) { threshold = NarrowWideThreshold(next); if (!threshold.isValid()) break; BarAndSpace<int> digits, numWide; for (int i = 0; i < 10; ++i) { if (next[i] > threshold[i] * 2) break; numWide[i] += next[i] > threshold[i]; digits[i] += weights[i/2] * (next[i] > threshold[i]); } if (numWide.bar != 2 || numWide.space != 2) break; for (int i = 0; i < 2; ++i) txt.push_back(ToDigit(digits[i] == 11 ? 0 : digits[i])); next.skipSymbol(); } next = next.subView(0, 3); if (Size(txt) < minCharCount || !next.isValid()) return {}; // Check quiet zone size if (!(next.isAtLastBar() || next[3] > minQuietZone * (threshold.bar + threshold.space) / 3)) return {}; // Check stop pattern if (next[0] < threshold[0] || next[1] > threshold[1] || next[2] > threshold[2]) return {}; Error error = _opts.validateITFCheckSum() && !GTIN::IsCheckDigitValid(txt) ? ChecksumError() : Error(); // Symbology identifier ISO/IEC 16390:2007 Annex C Table C.1 // See also GS1 General Specifications 5.1.2 Figure 5.1.2-2 SymbologyIdentifier symbologyIdentifier = {'I', GTIN::IsCheckDigitValid(txt) ? '1' : '0'}; int xStop = next.pixelsTillEnd(); return Barcode(txt, rowNumber, xStart, xStop, BarcodeFormat::ITF, symbologyIdentifier, error); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODITFReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
703
```c++ /* */ #include "ODCodabarReader.h" #include "ReaderOptions.h" #include "Barcode.h" #include "ZXAlgorithms.h" #include <string> #include <memory> namespace ZXing::OneD { static const char ALPHABET[] = "0123456789-$:/.+ABCD"; // These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of // each int correspond to the pattern of wide and narrow, with 1s representing wide and 0s representing narrow. static const int CHARACTER_ENCODINGS[] = { 0x03, 0x06, 0x09, 0x60, 0x12, 0x42, 0x21, 0x24, 0x30, 0x48, // 0-9 0x0c, 0x18, 0x45, 0x51, 0x54, 0x15, 0x1A, 0x29, 0x0B, 0x0E, // -$:/.+ABCD }; static_assert(Size(ALPHABET) - 1 == Size(CHARACTER_ENCODINGS), "table size mismatch"); // some industries use a checksum standard but this is not part of the original codabar standard // for more information see : path_to_url // each character has 4 bars and 3 spaces constexpr int CHAR_LEN = 7; // quiet zone is half the width of a character symbol constexpr float QUIET_ZONE_SCALE = 0.5f; // official start and stop symbols are "ABCD" // some codabar generator allow the codabar string to be closed by every // character. This will cause lots of false positives! bool IsLeftGuard(const PatternView& view, int spaceInPixel) { return spaceInPixel > view.sum() * QUIET_ZONE_SCALE && Contains({0x1A, 0x29, 0x0B, 0x0E}, RowReader::NarrowWideBitPattern(view)); } Barcode CodabarReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>&) const { // minimal number of characters that must be present (including start, stop and checksum characters) // absolute minimum would be 2 (meaning 0 'content'). everything below 4 produces too many false // positives. const int minCharCount = 4; auto isStartOrStopSymbol = [](char c) { return 'A' <= c && c <= 'D'; }; next = FindLeftGuard<CHAR_LEN>(next, minCharCount * CHAR_LEN, IsLeftGuard); if (!next.isValid()) return {}; int xStart = next.pixelsInFront(); int maxInterCharacterSpace = next.sum() / 2; // spec actually says 1 narrow space, width/2 is about 4 std::string txt; txt.reserve(20); txt += DecodeNarrowWidePattern(next, CHARACTER_ENCODINGS, ALPHABET); // read off the start pattern if (!isStartOrStopSymbol(txt.back())) return {}; do { // check remaining input width and inter-character space if (!next.skipSymbol() || !next.skipSingle(maxInterCharacterSpace)) return {}; txt += DecodeNarrowWidePattern(next, CHARACTER_ENCODINGS, ALPHABET); if (txt.back() == 0) return {}; } while (!isStartOrStopSymbol(txt.back())); // next now points to the last decoded symbol // check txt length and whitespace after the last char. See also FindStartPattern. if (Size(txt) < minCharCount || !next.hasQuietZoneAfter(QUIET_ZONE_SCALE)) return {}; // remove stop/start characters if (!_opts.returnCodabarStartEnd()) txt = txt.substr(1, txt.size() - 2); // symbology identifier ISO/IEC 15424:2008 4.4.9 // if checksum processing were implemented and checksum present and stripped then modifier would be 4 SymbologyIdentifier symbologyIdentifier = {'F', '0'}; int xStop = next.pixelsTillEnd(); return Barcode(txt, rowNumber, xStart, xStop, BarcodeFormat::Codabar, symbologyIdentifier); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODCodabarReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
937
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitMatrix; namespace OneD { /** * This object renders a UPC-A code as a {@link BitMatrix}. * * @author qwandor@google.com (Andrew Walbran) */ class UPCAWriter { public: UPCAWriter& setMargin(int sidesMargin) { _sidesMargin = sidesMargin; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _sidesMargin = -1; }; } // OneD } // ZXing ```
/content/code_sandbox/core/src/oned/ODUPCAWriter.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
147
```c++ /* */ #include "ODUPCEANCommon.h" namespace ZXing::OneD { const std::array<int, 3> UPCEANCommon::START_END_PATTERN = { 1, 1, 1 }; const std::array<int, 5> UPCEANCommon::MIDDLE_PATTERN = { 1, 1, 1, 1, 1 }; const std::array<int, 6> UPCEANCommon::UPCE_END_PATTERN = { 1, 1, 1, 1, 1, 1 }; const std::array<std::array<int, 4>, 10> UPCEANCommon::L_PATTERNS = { 3, 2, 1, 1, // 0 2, 2, 2, 1, // 1 2, 1, 2, 2, // 2 1, 4, 1, 1, // 3 1, 1, 3, 2, // 4 1, 2, 3, 1, // 5 1, 1, 1, 4, // 6 1, 3, 1, 2, // 7 1, 2, 1, 3, // 8 3, 1, 1, 2, // 9 }; const std::array<std::array<int, 4>, 20> UPCEANCommon::L_AND_G_PATTERNS = { 3, 2, 1, 1, // 0 2, 2, 2, 1, // 1 2, 1, 2, 2, // 2 1, 4, 1, 1, // 3 1, 1, 3, 2, // 4 1, 2, 3, 1, // 5 1, 1, 1, 4, // 6 1, 3, 1, 2, // 7 1, 2, 1, 3, // 8 3, 1, 1, 2, // 9 // reversed 1, 1, 2, 3, // 10 1, 2, 2, 2, // 11 2, 2, 1, 2, // 12 1, 1, 4, 1, // 13 2, 3, 1, 1, // 14 1, 3, 2, 1, // 15 4, 1, 1, 1, // 16 2, 1, 3, 1, // 17 3, 1, 2, 1, // 18 2, 1, 1, 3, // 19 }; // For an UPC-E barcode, the final digit is represented by the parities used // to encode the middle six digits, according to the table below. // // Parity of next 6 digits // Digit 0 1 2 3 4 5 // 0 Even Even Even Odd Odd Odd // 1 Even Even Odd Even Odd Odd // 2 Even Even Odd Odd Even Odd // 3 Even Even Odd Odd Odd Even // 4 Even Odd Even Even Odd Odd // 5 Even Odd Odd Even Even Odd // 6 Even Odd Odd Odd Even Even // 7 Even Odd Even Odd Even Odd // 8 Even Odd Even Odd Odd Even // 9 Even Odd Odd Even Odd Even // // The encoding is represented by the following array, which is a bit pattern // using Odd = 0 and Even = 1. For example, 5 is represented by: // // Odd Even Even Odd Odd Even // in binary: // 0 1 1 0 0 1 == 0x19 // const std::array<int, 20> UPCEANCommon::NUMSYS_AND_CHECK_DIGIT_PATTERNS = { 0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25, 0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A, }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODUPCEANCommon.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,107
```c++ /* */ #include "ODDataBarExpandedBitDecoder.h" #include "BitArray.h" #include "Error.h" #include "GTIN.h" namespace ZXing::OneD::DataBar { constexpr char GS = 29; // FNC1 static std::string DecodeGeneralPurposeBits(BitArrayView& bits) { enum State { NUMERIC, ALPHA, ISO_IEC_646 }; State state = NUMERIC; std::string res; auto decode5Bits = [](State& state, std::string& res, BitArrayView& bits) { int v = bits.readBits(5); if (v == 4) { state = state == ALPHA ? ISO_IEC_646 : ALPHA; } else if (v == 15) { // FNC1 + latch to Numeric res.push_back(GS); state = NUMERIC; // Allow for some generators incorrectly placing a numeric latch "000" after an FNC1 if (bits.size() >= 7 && bits.peakBits(7) < 8) bits.skipBits(3); } else { res.push_back(v + 43); } }; auto isPadding = [](State state, BitArrayView& bits) { bool res = (state == NUMERIC) ? bits.size() < 4 : bits.size() < 5 && (0b00100 >> (5 - bits.size()) == bits.peakBits(bits.size())); if (res) bits.skipBits(bits.size()); return res; }; while(bits.size() >= 3) { switch(state) { case NUMERIC: if (isPadding(state, bits)) break; if (bits.size() < 7) { int v = bits.readBits(4); if (v > 0) res.push_back(ToDigit(v - 1)); } else if (bits.peakBits(4) == 0) { bits.skipBits(4); state = ALPHA; } else { int v = bits.readBits(7); for (int digit : {(v - 8) / 11, (v - 8) % 11}) res.push_back(digit == 10 ? GS : ToDigit(digit)); } break; case ALPHA: if (isPadding(state, bits)) break; if (bits.peakBits(1) == 1) { constexpr char const* lut58to62 = R"(*,-./)"; int v = bits.readBits(6); if (v < 58) res.push_back(v + 33); else if (v < 63) res.push_back(lut58to62[v - 58]); else throw FormatError(); } else if (bits.peakBits(3) == 0) { bits.skipBits(3); state = NUMERIC; } else { decode5Bits(state, res, bits); } break; case ISO_IEC_646: if (isPadding(state, bits)) break; if (bits.peakBits(3) == 0) { bits.skipBits(3); state = NUMERIC; } else { int v = bits.peakBits(5); if (v < 16) { decode5Bits(state, res, bits); } else if (v < 29) { v = bits.readBits(7); res.push_back(v < 90 ? v + 1 : v + 7); } else { constexpr char const* lut232to252 = R"(!"%&'()*+,-./:;<=>?_ )"; v = bits.readBits(8); if (v < 232 || 252 < v) throw FormatError(); res.push_back(lut232to252[v - 232]); } } break; } } // in NUMERIC encodation there might be a trailing FNC1 that needs to be ignored if (res.size() && res.back() == GS) res.pop_back(); return res; } static std::string DecodeCompressedGTIN(std::string prefix, BitArrayView& bits) { for (int i = 0; i < 4; ++i) prefix.append(ToString(bits.readBits(10), 3)); prefix.push_back(GTIN::ComputeCheckDigit(prefix.substr(2))); return prefix; } static std::string DecodeAI01GTIN(BitArrayView& bits) { return DecodeCompressedGTIN("019", bits); } static std::string DecodeAI01AndOtherAIs(BitArrayView& bits) { bits.skipBits(2); // Variable length symbol bit field auto header = DecodeCompressedGTIN("01" + std::to_string(bits.readBits(4)), bits); auto trailer = DecodeGeneralPurposeBits(bits); return header + trailer; } static std::string DecodeAnyAI(BitArrayView& bits) { bits.skipBits(2); // Variable length symbol bit field return DecodeGeneralPurposeBits(bits); } static std::string DecodeAI013103(BitArrayView& bits) { std::string buffer = DecodeAI01GTIN(bits); buffer.append("3103"); buffer.append(ToString(bits.readBits(15), 6)); return buffer; } static std::string DecodeAI01320x(BitArrayView& bits) { std::string buffer = DecodeAI01GTIN(bits); int weight = bits.readBits(15); buffer.append(weight < 10000 ? "3202" : "3203"); buffer.append(ToString(weight < 10000 ? weight : weight - 10000, 6)); return buffer; } static std::string DecodeAI0139yx(BitArrayView& bits, char y) { bits.skipBits(2); // Variable length symbol bit field std::string buffer = DecodeAI01GTIN(bits); buffer.append("39"); buffer.push_back(y); buffer.append(std::to_string(bits.readBits(2))); if (y == '3') buffer.append(ToString(bits.readBits(10), 3)); auto trailer = DecodeGeneralPurposeBits(bits); if (trailer.empty()) return {}; return buffer + trailer; } static std::string DecodeAI013x0x1x(BitArrayView& bits, const char* aiPrefix, const char* dateCode) { std::string buffer = DecodeAI01GTIN(bits); buffer.append(aiPrefix); int weight = bits.readBits(20); buffer.append(std::to_string(weight / 100000)); buffer.append(ToString(weight % 100000, 6)); int date = bits.readBits(16); if (date != 38400) { buffer.append(dateCode); int day = date % 32; date /= 32; int month = date % 12 + 1; date /= 12; int year = date; buffer.append(ToString(year, 2)); buffer.append(ToString(month, 2)); buffer.append(ToString(day, 2)); } return buffer; } std::string DecodeExpandedBits(const BitArray& _bits) { auto bits = BitArrayView(_bits); bits.readBits(1); // skip linkage bit if (bits.peakBits(1) == 1) return DecodeAI01AndOtherAIs(bits.skipBits(1)); if (bits.peakBits(2) == 0) return DecodeAnyAI(bits.skipBits(2)); switch (bits.peakBits(4)) { case 4: return DecodeAI013103(bits.skipBits(4)); case 5: return DecodeAI01320x(bits.skipBits(4)); } switch (bits.peakBits(5)) { case 12: return DecodeAI0139yx(bits.skipBits(5), '2'); case 13: return DecodeAI0139yx(bits.skipBits(5), '3'); } switch (bits.readBits(7)) { case 56: return DecodeAI013x0x1x(bits, "310", "11"); case 57: return DecodeAI013x0x1x(bits, "320", "11"); case 58: return DecodeAI013x0x1x(bits, "310", "13"); case 59: return DecodeAI013x0x1x(bits, "320", "13"); case 60: return DecodeAI013x0x1x(bits, "310", "15"); case 61: return DecodeAI013x0x1x(bits, "320", "15"); case 62: return DecodeAI013x0x1x(bits, "310", "17"); case 63: return DecodeAI013x0x1x(bits, "320", "17"); } return {}; } } // namespace ZXing::OneD::DataBar ```
/content/code_sandbox/core/src/oned/ODDataBarExpandedBitDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,917
```objective-c /* */ #pragma once #include "ODRowReader.h" namespace ZXing::OneD { /** * Decodes DataBar (formerly known as RSS) sybmols, including truncated and stacked variants. See ISO/IEC 24724:2006. */ class DataBarReader : public RowReader { public: using RowReader::RowReader; Barcode decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>& state) const override; }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODDataBarReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
111
```c++ /* */ #include "ODReader.h" #include "BinaryBitmap.h" #include "ReaderOptions.h" #include "ODCodabarReader.h" #include "ODCode128Reader.h" #include "ODCode39Reader.h" #include "ODCode93Reader.h" #include "ODDataBarExpandedReader.h" #include "ODDataBarReader.h" #include "ODDXFilmEdgeReader.h" #include "ODITFReader.h" #include "ODMultiUPCEANReader.h" #include "Barcode.h" #include <algorithm> #include <utility> #ifdef PRINT_DEBUG #include "BitMatrix.h" #include "BitMatrixIO.h" #endif namespace ZXing { void IncrementLineCount(Barcode& r) { ++r._lineCount; } } // namespace ZXing namespace ZXing::OneD { Reader::Reader(const ReaderOptions& opts) : ZXing::Reader(opts) { _readers.reserve(8); auto formats = opts.formats().empty() ? BarcodeFormat::Any : opts.formats(); if (formats.testFlags(BarcodeFormat::EAN13 | BarcodeFormat::UPCA | BarcodeFormat::EAN8 | BarcodeFormat::UPCE)) _readers.emplace_back(new MultiUPCEANReader(opts)); if (formats.testFlag(BarcodeFormat::Code39)) _readers.emplace_back(new Code39Reader(opts)); if (formats.testFlag(BarcodeFormat::Code93)) _readers.emplace_back(new Code93Reader(opts)); if (formats.testFlag(BarcodeFormat::Code128)) _readers.emplace_back(new Code128Reader(opts)); if (formats.testFlag(BarcodeFormat::ITF)) _readers.emplace_back(new ITFReader(opts)); if (formats.testFlag(BarcodeFormat::Codabar)) _readers.emplace_back(new CodabarReader(opts)); if (formats.testFlags(BarcodeFormat::DataBar)) _readers.emplace_back(new DataBarReader(opts)); if (formats.testFlags(BarcodeFormat::DataBarExpanded)) _readers.emplace_back(new DataBarExpandedReader(opts)); if (formats.testFlag(BarcodeFormat::DXFilmEdge)) _readers.emplace_back(new DXFilmEdgeReader(opts)); } Reader::~Reader() = default; /** * We're going to examine rows from the middle outward, searching alternately above and below the * middle, and farther out each time. rowStep is the number of rows between each successive * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then * middle + rowStep, then middle - (2 * rowStep), etc. * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the * image if "trying harder". */ static Barcodes DoDecode(const std::vector<std::unique_ptr<RowReader>>& readers, const BinaryBitmap& image, bool tryHarder, bool rotate, bool isPure, int maxSymbols, int minLineCount, bool returnErrors) { Barcodes res; std::vector<std::unique_ptr<RowReader::DecodingState>> decodingState(readers.size()); int width = image.width(); int height = image.height(); if (rotate) std::swap(width, height); int middle = height / 2; // TODO: find a better heuristic/parameterization if maxSymbols != 1 int rowStep = std::max(1, height / ((tryHarder && !isPure) ? (maxSymbols == 1 ? 256 : 512) : 32)); int maxLines = tryHarder ? height : // Look at the whole image, not just the center 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image if (isPure) minLineCount = 1; else minLineCount = std::min(minLineCount, height); std::vector<int> checkRows; PatternRow bars; bars.reserve(128); // e.g. EAN-13 has 59 bars/spaces #ifdef PRINT_DEBUG BitMatrix dbg(width, height); #endif for (int i = 0; i < maxLines; i++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (i + 1) / 2; bool isAbove = (i & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); bool isCheckRow = false; if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // See if we have additional check rows (see below) to process if (checkRows.size()) { --i; rowNumber = checkRows.back(); checkRows.pop_back(); isCheckRow = true; if (rowNumber < 0 || rowNumber >= height) continue; } if (!image.getPatternRow(rowNumber, rotate ? 90 : 0, bars)) continue; #ifdef PRINT_DEBUG bool val = false; int x = 0; for (auto b : bars) { for(int j = 0; j < b; ++j) dbg.set(x++, rowNumber, val); val = !val; } #endif // While we have the image data in a PatternRow, it's fairly cheap to reverse it in place to // handle decoding upside down barcodes. // TODO: the DataBarExpanded (stacked) decoder depends on seeing each line from both directions. This // 'surprising' and inconsistent. It also requires the decoderState to be shared between normal and reversed // scans, which makes no sense in general because it would mix partial detection data from two codes of the same // type next to each other. See also path_to_url for (bool upsideDown : {false, true}) { // trying again? if (upsideDown) { // reverse the row and continue std::reverse(bars.begin(), bars.end()); } // Look for a barcode for (size_t r = 0; r < readers.size(); ++r) { // If this is a pure symbol, then checking a single non-empty line is sufficient for all but the stacked // DataBar codes. They are the only ones using the decodingState, which we can use as a flag here. if (isPure && i && !decodingState[r]) continue; PatternView next(bars); do { Barcode result = readers[r]->decodePattern(rowNumber, next, decodingState[r]); if (result.isValid() || (returnErrors && result.error())) { IncrementLineCount(result); if (upsideDown) { // update position (flip horizontally). auto points = result.position(); for (auto& p : points) { p = {width - p.x - 1, p.y}; } result.setPosition(std::move(points)); } if (rotate) { auto points = result.position(); for (auto& p : points) { p = {p.y, width - p.x - 1}; } result.setPosition(std::move(points)); } // check if we know this code already for (auto& other : res) { if (result == other) { // merge the position information auto dTop = maxAbsComponent(other.position().topLeft() - result.position().topLeft()); auto dBot = maxAbsComponent(other.position().bottomLeft() - result.position().topLeft()); auto points = other.position(); if (dTop < dBot || (dTop == dBot && rotate ^ (sumAbsComponent(points[0]) > sumAbsComponent(result.position()[0])))) { points[0] = result.position()[0]; points[1] = result.position()[1]; } else { points[2] = result.position()[2]; points[3] = result.position()[3]; } other.setPosition(points); IncrementLineCount(other); // clear the result, so we don't insert it again below result = Barcode(); break; } } if (result.format() != BarcodeFormat::None) { res.push_back(std::move(result)); // if we found a valid code we have not seen before but a minLineCount > 1, // add additional check rows above and below the current one if (!isCheckRow && minLineCount > 1 && rowStep > 1) { checkRows = {rowNumber - 1, rowNumber + 1}; if (rowStep > 2) checkRows.insert(checkRows.end(), {rowNumber - 2, rowNumber + 2}); } } if (maxSymbols && Reduce(res, 0, [&](int s, const Barcode& r) { return s + (r.lineCount() >= minLineCount); }) == maxSymbols) { goto out; } } // make sure we make progress and we start the next try on a bar next.shift(2 - (next.index() % 2)); next.extend(); } while (tryHarder && next.size()); } } } out: // remove all symbols with insufficient line count auto it = std::remove_if(res.begin(), res.end(), [&](auto&& r) { return r.lineCount() < minLineCount; }); res.erase(it, res.end()); // if symbols overlap, remove the one with a lower line count for (auto a = res.begin(); a != res.end(); ++a) for (auto b = std::next(a); b != res.end(); ++b) if (HaveIntersectingBoundingBoxes(a->position(), b->position())) *(a->lineCount() < b->lineCount() ? a : b) = Barcode(); //TODO: C++20 res.erase_if() it = std::remove_if(res.begin(), res.end(), [](auto&& r) { return r.format() == BarcodeFormat::None; }); res.erase(it, res.end()); #ifdef PRINT_DEBUG SaveAsPBM(dbg, rotate ? "od-log-r.pnm" : "od-log.pnm"); #endif return res; } Barcode Reader::decode(const BinaryBitmap& image) const { auto result = DoDecode(_readers, image, _opts.tryHarder(), false, _opts.isPure(), 1, _opts.minLineCount(), _opts.returnErrors()); if (result.empty() && _opts.tryRotate()) result = DoDecode(_readers, image, _opts.tryHarder(), true, _opts.isPure(), 1, _opts.minLineCount(), _opts.returnErrors()); return FirstOrDefault(std::move(result)); } Barcodes Reader::decode(const BinaryBitmap& image, int maxSymbols) const { auto resH = DoDecode(_readers, image, _opts.tryHarder(), false, _opts.isPure(), maxSymbols, _opts.minLineCount(), _opts.returnErrors()); if ((!maxSymbols || Size(resH) < maxSymbols) && _opts.tryRotate()) { auto resV = DoDecode(_readers, image, _opts.tryHarder(), true, _opts.isPure(), maxSymbols - Size(resH), _opts.minLineCount(), _opts.returnErrors()); resH.insert(resH.end(), resV.begin(), resV.end()); } return resH; } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,581
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitMatrix; namespace OneD { /** * This object renders an UPC-E code as a {@link BitMatrix}. * * @author 0979097955s@gmail.com (RX) */ class UPCEWriter { public: UPCEWriter& setMargin(int sidesMargin) { _sidesMargin = sidesMargin; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _sidesMargin = -1; }; } // OneD } // ZXing ```
/content/code_sandbox/core/src/oned/ODUPCEWriter.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
146
```c++ /* */ #include "ODITFWriter.h" #include "ODWriterHelper.h" #include "Utf.h" #include <array> #include <stdexcept> #include <vector> namespace ZXing::OneD { static const std::array<int, 4> START_PATTERN = { 1, 1, 1, 1 }; static const std::array<int, 3> END_PATTERN = { 3, 1, 1 }; static const int W = 3; // Pixel width of a wide line static const int N = 1; // Pixed width of a narrow line /** * Patterns of Wide / Narrow lines to indicate each digit */ static const std::array<std::array<int, 5>, 10> PATTERNS = { N, N, W, W, N, // 0 W, N, N, N, W, // 1 N, W, N, N, W, // 2 W, W, N, N, N, // 3 N, N, W, N, W, // 4 W, N, W, N, N, // 5 N, W, W, N, N, // 6 N, N, N, W, W, // 7 W, N, N, W, N, // 8 N, W, N, W, N, // 9 }; BitMatrix ITFWriter::encode(const std::wstring& contents, int width, int height) const { size_t length = contents.length(); if (length == 0) { throw std::invalid_argument("Found empty contents"); } if (length % 2 != 0) { throw std::invalid_argument("The length of the input should be even"); } if (length > 80) { throw std::invalid_argument("Requested contents should be less than 80 digits long"); } std::vector<bool> result(9 + 9 * length, false); int pos = WriterHelper::AppendPattern(result, 0, START_PATTERN, true); for (size_t i = 0; i < length; i += 2) { int one = contents[i] - '0'; int two = contents[i + 1] - '0'; if (one < 0 || one > 9 || two < 0 || two > 9) { throw std::invalid_argument("Contents should contain only digits: 0-9"); } std::array<int, 10> encoding = {}; for (int j = 0; j < 5; j++) { encoding[2 * j] = PATTERNS[one][j]; encoding[2 * j + 1] = PATTERNS[two][j]; } pos += WriterHelper::AppendPattern(result, pos, encoding, true); } WriterHelper::AppendPattern(result, pos, END_PATTERN, true); return WriterHelper::RenderResult(result, width, height, _sidesMargin >= 0 ? _sidesMargin : 10); } BitMatrix ITFWriter::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODITFWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
709
```c++ /* */ #include "ODDXFilmEdgeReader.h" #include "Barcode.h" #include <optional> #include <vector> namespace ZXing::OneD { namespace { // Detection is made from center outward. // We ensure the clock track is decoded before the data track to avoid false positives. // They are two version of a DX Edge codes : with and without frame number. // The clock track is longer if the DX code contains the frame number (more recent version) constexpr int CLOCK_LENGTH_FN = 31; constexpr int CLOCK_LENGTH_NO_FN = 23; // data track length, without the start and stop patterns constexpr int DATA_LENGTH_FN = 23; constexpr int DATA_LENGTH_NO_FN = 15; constexpr auto CLOCK_PATTERN_FN = FixedPattern<25, CLOCK_LENGTH_FN>{5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3}; constexpr auto CLOCK_PATTERN_NO_FN = FixedPattern<17, CLOCK_LENGTH_NO_FN>{5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3}; constexpr auto DATA_START_PATTERN = FixedPattern<5, 5>{1, 1, 1, 1, 1}; constexpr auto DATA_STOP_PATTERN = FixedPattern<3, 3>{1, 1, 1}; template <int N, int SUM> bool IsPattern(PatternView& view, const FixedPattern<N, SUM>& pattern, float minQuietZone) { view = view.subView(0, N); return view.isValid() && IsPattern(view, pattern, view.isAtFirstBar() ? std::numeric_limits<int>::max() : view[-1], minQuietZone); } bool DistIsBelowThreshold(PointI a, PointI b, PointI threshold) { return std::abs(a.x - b.x) < threshold.x && std::abs(a.y - b.y) < threshold.y; } // DX Film Edge clock track found on 35mm films. struct Clock { bool hasFrameNr = false; // Clock track (thus data track) with frame number (longer version) int rowNumber = 0; int xStart = 0; // Beginning of the clock track on the X-axis, in pixels int xStop = 0; // End of the clock track on the X-axis, in pixels int dataLength() const { return hasFrameNr ? DATA_LENGTH_FN : DATA_LENGTH_NO_FN; } float moduleSize() const { return float(xStop - xStart) / (hasFrameNr ? CLOCK_LENGTH_FN : CLOCK_LENGTH_NO_FN); } bool isCloseTo(PointI p, int x) const { return DistIsBelowThreshold(p, {x, rowNumber}, PointI(moduleSize() * PointF{0.5, 4})); } bool isCloseToStart(int x, int y) const { return isCloseTo({x, y}, xStart); } bool isCloseToStop(int x, int y) const { return isCloseTo({x, y}, xStop); } }; struct DXFEState : public RowReader::DecodingState { int centerRow = 0; std::vector<Clock> clocks; // see if we a clock that starts near {x, y} Clock* findClock(int x, int y) { auto i = FindIf(clocks, [start = PointI{x, y}](auto& v) { return v.isCloseToStart(start.x, start.y); }); return i != clocks.end() ? &(*i) : nullptr; } // add/update clock void addClock(const Clock& clock) { if (Clock* i = findClock(clock.xStart, clock.rowNumber)) *i = clock; else clocks.push_back(clock); } }; std::optional<Clock> CheckForClock(int rowNumber, PatternView& view) { Clock clock; if (IsPattern(view, CLOCK_PATTERN_FN, 0.5)) // On FN versions, the decimal number can be really close to the clock clock.hasFrameNr = true; else if (IsPattern(view, CLOCK_PATTERN_NO_FN, 2.0)) clock.hasFrameNr = false; else return {}; clock.rowNumber = rowNumber; clock.xStart = view.pixelsInFront(); clock.xStop = view.pixelsTillEnd(); return clock; } } // namespace Barcode DXFilmEdgeReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>& state) const { if (!state) { state.reset(new DXFEState); static_cast<DXFEState*>(state.get())->centerRow = rowNumber; } auto dxState = static_cast<DXFEState*>(state.get()); // Only consider rows below the center row of the image if (!_opts.tryRotate() && rowNumber < dxState->centerRow) return {}; // Look for a pattern that is part of both the clock as well as the data track (ommitting the first bar) constexpr auto Is4x1 = [](const PatternView& view, int spaceInPixel) { // find min/max of 4 consecutive bars/spaces and make sure they are close together auto [m, M] = std::minmax({view[1], view[2], view[3], view[4]}); return M <= m * 4 / 3 + 1 && spaceInPixel > m / 2; }; // 12 is the minimum size of the data track (at least one product class bit + one parity bit) next = FindLeftGuard<4>(next, 10, Is4x1); if (!next.isValid()) return {}; // Check if the 4x1 pattern is part of a clock track if (auto clock = CheckForClock(rowNumber, next)) { dxState->addClock(*clock); next.skipSymbol(); return {}; } // Without at least one clock track, we stop here if (dxState->clocks.empty()) return {}; constexpr float minDataQuietZone = 0.5; if (!IsPattern(next, DATA_START_PATTERN, minDataQuietZone)) return {}; auto xStart = next.pixelsInFront(); // Only consider data tracks that are next to a clock track auto clock = dxState->findClock(xStart, rowNumber); if (!clock) return {}; // Skip the data start pattern (black, white, black, white, black) // The first signal bar is always white: this is the // separation between the start pattern and the product number next.skipSymbol(); // Read the data bits BitArray dataBits; while (next.isValid(1) && dataBits.size() < clock->dataLength()) { int modules = int(next[0] / clock->moduleSize() + 0.5); // even index means we are at a bar, otherwise at a space dataBits.appendBits(next.index() % 2 == 0 ? 0xFFFFFFFF : 0x0, modules); next.shift(1); } // Check the data track length if (dataBits.size() != clock->dataLength()) return {}; next = next.subView(0, DATA_STOP_PATTERN.size()); // Check there is the Stop pattern at the end of the data track if (!next.isValid() || !IsRightGuard(next, DATA_STOP_PATTERN, minDataQuietZone)) return {}; // The following bits are always white (=false), they are separators. if (dataBits.get(0) || dataBits.get(8) || (clock->hasFrameNr ? (dataBits.get(20) || dataBits.get(22)) : dataBits.get(14))) return {}; // Check the parity bit auto signalSum = Reduce(dataBits.begin(), dataBits.end() - 2, 0); auto parityBit = *(dataBits.end() - 2); if (signalSum % 2 != (int)parityBit) return {}; // Compute the DX 1 number (product number) auto productNumber = ToInt(dataBits, 1, 7); if (!productNumber) return {}; // Compute the DX 2 number (generation number) auto generationNumber = ToInt(dataBits, 9, 4); // Generate the textual representation. // Eg: 115-10/11A means: DX1 = 115, DX2 = 10, Frame number = 11A std::string txt; txt.reserve(10); txt = std::to_string(productNumber) + "-" + std::to_string(generationNumber); if (clock->hasFrameNr) { auto frameNr = ToInt(dataBits, 13, 6); txt += "/" + std::to_string(frameNr); if (dataBits.get(19)) txt += "A"; } auto xStop = next.pixelsTillEnd(); // The found data track must end near the clock track if (!clock->isCloseToStop(xStop, rowNumber)) return {}; // Update the clock coordinates with the latest corresponding data track // This may improve signal detection for next row iterations clock->xStart = xStart; clock->xStop = xStop; return Barcode(txt, rowNumber, xStart, xStop, BarcodeFormat::DXFilmEdge, {}); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODDXFilmEdgeReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,080
```c++ /* */ #include "ODWriterHelper.h" #include "BitMatrix.h" #include <algorithm> namespace ZXing::OneD { /** * @return a byte array of horizontal pixels (0 = white, 1 = black) */ BitMatrix WriterHelper::RenderResult(const std::vector<bool>& code, int width, int height, int sidesMargin) { int inputWidth = Size(code); // Add quiet zone on both sides. int fullWidth = inputWidth + sidesMargin; int outputWidth = std::max(width, fullWidth); int outputHeight = std::max(1, height); int multiple = outputWidth / fullWidth; int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; BitMatrix result(outputWidth, outputHeight); for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (code[inputX]) { result.setRegion(outputX, 0, multiple, outputHeight); } } return result; } /** * @param target encode black/white pattern into this array * @param pos position to start encoding at in {@code target} * @param pattern lengths of black/white runs to encode * @param startColor starting color - false for white, true for black * @return the number of elements added to target. */ int WriterHelper::AppendPattern(std::vector<bool>& target, int pos, const int* pattern, size_t patternCount, bool startColor) { bool color = startColor; int numAdded = 0; for (size_t i = 0; i < patternCount; ++i) { int s = pattern[i]; for (int j = 0; j < s; j++) { target[pos++] = color; } numAdded += s; color = !color; // flip color after each segment } return numAdded; } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODWriterHelper.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
421
```c++ /* */ #include "ODCode128Patterns.h" namespace ZXing::OneD::Code128 { const std::array<std::array<int, 6>, 107> CODE_PATTERNS = { { { 2, 1, 2, 2, 2, 2 }, // 0 { 2, 2, 2, 1, 2, 2 }, { 2, 2, 2, 2, 2, 1 }, { 1, 2, 1, 2, 2, 3 }, { 1, 2, 1, 3, 2, 2 }, { 1, 3, 1, 2, 2, 2 }, // 5 { 1, 2, 2, 2, 1, 3 }, { 1, 2, 2, 3, 1, 2 }, { 1, 3, 2, 2, 1, 2 }, { 2, 2, 1, 2, 1, 3 }, { 2, 2, 1, 3, 1, 2 }, // 10 { 2, 3, 1, 2, 1, 2 }, { 1, 1, 2, 2, 3, 2 }, { 1, 2, 2, 1, 3, 2 }, { 1, 2, 2, 2, 3, 1 }, { 1, 1, 3, 2, 2, 2 }, // 15 { 1, 2, 3, 1, 2, 2 }, { 1, 2, 3, 2, 2, 1 }, { 2, 2, 3, 2, 1, 1 }, { 2, 2, 1, 1, 3, 2 }, { 2, 2, 1, 2, 3, 1 }, // 20 { 2, 1, 3, 2, 1, 2 }, { 2, 2, 3, 1, 1, 2 }, { 3, 1, 2, 1, 3, 1 }, { 3, 1, 1, 2, 2, 2 }, { 3, 2, 1, 1, 2, 2 }, // 25 { 3, 2, 1, 2, 2, 1 }, { 3, 1, 2, 2, 1, 2 }, { 3, 2, 2, 1, 1, 2 }, { 3, 2, 2, 2, 1, 1 }, { 2, 1, 2, 1, 2, 3 }, // 30 { 2, 1, 2, 3, 2, 1 }, { 2, 3, 2, 1, 2, 1 }, { 1, 1, 1, 3, 2, 3 }, { 1, 3, 1, 1, 2, 3 }, { 1, 3, 1, 3, 2, 1 }, // 35 { 1, 1, 2, 3, 1, 3 }, { 1, 3, 2, 1, 1, 3 }, { 1, 3, 2, 3, 1, 1 }, { 2, 1, 1, 3, 1, 3 }, { 2, 3, 1, 1, 1, 3 }, // 40 { 2, 3, 1, 3, 1, 1 }, { 1, 1, 2, 1, 3, 3 }, { 1, 1, 2, 3, 3, 1 }, { 1, 3, 2, 1, 3, 1 }, { 1, 1, 3, 1, 2, 3 }, // 45 { 1, 1, 3, 3, 2, 1 }, { 1, 3, 3, 1, 2, 1 }, { 3, 1, 3, 1, 2, 1 }, { 2, 1, 1, 3, 3, 1 }, { 2, 3, 1, 1, 3, 1 }, // 50 { 2, 1, 3, 1, 1, 3 }, { 2, 1, 3, 3, 1, 1 }, { 2, 1, 3, 1, 3, 1 }, { 3, 1, 1, 1, 2, 3 }, { 3, 1, 1, 3, 2, 1 }, // 55 { 3, 3, 1, 1, 2, 1 }, { 3, 1, 2, 1, 1, 3 }, { 3, 1, 2, 3, 1, 1 }, { 3, 3, 2, 1, 1, 1 }, { 3, 1, 4, 1, 1, 1 }, // 60 { 2, 2, 1, 4, 1, 1 }, { 4, 3, 1, 1, 1, 1 }, { 1, 1, 1, 2, 2, 4 }, { 1, 1, 1, 4, 2, 2 }, { 1, 2, 1, 1, 2, 4 }, // 65 { 1, 2, 1, 4, 2, 1 }, { 1, 4, 1, 1, 2, 2 }, { 1, 4, 1, 2, 2, 1 }, { 1, 1, 2, 2, 1, 4 }, { 1, 1, 2, 4, 1, 2 }, // 70 { 1, 2, 2, 1, 1, 4 }, { 1, 2, 2, 4, 1, 1 }, { 1, 4, 2, 1, 1, 2 }, { 1, 4, 2, 2, 1, 1 }, { 2, 4, 1, 2, 1, 1 }, // 75 { 2, 2, 1, 1, 1, 4 }, { 4, 1, 3, 1, 1, 1 }, { 2, 4, 1, 1, 1, 2 }, { 1, 3, 4, 1, 1, 1 }, { 1, 1, 1, 2, 4, 2 }, // 80 { 1, 2, 1, 1, 4, 2 }, { 1, 2, 1, 2, 4, 1 }, { 1, 1, 4, 2, 1, 2 }, { 1, 2, 4, 1, 1, 2 }, { 1, 2, 4, 2, 1, 1 }, // 85 { 4, 1, 1, 2, 1, 2 }, { 4, 2, 1, 1, 1, 2 }, { 4, 2, 1, 2, 1, 1 }, { 2, 1, 2, 1, 4, 1 }, { 2, 1, 4, 1, 2, 1 }, // 90 { 4, 1, 2, 1, 2, 1 }, { 1, 1, 1, 1, 4, 3 }, { 1, 1, 1, 3, 4, 1 }, { 1, 3, 1, 1, 4, 1 }, { 1, 1, 4, 1, 1, 3 }, // 95 { 1, 1, 4, 3, 1, 1 }, { 4, 1, 1, 1, 1, 3 }, { 4, 1, 1, 3, 1, 1 }, { 1, 1, 3, 1, 4, 1 }, { 1, 1, 4, 1, 3, 1 }, // 100 { 3, 1, 1, 1, 4, 1 }, { 4, 1, 1, 1, 3, 1 }, { 2, 1, 1, 4, 1, 2 }, { 2, 1, 1, 2, 1, 4 }, { 2, 1, 1, 2, 3, 2 }, // 105 { 2, 3, 3, 1, 1, 1 } // STOP_CODE followed by 2-wide termination bar } }; } // namespace ZXing::OneD::Code128 ```
/content/code_sandbox/core/src/oned/ODCode128Patterns.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,297
```c++ /* */ #include "ODCode39Writer.h" #include "CharacterSet.h" #include "ODWriterHelper.h" #include "TextEncoder.h" #include "Utf.h" #include "ZXAlgorithms.h" #include <array> #include <stdexcept> #include <vector> namespace ZXing::OneD { static const char ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; /** * These represent the encodings of characters, as patterns of wide and narrow bars. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow, * with 1s representing "wide" and 0s representing narrow. */ static const int CHARACTER_ENCODINGS[] = { 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* 0x0A8, 0x0A2, 0x08A, 0x02A // $-% }; static_assert(Size(ALPHABET) - 1 == Size(CHARACTER_ENCODINGS), "table size mismatch"); static const int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; static void ToIntArray(int a, std::array<int, 9>& toReturn) { for (int i = 0; i < 9; ++i) { toReturn[i] = (a & (1 << (8 - i))) == 0 ? 1 : 2; } } static std::string ToHexString(int c) { const char* digits = "0123456789abcdef"; std::string val(4, '0'); val[1] = 'x'; val[2] = digits[(c >> 4) & 0xf]; val[3] = digits[c & 0xf]; return val; } static std::string TryToConvertToExtendedMode(const std::wstring& contents) { size_t length = contents.length(); std::string extendedContent; extendedContent.reserve(length * 2); for (size_t i = 0; i < length; i++) { int character = contents[i]; switch (character) { case '\0': extendedContent.append("%U"); break; case ' ': case '-': case '.': extendedContent.push_back((char)character); break; case '@': extendedContent.append("%V"); break; case '`': extendedContent.append("%W"); break; default: if (character > 0 && character < 27) { extendedContent.push_back('$'); extendedContent.push_back((char)('A' + (character - 1))); } else if (character > 26 && character < ' ') { extendedContent.push_back('%'); extendedContent.push_back((char)('A' + (character - 27))); } else if ((character > ' ' && character < '-') || character == '/' || character == ':') { extendedContent.push_back('/'); extendedContent.push_back((char)('A' + (character - 33))); } else if (character > '/' && character < ':') { extendedContent.push_back((char)('0' + (character - 48))); } else if (character > ':' && character < '@') { extendedContent.push_back('%'); extendedContent.push_back((char)('F' + (character - 59))); } else if (character > '@' && character < '[') { extendedContent.push_back((char)('A' + (character - 65))); } else if (character > 'Z' && character < '`') { extendedContent.push_back('%'); extendedContent.push_back((char)('K' + (character - 91))); } else if (character > '`' && character < '{') { extendedContent.push_back('+'); extendedContent.push_back((char)('A' + (character - 97))); } else if (character > 'z' && character < 128) { extendedContent.push_back('%'); extendedContent.push_back((char)('P' + (character - 123))); } else { throw std::invalid_argument("Requested content contains a non-encodable character: '" + ToHexString(character) + "'"); } break; } } return extendedContent; } BitMatrix Code39Writer::encode(const std::wstring& contents, int width, int height) const { size_t length = contents.length(); if (length == 0) { throw std::invalid_argument("Found empty contents"); } if (length > 80) { throw std::invalid_argument("Requested contents should be less than 80 digits long"); } std::string extendedContent; for (size_t i = 0; i < length; i++) { int indexInString = IndexOf(ALPHABET, contents[i]); if (indexInString < 0) { extendedContent = TryToConvertToExtendedMode(contents); length = extendedContent.length(); if (length > 80) { throw std::invalid_argument("Requested contents should be less than 80 digits long, but got " + std::to_string(length) + " (extended full ASCII mode)"); } break; } } if (extendedContent.empty()) { extendedContent = TextEncoder::FromUnicode(contents, CharacterSet::ISO8859_1); } std::array<int, 9> widths = {}; size_t codeWidth = 24 + 1 + (13 * length); std::vector<bool> result(codeWidth, false); ToIntArray(ASTERISK_ENCODING, widths); int pos = WriterHelper::AppendPattern(result, 0, widths, true); std::array<int, 1> narrowWhite = { 1 }; pos += WriterHelper::AppendPattern(result, pos, narrowWhite, false); //append next character to byte matrix for (size_t i = 0; i < length; ++i) { int indexInString = IndexOf(ALPHABET, extendedContent[i]); ToIntArray(CHARACTER_ENCODINGS[indexInString], widths); pos += WriterHelper::AppendPattern(result, pos, widths, true); pos += WriterHelper::AppendPattern(result, pos, narrowWhite, false); } ToIntArray(ASTERISK_ENCODING, widths); WriterHelper::AppendPattern(result, pos, widths, true); return WriterHelper::RenderResult(result, width, height, _sidesMargin >= 0 ? _sidesMargin : 10); } BitMatrix Code39Writer::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODCode39Writer.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,680
```objective-c /* */ #pragma once #include "ODRowReader.h" namespace ZXing::OneD { class CodabarReader : public RowReader { public: using RowReader::RowReader; Barcode decodePattern(int rowNumber, PatternView& next, std::unique_ptr<DecodingState>& state) const override; }; } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODCodabarReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
76
```c++ /* */ #include "ODCode128Writer.h" #include "ODCode128Patterns.h" #include "ODWriterHelper.h" #include "Utf.h" #include <list> #include <numeric> #include <stdexcept> #include <vector> namespace ZXing::OneD { static const int CODE_START_A = 103; static const int CODE_START_B = 104; static const int CODE_START_C = 105; static const int CODE_CODE_A = 101; static const int CODE_CODE_B = 100; static const int CODE_CODE_C = 99; static const int CODE_STOP = 106; // Dummy characters used to specify control characters in input static const auto ESCAPE_FNC_1 = L'\u00f1'; static const auto ESCAPE_FNC_2 = L'\u00f2'; static const auto ESCAPE_FNC_3 = L'\u00f3'; static const auto ESCAPE_FNC_4 = L'\u00f4'; static const int CODE_FNC_1 = 102; // Code A, Code B, Code C static const int CODE_FNC_2 = 97; // Code A, Code B static const int CODE_FNC_3 = 96; // Code A, Code B static const int CODE_FNC_4_A = 101; // Code A static const int CODE_FNC_4_B = 100; // Code B // Results of minimal lookahead for code C enum class CType { UNCODABLE, ONE_DIGIT, TWO_DIGITS, FNC_1 }; static CType FindCType(const std::wstring& value, int start) { int last = Size(value); if (start >= last) { return CType::UNCODABLE; } wchar_t c = value[start]; if (c == ESCAPE_FNC_1) { return CType::FNC_1; } if (c < '0' || c > '9') { return CType::UNCODABLE; } if (start + 1 >= last) { return CType::ONE_DIGIT; } c = value[start + 1]; if (c < '0' || c > '9') { return CType::ONE_DIGIT; } return CType::TWO_DIGITS; } static int ChooseCode(const std::wstring& value, int start, int oldCode) { CType lookahead = FindCType(value, start); if (lookahead == CType::ONE_DIGIT) { if (oldCode == CODE_CODE_A) { return CODE_CODE_A; } return CODE_CODE_B; } if (lookahead == CType::UNCODABLE) { if (start < Size(value)) { int c = value[start]; if (c < ' ' || (oldCode == CODE_CODE_A && (c < '`' || (c >= ESCAPE_FNC_1 && c <= ESCAPE_FNC_4)))) { // can continue in code A, encodes ASCII 0 to 95 or FNC1 to FNC4 return CODE_CODE_A; } } return CODE_CODE_B; // no choice } if (oldCode == CODE_CODE_A && lookahead == CType::FNC_1) { return CODE_CODE_A; } if (oldCode == CODE_CODE_C) { // can continue in code C return CODE_CODE_C; } if (oldCode == CODE_CODE_B) { if (lookahead == CType::FNC_1) { return CODE_CODE_B; // can continue in code B } // Seen two consecutive digits, see what follows lookahead = FindCType(value, start + 2); if (lookahead == CType::UNCODABLE || lookahead == CType::ONE_DIGIT) { return CODE_CODE_B; // not worth switching now } if (lookahead == CType::FNC_1) { // two digits, then FNC_1... lookahead = FindCType(value, start + 3); if (lookahead == CType::TWO_DIGITS) { // then two more digits, switch return CODE_CODE_C; } else { return CODE_CODE_B; // otherwise not worth switching } } // At this point, there are at least 4 consecutive digits. // Look ahead to choose whether to switch now or on the next round. int index = start + 4; while ((lookahead = FindCType(value, index)) == CType::TWO_DIGITS) { index += 2; } if (lookahead == CType::ONE_DIGIT) { // odd number of digits, switch later return CODE_CODE_B; } return CODE_CODE_C; // even number of digits, switch now } // Here oldCode == 0, which means we are choosing the initial code if (lookahead == CType::FNC_1) { // ignore FNC_1 lookahead = FindCType(value, start + 1); } if (lookahead == CType::TWO_DIGITS) { // at least two digits, start in code C return CODE_CODE_C; } return CODE_CODE_B; } BitMatrix Code128Writer::encode(const std::wstring& contents, int width, int height) const { // Check length int length = Size(contents); if (length < 1 || length > 80) { throw std::invalid_argument("Contents length should be between 1 and 80 characters"); } // Check content for (int i = 0; i < length; ++i) { int c = contents[i]; switch (c) { case ESCAPE_FNC_1: case ESCAPE_FNC_2: case ESCAPE_FNC_3: case ESCAPE_FNC_4: break; default: if (c > 127) { // support for FNC4 isn't implemented, no full Latin-1 character set available at the moment throw std::invalid_argument("Bad character in input: " + ToUtf8(contents.substr(i, 1))); } } } std::list<std::array<int, 6>> patterns; // temporary storage for patterns int checkSum = 0; int checkWeight = 1; int codeSet = 0; // selected code (CODE_CODE_B or CODE_CODE_C) int position = 0; // position in contents while (position < length) { //Select code to use int newCodeSet = ChooseCode(contents, position, codeSet); //Get the pattern index int patternIndex; if (newCodeSet == codeSet) { // Encode the current character // First handle escapes switch (contents[position]) { case ESCAPE_FNC_1: patternIndex = CODE_FNC_1; break; case ESCAPE_FNC_2: patternIndex = CODE_FNC_2; break; case ESCAPE_FNC_3: patternIndex = CODE_FNC_3; break; case ESCAPE_FNC_4: patternIndex = (codeSet == CODE_CODE_A) ? CODE_FNC_4_A : CODE_FNC_4_B; break; default: // Then handle normal characters otherwise if (codeSet == CODE_CODE_A) { patternIndex = contents[position] - ' '; if (patternIndex < 0) { // everything below a space character comes behind the underscore in the code patterns table patternIndex += '`'; } } else if (codeSet == CODE_CODE_B) { patternIndex = contents[position] - ' '; } else { // CODE_CODE_C patternIndex = (contents[position] - '0') * 10 + (position + 1 < length ? contents[position + 1] - '0' : 0); position++; // Also incremented below } } position++; } else { // Should we change the current code? // Do we have a code set? if (codeSet == 0) { // No, we don't have a code set if (newCodeSet == CODE_CODE_A) { patternIndex = CODE_START_A; } else if (newCodeSet == CODE_CODE_B) { patternIndex = CODE_START_B; } else { // CODE_CODE_C patternIndex = CODE_START_C; } } else { // Yes, we have a code set patternIndex = newCodeSet; } codeSet = newCodeSet; } // Get the pattern patterns.push_back(Code128::CODE_PATTERNS[patternIndex]); // Compute checksum checkSum += patternIndex * checkWeight; if (position != 0) { checkWeight++; } } // Compute and append checksum checkSum %= 103; patterns.push_back(Code128::CODE_PATTERNS[checkSum]); // Append stop code patterns.push_back(Code128::CODE_PATTERNS[CODE_STOP]); // Compute code width int codeWidth = 2; // termination bar for (const auto& pattern : patterns) { codeWidth += Reduce(pattern); } // Compute result std::vector<bool> result(codeWidth, false); const auto op = [&result](auto pos, const auto& pattern){ return pos + WriterHelper::AppendPattern(result, pos, pattern, true);}; auto pos = std::accumulate(std::begin(patterns), std::end(patterns), int{}, op); // Append termination bar result[pos++] = true; result[pos++] = true; return WriterHelper::RenderResult(result, width, height, _sidesMargin >= 0 ? _sidesMargin : 10); } BitMatrix Code128Writer::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::OneD ```
/content/code_sandbox/core/src/oned/ODCode128Writer.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,221
```objective-c /* */ #pragma once #include "ODRowReader.h" #include "Pattern.h" #include "Barcode.h" #include <array> #include <cmath> namespace ZXing::OneD::DataBar { inline bool IsFinder(int a, int b, int c, int d, int e) { // a,b,c,d,e, g | sum(a..e) = 15 // ------------ // 1,1,2 // | | |,1,1, 1 // 3,8,9 // use only pairs of bar+space to limit effect of poor threshold: // b+c can be 10, 11 or 12 modules, d+e is always 2 int w = 2 * (b + c), n = d + e; // the offsets (5 and 2) are there to reduce quantization effects for small module sizes // TODO: review after switch to sub-pixel bar width calculation bool x = (w + 5 > 9 * n) && (w - 5 < 13 * n) && // (b < 5 + 9 * d) && // (c < 5 + 10 * e) && (a < 2 + 4 * e) && (4 * a > n); #if !defined(NDEBUG) && 0 printf("["); for (bool v : {w + 5 > 9 * n, w - 5 < 13 * n, // b < 5 + 9 * d, // c < 5 + 10 * e, a < 2 + 4 * e, 4 * a > n}) printf(" %d", v); printf("]"); fflush(stdout); #endif return x; }; inline PatternView Finder(const PatternView& view) { return view.subView(8, 5); } inline PatternView LeftChar(const PatternView& view) { return view.subView(0, 8); } inline PatternView RightChar(const PatternView& view) { return view.subView(13, 8); } inline float ModSizeFinder(const PatternView& view) { return Finder(view).sum() / 15.f; } inline bool IsGuard(int a, int b) { // printf(" (%d, %d)", a, b); return a > b * 3 / 4 - 2 && a < b * 5 / 4 + 2; } inline bool IsCharacter(const PatternView& view, int modules, float modSizeRef) { float err = std::abs(float(view.sum()) / modules / modSizeRef - 1); return err < 0.1f; } struct Character { int value = -1, checksum = 0; operator bool() const noexcept { return value != -1; } bool operator==(const Character& o) const noexcept { return value == o.value && checksum == o.checksum; } bool operator!=(const Character& o) const { return !(*this == o); } }; struct Pair { Character left, right; int finder = 0, xStart = -1, xStop = 1, y = -1, count = 1; operator bool() const noexcept { return finder != 0; } bool operator==(const Pair& o) const noexcept { return finder == o.finder && left == o.left && right == o.right; } bool operator!=(const Pair& o) const noexcept { return !(*this == o); } }; struct PairHash { std::size_t operator()(const Pair& p) const noexcept { return p.left.value ^ p.left.checksum ^ p.right.value ^ p.right.checksum ^ p.finder; } }; constexpr int FULL_PAIR_SIZE = 8 + 5 + 8; constexpr int HALF_PAIR_SIZE = 8 + 5 + 2; // half has to be followed by a guard pattern template<typename T> int ParseFinderPattern(const PatternView& view, bool reversed, T l2rPattern, T r2lPattern) { constexpr float MAX_AVG_VARIANCE = 0.2f; constexpr float MAX_INDIVIDUAL_VARIANCE = 0.45f; int i = 1 + RowReader::DecodeDigit(view, reversed ? r2lPattern : l2rPattern, MAX_AVG_VARIANCE, MAX_INDIVIDUAL_VARIANCE, true); return reversed ? -i : i; } using Array4I = std::array<int, 4>; bool ReadDataCharacterRaw(const PatternView& view, int numModules, bool reversed, Array4I& oddPattern, Array4I& evnPattern); int GetValue(const Array4I& widths, int maxWidth, bool noNarrow); Position EstimatePosition(const Pair& first, const Pair& last); int EstimateLineCount(const Pair& first, const Pair& last); } // namespace ZXing::OneD::DataBar ```
/content/code_sandbox/core/src/oned/ODDataBarCommon.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,068
```objective-c /* */ #pragma once #include <vector> namespace ZXing { class DecoderResult; namespace Pdf417 { DecoderResult Decode(const std::vector<int>& codewords); } // namespace Pdf417 } // namespace ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDecoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
47
```c++ /* */ #include "PDFModulusPoly.h" #include "PDFModulusGF.h" #include <algorithm> #include <stdexcept> namespace ZXing { namespace Pdf417 { ModulusPoly::ModulusPoly(const ModulusGF& field, const std::vector<int>& coefficients) : _field(&field) { size_t coefficientsLength = coefficients.size(); if (coefficientsLength > 1 && coefficients[0] == 0) { // Leading term must be non-zero for anything except the constant polynomial "0" size_t firstNonZero = 1; while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { firstNonZero++; } if (firstNonZero == coefficientsLength) { _coefficients.resize(1, 0); } else { _coefficients.resize(coefficientsLength - firstNonZero); std::copy(coefficients.begin() + firstNonZero, coefficients.end(), _coefficients.begin()); } } else { _coefficients = coefficients; } } /** * @return evaluation of this polynomial at a given point */ int ModulusPoly::evaluateAt(int a) const { if (a == 0) // return the x^0 coefficient return coefficient(0); if (a == 1) // return the sum of the coefficients return Reduce(_coefficients, 0, [this](auto res, auto coef) { return _field->add(res, coef); }); return std::accumulate(_coefficients.begin(), _coefficients.end(), 0, [this, a](auto res, auto coef) { return _field->add(_field->multiply(a, res), coef); }); } ModulusPoly ModulusPoly::add(const ModulusPoly& other) const { if (_field != other._field) { throw std::invalid_argument("ModulusPolys do not have same ModulusGF field"); } if (isZero()) { return other; } if (other.isZero()) { return *this; } auto smallerCoefficients = &_coefficients; auto largerCoefficients = &other._coefficients; if (smallerCoefficients->size() > largerCoefficients->size()) { std::swap(smallerCoefficients, largerCoefficients); } std::vector<int> sumDiff(largerCoefficients->size()); size_t lengthDiff = largerCoefficients->size() - smallerCoefficients->size(); // Copy high-order terms only found in higher-degree polynomial's coefficients std::copy_n(largerCoefficients->begin(), lengthDiff, sumDiff.begin()); for (size_t i = lengthDiff; i < largerCoefficients->size(); i++) { sumDiff[i] = _field->add((*smallerCoefficients)[i - lengthDiff], (*largerCoefficients)[i]); } return ModulusPoly(*_field, sumDiff); } ModulusPoly ModulusPoly::subtract(const ModulusPoly& other) const { if (_field != other._field) { throw std::invalid_argument("ModulusPolys do not have same ModulusGF field"); } if (other.isZero()) { return *this; } return add(other.negative()); } ModulusPoly ModulusPoly::multiply(const ModulusPoly& other) const { if (_field != other._field) { throw std::invalid_argument("ModulusPolys do not have same ModulusGF field"); } if (isZero() || other.isZero()) { return _field->zero(); } auto& aCoefficients = _coefficients; size_t aLength = aCoefficients.size(); auto& bCoefficients = other._coefficients; size_t bLength = bCoefficients.size(); std::vector<int> product(aLength + bLength - 1, 0); for (size_t i = 0; i < aLength; i++) { int aCoeff = aCoefficients[i]; for (size_t j = 0; j < bLength; j++) { product[i + j] = _field->add(product[i + j], _field->multiply(aCoeff, bCoefficients[j])); } } return ModulusPoly(*_field, product); } ModulusPoly ModulusPoly::negative() const { size_t size = _coefficients.size(); std::vector<int> negativeCoefficients(size); for (size_t i = 0; i < size; i++) { negativeCoefficients[i] = _field->subtract(0, _coefficients[i]); } return ModulusPoly(*_field, negativeCoefficients); } ModulusPoly ModulusPoly::multiply(int scalar) const { if (scalar == 0) { return _field->zero(); } if (scalar == 1) { return *this; } size_t size = _coefficients.size(); std::vector<int> product(size); for (size_t i = 0; i < size; i++) { product[i] = _field->multiply(_coefficients[i], scalar); } return ModulusPoly(*_field, product); } ModulusPoly ModulusPoly::multiplyByMonomial(int degree, int coefficient) const { if (degree < 0) { throw std::invalid_argument("degree < 0"); } if (coefficient == 0) { return _field->zero(); } size_t size = _coefficients.size(); std::vector<int> product(size + degree, 0); for (size_t i = 0; i < size; i++) { product[i] = _field->multiply(_coefficients[i], coefficient); } return ModulusPoly(*_field, product); } void ModulusPoly::divide(const ModulusPoly& other, ModulusPoly& quotient, ModulusPoly& remainder) const { if (_field != other._field) { throw std::invalid_argument("ModulusPolys do not have same ModulusGF field"); } if (other.isZero()) { throw std::invalid_argument("Divide by 0"); } quotient = _field->zero(); remainder = *this; int denominatorLeadingTerm = other.coefficient(other.degree()); int inverseDenominatorLeadingTerm = _field->inverse(denominatorLeadingTerm); while (remainder.degree() >= other.degree() && !remainder.isZero()) { int degreeDifference = remainder.degree() - other.degree(); int scale = _field->multiply(remainder.coefficient(remainder.degree()), inverseDenominatorLeadingTerm); ModulusPoly term = other.multiplyByMonomial(degreeDifference, scale); ModulusPoly iterationQuotient = _field->buildMonomial(degreeDifference, scale); quotient = quotient.add(iterationQuotient); remainder = remainder.subtract(term); } } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFModulusPoly.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,480
```c++ /* */ #include "PDFDetectionResultColumn.h" #include "PDFBarcodeMetadata.h" #include "PDFBarcodeValue.h" #include "ZXAlgorithms.h" #include <algorithm> #include <stdexcept> namespace ZXing { namespace Pdf417 { static const int MAX_NEARBY_DISTANCE = 5; static const int MIN_ROWS_IN_BARCODE = 3; static const int MAX_ROWS_IN_BARCODE = 90; DetectionResultColumn::DetectionResultColumn(const BoundingBox& boundingBox, RowIndicator rowIndicator) : _boundingBox(boundingBox), _rowIndicator(rowIndicator) { if (boundingBox.maxY() < boundingBox.minY()) { throw std::invalid_argument("Invalid bounding box"); } _codewords.resize(boundingBox.maxY() - boundingBox.minY() + 1); } Nullable<Codeword> DetectionResultColumn::codewordNearby(int imageRow) const { int index = imageRowToCodewordIndex(imageRow); if (_codewords[index] != nullptr) { return _codewords[index]; } for (int i = 1; i < MAX_NEARBY_DISTANCE; i++) { int nearImageRow = imageRowToCodewordIndex(imageRow) - i; if (nearImageRow >= 0) { if (_codewords[nearImageRow] != nullptr) { return _codewords[nearImageRow]; } } nearImageRow = imageRowToCodewordIndex(imageRow) + i; if (nearImageRow < Size(_codewords)) { if (_codewords[nearImageRow] != nullptr) { return _codewords[nearImageRow]; } } } return nullptr; } void DetectionResultColumn::setRowNumbers() { for (auto& codeword : allCodewords()) { if (codeword != nullptr) { codeword.value().setRowNumberAsRowIndicatorColumn(); } } } static void RemoveIncorrectCodewords(bool isLeft, std::vector<Nullable<Codeword>>& codewords, const BarcodeMetadata& barcodeMetadata) { // Remove codewords which do not match the metadata // TODO Maybe we should keep the incorrect codewords for the start and end positions? for (auto& item : codewords) { if (item == nullptr) { continue; } const auto& codeword = item.value(); int rowIndicatorValue = codeword.value() % 30; int codewordRowNumber = codeword.rowNumber(); if (codewordRowNumber > barcodeMetadata.rowCount()) { item = nullptr; continue; } if (!isLeft) { codewordRowNumber += 2; } switch (codewordRowNumber % 3) { case 0: if (rowIndicatorValue * 3 + 1 != barcodeMetadata.rowCountUpperPart()) { item = nullptr; } break; case 1: if (rowIndicatorValue / 3 != barcodeMetadata.errorCorrectionLevel() || rowIndicatorValue % 3 != barcodeMetadata.rowCountLowerPart()) { item = nullptr; } break; case 2: if (rowIndicatorValue + 1 != barcodeMetadata.columnCount()) { item = nullptr; } break; } } } // TODO implement properly // TODO maybe we should add missing codewords to store the correct row number to make // finding row numbers for other columns easier // use row height count to make detection of invalid row numbers more reliable void DetectionResultColumn::adjustCompleteIndicatorColumnRowNumbers(const BarcodeMetadata& barcodeMetadata) { if (!isRowIndicator()) { return; } auto& codewords = allCodewords(); setRowNumbers(); RemoveIncorrectCodewords(isLeftRowIndicator(), codewords, barcodeMetadata); const auto& bb = boundingBox(); auto top = isLeftRowIndicator() ? bb.topLeft() : bb.topRight(); auto bottom = isLeftRowIndicator() ? bb.bottomLeft() : bb.bottomRight(); int firstRow = imageRowToCodewordIndex((int)top.value().y()); int lastRow = imageRowToCodewordIndex((int)bottom.value().y()); // We need to be careful using the average row height. Barcode could be skewed so that we have smaller and // taller rows //float averageRowHeight = (lastRow - firstRow) / (float)barcodeMetadata.rowCount(); int barcodeRow = -1; int maxRowHeight = 1; int currentRowHeight = 0; int increment = 1; for (int codewordsRow = firstRow; codewordsRow < lastRow; codewordsRow++) { if (codewords[codewordsRow] == nullptr) { continue; } Codeword codeword = codewords[codewordsRow]; if (barcodeRow == -1 && codeword.rowNumber() == barcodeMetadata.rowCount() - 1) { increment = -1; barcodeRow = barcodeMetadata.rowCount(); } // float expectedRowNumber = (codewordsRow - firstRow) / averageRowHeight; // if (Math.abs(codeword.getRowNumber() - expectedRowNumber) > 2) { // SimpleLog.log(LEVEL.WARNING, // "Removing codeword, rowNumberSkew too high, codeword[" + codewordsRow + "]: Expected Row: " + // expectedRowNumber + ", RealRow: " + codeword.getRowNumber() + ", value: " + codeword.getValue()); // codewords[codewordsRow] = null; // } int rowDifference = codeword.rowNumber() - barcodeRow; if (rowDifference == 0) { currentRowHeight++; } else if (rowDifference == increment) { maxRowHeight = std::max(maxRowHeight, currentRowHeight); currentRowHeight = 1; barcodeRow = codeword.rowNumber(); } else if (rowDifference < 0 || codeword.rowNumber() >= barcodeMetadata.rowCount() || rowDifference > codewordsRow) { codewords[codewordsRow] = nullptr; } else { int checkedRows; if (maxRowHeight > 2) { checkedRows = (maxRowHeight - 2) * rowDifference; } else { checkedRows = rowDifference; } bool closePreviousCodewordFound = checkedRows >= codewordsRow; for (int i = 1; i <= checkedRows && !closePreviousCodewordFound; i++) { // there must be (height * rowDifference) number of codewords missing. For now we assume height = 1. // This should hopefully get rid of most problems already. closePreviousCodewordFound = codewords[codewordsRow - i] != nullptr; } if (closePreviousCodewordFound) { codewords[codewordsRow] = nullptr; } else { barcodeRow = codeword.rowNumber(); currentRowHeight = 1; } } } //return static_cast<int>(averageRowHeight + 0.5); } // TODO maybe we should add missing codewords to store the correct row number to make // finding row numbers for other columns easier // use row height count to make detection of invalid row numbers more reliable void DetectionResultColumn::adjustIncompleteIndicatorColumnRowNumbers(const BarcodeMetadata& barcodeMetadata) { if (!isRowIndicator()) { return; } const auto& bb = boundingBox(); auto top = isLeftRowIndicator() ? bb.topLeft() : bb.topRight(); auto bottom = isLeftRowIndicator() ? bb.bottomLeft() : bb.bottomRight(); int firstRow = imageRowToCodewordIndex((int)top.value().y()); int lastRow = imageRowToCodewordIndex((int)bottom.value().y()); //float averageRowHeight = (lastRow - firstRow) / (float)barcodeMetadata.rowCount(); auto& codewords = allCodewords(); int barcodeRow = -1; int maxRowHeight = 1; int currentRowHeight = 0; for (int codewordsRow = firstRow; codewordsRow < lastRow; codewordsRow++) { if (codewords[codewordsRow] == nullptr) { continue; } auto& item = codewords[codewordsRow]; auto& codeword = item.value(); codeword.setRowNumberAsRowIndicatorColumn(); int rowDifference = codeword.rowNumber() - barcodeRow; // TODO improve handling with case where first row indicator doesn't start with 0 if (rowDifference == 0) { currentRowHeight++; } else if (rowDifference == 1) { maxRowHeight = std::max(maxRowHeight, currentRowHeight); currentRowHeight = 1; barcodeRow = codeword.rowNumber(); } else if (codeword.rowNumber() >= barcodeMetadata.rowCount()) { item = nullptr; } else { barcodeRow = codeword.rowNumber(); currentRowHeight = 1; } } //return static_cast<int>(averageRowHeight + 0.5); } // This is example of bad design, a getter should not modify object's state bool DetectionResultColumn::getRowHeights(std::vector<int>& result) { BarcodeMetadata barcodeMetadata; if (!getBarcodeMetadata(barcodeMetadata)) { return false; } adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata); result.resize(barcodeMetadata.rowCount()); for (auto& item : allCodewords()) { if (item != nullptr) { size_t rowNumber = item.value().rowNumber(); if (rowNumber >= result.size()) { // We have more rows than the barcode metadata allows for, ignore them. continue; } result[rowNumber]++; } // else throw exception? } return true; } // This is example of bad design, a getter should not modify object's state bool DetectionResultColumn::getBarcodeMetadata(BarcodeMetadata& result) { if (!isRowIndicator()) { return false; } auto& codewords = allCodewords(); BarcodeValue barcodeColumnCount; BarcodeValue barcodeRowCountUpperPart; BarcodeValue barcodeRowCountLowerPart; BarcodeValue barcodeECLevel; for (auto& item : codewords) { if (item == nullptr) { continue; } auto& codeword = item.value(); codeword.setRowNumberAsRowIndicatorColumn(); int rowIndicatorValue = codeword.value() % 30; int codewordRowNumber = codeword.rowNumber(); if (!isLeftRowIndicator()) { codewordRowNumber += 2; } switch (codewordRowNumber % 3) { case 0: barcodeRowCountUpperPart.setValue(rowIndicatorValue * 3 + 1); break; case 1: barcodeECLevel.setValue(rowIndicatorValue / 3); barcodeRowCountLowerPart.setValue(rowIndicatorValue % 3); break; case 2: barcodeColumnCount.setValue(rowIndicatorValue + 1); break; } } // Maybe we should check if we have ambiguous values? auto cc = barcodeColumnCount.value(); auto rcu = barcodeRowCountUpperPart.value(); auto rcl = barcodeRowCountLowerPart.value(); auto ec = barcodeECLevel.value(); if (cc.empty() || rcu.empty() || rcl.empty() || ec.empty() || cc[0] < 1 || rcu[0] + rcl[0] < MIN_ROWS_IN_BARCODE || rcu[0] + rcl[0] > MAX_ROWS_IN_BARCODE) { return false; } result = { cc[0], rcu[0], rcl[0], ec[0] }; RemoveIncorrectCodewords(isLeftRowIndicator(), codewords, result); return true; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDetectionResultColumn.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,727
```objective-c /* */ #pragma once #include "PDFModulusPoly.h" #include "ZXConfig.h" #include <stdexcept> #include <vector> namespace ZXing { namespace Pdf417 { /** * <p>A field based on powers of a generator integer, modulo some modulus.< / p> * * @author Sean Owen * @see com.google.zxing.common.reedsolomon.GenericGF */ class ModulusGF { int _modulus; std::vector<short> _expTable; std::vector<short> _logTable; ModulusPoly _zero; ModulusPoly _one; // avoid using the '%' modulo operator => ReedSolomon computation is more than twice as fast // see also path_to_url static int fast_mod(int a, int d) { return a < d ? a : a - d; } public: ModulusGF(int modulus, int generator); const ModulusPoly& zero() const { return _zero; } const ModulusPoly& one() const { return _one; } ModulusPoly buildMonomial(int degree, int coefficient) const; int add(int a, int b) const { return fast_mod(a + b, _modulus); } int subtract(int a, int b) const { return fast_mod(_modulus + a - b, _modulus); } int exp(int a) const { return _expTable.at(a); } int log(int a) const { if (a == 0) { throw std::invalid_argument("a == 0"); } return _logTable[a]; } int inverse(int a) const { if (a == 0) { throw std::invalid_argument("a == 0"); } return _expTable[_modulus - _logTable[a] - 1]; } int multiply(int a, int b) const { if (a == 0 || b == 0) { return 0; } #ifdef ZX_REED_SOLOMON_USE_MORE_MEMORY_FOR_SPEED return _expTable[_logTable[a] + _logTable[b]]; #else return _expTable[fast_mod(_logTable[a] + _logTable[b], _modulus - 1)]; #endif } int size() const { return _modulus; } }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFModulusGF.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
512
```objective-c /* */ #pragma once #include "CustomData.h" #include <string> #include <vector> namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau */ class DecoderResultExtra : public CustomData { int _segmentIndex = -1; std::string _fileId; std::vector<int> _optionalData; bool _lastSegment = false; int _segmentCount = -1; std::string _sender; std::string _addressee; std::string _fileName; int64_t _fileSize = -1; int64_t _timestamp = -1; int _checksum = -1; public: int segmentIndex() const { return _segmentIndex; } // -1 if not set void setSegmentIndex(int segmentIndex) { _segmentIndex = segmentIndex; } std::string fileId() const { return _fileId; } void setFileId(const std::string& fileId) { _fileId = fileId; } const std::vector<int>& optionalData() const { return _optionalData; } void setOptionalData(const std::vector<int>& optionalData) { _optionalData = optionalData; } bool isLastSegment() const { return _lastSegment; } void setLastSegment(bool lastSegment) { _lastSegment = lastSegment; } int segmentCount() const { return _segmentCount; } void setSegmentCount(int segmentCount) { _segmentCount = segmentCount; } std::string sender() const { // UTF-8 return _sender; } void setSender(const std::string& sender) { _sender = sender; } std::string addressee() const { // UTF-8 return _addressee; } void setAddressee(const std::string& addressee) { _addressee = addressee; } std::string fileName() const { // UTF-8 return _fileName; } void setFileName(const std::string& fileName) { _fileName = fileName; } // -1 if not set int64_t fileSize() const { return _fileSize; } void setFileSize(int64_t fileSize) { _fileSize = fileSize; } // 16-bit CRC checksum using CCITT-16, -1 if not set int checksum() const { return _checksum; } void setChecksum(int checksum) { _checksum = checksum; } // Unix epock timestamp, elapsed seconds since 1970-01-01, -1 if not set int64_t timestamp() const { return _timestamp; } void setTimestamp(int64_t timestamp) { _timestamp = timestamp; } }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDecoderResultExtra.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
603
```objective-c /* */ #pragma once namespace ZXing { namespace Pdf417 { enum class Compaction { AUTO, TEXT, BYTE, NUMERIC }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFCompaction.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
42
```c++ /* */ #include "PDFBarcodeValue.h" #include <algorithm> namespace ZXing { namespace Pdf417 { /** * Add an occurrence of a value */ void BarcodeValue::setValue(int value) { _values[value] += 1; } /** * Determines the maximum occurrence of a set value and returns all values which were set with this occurrence. * @return an array of int, containing the values with the highest occurrence, or null, if no value was set */ std::vector<int> BarcodeValue::value() const { std::vector<int> result; if (!_values.empty()) { int maxConfidence = std::max_element(_values.begin(), _values.end(), [](auto& l, auto& r) { return l.second < r.second; })->second; for (auto [value, count] : _values) if (count == maxConfidence) result.push_back(value); } return result; } int BarcodeValue::confidence(int value) const { auto it = _values.find(value); return it != _values.end() ? it->second : 0; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFBarcodeValue.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
243
```c++ /* */ #include "PDFScanningDecoder.h" #include "BitMatrix.h" #include "DecoderResult.h" #include "PDFBarcodeMetadata.h" #include "PDFBarcodeValue.h" #include "PDFCodewordDecoder.h" #include "PDFDetectionResult.h" #include "PDFDecoder.h" #include "PDFModulusGF.h" #include "ZXAlgorithms.h" #include "ZXTestSupport.h" #include <cmath> namespace ZXing { namespace Pdf417 { static const int CODEWORD_SKEW_SIZE = 2; static const int MAX_ERRORS = 3; static const int MAX_EC_CODEWORDS = 512; using ModuleBitCountType = std::array<int, CodewordDecoder::BARS_IN_MODULE>; static int AdjustCodewordStartColumn(const BitMatrix& image, int minColumn, int maxColumn, bool leftToRight, int codewordStartColumn, int imageRow) { int correctedStartColumn = codewordStartColumn; int increment = leftToRight ? -1 : 1; // there should be no black pixels before the start column. If there are, then we need to start earlier. for (int i = 0; i < 2; i++) { while ((leftToRight ? correctedStartColumn >= minColumn : correctedStartColumn < maxColumn) && leftToRight == image.get(correctedStartColumn, imageRow)) { if (std::abs(codewordStartColumn - correctedStartColumn) > CODEWORD_SKEW_SIZE) { return codewordStartColumn; } correctedStartColumn += increment; } increment = -increment; leftToRight = !leftToRight; } return correctedStartColumn; } static bool GetModuleBitCount(const BitMatrix& image, int minColumn, int maxColumn, bool leftToRight, int startColumn, int imageRow, ModuleBitCountType& moduleBitCount) { int imageColumn = startColumn; size_t moduleNumber = 0; int increment = leftToRight ? 1 : -1; bool previousPixelValue = leftToRight; std::fill(moduleBitCount.begin(), moduleBitCount.end(), 0); while ((leftToRight ? (imageColumn < maxColumn) : (imageColumn >= minColumn)) && moduleNumber < moduleBitCount.size()) { if (image.get(imageColumn, imageRow) == previousPixelValue) { moduleBitCount[moduleNumber] += 1; imageColumn += increment; } else { moduleNumber += 1; previousPixelValue = !previousPixelValue; } } return moduleNumber == moduleBitCount.size() || (imageColumn == (leftToRight ? maxColumn : minColumn) && moduleNumber == moduleBitCount.size() - 1); } static bool CheckCodewordSkew(int codewordSize, int minCodewordWidth, int maxCodewordWidth) { return minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize && codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE; } static ModuleBitCountType GetBitCountForCodeword(int codeword) { ModuleBitCountType result; result.fill(0); int previousValue = 0; int i = Size(result) - 1; while (true) { if ((codeword & 0x1) != previousValue) { previousValue = codeword & 0x1; i--; if (i < 0) { break; } } result[i]++; codeword >>= 1; } return result; } static int GetCodewordBucketNumber(const ModuleBitCountType& moduleBitCount) { return (moduleBitCount[0] - moduleBitCount[2] + moduleBitCount[4] - moduleBitCount[6] + 9) % 9; } static int GetCodewordBucketNumber(int codeword) { return GetCodewordBucketNumber(GetBitCountForCodeword(codeword)); } static Nullable<Codeword> DetectCodeword(const BitMatrix& image, int minColumn, int maxColumn, bool leftToRight, int startColumn, int imageRow, int minCodewordWidth, int maxCodewordWidth) { startColumn = AdjustCodewordStartColumn(image, minColumn, maxColumn, leftToRight, startColumn, imageRow); // we usually know fairly exact now how long a codeword is. We should provide minimum and maximum expected length // and try to adjust the read pixels, e.g. remove single pixel errors or try to cut off exceeding pixels. // min and maxCodewordWidth should not be used as they are calculated for the whole barcode an can be inaccurate // for the current position ModuleBitCountType moduleBitCount; if (!GetModuleBitCount(image, minColumn, maxColumn, leftToRight, startColumn, imageRow, moduleBitCount)) { return nullptr; } int endColumn; int codewordBitCount = Reduce(moduleBitCount); if (leftToRight) { endColumn = startColumn + codewordBitCount; } else { std::reverse(moduleBitCount.begin(), moduleBitCount.end()); endColumn = startColumn; startColumn = endColumn - codewordBitCount; } // TODO implement check for width and correction of black and white bars // use start (and maybe stop pattern) to determine if blackbars are wider than white bars. If so, adjust. // should probably done only for codewords with a lot more than 17 bits. // The following fixes 10-1.png, which has wide black bars and small white bars // for (int i = 0; i < moduleBitCount.length; i++) { // if (i % 2 == 0) { // moduleBitCount[i]--; // } else { // moduleBitCount[i]++; // } // } // We could also use the width of surrounding codewords for more accurate results, but this seems // sufficient for now if (!CheckCodewordSkew(codewordBitCount, minCodewordWidth, maxCodewordWidth)) { // We could try to use the startX and endX position of the codeword in the same column in the previous row, // create the bit count from it and normalize it to 8. This would help with single pixel errors. return nullptr; } int decodedValue = CodewordDecoder::GetDecodedValue(moduleBitCount); if (decodedValue != -1) { int codeword = CodewordDecoder::GetCodeword(decodedValue); if (codeword != -1) { return Codeword(startColumn, endColumn, GetCodewordBucketNumber(decodedValue), codeword); } } return nullptr; } static DetectionResultColumn GetRowIndicatorColumn(const BitMatrix& image, const BoundingBox& boundingBox, const ResultPoint& startPoint, bool leftToRight, int minCodewordWidth, int maxCodewordWidth) { DetectionResultColumn rowIndicatorColumn(boundingBox, leftToRight ? DetectionResultColumn::RowIndicator::Left : DetectionResultColumn::RowIndicator::Right); for (int i = 0; i < 2; i++) { int increment = i == 0 ? 1 : -1; int startColumn = (int)startPoint.x(); for (int imageRow = (int)startPoint.y(); imageRow <= boundingBox.maxY() && imageRow >= boundingBox.minY(); imageRow += increment) { auto codeword = DetectCodeword(image, 0, image.width(), leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth); if (codeword != nullptr) { rowIndicatorColumn.setCodeword(imageRow, codeword); if (leftToRight) { startColumn = codeword.value().startX(); } else { startColumn = codeword.value().endX(); } } } } return rowIndicatorColumn; } static bool GetBarcodeMetadata(Nullable<DetectionResultColumn>& leftRowIndicatorColumn, Nullable<DetectionResultColumn>& rightRowIndicatorColumn, BarcodeMetadata& result) { BarcodeMetadata leftBarcodeMetadata; if (leftRowIndicatorColumn == nullptr || !leftRowIndicatorColumn.value().getBarcodeMetadata(leftBarcodeMetadata)) { return rightRowIndicatorColumn != nullptr && rightRowIndicatorColumn.value().getBarcodeMetadata(result); } BarcodeMetadata rightBarcodeMetadata; if (rightRowIndicatorColumn == nullptr || !rightRowIndicatorColumn.value().getBarcodeMetadata(rightBarcodeMetadata)) { result = leftBarcodeMetadata; return true; } if (leftBarcodeMetadata.columnCount() != rightBarcodeMetadata.columnCount() && leftBarcodeMetadata.errorCorrectionLevel() != rightBarcodeMetadata.errorCorrectionLevel() && leftBarcodeMetadata.rowCount() != rightBarcodeMetadata.rowCount()) { return false; } result = leftBarcodeMetadata; return true; } template <typename Iter> static auto GetMax(Iter start, Iter end) -> typename std::remove_reference<decltype(*start)>::type { auto it = std::max_element(start, end); return it != end ? *it : -1; } static bool AdjustBoundingBox(Nullable<DetectionResultColumn>& rowIndicatorColumn, Nullable<BoundingBox>& result) { if (rowIndicatorColumn == nullptr) { result = nullptr; return true; } std::vector<int> rowHeights; if (!rowIndicatorColumn.value().getRowHeights(rowHeights)) { result = nullptr; return true; } int maxRowHeight = GetMax(rowHeights.begin(), rowHeights.end()); int missingStartRows = 0; for (int rowHeight : rowHeights) { missingStartRows += maxRowHeight - rowHeight; if (rowHeight > 0) { break; } } auto& codewords = rowIndicatorColumn.value().allCodewords(); for (int row = 0; missingStartRows > 0 && codewords[row] == nullptr; row++) { missingStartRows--; } int missingEndRows = 0; for (int row = Size(rowHeights) - 1; row >= 0; row--) { missingEndRows += maxRowHeight - rowHeights[row]; if (rowHeights[row] > 0) { break; } } for (int row = Size(codewords) - 1; missingEndRows > 0 && codewords[row] == nullptr; row--) { missingEndRows--; } BoundingBox box; if (BoundingBox::AddMissingRows(rowIndicatorColumn.value().boundingBox(), missingStartRows, missingEndRows, rowIndicatorColumn.value().isLeftRowIndicator(), box)) { result = box; return true; } return false; } static bool Merge(Nullable<DetectionResultColumn>& leftRowIndicatorColumn, Nullable<DetectionResultColumn>& rightRowIndicatorColumn, DetectionResult& result) { if (leftRowIndicatorColumn != nullptr || rightRowIndicatorColumn != nullptr) { BarcodeMetadata barcodeMetadata; if (GetBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn, barcodeMetadata)) { Nullable<BoundingBox> leftBox, rightBox, mergedBox; if (AdjustBoundingBox(leftRowIndicatorColumn, leftBox) && AdjustBoundingBox(rightRowIndicatorColumn, rightBox) && BoundingBox::Merge(leftBox, rightBox, mergedBox)) { result.init(barcodeMetadata, mergedBox); return true; } } } return false; } static bool IsValidBarcodeColumn(const DetectionResult& detectionResult, int barcodeColumn) { return barcodeColumn >= 0 && barcodeColumn <= detectionResult.barcodeColumnCount() + 1; } static int GetStartColumn(const DetectionResult& detectionResult, int barcodeColumn, int imageRow, bool leftToRight) { int offset = leftToRight ? 1 : -1; Nullable<Codeword> codeword; if (IsValidBarcodeColumn(detectionResult, barcodeColumn - offset)) { codeword = detectionResult.column(barcodeColumn - offset).value().codeword(imageRow); } if (codeword != nullptr) { return leftToRight ? codeword.value().endX() : codeword.value().startX(); } codeword = detectionResult.column(barcodeColumn).value().codewordNearby(imageRow); if (codeword != nullptr) { return leftToRight ? codeword.value().startX() : codeword.value().endX(); } if (IsValidBarcodeColumn(detectionResult, barcodeColumn - offset)) { codeword = detectionResult.column(barcodeColumn - offset).value().codewordNearby(imageRow); } if (codeword != nullptr) { return leftToRight ? codeword.value().endX() : codeword.value().startX(); } int skippedColumns = 0; while (IsValidBarcodeColumn(detectionResult, barcodeColumn - offset)) { barcodeColumn -= offset; for (auto& previousRowCodeword : detectionResult.column(barcodeColumn).value().allCodewords()) { if (previousRowCodeword != nullptr) { return (leftToRight ? previousRowCodeword.value().endX() : previousRowCodeword.value().startX()) + offset * skippedColumns * (previousRowCodeword.value().endX() - previousRowCodeword.value().startX()); } } skippedColumns++; } return leftToRight ? detectionResult.getBoundingBox().value().minX() : detectionResult.getBoundingBox().value().maxX(); } static std::vector<std::vector<BarcodeValue>> CreateBarcodeMatrix(DetectionResult& detectionResult) { std::vector<std::vector<BarcodeValue>> barcodeMatrix(detectionResult.barcodeRowCount()); for (auto& row : barcodeMatrix) { row.resize(detectionResult.barcodeColumnCount() + 2); } int column = 0; for (auto& resultColumn : detectionResult.allColumns()) { if (resultColumn != nullptr) { for (auto& codeword : resultColumn.value().allCodewords()) { if (codeword != nullptr) { int rowNumber = codeword.value().rowNumber(); if (rowNumber >= 0) { if (rowNumber >= Size(barcodeMatrix)) { // We have more rows than the barcode metadata allows for, ignore them. continue; } barcodeMatrix[rowNumber][column].setValue(codeword.value().value()); } } } } column++; } return barcodeMatrix; } static int GetNumberOfECCodeWords(int barcodeECLevel) { return 2 << barcodeECLevel; } static bool AdjustCodewordCount(const DetectionResult& detectionResult, std::vector<std::vector<BarcodeValue>>& barcodeMatrix) { auto numberOfCodewords = barcodeMatrix[0][1].value(); int calculatedNumberOfCodewords = detectionResult.barcodeColumnCount() * detectionResult.barcodeRowCount() - GetNumberOfECCodeWords(detectionResult.barcodeECLevel()); if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > CodewordDecoder::MAX_CODEWORDS_IN_BARCODE) calculatedNumberOfCodewords = 0; if (numberOfCodewords.empty()) { if (!calculatedNumberOfCodewords) return false; barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords); } else if (calculatedNumberOfCodewords && numberOfCodewords[0] != calculatedNumberOfCodewords) { // The calculated one is more reliable as it is derived from the row indicator columns barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords); } return true; } // +++++++++++++++++++++++++++++++++++ Error Correction static const ModulusGF& GetModulusGF() { static const ModulusGF field(CodewordDecoder::NUMBER_OF_CODEWORDS, 3); return field; } static bool RunEuclideanAlgorithm(ModulusPoly a, ModulusPoly b, int R, ModulusPoly& sigma, ModulusPoly& omega) { const ModulusGF& field = GetModulusGF(); // Assume a's degree is >= b's if (a.degree() < b.degree()) { swap(a, b); } ModulusPoly rLast = a; ModulusPoly r = b; ModulusPoly tLast = field.zero(); ModulusPoly t = field.one(); // Run Euclidean algorithm until r's degree is less than R/2 while (r.degree() >= R / 2) { ModulusPoly rLastLast = rLast; ModulusPoly tLastLast = tLast; rLast = r; tLast = t; // Divide rLastLast by rLast, with quotient in q and remainder in r if (rLast.isZero()) { // Oops, Euclidean algorithm already terminated? return false; } r = rLastLast; ModulusPoly q = field.zero(); int denominatorLeadingTerm = rLast.coefficient(rLast.degree()); int dltInverse = field.inverse(denominatorLeadingTerm); while (r.degree() >= rLast.degree() && !r.isZero()) { int degreeDiff = r.degree() - rLast.degree(); int scale = field.multiply(r.coefficient(r.degree()), dltInverse); q = q.add(field.buildMonomial(degreeDiff, scale)); r = r.subtract(rLast.multiplyByMonomial(degreeDiff, scale)); } t = q.multiply(tLast).subtract(tLastLast).negative(); } int sigmaTildeAtZero = t.coefficient(0); if (sigmaTildeAtZero == 0) { return false; } int inverse = field.inverse(sigmaTildeAtZero); sigma = t.multiply(inverse); omega = r.multiply(inverse); return true; } static bool FindErrorLocations(const ModulusPoly& errorLocator, std::vector<int>& result) { const ModulusGF& field = GetModulusGF(); // This is a direct application of Chien's search int numErrors = errorLocator.degree(); result.resize(numErrors); int e = 0; for (int i = 1; i < field.size() && e < numErrors; i++) { if (errorLocator.evaluateAt(i) == 0) { result[e] = field.inverse(i); e++; } } return e == numErrors; } static std::vector<int> FindErrorMagnitudes(const ModulusPoly& errorEvaluator, const ModulusPoly& errorLocator, const std::vector<int>& errorLocations) { const ModulusGF& field = GetModulusGF(); int errorLocatorDegree = errorLocator.degree(); std::vector<int> formalDerivativeCoefficients(errorLocatorDegree); for (int i = 1; i <= errorLocatorDegree; i++) { formalDerivativeCoefficients[errorLocatorDegree - i] = field.multiply(i, errorLocator.coefficient(i)); } ModulusPoly formalDerivative(field, formalDerivativeCoefficients); // This is directly applying Forney's Formula std::vector<int> result(errorLocations.size()); for (size_t i = 0; i < result.size(); i++) { int xiInverse = field.inverse(errorLocations[i]); int numerator = field.subtract(0, errorEvaluator.evaluateAt(xiInverse)); int denominator = field.inverse(formalDerivative.evaluateAt(xiInverse)); result[i] = field.multiply(numerator, denominator); } return result; } /** * @param received received codewords * @param numECCodewords number of those codewords used for EC * @param erasures location of erasures * @return false if errors cannot be corrected, maybe because of too many errors */ ZXING_EXPORT_TEST_ONLY bool DecodeErrorCorrection(std::vector<int>& received, int numECCodewords, const std::vector<int>& erasures [[maybe_unused]], int& nbErrors) { const ModulusGF& field = GetModulusGF(); ModulusPoly poly(field, received); std::vector<int> S(numECCodewords); bool error = false; for (int i = numECCodewords; i > 0; i--) { int eval = poly.evaluateAt(field.exp(i)); S[numECCodewords - i] = eval; if (eval != 0) { error = true; } } if (!error) { nbErrors = 0; return true; } // ModulusPoly knownErrors = field.one(); // for (int erasure : erasures) { // int b = field.exp(Size(received) - 1 - erasure); // // Add (1 - bx) term: // ModulusPoly term(field, { field.subtract(0, b), 1 }); // knownErrors = knownErrors.multiply(term); // } ModulusPoly syndrome(field, S); // syndrome = syndrome.multiply(knownErrors); ModulusPoly sigma, omega; if (!RunEuclideanAlgorithm(field.buildMonomial(numECCodewords, 1), syndrome, numECCodewords, sigma, omega)) { return false; } // sigma = sigma.multiply(knownErrors); std::vector<int> errorLocations; if (!FindErrorLocations(sigma, errorLocations)) { return false; } std::vector<int> errorMagnitudes = FindErrorMagnitudes(omega, sigma, errorLocations); int receivedSize = Size(received); for (size_t i = 0; i < errorLocations.size(); i++) { int position = receivedSize - 1 - field.log(errorLocations[i]); if (position < 0) { return false; } received[position] = field.subtract(received[position], errorMagnitudes[i]); } nbErrors = Size(errorLocations); return true; } // --------------------------------------- Error Correction /** * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to * correct the errors in-place.</p> * * @param codewords data and error correction codewords * @param erasures positions of any known erasures * @param numECCodewords number of error correction codewords that are available in codewords * @return false if error correction fails */ static bool CorrectErrors(std::vector<int>& codewords, const std::vector<int>& erasures, int numECCodewords, int& errorCount) { if (Size(erasures) > numECCodewords / 2 + MAX_ERRORS || numECCodewords < 0 || numECCodewords > MAX_EC_CODEWORDS) { // Too many errors or EC Codewords is corrupted return false; } return DecodeErrorCorrection(codewords, numECCodewords, erasures, errorCount); } /** * Verify that all is OK with the codeword array. */ static bool VerifyCodewordCount(std::vector<int>& codewords, int numECCodewords) { if (codewords.size() < 4) { // Codeword array size should be at least 4 allowing for // Count CW, At least one Data CW, Error Correction CW, Error Correction CW return false; } // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad // codewords, but excluding the number of error correction codewords. int numberOfCodewords = codewords[0]; if (numberOfCodewords > Size(codewords)) { return false; } assert(numECCodewords >= 2); if (numberOfCodewords + numECCodewords != Size(codewords)) { // Reset to the length of the array less number of Error Codewords if (numECCodewords < Size(codewords)) { codewords[0] = Size(codewords) - numECCodewords; } else { return false; } } return true; } static DecoderResult DecodeCodewords(std::vector<int>& codewords, int numECCodewords, const std::vector<int>& erasures) { if (codewords.empty()) return FormatError(); int correctedErrorsCount = 0; if (!CorrectErrors(codewords, erasures, numECCodewords, correctedErrorsCount)) return ChecksumError(); if (!VerifyCodewordCount(codewords, numECCodewords)) return FormatError(); // Decode the codewords return Decode(codewords).setEcLevel(std::to_string(numECCodewords * 100 / Size(codewords)) + "%"); } DecoderResult DecodeCodewords(std::vector<int>& codewords, int numECCodeWords) { for (auto& cw : codewords) cw = std::clamp(cw, 0, CodewordDecoder::MAX_CODEWORDS_IN_BARCODE); // erasures array has never been actually used inside the error correction code return DecodeCodewords(codewords, numECCodeWords, {}); } /** * This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The * current error correction implementation doesn't deal with erasures very well, so it's better to provide a value * for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of * the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the * ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes, * so decoding the normal barcodes is not affected by this. * * @param erasureArray contains the indexes of erasures * @param ambiguousIndexes array with the indexes that have more than one most likely value * @param ambiguousIndexValues two dimensional array that contains the ambiguous values. The first dimension must * be the same length as the ambiguousIndexes array */ static DecoderResult CreateDecoderResultFromAmbiguousValues(int ecLevel, std::vector<int>& codewords, const std::vector<int>& erasureArray, const std::vector<int>& ambiguousIndexes, const std::vector<std::vector<int>>& ambiguousIndexValues) { std::vector<int> ambiguousIndexCount(ambiguousIndexes.size(), 0); int tries = 100; while (tries-- > 0) { for (size_t i = 0; i < ambiguousIndexCount.size(); i++) { codewords[ambiguousIndexes[i]] = ambiguousIndexValues[i][ambiguousIndexCount[i]]; } auto result = DecodeCodewords(codewords, NumECCodeWords(ecLevel), erasureArray); if (result.error() != Error::Checksum) { return result; } if (ambiguousIndexCount.empty()) { return ChecksumError(); } for (size_t i = 0; i < ambiguousIndexCount.size(); i++) { if (ambiguousIndexCount[i] < Size(ambiguousIndexValues[i]) - 1) { ambiguousIndexCount[i]++; break; } else { ambiguousIndexCount[i] = 0; if (i == ambiguousIndexCount.size() - 1) { return ChecksumError(); } } } } return ChecksumError(); } static DecoderResult CreateDecoderResult(DetectionResult& detectionResult) { auto barcodeMatrix = CreateBarcodeMatrix(detectionResult); if (!AdjustCodewordCount(detectionResult, barcodeMatrix)) { return {}; } std::vector<int> erasures; std::vector<int> codewords(detectionResult.barcodeRowCount() * detectionResult.barcodeColumnCount(), 0); std::vector<std::vector<int>> ambiguousIndexValues; std::vector<int> ambiguousIndexesList; for (int row = 0; row < detectionResult.barcodeRowCount(); row++) { for (int column = 0; column < detectionResult.barcodeColumnCount(); column++) { auto values = barcodeMatrix[row][column + 1].value(); int codewordIndex = row * detectionResult.barcodeColumnCount() + column; if (values.empty()) { erasures.push_back(codewordIndex); } else if (values.size() == 1) { codewords[codewordIndex] = values[0]; } else { ambiguousIndexesList.push_back(codewordIndex); ambiguousIndexValues.push_back(values); } } } return CreateDecoderResultFromAmbiguousValues(detectionResult.barcodeECLevel(), codewords, erasures, ambiguousIndexesList, ambiguousIndexValues); } // TODO don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern // columns. That way width can be deducted from the pattern column. // This approach also allows detecting more details about the barcode, e.g. if a bar type (white or black) is wider // than it should be. This can happen if the scanner used a bad blackpoint. DecoderResult ScanningDecoder::Decode(const BitMatrix& image, const Nullable<ResultPoint>& imageTopLeft, const Nullable<ResultPoint>& imageBottomLeft, const Nullable<ResultPoint>& imageTopRight, const Nullable<ResultPoint>& imageBottomRight, int minCodewordWidth, int maxCodewordWidth) { BoundingBox boundingBox; if (!BoundingBox::Create(image.width(), image.height(), imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight, boundingBox)) { return {}; } Nullable<DetectionResultColumn> leftRowIndicatorColumn, rightRowIndicatorColumn; DetectionResult detectionResult; for (int i = 0; i < 2; i++) { if (imageTopLeft != nullptr) { leftRowIndicatorColumn = GetRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth); } if (imageTopRight != nullptr) { rightRowIndicatorColumn = GetRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth); } if (!Merge(leftRowIndicatorColumn, rightRowIndicatorColumn, detectionResult)) { return {}; } if (i == 0 && detectionResult.getBoundingBox() != nullptr && (detectionResult.getBoundingBox().value().minY() < boundingBox.minY() || detectionResult.getBoundingBox().value().maxY() > boundingBox.maxY())) { boundingBox = detectionResult.getBoundingBox(); } else { detectionResult.setBoundingBox(boundingBox); break; } } int maxBarcodeColumn = detectionResult.barcodeColumnCount() + 1; detectionResult.setColumn(0, leftRowIndicatorColumn); detectionResult.setColumn(maxBarcodeColumn, rightRowIndicatorColumn); bool leftToRight = leftRowIndicatorColumn != nullptr; for (int barcodeColumnCount = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++) { int barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount; if (detectionResult.column(barcodeColumn) != nullptr) { // This will be the case for the opposite row indicator column, which doesn't need to be decoded again. continue; } DetectionResultColumn::RowIndicator rowIndicator = barcodeColumn == 0 ? DetectionResultColumn::RowIndicator::Left : (barcodeColumn == maxBarcodeColumn ? DetectionResultColumn::RowIndicator::Right : DetectionResultColumn::RowIndicator::None); detectionResult.setColumn(barcodeColumn, DetectionResultColumn(boundingBox, rowIndicator)); int startColumn = -1; int previousStartColumn = startColumn; // TODO start at a row for which we know the start position, then detect upwards and downwards from there. for (int imageRow = boundingBox.minY(); imageRow <= boundingBox.maxY(); imageRow++) { startColumn = GetStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight); if (startColumn < 0 || startColumn > boundingBox.maxX()) { if (previousStartColumn == -1) { continue; } startColumn = previousStartColumn; } Nullable<Codeword> codeword = DetectCodeword(image, boundingBox.minX(), boundingBox.maxX(), leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth); if (codeword != nullptr) { detectionResult.column(barcodeColumn).value().setCodeword(imageRow, codeword); previousStartColumn = startColumn; UpdateMinMax(minCodewordWidth, maxCodewordWidth, codeword.value().width()); } } } return CreateDecoderResult(detectionResult); } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFScanningDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
7,301
```objective-c /* */ #pragma once namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau */ class BarcodeMetadata { int _columnCount = 0; int _errorCorrectionLevel = 0; int _rowCountUpperPart = 0; int _rowCountLowerPart = 0; public: BarcodeMetadata() = default; BarcodeMetadata(int columnCount, int rowCountUpperPart, int rowCountLowerPart, int errorCorrectionLevel) : _columnCount(columnCount), _errorCorrectionLevel(errorCorrectionLevel), _rowCountUpperPart(rowCountUpperPart), _rowCountLowerPart(rowCountLowerPart) { } int columnCount() const { return _columnCount; } int errorCorrectionLevel() const { return _errorCorrectionLevel; } int rowCount() const { return _rowCountUpperPart + _rowCountLowerPart; } int rowCountUpperPart() const { return _rowCountUpperPart; } int rowCountLowerPart() const { return _rowCountLowerPart; } }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFBarcodeMetadata.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
227
```c++ /* */ #include "PDFHighLevelEncoder.h" #include "PDFCompaction.h" #include "CharacterSet.h" #include "ECI.h" #include "TextEncoder.h" #include "ZXBigInteger.h" #include "ZXAlgorithms.h" #include <cstdint> #include <algorithm> #include <string> #include <stdexcept> namespace ZXing { namespace Pdf417 { /** * code for Text compaction */ static const int TEXT_COMPACTION = 0; /** * code for Byte compaction */ static const int BYTE_COMPACTION = 1; /** * code for Numeric compaction */ static const int NUMERIC_COMPACTION = 2; /** * Text compaction submode Alpha */ static const int SUBMODE_ALPHA = 0; /** * Text compaction submode Lower */ static const int SUBMODE_LOWER = 1; /** * Text compaction submode Mixed */ static const int SUBMODE_MIXED = 2; /** * Text compaction submode Punctuation */ static const int SUBMODE_PUNCTUATION = 3; /** * mode latch to Text Compaction mode */ static const int LATCH_TO_TEXT = 900; /** * mode latch to Byte Compaction mode (number of characters NOT a multiple of 6) */ static const int LATCH_TO_BYTE_PADDED = 901; /** * mode latch to Numeric Compaction mode */ static const int LATCH_TO_NUMERIC = 902; /** * mode shift to Byte Compaction mode */ static const int SHIFT_TO_BYTE = 913; /** * mode latch to Byte Compaction mode (number of characters a multiple of 6) */ static const int LATCH_TO_BYTE = 924; /** * identifier for a user defined Extended Channel Interpretation (ECI) */ static const int ECI_USER_DEFINED = 925; /** * identifier for a general purpose ECO format */ static const int ECI_GENERAL_PURPOSE = 926; /** * identifier for an ECI of a character set of code page */ static const int ECI_CHARSET = 927; /** * Raw code table for text compaction Mixed sub-mode */ //static const uint8_t TEXT_MIXED_RAW[] = { // 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 38, 13, 9, 44, 58, // 35, 45, 46, 36, 47, 43, 37, 42, 61, 94, 0, 32, 0, 0, 0 }; /** * Raw code table for text compaction: Punctuation sub-mode */ //static const uint8_t TEXT_PUNCTUATION_RAW[] = { // 59, 60, 62, 64, 91, 92, 93, 95, 96, 126, 33, 13, 9, 44, 58, // 10, 45, 46, 36, 47, 34, 124, 42, 40, 41, 63, 123, 125, 39, 0 }; //static { // //Construct inverse lookups // Arrays.fill(MIXED, (byte)-1); // for (byte i = 0; i < TEXT_MIXED_RAW.length; i++) { // byte b = TEXT_MIXED_RAW[i]; // if (b > 0) { // MIXED[b] = i; // } // } // Arrays.fill(PUNCTUATION, (byte)-1); // for (byte i = 0; i < TEXT_PUNCTUATION_RAW.length; i++) { // byte b = TEXT_PUNCTUATION_RAW[i]; // if (b > 0) { // PUNCTUATION[b] = i; // } // } //} static const int8_t MIXED[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 12, -1, -1, -1, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, -1, -1, 15, 18, 21, 10, -1, -1, -1, 22, 20, 13, 16, 17, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, -1, -1, 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; static const int8_t PUNCTUATION[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 12, 15, -1, -1, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 20, -1, 18, -1, -1, 28, 23, 24, 22, -1, 13, 16, 17, 19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 14, 0, 1, -1, 2, 25, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 5, 6, -1, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 21, 27, 9, -1, }; static void EncodingECI(int eci, std::vector<int>& buffer) { if (eci >= 0 && eci < 900) { buffer.push_back(ECI_CHARSET); buffer.push_back(eci); } else if (eci >= 900 && eci < 810900) { buffer.push_back(ECI_GENERAL_PURPOSE); buffer.push_back(eci / 900 - 1); buffer.push_back(eci % 900); } else if (eci >= 810900 && eci < 811800) { buffer.push_back(ECI_USER_DEFINED); buffer.push_back(eci - 810900); } else { throw std::invalid_argument("ECI number not in valid range from 0..811799"); } } static bool IsDigit(int ch) { return ch >= '0' && ch <= '9'; } static bool IsAlphaUpper(int ch) { return ch == ' ' || (ch >= 'A' && ch <= 'Z'); } static bool IsAlphaLower(int ch) { return ch == ' ' || (ch >= 'a' && ch <= 'z'); } static bool IsMixed(int ch) { return (ch & 0x7f) == ch && MIXED[ch] != -1; } static bool IsPunctuation(int ch) { return (ch & 0x7f) == ch && PUNCTUATION[ch] != -1; } static bool IsText(int ch) { return ch == '\t' || ch == '\n' || ch == '\r' || (ch >= 32 && ch <= 126); } /** * Encode parts of the message using Text Compaction as described in ISO/IEC 15438:2001(E), * chapter 4.4.2. * * @param msg the message * @param startpos the start position within the message * @param count the number of characters to encode * @param submode should normally be SUBMODE_ALPHA * @param output receives the encoded codewords * @return the text submode in which this method ends */ static int EncodeText(const std::wstring& msg, int startpos, int count, int submode, std::vector<int>& output) { std::vector<int> tmp; tmp.reserve(count); int idx = 0; while (true) { int ch = msg[startpos + idx]; switch (submode) { case SUBMODE_ALPHA: if (IsAlphaUpper(ch)) { tmp.push_back(ch == ' ' ? 26 : (ch - 65)); // space } else if (IsAlphaLower(ch)) { submode = SUBMODE_LOWER; tmp.push_back(27); // ll continue; } else if (IsMixed(ch)) { submode = SUBMODE_MIXED; tmp.push_back(28); // ml continue; } else { tmp.push_back(29); // ps tmp.push_back(PUNCTUATION[ch]); } break; case SUBMODE_LOWER: if (IsAlphaLower(ch)) { tmp.push_back(ch == ' ' ? 26 : (ch - 97)); // space } else if (IsAlphaUpper(ch)) { tmp.push_back(27); // as tmp.push_back(ch - 65); // space cannot happen here, it is also in "Lower" } else if (IsMixed(ch)) { submode = SUBMODE_MIXED; tmp.push_back(28); // ml continue; } else { tmp.push_back(29); // ps tmp.push_back(PUNCTUATION[ch]); } break; case SUBMODE_MIXED: if (IsMixed(ch)) { tmp.push_back(MIXED[ch]); } else if (IsAlphaUpper(ch)) { submode = SUBMODE_ALPHA; tmp.push_back(28); // al continue; } else if (IsAlphaLower(ch)) { submode = SUBMODE_LOWER; tmp.push_back(27); // ll continue; } else { if (startpos + idx + 1 < count) { int next = msg[startpos + idx + 1]; if (IsPunctuation(next)) { submode = SUBMODE_PUNCTUATION; tmp.push_back(25); // pl continue; } } tmp.push_back(29); // ps tmp.push_back(PUNCTUATION[ch]); } break; default: // SUBMODE_PUNCTUATION if (IsPunctuation(ch)) { tmp.push_back(PUNCTUATION[ch]); } else { submode = SUBMODE_ALPHA; tmp.push_back(29); // al continue; } } idx++; if (idx >= count) { break; } } int h = 0; size_t len = tmp.size(); for (size_t i = 0; i < len; i++) { bool odd = (i % 2) != 0; if (odd) { h = (h * 30) + tmp[i]; output.push_back(h); } else { h = tmp[i]; } } if ((len % 2) != 0) { output.push_back((h * 30) + 29); //ps } return submode; } /** * Encode parts of the message using Byte Compaction as described in ISO/IEC 15438:2001(E), * chapter 4.4.3. The Unicode characters will be converted to binary using the cp437 * codepage. * * @param bytes the message converted to a byte array * @param startpos the start position within the message * @param count the number of bytes to encode * @param startmode the mode from which this method starts * @param output receives the encoded codewords */ static void EncodeBinary(const std::string& bytes, int startpos, int count, int startmode, std::vector<int>& output) { if (count == 1 && startmode == TEXT_COMPACTION) { output.push_back(SHIFT_TO_BYTE); } else { if ((count % 6) == 0) { output.push_back(LATCH_TO_BYTE); } else { output.push_back(LATCH_TO_BYTE_PADDED); } } int idx = startpos; // Encode sixpacks if (count >= 6) { int chars[5]; while ((startpos + count - idx) >= 6) { long t = 0; for (int i = 0; i < 6; i++) { t <<= 8; t += bytes[idx + i] & 0xff; } for (int i = 0; i < 5; i++) { chars[i] = t % 900; t /= 900; } for (int i = 4; i >= 0; i--) { output.push_back(chars[i]); } idx += 6; } } //Encode rest (remaining n<5 bytes if any) for (int i = idx; i < startpos + count; i++) { int ch = bytes[i] & 0xff; output.push_back(ch); } } static void EncodeNumeric(const std::wstring& msg, int startpos, int count, std::vector<int>& output) { int idx = 0; std::vector<int> tmp; tmp.reserve(count / 3 + 1); BigInteger num900(900); while (idx < count) { tmp.clear(); int len = std::min(44, count - idx); auto part = L"1" + msg.substr(startpos + idx, len); BigInteger bigint, r; BigInteger::TryParse(part, bigint); do { BigInteger::Divide(bigint, num900, bigint, r); tmp.push_back(r.toInt()); } while (!bigint.isZero()); //Reverse temporary string output.insert(output.end(), tmp.rbegin(), tmp.rend()); idx += len; } } /** * Determines the number of consecutive characters that are encodable using numeric compaction. * * @param msg the message * @param startpos the start position within the message * @return the requested character count */ static int DetermineConsecutiveDigitCount(const std::wstring& msg, int startpos) { int count = 0; size_t len = msg.length(); size_t idx = startpos; if (idx < len) { int ch = msg[idx]; while (IsDigit(ch) && idx < len) { count++; idx++; if (idx < len) { ch = msg[idx]; } } } return count; } /** * Determines the number of consecutive characters that are encodable using text compaction. * * @param msg the message * @param startpos the start position within the message * @return the requested character count */ static int DetermineConsecutiveTextCount(const std::wstring& msg, int startpos) { size_t len = msg.length(); size_t idx = startpos; while (idx < len) { int ch = msg[idx]; int numericCount = 0; while (numericCount < 13 && IsDigit(ch) && idx < len) { numericCount++; idx++; if (idx < len) { ch = msg[idx]; } } if (numericCount >= 13) { return static_cast<int>(idx - startpos - numericCount); } if (numericCount > 0) { //Heuristic: All text-encodable chars or digits are binary encodable continue; } ch = msg[idx]; //Check if character is encodable if (!IsText(ch)) { break; } idx++; } return static_cast<int>(idx - startpos); } /** * Determines the number of consecutive characters that are encodable using binary compaction. * * @param msg the message * @param startpos the start position within the message * @return the requested character count */ static int DetermineConsecutiveBinaryCount(const std::wstring& msg, int startpos) { size_t len = msg.length(); size_t idx = startpos; while (idx < len) { int ch = msg[idx]; int numericCount = 0; while (numericCount < 13 && IsDigit(ch)) { numericCount++; //textCount++; size_t i = idx + numericCount; if (i >= len) { break; } ch = msg[i]; } if (numericCount >= 13) { return static_cast<int>(idx - startpos); } idx++; } return static_cast<int>(idx - startpos); } /** * Performs high-level encoding of a PDF417 message using the algorithm described in annex P * of ISO/IEC 15438:2001(E). If byte compaction has been selected, then only byte compaction * is used. * * @param msg the message * @param compaction compaction mode to use * @param encoding character encoding used to encode in default or byte compaction * or {@code null} for default / not applicable * @return the encoded message (the char values range from 0 to 928) */ std::vector<int> HighLevelEncoder::EncodeHighLevel(const std::wstring& msg, Compaction compaction, CharacterSet encoding) { std::vector<int> highLevel; highLevel.reserve(highLevel.size() + msg.length()); //the codewords 0..928 are encoded as Unicode characters if (encoding != CharacterSet::ISO8859_1) { EncodingECI(ToInt(ToECI(encoding)), highLevel); } int len = Size(msg); int p = 0; int textSubMode = SUBMODE_ALPHA; // User selected encoding mode if (compaction == Compaction::TEXT) { EncodeText(msg, p, len, textSubMode, highLevel); } else if (compaction == Compaction::BYTE) { std::string bytes = TextEncoder::FromUnicode(msg, encoding); EncodeBinary(bytes, p, Size(bytes), BYTE_COMPACTION, highLevel); } else if (compaction == Compaction::NUMERIC) { highLevel.push_back(LATCH_TO_NUMERIC); EncodeNumeric(msg, p, len, highLevel); } else { int encodingMode = TEXT_COMPACTION; //Default mode, see 4.4.2.1 while (p < len) { int n = DetermineConsecutiveDigitCount(msg, p); if (n >= 13) { highLevel.push_back(LATCH_TO_NUMERIC); encodingMode = NUMERIC_COMPACTION; textSubMode = SUBMODE_ALPHA; //Reset after latch EncodeNumeric(msg, p, n, highLevel); p += n; } else { int t = DetermineConsecutiveTextCount(msg, p); if (t >= 5 || n == len) { if (encodingMode != TEXT_COMPACTION) { highLevel.push_back(LATCH_TO_TEXT); encodingMode = TEXT_COMPACTION; textSubMode = SUBMODE_ALPHA; //start with submode alpha after latch } textSubMode = EncodeText(msg, p, t, textSubMode, highLevel); p += t; } else { int b = DetermineConsecutiveBinaryCount(msg, p); if (b == 0) { b = 1; } std::string bytes = TextEncoder::FromUnicode(msg.substr(p, b), encoding); if (bytes.length() == 1 && encodingMode == TEXT_COMPACTION) { //Switch for one byte (instead of latch) EncodeBinary(bytes, 0, 1, TEXT_COMPACTION, highLevel); } else { //Mode latch performed by encodeBinary() EncodeBinary(bytes, 0, Size(bytes), encodingMode, highLevel); encodingMode = BYTE_COMPACTION; textSubMode = SUBMODE_ALPHA; //Reset after latch } p += b; } } } } return highLevel; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFHighLevelEncoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
4,839
```objective-c /* */ #pragma once #include "CharacterSet.h" #include <string> #include <vector> namespace ZXing { namespace Pdf417 { enum class Compaction; /** * PDF417 high-level encoder following the algorithm described in ISO/IEC 15438:2001(E) in * annex P. */ class HighLevelEncoder { public: static std::vector<int> EncodeHighLevel(const std::wstring& msg, Compaction compaction, CharacterSet encoding); }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFHighLevelEncoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
107
```objective-c /* */ #pragma once #include <cstdlib> #include <string> #include <type_traits> #include <utility> #include <vector> namespace ZXing { /** * All credits on BigInteger below go to Matt McCutchen, as the code below is extracted/modified from his C++ Big Integer Library (path_to_url */ class BigInteger { public: using Block = size_t; // The number of bits in a block //static const unsigned int N = 8 * sizeof(Block); // Constructs zero. BigInteger() = default; template <typename T> BigInteger(T x, typename std::enable_if_t<std::is_integral_v<T> && std::is_unsigned_v<T>>* = nullptr) : mag(1, x) {} template <typename T> BigInteger(T x, typename std::enable_if_t<std::is_integral_v<T> && std::is_signed_v<T>>* = nullptr) : negative(x < 0), mag(1, std::abs(x)) {} static bool TryParse(const std::string& str, BigInteger& result); static bool TryParse(const std::wstring& str, BigInteger& result); bool isZero() const { return mag.empty(); } std::string toString() const; int toInt() const; BigInteger& operator+=(BigInteger&& a) { if (mag.empty()) *this = std::move(a); else Add(*this, a, *this); return *this; } friend BigInteger operator+(const BigInteger& a, const BigInteger& b) { BigInteger c; BigInteger::Add(a, b, c); return c; } friend BigInteger operator-(const BigInteger& a, const BigInteger& b) { BigInteger c; BigInteger::Subtract(a, b, c); return c; } friend BigInteger operator*(const BigInteger& a, const BigInteger& b) { BigInteger c; BigInteger::Multiply(a, b, c); return c; } static void Add(const BigInteger& a, const BigInteger &b, BigInteger& c); static void Subtract(const BigInteger& a, const BigInteger &b, BigInteger& c); static void Multiply(const BigInteger& a, const BigInteger &b, BigInteger& c); static void Divide(const BigInteger& a, const BigInteger &b, BigInteger& quotient, BigInteger& remainder); private: bool negative = false; std::vector<Block> mag; }; } // ZXing ```
/content/code_sandbox/core/src/pdf417/ZXBigInteger.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
511
```objective-c /* */ #pragma once namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau */ class Codeword { static const int BARCODE_ROW_UNKNOWN = -1; int _startX = 0; int _endX = 0; int _bucket = 0; int _value = 0; int _rowNumber = BARCODE_ROW_UNKNOWN; public: Codeword() {} Codeword(int startX, int endX, int bucket, int value) : _startX(startX), _endX(endX), _bucket(bucket), _value(value) {} bool hasValidRowNumber() const { return isValidRowNumber(_rowNumber); } bool isValidRowNumber(int rowNumber) const { return rowNumber != BARCODE_ROW_UNKNOWN && _bucket == (rowNumber % 3) * 3; } void setRowNumberAsRowIndicatorColumn() { _rowNumber = (_value / 30) * 3 + _bucket / 3; } int width() const { return _endX - _startX; } int startX() const { return _startX; } int endX() const { return _endX; } int bucket() const { return _bucket; } int value() const { return _value; } int rowNumber() const { return _rowNumber; } void setRowNumber(int rowNumber) { _rowNumber = rowNumber; } }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFCodeword.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
329
```objective-c /* */ #pragma once #include "CharacterSet.h" #include <string> #include <memory> namespace ZXing { class BitMatrix; namespace Pdf417 { enum class Compaction; class Encoder; /** * @author Jacob Haynes * @author qwandor@google.com (Andrew Walbran) */ class Writer { public: Writer(); Writer(Writer &&) noexcept; ~Writer(); Writer& setMargin(int margin) { _margin = margin; return *this; } Writer& setErrorCorrectionLevel(int ecLevel) { _ecLevel = ecLevel; return *this; } /** * Sets max/min row/col values * * @param maxCols maximum allowed columns * @param minCols minimum allowed columns * @param maxRows maximum allowed rows * @param minRows minimum allowed rows */ Writer& setDimensions(int minCols, int maxCols, int minRows, int maxRows); /** * @param compaction compaction mode to use */ Writer& setCompaction(Compaction compaction); /** * @param compact if true, enables compaction */ Writer& setCompact(bool compact); /** * @param encoding sets character encoding to use */ Writer& setEncoding(CharacterSet encoding); BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: int _margin = -1; int _ecLevel = -1; std::unique_ptr<Encoder> _encoder; }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFWriter.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
355
```c++ /* */ #include "PDFWriter.h" #include "PDFEncoder.h" #include "BitMatrix.h" #include "Utf.h" #include <utility> namespace ZXing { namespace Pdf417 { /** * default white space (margin) around the code */ static const int WHITE_SPACE = 30; /** * default error correction level */ static const int DEFAULT_ERROR_CORRECTION_LEVEL = 2; /** * Takes and rotates the it 90 degrees */ static void RotateArray(const std::vector<std::vector<bool>>& input, std::vector<std::vector<bool>>& output) { size_t height = input.size(); size_t width = input[0].size(); output.resize(width); for (size_t i = 0; i < width; ++i) { output[i].resize(height); } for (size_t ii = 0; ii < height; ++ii) { // This makes the direction consistent on screen when rotating the screen size_t inverseii = height - ii - 1; for (size_t jj = 0; jj < width; ++jj) { output[jj][inverseii] = input[ii][jj]; } } } /** * This takes an array holding the values of the PDF 417 * * @param input a byte array of information with 0 is black, and 1 is white * @param margin border around the barcode * @return BitMatrix of the input */ static BitMatrix BitMatrixFromBitArray(const std::vector<std::vector<bool>>& input, int margin) { // Creates the bitmatrix with extra space for whitespace int width = Size(input[0]); int height = Size(input); BitMatrix result(width + 2 * margin, height + 2 * margin); for (int y = 0, yOutput = static_cast<int>(result.height()) - margin - 1; y < height; y++, yOutput--) { for (int x = 0; x < width; ++x) { // Zero is white in the bytematrix if (input[y][x]) { result.set(x + margin, yOutput); } } } return result; } BitMatrix Writer::encode(const std::wstring& contents, int width, int height) const { int margin = _margin >= 0 ? _margin : WHITE_SPACE; int ecLevel = _ecLevel >= 0 ? _ecLevel : DEFAULT_ERROR_CORRECTION_LEVEL; BarcodeMatrix resultMatrix = _encoder->generateBarcodeLogic(contents, ecLevel); int aspectRatio = 4; // keep in sync with MODULE_RATIO in PDFEncoder.cpp std::vector<std::vector<bool>> originalScale; resultMatrix.getScaledMatrix(1, aspectRatio, originalScale); bool rotated = false; if ((height > width) != (originalScale[0].size() < originalScale.size())) { std::vector<std::vector<bool>> temp; RotateArray(originalScale, temp); originalScale = temp; rotated = true; } int scaleX = width / Size(originalScale[0]); int scaleY = height / Size(originalScale); int scale; if (scaleX < scaleY) { scale = scaleX; } else { scale = scaleY; } if (scale > 1) { std::vector<std::vector<bool>> scaledMatrix; resultMatrix.getScaledMatrix(scale, scale * aspectRatio, scaledMatrix); if (rotated) { std::vector<std::vector<bool>> temp; RotateArray(scaledMatrix, temp); scaledMatrix = temp; } return BitMatrixFromBitArray(scaledMatrix, margin); } else { return BitMatrixFromBitArray(originalScale, margin); } } BitMatrix Writer::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } Writer::Writer() { _encoder.reset(new Encoder); } Writer::Writer(Writer &&other) noexcept: _margin(other._margin), _ecLevel(other._ecLevel), _encoder(std::move(other._encoder)) { } Writer::~Writer() { } Writer& Writer::setDimensions(int minCols, int maxCols, int minRows, int maxRows) { _encoder->setDimensions(minCols, maxCols, minRows, maxRows); return *this; } Writer& Writer::setCompaction(Compaction compaction) { _encoder->setCompaction(compaction); return *this; } /** * @param compact if true, enables compaction */ Writer& Writer::setCompact(bool compact) { _encoder->setCompact(compact); return *this; } /** * @param encoding sets character encoding to use */ Writer& Writer::setEncoding(CharacterSet encoding) { _encoder->setEncoding(encoding); return *this; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,040
```objective-c /* */ #pragma once #include "ZXNullable.h" #include "ResultPoint.h" namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau */ class BoundingBox { int _imgWidth; int _imgHeight; Nullable<ResultPoint> _topLeft; Nullable<ResultPoint> _bottomLeft; Nullable<ResultPoint> _topRight; Nullable<ResultPoint> _bottomRight; int _minX; int _maxX; int _minY; int _maxY; public: BoundingBox(); int minX() const { return _minX; } int maxX() const { return _maxX; } int minY() const { return _minY; } int maxY() const { return _maxY; } Nullable<ResultPoint> topLeft() const { return _topLeft; } Nullable<ResultPoint> topRight() const { return _topRight; } Nullable<ResultPoint> bottomLeft() const { return _bottomLeft; } Nullable<ResultPoint> bottomRight() const { return _bottomRight; } static bool Create(int imgWidth, int imgHeight, const Nullable<ResultPoint>& topLeft, const Nullable<ResultPoint>& bottomLeft, const Nullable<ResultPoint>& topRight, const Nullable<ResultPoint>& bottomRight, BoundingBox& result); static bool Merge(const Nullable<BoundingBox>& leftBox, const Nullable<BoundingBox>& rightBox, Nullable<BoundingBox>& result); static bool AddMissingRows(const BoundingBox&box, int missingStartRows, int missingEndRows, bool isLeft, BoundingBox& result); private: void calculateMinMaxValues(); }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFBoundingBox.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
356
```objective-c /* */ #pragma once #include "CharacterSet.h" #include "PDFCompaction.h" #include "ZXAlgorithms.h" #include <string> #include <vector> namespace ZXing { namespace Pdf417 { /** * @author Jacob Haynes */ class BarcodeRow { std::vector<bool> _row; int _currentLocation = 0; // A tacker for position in the bar public: explicit BarcodeRow(int width = 0) : _row(width, false) {} void init(int width) { _row.resize(width, false); _currentLocation = 0; } void set(int x, bool black) { _row.at(x) = black; } /** * @param black A boolean which is true if the bar black false if it is white * @param width How many spots wide the bar is. */ void addBar(bool black, int width) { for (int ii = 0; ii < width; ii++) { _row.at(_currentLocation++) = black; } } /** * This function scales the row * * @param scale How much you want the image to be scaled, must be greater than or equal to 1. * @param output the scaled row */ void getScaledRow(int scale, std::vector<bool>& output) const { output.resize(_row.size() * scale); for (size_t i = 0; i < output.size(); ++i) { output[i] = _row[i / scale]; } } }; /** * Holds all of the information for a barcode in a format where it can be easily accessible * * @author Jacob Haynes */ class BarcodeMatrix { std::vector<BarcodeRow> _matrix; int _width = 0; int _currentRow = -1; public: BarcodeMatrix() {} /** * @param height the height of the matrix (Rows) * @param width the width of the matrix (Cols) */ BarcodeMatrix(int height, int width) { init(height, width); } void init(int height, int width) { _matrix.resize(height); for (int i = 0; i < height; ++i) { _matrix[i].init((width + 4) * 17 + 1); } _width = width * 17; _currentRow = -1; } void set(int x, int y, bool value) { _matrix[y].set(x, value); } void startRow() { ++_currentRow; } const BarcodeRow& currentRow() const { return _matrix[_currentRow]; } BarcodeRow& currentRow() { return _matrix[_currentRow]; } void getScaledMatrix(int xScale, int yScale, std::vector<std::vector<bool>>& output) { output.resize(_matrix.size() * yScale); int yMax = Size(output); for (int i = 0; i < yMax; i++) { _matrix[i / yScale].getScaledRow(xScale, output[yMax - i - 1]); } } }; /** * Top-level class for the logic part of the PDF417 implementation. * C++ port: this class was named PDF417 in Java code. Since that name * does say much in the context of PDF417 writer, it's renamed here Encoder * to follow the same naming convention with other modules. */ class Encoder { public: explicit Encoder(bool compact = false) : _compact(compact) {} BarcodeMatrix generateBarcodeLogic(const std::wstring& msg, int errorCorrectionLevel) const; /** * Sets max/min row/col values * * @param maxCols maximum allowed columns * @param minCols minimum allowed columns * @param maxRows maximum allowed rows * @param minRows minimum allowed rows */ void setDimensions(int minCols, int maxCols, int minRows, int maxRows) { _minCols = minCols; _maxCols = maxCols; _minRows = minRows; _maxRows = maxRows; } /** * @param compaction compaction mode to use */ void setCompaction(Compaction compaction) { _compaction = compaction; } /** * @param compact if true, enables compaction */ void setCompact(bool compact) { _compact = compact; } /** * @param encoding sets character encoding to use */ void setEncoding(CharacterSet encoding) { _encoding = encoding; } static int GetRecommendedMinimumErrorCorrectionLevel(int n); private: bool _compact; Compaction _compaction = Compaction::AUTO; CharacterSet _encoding = CharacterSet::ISO8859_1; int _minCols = 2; int _maxCols = 30; int _minRows = 2; int _maxRows = 30; }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFEncoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,086
```objective-c /* */ #pragma once #include <vector> namespace ZXing { class BitMatrix; class ResultPoint; class DecoderResult; template <typename T> class Nullable; namespace Pdf417 { /** * @author Guenther Grau */ class ScanningDecoder { public: static DecoderResult Decode(const BitMatrix& image, const Nullable<ResultPoint>& imageTopLeft, const Nullable<ResultPoint>& imageBottomLeft, const Nullable<ResultPoint>& imageTopRight, const Nullable<ResultPoint>& imageBottomRight, int minCodewordWidth, int maxCodewordWidth); }; inline int NumECCodeWords(int ecLevel) { return 1 << (ecLevel + 1); } DecoderResult DecodeCodewords(std::vector<int>& codewords, int numECCodeWords); } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFScanningDecoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
175
```objective-c /* */ #pragma once #include "PDFBoundingBox.h" #include "PDFCodeword.h" #include "ZXNullable.h" #include <vector> namespace ZXing { namespace Pdf417 { class BarcodeMetadata; /** * @author Guenther Grau */ class DetectionResultColumn { public: enum class RowIndicator { None, Left, Right, }; DetectionResultColumn() {} explicit DetectionResultColumn(const BoundingBox& boundingBox, RowIndicator rowInd = RowIndicator::None); bool isRowIndicator() const { return _rowIndicator != RowIndicator::None; } bool isLeftRowIndicator() const { return _rowIndicator == RowIndicator::Left; } Nullable<Codeword> codewordNearby(int imageRow) const; int imageRowToCodewordIndex(int imageRow) const { return imageRow - _boundingBox.minY(); } void setCodeword(int imageRow, Codeword codeword) { _codewords[imageRowToCodewordIndex(imageRow)] = codeword; } Nullable<Codeword> codeword(int imageRow) const { return _codewords[imageRowToCodewordIndex(imageRow)]; } const BoundingBox& boundingBox() const { return _boundingBox; } const std::vector<Nullable<Codeword>>& allCodewords() const { return _codewords; } std::vector<Nullable<Codeword>>& allCodewords() { return _codewords; } void adjustCompleteIndicatorColumnRowNumbers(const BarcodeMetadata& barcodeMetadata); bool getRowHeights(std::vector<int>& result); // not const, since it modifies object's state bool getBarcodeMetadata(BarcodeMetadata& result); // not const, since it modifies object's state private: BoundingBox _boundingBox; std::vector<Nullable<Codeword>> _codewords; RowIndicator _rowIndicator = RowIndicator::None; void setRowNumbers(); void adjustIncompleteIndicatorColumnRowNumbers(const BarcodeMetadata& barcodeMetadata); }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDetectionResultColumn.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
457
```c++ /* */ #include "PDFCodewordDecoder.h" #include "BitArray.h" #include "ZXAlgorithms.h" #include <algorithm> #include <array> #include <cstdint> #include <limits> namespace ZXing { namespace Pdf417 { static constexpr const int SYMBOL_COUNT = 2787; /** * The sorted table of all possible symbols. Extracted from the PDF417 * specification. The index of a symbol in this table corresponds to the * index into the codeword table. * Note: stored in the table are only the 16 least significant bits (of 17), * each full symbol is preceded by a 1-bit, see getSymbol(); */ static constexpr const std::array<uint16_t, 2787> SYMBOL_TABLE = { 0x025e, 0x027a, 0x029e, 0x02bc, 0x02f2, 0x02f4, 0x032e, 0x034e, 0x035c, 0x0396, 0x03a6, 0x03ac, 0x0422, 0x0428, 0x0436, 0x0442, 0x0444, 0x0448, 0x0450, 0x045e, 0x0466, 0x046c, 0x047a, 0x0482, 0x049e, 0x04a0, 0x04bc, 0x04c6, 0x04d8, 0x04ee, 0x04f2, 0x04f4, 0x0504, 0x0508, 0x0510, 0x051e, 0x0520, 0x053c, 0x0540, 0x0578, 0x0586, 0x058c, 0x0598, 0x05b0, 0x05be, 0x05ce, 0x05dc, 0x05e2, 0x05e4, 0x05e8, 0x05f6, 0x062e, 0x064e, 0x065c, 0x068e, 0x069c, 0x06b8, 0x06de, 0x06fa, 0x0716, 0x0726, 0x072c, 0x0746, 0x074c, 0x0758, 0x076e, 0x0792, 0x0794, 0x07a2, 0x07a4, 0x07a8, 0x07b6, 0x0822, 0x0828, 0x0842, 0x0848, 0x0850, 0x085e, 0x0866, 0x086c, 0x087a, 0x0882, 0x0884, 0x0890, 0x089e, 0x08a0, 0x08bc, 0x08c6, 0x08cc, 0x08d8, 0x08ee, 0x08f2, 0x08f4, 0x0902, 0x0908, 0x091e, 0x0920, 0x093c, 0x0940, 0x0978, 0x0986, 0x0998, 0x09b0, 0x09be, 0x09ce, 0x09dc, 0x09e2, 0x09e4, 0x09e8, 0x09f6, 0x0a08, 0x0a10, 0x0a1e, 0x0a20, 0x0a3c, 0x0a40, 0x0a78, 0x0af0, 0x0b06, 0x0b0c, 0x0b18, 0x0b30, 0x0b3e, 0x0b60, 0x0b7c, 0x0b8e, 0x0b9c, 0x0bb8, 0x0bc2, 0x0bc4, 0x0bc8, 0x0bd0, 0x0bde, 0x0be6, 0x0bec, 0x0c2e, 0x0c4e, 0x0c5c, 0x0c62, 0x0c64, 0x0c68, 0x0c76, 0x0c8e, 0x0c9c, 0x0cb8, 0x0cc2, 0x0cc4, 0x0cc8, 0x0cd0, 0x0cde, 0x0ce6, 0x0cec, 0x0cfa, 0x0d0e, 0x0d1c, 0x0d38, 0x0d70, 0x0d7e, 0x0d82, 0x0d84, 0x0d88, 0x0d90, 0x0d9e, 0x0da0, 0x0dbc, 0x0dc6, 0x0dcc, 0x0dd8, 0x0dee, 0x0df2, 0x0df4, 0x0e16, 0x0e26, 0x0e2c, 0x0e46, 0x0e58, 0x0e6e, 0x0e86, 0x0e8c, 0x0e98, 0x0eb0, 0x0ebe, 0x0ece, 0x0edc, 0x0f0a, 0x0f12, 0x0f14, 0x0f22, 0x0f28, 0x0f36, 0x0f42, 0x0f44, 0x0f48, 0x0f50, 0x0f5e, 0x0f66, 0x0f6c, 0x0fb2, 0x0fb4, 0x1022, 0x1028, 0x1042, 0x1048, 0x1050, 0x105e, 0x107a, 0x1082, 0x1084, 0x1090, 0x109e, 0x10a0, 0x10bc, 0x10c6, 0x10cc, 0x10d8, 0x10ee, 0x10f2, 0x10f4, 0x1102, 0x111e, 0x1120, 0x113c, 0x1140, 0x1178, 0x1186, 0x1198, 0x11b0, 0x11be, 0x11ce, 0x11dc, 0x11e2, 0x11e4, 0x11e8, 0x11f6, 0x1208, 0x121e, 0x1220, 0x1278, 0x12f0, 0x130c, 0x1330, 0x133e, 0x1360, 0x137c, 0x138e, 0x139c, 0x13b8, 0x13c2, 0x13c8, 0x13d0, 0x13de, 0x13e6, 0x13ec, 0x1408, 0x1410, 0x141e, 0x1420, 0x143c, 0x1440, 0x1478, 0x14f0, 0x15e0, 0x160c, 0x1618, 0x1630, 0x163e, 0x1660, 0x167c, 0x16c0, 0x16f8, 0x171c, 0x1738, 0x1770, 0x177e, 0x1782, 0x1784, 0x1788, 0x1790, 0x179e, 0x17a0, 0x17bc, 0x17c6, 0x17cc, 0x17d8, 0x17ee, 0x182e, 0x1834, 0x184e, 0x185c, 0x1862, 0x1864, 0x1868, 0x1876, 0x188e, 0x189c, 0x18b8, 0x18c2, 0x18c8, 0x18d0, 0x18de, 0x18e6, 0x18ec, 0x18fa, 0x190e, 0x191c, 0x1938, 0x1970, 0x197e, 0x1982, 0x1984, 0x1990, 0x199e, 0x19a0, 0x19bc, 0x19c6, 0x19cc, 0x19d8, 0x19ee, 0x19f2, 0x19f4, 0x1a0e, 0x1a1c, 0x1a38, 0x1a70, 0x1a7e, 0x1ae0, 0x1afc, 0x1b08, 0x1b10, 0x1b1e, 0x1b20, 0x1b3c, 0x1b40, 0x1b78, 0x1b8c, 0x1b98, 0x1bb0, 0x1bbe, 0x1bce, 0x1bdc, 0x1be2, 0x1be4, 0x1be8, 0x1bf6, 0x1c16, 0x1c26, 0x1c2c, 0x1c46, 0x1c4c, 0x1c58, 0x1c6e, 0x1c86, 0x1c98, 0x1cb0, 0x1cbe, 0x1cce, 0x1cdc, 0x1ce2, 0x1ce4, 0x1ce8, 0x1cf6, 0x1d06, 0x1d0c, 0x1d18, 0x1d30, 0x1d3e, 0x1d60, 0x1d7c, 0x1d8e, 0x1d9c, 0x1db8, 0x1dc4, 0x1dc8, 0x1dd0, 0x1dde, 0x1de6, 0x1dec, 0x1dfa, 0x1e0a, 0x1e12, 0x1e14, 0x1e22, 0x1e24, 0x1e28, 0x1e36, 0x1e42, 0x1e44, 0x1e50, 0x1e5e, 0x1e66, 0x1e6c, 0x1e82, 0x1e84, 0x1e88, 0x1e90, 0x1e9e, 0x1ea0, 0x1ebc, 0x1ec6, 0x1ecc, 0x1ed8, 0x1eee, 0x1f1a, 0x1f2e, 0x1f32, 0x1f34, 0x1f4e, 0x1f5c, 0x1f62, 0x1f64, 0x1f68, 0x1f76, 0x2048, 0x205e, 0x2082, 0x2084, 0x2090, 0x209e, 0x20a0, 0x20bc, 0x20d8, 0x20f2, 0x20f4, 0x2108, 0x211e, 0x2120, 0x213c, 0x2140, 0x2178, 0x2186, 0x2198, 0x21b0, 0x21be, 0x21e2, 0x21e4, 0x21e8, 0x21f6, 0x2204, 0x2210, 0x221e, 0x2220, 0x2278, 0x22f0, 0x2306, 0x230c, 0x2330, 0x233e, 0x2360, 0x237c, 0x238e, 0x239c, 0x23b8, 0x23c2, 0x23c8, 0x23d0, 0x23e6, 0x23ec, 0x241e, 0x2420, 0x243c, 0x24f0, 0x25e0, 0x2618, 0x263e, 0x2660, 0x267c, 0x26c0, 0x26f8, 0x2738, 0x2770, 0x277e, 0x2782, 0x2784, 0x2790, 0x279e, 0x27a0, 0x27bc, 0x27c6, 0x27cc, 0x27d8, 0x27ee, 0x2820, 0x283c, 0x2840, 0x2878, 0x28f0, 0x29e0, 0x2bc0, 0x2c18, 0x2c30, 0x2c3e, 0x2c60, 0x2c7c, 0x2cc0, 0x2cf8, 0x2df0, 0x2e1c, 0x2e38, 0x2e70, 0x2e7e, 0x2ee0, 0x2efc, 0x2f04, 0x2f08, 0x2f10, 0x2f20, 0x2f3c, 0x2f40, 0x2f78, 0x2f86, 0x2f8c, 0x2f98, 0x2fb0, 0x2fbe, 0x2fce, 0x2fdc, 0x302e, 0x304e, 0x305c, 0x3062, 0x3068, 0x308e, 0x309c, 0x30b8, 0x30c2, 0x30c8, 0x30d0, 0x30de, 0x30ec, 0x30fa, 0x310e, 0x3138, 0x3170, 0x317e, 0x3182, 0x3184, 0x3190, 0x319e, 0x31a0, 0x31bc, 0x31c6, 0x31cc, 0x31d8, 0x31f2, 0x31f4, 0x320e, 0x321c, 0x3270, 0x327e, 0x32e0, 0x32fc, 0x3308, 0x331e, 0x3320, 0x333c, 0x3340, 0x3378, 0x3386, 0x3398, 0x33b0, 0x33be, 0x33ce, 0x33dc, 0x33e2, 0x33e4, 0x33e8, 0x33f6, 0x340e, 0x341c, 0x3438, 0x3470, 0x347e, 0x34e0, 0x34fc, 0x35c0, 0x35f8, 0x3608, 0x3610, 0x361e, 0x3620, 0x363c, 0x3640, 0x3678, 0x36f0, 0x370c, 0x3718, 0x3730, 0x373e, 0x3760, 0x377c, 0x379c, 0x37b8, 0x37c2, 0x37c4, 0x37c8, 0x37d0, 0x37de, 0x37e6, 0x37ec, 0x3816, 0x3826, 0x382c, 0x3846, 0x384c, 0x3858, 0x386e, 0x3874, 0x3886, 0x3898, 0x38b0, 0x38be, 0x38ce, 0x38dc, 0x38e2, 0x38e4, 0x38e8, 0x3906, 0x390c, 0x3930, 0x393e, 0x3960, 0x397c, 0x398e, 0x399c, 0x39b8, 0x39c8, 0x39d0, 0x39de, 0x39e6, 0x39ec, 0x39fa, 0x3a06, 0x3a0c, 0x3a18, 0x3a30, 0x3a3e, 0x3a60, 0x3a7c, 0x3ac0, 0x3af8, 0x3b0e, 0x3b1c, 0x3b38, 0x3b70, 0x3b7e, 0x3b88, 0x3b90, 0x3b9e, 0x3ba0, 0x3bbc, 0x3bcc, 0x3bd8, 0x3bee, 0x3bf2, 0x3bf4, 0x3c12, 0x3c14, 0x3c22, 0x3c24, 0x3c28, 0x3c36, 0x3c42, 0x3c48, 0x3c50, 0x3c5e, 0x3c66, 0x3c6c, 0x3c82, 0x3c84, 0x3c90, 0x3c9e, 0x3ca0, 0x3cbc, 0x3cc6, 0x3ccc, 0x3cd8, 0x3cee, 0x3d02, 0x3d04, 0x3d08, 0x3d10, 0x3d1e, 0x3d20, 0x3d3c, 0x3d40, 0x3d78, 0x3d86, 0x3d8c, 0x3d98, 0x3db0, 0x3dbe, 0x3dce, 0x3ddc, 0x3de4, 0x3de8, 0x3df6, 0x3e1a, 0x3e2e, 0x3e32, 0x3e34, 0x3e4e, 0x3e5c, 0x3e62, 0x3e64, 0x3e68, 0x3e76, 0x3e8e, 0x3e9c, 0x3eb8, 0x3ec2, 0x3ec4, 0x3ec8, 0x3ed0, 0x3ede, 0x3ee6, 0x3eec, 0x3f26, 0x3f2c, 0x3f3a, 0x3f46, 0x3f4c, 0x3f58, 0x3f6e, 0x3f72, 0x3f74, 0x4082, 0x409e, 0x40a0, 0x40bc, 0x4104, 0x4108, 0x4110, 0x411e, 0x4120, 0x413c, 0x4140, 0x4178, 0x418c, 0x4198, 0x41b0, 0x41be, 0x41e2, 0x41e4, 0x41e8, 0x4208, 0x4210, 0x421e, 0x4220, 0x423c, 0x4240, 0x4278, 0x42f0, 0x4306, 0x430c, 0x4318, 0x4330, 0x433e, 0x4360, 0x437c, 0x438e, 0x43c2, 0x43c4, 0x43c8, 0x43d0, 0x43e6, 0x43ec, 0x4408, 0x4410, 0x441e, 0x4420, 0x443c, 0x4440, 0x4478, 0x44f0, 0x45e0, 0x460c, 0x4618, 0x4630, 0x463e, 0x4660, 0x467c, 0x46c0, 0x46f8, 0x471c, 0x4738, 0x4770, 0x477e, 0x4782, 0x4784, 0x4788, 0x4790, 0x47a0, 0x47bc, 0x47c6, 0x47cc, 0x47d8, 0x47ee, 0x4810, 0x4820, 0x483c, 0x4840, 0x4878, 0x48f0, 0x49e0, 0x4bc0, 0x4c30, 0x4c3e, 0x4c60, 0x4c7c, 0x4cc0, 0x4cf8, 0x4df0, 0x4e38, 0x4e70, 0x4e7e, 0x4ee0, 0x4efc, 0x4f04, 0x4f08, 0x4f10, 0x4f1e, 0x4f20, 0x4f3c, 0x4f40, 0x4f78, 0x4f86, 0x4f8c, 0x4f98, 0x4fb0, 0x4fce, 0x4fdc, 0x5020, 0x5040, 0x5078, 0x50f0, 0x51e0, 0x53c0, 0x5860, 0x587c, 0x58c0, 0x58f8, 0x59f0, 0x5be0, 0x5c70, 0x5c7e, 0x5ce0, 0x5cfc, 0x5dc0, 0x5df8, 0x5e08, 0x5e10, 0x5e20, 0x5e40, 0x5e78, 0x5ef0, 0x5f0c, 0x5f18, 0x5f30, 0x5f60, 0x5f7c, 0x5f8e, 0x5f9c, 0x5fb8, 0x604e, 0x605c, 0x608e, 0x609c, 0x60b8, 0x60c2, 0x60c4, 0x60c8, 0x60de, 0x610e, 0x611c, 0x6138, 0x6170, 0x617e, 0x6184, 0x6188, 0x6190, 0x619e, 0x61a0, 0x61bc, 0x61c6, 0x61cc, 0x61d8, 0x61f2, 0x61f4, 0x620e, 0x621c, 0x6238, 0x6270, 0x627e, 0x62e0, 0x62fc, 0x6304, 0x6308, 0x6310, 0x631e, 0x6320, 0x633c, 0x6340, 0x6378, 0x6386, 0x638c, 0x6398, 0x63b0, 0x63be, 0x63ce, 0x63dc, 0x63e2, 0x63e4, 0x63e8, 0x63f6, 0x640e, 0x641c, 0x6438, 0x6470, 0x647e, 0x64e0, 0x64fc, 0x65c0, 0x65f8, 0x6610, 0x661e, 0x6620, 0x663c, 0x6640, 0x6678, 0x66f0, 0x6718, 0x6730, 0x673e, 0x6760, 0x677c, 0x678e, 0x679c, 0x67b8, 0x67c2, 0x67c4, 0x67c8, 0x67d0, 0x67de, 0x67e6, 0x67ec, 0x681c, 0x6838, 0x6870, 0x68e0, 0x68fc, 0x69c0, 0x69f8, 0x6bf0, 0x6c10, 0x6c1e, 0x6c20, 0x6c3c, 0x6c40, 0x6c78, 0x6cf0, 0x6de0, 0x6e18, 0x6e30, 0x6e3e, 0x6e60, 0x6e7c, 0x6ec0, 0x6ef8, 0x6f1c, 0x6f38, 0x6f70, 0x6f7e, 0x6f84, 0x6f88, 0x6f90, 0x6f9e, 0x6fa0, 0x6fbc, 0x6fc6, 0x6fcc, 0x6fd8, 0x7026, 0x702c, 0x7046, 0x704c, 0x7058, 0x706e, 0x7086, 0x708c, 0x7098, 0x70b0, 0x70be, 0x70ce, 0x70dc, 0x70e8, 0x7106, 0x710c, 0x7118, 0x7130, 0x713e, 0x7160, 0x717c, 0x718e, 0x719c, 0x71b8, 0x71c2, 0x71c4, 0x71c8, 0x71d0, 0x71de, 0x71e6, 0x71ec, 0x71fa, 0x7206, 0x720c, 0x7218, 0x7230, 0x723e, 0x7260, 0x727c, 0x72c0, 0x72f8, 0x730e, 0x731c, 0x7338, 0x7370, 0x737e, 0x7388, 0x7390, 0x739e, 0x73a0, 0x73bc, 0x73cc, 0x73d8, 0x73ee, 0x73f2, 0x73f4, 0x740c, 0x7418, 0x7430, 0x743e, 0x7460, 0x747c, 0x74c0, 0x74f8, 0x75f0, 0x760e, 0x761c, 0x7638, 0x7670, 0x767e, 0x76e0, 0x76fc, 0x7708, 0x7710, 0x771e, 0x7720, 0x773c, 0x7740, 0x7778, 0x7798, 0x77b0, 0x77be, 0x77dc, 0x77e2, 0x77e4, 0x77e8, 0x7822, 0x7824, 0x7828, 0x7836, 0x7842, 0x7844, 0x7848, 0x7850, 0x785e, 0x7866, 0x786c, 0x7882, 0x7884, 0x7888, 0x7890, 0x789e, 0x78a0, 0x78bc, 0x78c6, 0x78cc, 0x78d8, 0x78ee, 0x78f2, 0x78f4, 0x7902, 0x7904, 0x7908, 0x7910, 0x791e, 0x7920, 0x793c, 0x7940, 0x7978, 0x7986, 0x798c, 0x7998, 0x79b0, 0x79be, 0x79ce, 0x79dc, 0x79e2, 0x79e4, 0x79e8, 0x79f6, 0x7a04, 0x7a08, 0x7a10, 0x7a1e, 0x7a20, 0x7a3c, 0x7a40, 0x7a78, 0x7af0, 0x7b06, 0x7b0c, 0x7b18, 0x7b30, 0x7b3e, 0x7b60, 0x7b7c, 0x7b8e, 0x7b9c, 0x7bb8, 0x7bc4, 0x7bc8, 0x7bd0, 0x7bde, 0x7be6, 0x7bec, 0x7c2e, 0x7c32, 0x7c34, 0x7c4e, 0x7c5c, 0x7c62, 0x7c64, 0x7c68, 0x7c76, 0x7c8e, 0x7c9c, 0x7cb8, 0x7cc2, 0x7cc4, 0x7cc8, 0x7cd0, 0x7cde, 0x7ce6, 0x7cec, 0x7d0e, 0x7d1c, 0x7d38, 0x7d70, 0x7d82, 0x7d84, 0x7d88, 0x7d90, 0x7d9e, 0x7da0, 0x7dbc, 0x7dc6, 0x7dcc, 0x7dd8, 0x7dee, 0x7e26, 0x7e2c, 0x7e3a, 0x7e46, 0x7e4c, 0x7e58, 0x7e6e, 0x7e72, 0x7e74, 0x7e86, 0x7e8c, 0x7e98, 0x7eb0, 0x7ece, 0x7edc, 0x7ee2, 0x7ee4, 0x7ee8, 0x7ef6, 0x813a, 0x8172, 0x8174, 0x8216, 0x8226, 0x823a, 0x824c, 0x8258, 0x826e, 0x8272, 0x8274, 0x8298, 0x82be, 0x82e2, 0x82e4, 0x82e8, 0x82f6, 0x835e, 0x837a, 0x83ae, 0x83d6, 0x8416, 0x8426, 0x842c, 0x843a, 0x8446, 0x8458, 0x846e, 0x8472, 0x8474, 0x8486, 0x84b0, 0x84be, 0x84ce, 0x84dc, 0x84e2, 0x84e4, 0x84e8, 0x84f6, 0x8506, 0x850c, 0x8518, 0x8530, 0x853e, 0x8560, 0x857c, 0x858e, 0x859c, 0x85b8, 0x85c2, 0x85c4, 0x85c8, 0x85d0, 0x85de, 0x85e6, 0x85ec, 0x85fa, 0x8612, 0x8614, 0x8622, 0x8628, 0x8636, 0x8642, 0x8650, 0x865e, 0x867a, 0x8682, 0x8684, 0x8688, 0x8690, 0x869e, 0x86a0, 0x86bc, 0x86c6, 0x86cc, 0x86d8, 0x86ee, 0x86f2, 0x86f4, 0x872e, 0x874e, 0x875c, 0x8796, 0x87a6, 0x87ac, 0x87d2, 0x87d4, 0x8826, 0x882c, 0x883a, 0x8846, 0x884c, 0x8858, 0x886e, 0x8872, 0x8874, 0x8886, 0x8898, 0x88b0, 0x88be, 0x88ce, 0x88dc, 0x88e2, 0x88e4, 0x88e8, 0x88f6, 0x890c, 0x8930, 0x893e, 0x8960, 0x897c, 0x898e, 0x89b8, 0x89c2, 0x89c8, 0x89d0, 0x89de, 0x89e6, 0x89ec, 0x89fa, 0x8a18, 0x8a30, 0x8a3e, 0x8a60, 0x8a7c, 0x8ac0, 0x8af8, 0x8b1c, 0x8b38, 0x8b70, 0x8b7e, 0x8b82, 0x8b84, 0x8b88, 0x8b90, 0x8b9e, 0x8ba0, 0x8bbc, 0x8bc6, 0x8bcc, 0x8bd8, 0x8bee, 0x8bf2, 0x8bf4, 0x8c22, 0x8c24, 0x8c28, 0x8c36, 0x8c42, 0x8c48, 0x8c50, 0x8c5e, 0x8c66, 0x8c7a, 0x8c82, 0x8c84, 0x8c90, 0x8c9e, 0x8ca0, 0x8cbc, 0x8ccc, 0x8cf2, 0x8cf4, 0x8d04, 0x8d08, 0x8d10, 0x8d1e, 0x8d20, 0x8d3c, 0x8d40, 0x8d78, 0x8d86, 0x8d98, 0x8dce, 0x8de2, 0x8de4, 0x8de8, 0x8e2e, 0x8e32, 0x8e34, 0x8e4e, 0x8e5c, 0x8e62, 0x8e64, 0x8e68, 0x8e8e, 0x8e9c, 0x8eb8, 0x8ec2, 0x8ec4, 0x8ec8, 0x8ed0, 0x8efa, 0x8f16, 0x8f26, 0x8f2c, 0x8f46, 0x8f4c, 0x8f58, 0x8f6e, 0x8f8a, 0x8f92, 0x8f94, 0x8fa2, 0x8fa4, 0x8fa8, 0x8fb6, 0x902c, 0x903a, 0x9046, 0x904c, 0x9058, 0x9072, 0x9074, 0x9086, 0x9098, 0x90b0, 0x90be, 0x90ce, 0x90dc, 0x90e2, 0x90e8, 0x90f6, 0x9106, 0x910c, 0x9130, 0x913e, 0x9160, 0x917c, 0x918e, 0x919c, 0x91b8, 0x91c2, 0x91c8, 0x91d0, 0x91de, 0x91e6, 0x91ec, 0x91fa, 0x9218, 0x923e, 0x9260, 0x927c, 0x92c0, 0x92f8, 0x9338, 0x9370, 0x937e, 0x9382, 0x9384, 0x9390, 0x939e, 0x93a0, 0x93bc, 0x93c6, 0x93cc, 0x93d8, 0x93ee, 0x93f2, 0x93f4, 0x9430, 0x943e, 0x9460, 0x947c, 0x94c0, 0x94f8, 0x95f0, 0x9638, 0x9670, 0x967e, 0x96e0, 0x96fc, 0x9702, 0x9704, 0x9708, 0x9710, 0x9720, 0x973c, 0x9740, 0x9778, 0x9786, 0x978c, 0x9798, 0x97b0, 0x97be, 0x97ce, 0x97dc, 0x97e2, 0x97e4, 0x97e8, 0x9822, 0x9824, 0x9842, 0x9848, 0x9850, 0x985e, 0x9866, 0x987a, 0x9882, 0x9884, 0x9890, 0x989e, 0x98a0, 0x98bc, 0x98cc, 0x98f2, 0x98f4, 0x9902, 0x9908, 0x991e, 0x9920, 0x993c, 0x9940, 0x9978, 0x9986, 0x9998, 0x99ce, 0x99e2, 0x99e4, 0x99e8, 0x9a08, 0x9a10, 0x9a1e, 0x9a20, 0x9a3c, 0x9a40, 0x9a78, 0x9af0, 0x9b18, 0x9b3e, 0x9b60, 0x9b9c, 0x9bc2, 0x9bc4, 0x9bc8, 0x9bd0, 0x9be6, 0x9c2e, 0x9c34, 0x9c4e, 0x9c5c, 0x9c62, 0x9c64, 0x9c68, 0x9c8e, 0x9c9c, 0x9cb8, 0x9cc2, 0x9cc8, 0x9cd0, 0x9ce6, 0x9cfa, 0x9d0e, 0x9d1c, 0x9d38, 0x9d70, 0x9d7e, 0x9d82, 0x9d84, 0x9d88, 0x9d90, 0x9da0, 0x9dcc, 0x9df2, 0x9df4, 0x9e16, 0x9e26, 0x9e2c, 0x9e46, 0x9e4c, 0x9e58, 0x9e74, 0x9e86, 0x9e8c, 0x9e98, 0x9eb0, 0x9ebe, 0x9ece, 0x9ee2, 0x9ee4, 0x9ee8, 0x9f0a, 0x9f12, 0x9f14, 0x9f22, 0x9f24, 0x9f28, 0x9f42, 0x9f44, 0x9f48, 0x9f50, 0x9f5e, 0x9f6c, 0x9f9a, 0x9fae, 0x9fb2, 0x9fb4, 0xa046, 0xa04c, 0xa072, 0xa074, 0xa086, 0xa08c, 0xa098, 0xa0b0, 0xa0be, 0xa0e2, 0xa0e4, 0xa0e8, 0xa0f6, 0xa106, 0xa10c, 0xa118, 0xa130, 0xa13e, 0xa160, 0xa17c, 0xa18e, 0xa19c, 0xa1b8, 0xa1c2, 0xa1c4, 0xa1c8, 0xa1d0, 0xa1de, 0xa1e6, 0xa1ec, 0xa218, 0xa230, 0xa23e, 0xa260, 0xa27c, 0xa2c0, 0xa2f8, 0xa31c, 0xa338, 0xa370, 0xa37e, 0xa382, 0xa384, 0xa388, 0xa390, 0xa39e, 0xa3a0, 0xa3bc, 0xa3c6, 0xa3cc, 0xa3d8, 0xa3ee, 0xa3f2, 0xa3f4, 0xa418, 0xa430, 0xa43e, 0xa460, 0xa47c, 0xa4c0, 0xa4f8, 0xa5f0, 0xa61c, 0xa638, 0xa670, 0xa67e, 0xa6e0, 0xa6fc, 0xa702, 0xa704, 0xa708, 0xa710, 0xa71e, 0xa720, 0xa73c, 0xa740, 0xa778, 0xa786, 0xa78c, 0xa798, 0xa7b0, 0xa7be, 0xa7ce, 0xa7dc, 0xa7e2, 0xa7e4, 0xa7e8, 0xa830, 0xa860, 0xa87c, 0xa8c0, 0xa8f8, 0xa9f0, 0xabe0, 0xac70, 0xac7e, 0xace0, 0xacfc, 0xadc0, 0xadf8, 0xae04, 0xae08, 0xae10, 0xae20, 0xae3c, 0xae40, 0xae78, 0xaef0, 0xaf06, 0xaf0c, 0xaf18, 0xaf30, 0xaf3e, 0xaf60, 0xaf7c, 0xaf8e, 0xaf9c, 0xafb8, 0xafc4, 0xafc8, 0xafd0, 0xafde, 0xb042, 0xb05e, 0xb07a, 0xb082, 0xb084, 0xb088, 0xb090, 0xb09e, 0xb0a0, 0xb0bc, 0xb0cc, 0xb0f2, 0xb0f4, 0xb102, 0xb104, 0xb108, 0xb110, 0xb11e, 0xb120, 0xb13c, 0xb140, 0xb178, 0xb186, 0xb198, 0xb1ce, 0xb1e2, 0xb1e4, 0xb1e8, 0xb204, 0xb208, 0xb210, 0xb21e, 0xb220, 0xb23c, 0xb240, 0xb278, 0xb2f0, 0xb30c, 0xb33e, 0xb360, 0xb39c, 0xb3c2, 0xb3c4, 0xb3c8, 0xb3d0, 0xb3e6, 0xb410, 0xb41e, 0xb420, 0xb43c, 0xb440, 0xb478, 0xb4f0, 0xb5e0, 0xb618, 0xb660, 0xb67c, 0xb6c0, 0xb738, 0xb782, 0xb784, 0xb788, 0xb790, 0xb79e, 0xb7a0, 0xb7cc, 0xb82e, 0xb84e, 0xb85c, 0xb88e, 0xb89c, 0xb8b8, 0xb8c2, 0xb8c4, 0xb8c8, 0xb8d0, 0xb8e6, 0xb8fa, 0xb90e, 0xb91c, 0xb938, 0xb970, 0xb97e, 0xb982, 0xb984, 0xb988, 0xb990, 0xb99e, 0xb9a0, 0xb9cc, 0xb9f2, 0xb9f4, 0xba0e, 0xba1c, 0xba38, 0xba70, 0xba7e, 0xbae0, 0xbafc, 0xbb08, 0xbb10, 0xbb20, 0xbb3c, 0xbb40, 0xbb98, 0xbbce, 0xbbe2, 0xbbe4, 0xbbe8, 0xbc16, 0xbc26, 0xbc2c, 0xbc46, 0xbc4c, 0xbc58, 0xbc72, 0xbc74, 0xbc86, 0xbc8c, 0xbc98, 0xbcb0, 0xbcbe, 0xbcce, 0xbce2, 0xbce4, 0xbce8, 0xbd06, 0xbd0c, 0xbd18, 0xbd30, 0xbd3e, 0xbd60, 0xbd7c, 0xbd9c, 0xbdc2, 0xbdc4, 0xbdc8, 0xbdd0, 0xbde6, 0xbdfa, 0xbe12, 0xbe14, 0xbe22, 0xbe24, 0xbe28, 0xbe42, 0xbe44, 0xbe48, 0xbe50, 0xbe5e, 0xbe66, 0xbe82, 0xbe84, 0xbe88, 0xbe90, 0xbe9e, 0xbea0, 0xbebc, 0xbecc, 0xbef4, 0xbf1a, 0xbf2e, 0xbf32, 0xbf34, 0xbf4e, 0xbf5c, 0xbf62, 0xbf64, 0xbf68, 0xc09a, 0xc0b2, 0xc0b4, 0xc11a, 0xc132, 0xc134, 0xc162, 0xc164, 0xc168, 0xc176, 0xc1ba, 0xc21a, 0xc232, 0xc234, 0xc24e, 0xc25c, 0xc262, 0xc264, 0xc268, 0xc276, 0xc28e, 0xc2c2, 0xc2c4, 0xc2c8, 0xc2d0, 0xc2de, 0xc2e6, 0xc2ec, 0xc2fa, 0xc316, 0xc326, 0xc33a, 0xc346, 0xc34c, 0xc372, 0xc374, 0xc41a, 0xc42e, 0xc432, 0xc434, 0xc44e, 0xc45c, 0xc462, 0xc464, 0xc468, 0xc476, 0xc48e, 0xc49c, 0xc4b8, 0xc4c2, 0xc4c8, 0xc4d0, 0xc4de, 0xc4e6, 0xc4ec, 0xc4fa, 0xc51c, 0xc538, 0xc570, 0xc57e, 0xc582, 0xc584, 0xc588, 0xc590, 0xc59e, 0xc5a0, 0xc5bc, 0xc5c6, 0xc5cc, 0xc5d8, 0xc5ee, 0xc5f2, 0xc5f4, 0xc616, 0xc626, 0xc62c, 0xc63a, 0xc646, 0xc64c, 0xc658, 0xc66e, 0xc672, 0xc674, 0xc686, 0xc68c, 0xc698, 0xc6b0, 0xc6be, 0xc6ce, 0xc6dc, 0xc6e2, 0xc6e4, 0xc6e8, 0xc712, 0xc714, 0xc722, 0xc728, 0xc736, 0xc742, 0xc744, 0xc748, 0xc750, 0xc75e, 0xc766, 0xc76c, 0xc77a, 0xc7ae, 0xc7d6, 0xc7ea, 0xc81a, 0xc82e, 0xc832, 0xc834, 0xc84e, 0xc85c, 0xc862, 0xc864, 0xc868, 0xc876, 0xc88e, 0xc89c, 0xc8b8, 0xc8c2, 0xc8c8, 0xc8d0, 0xc8de, 0xc8e6, 0xc8ec, 0xc8fa, 0xc90e, 0xc938, 0xc970, 0xc97e, 0xc982, 0xc984, 0xc990, 0xc99e, 0xc9a0, 0xc9bc, 0xc9c6, 0xc9cc, 0xc9d8, 0xc9ee, 0xc9f2, 0xc9f4, 0xca38, 0xca70, 0xca7e, 0xcae0, 0xcafc, 0xcb02, 0xcb04, 0xcb08, 0xcb10, 0xcb20, 0xcb3c, 0xcb40, 0xcb78, 0xcb86, 0xcb8c, 0xcb98, 0xcbb0, 0xcbbe, 0xcbce, 0xcbdc, 0xcbe2, 0xcbe4, 0xcbe8, 0xcbf6, 0xcc16, 0xcc26, 0xcc2c, 0xcc3a, 0xcc46, 0xcc58, 0xcc72, 0xcc74, 0xcc86, 0xccb0, 0xccbe, 0xccce, 0xcce2, 0xcce4, 0xcce8, 0xcd06, 0xcd0c, 0xcd18, 0xcd30, 0xcd3e, 0xcd60, 0xcd7c, 0xcd9c, 0xcdc2, 0xcdc4, 0xcdc8, 0xcdd0, 0xcdde, 0xcde6, 0xcdfa, 0xce22, 0xce28, 0xce42, 0xce50, 0xce5e, 0xce66, 0xce7a, 0xce82, 0xce84, 0xce88, 0xce90, 0xce9e, 0xcea0, 0xcebc, 0xcecc, 0xcef2, 0xcef4, 0xcf2e, 0xcf32, 0xcf34, 0xcf4e, 0xcf5c, 0xcf62, 0xcf64, 0xcf68, 0xcf96, 0xcfa6, 0xcfac, 0xcfca, 0xcfd2, 0xcfd4, 0xd02e, 0xd032, 0xd034, 0xd04e, 0xd05c, 0xd062, 0xd064, 0xd068, 0xd076, 0xd08e, 0xd09c, 0xd0b8, 0xd0c2, 0xd0c4, 0xd0c8, 0xd0d0, 0xd0de, 0xd0e6, 0xd0ec, 0xd0fa, 0xd11c, 0xd138, 0xd170, 0xd17e, 0xd182, 0xd184, 0xd188, 0xd190, 0xd19e, 0xd1a0, 0xd1bc, 0xd1c6, 0xd1cc, 0xd1d8, 0xd1ee, 0xd1f2, 0xd1f4, 0xd21c, 0xd238, 0xd270, 0xd27e, 0xd2e0, 0xd2fc, 0xd302, 0xd304, 0xd308, 0xd310, 0xd31e, 0xd320, 0xd33c, 0xd340, 0xd378, 0xd386, 0xd38c, 0xd398, 0xd3b0, 0xd3be, 0xd3ce, 0xd3dc, 0xd3e2, 0xd3e4, 0xd3e8, 0xd3f6, 0xd470, 0xd47e, 0xd4e0, 0xd4fc, 0xd5c0, 0xd5f8, 0xd604, 0xd608, 0xd610, 0xd620, 0xd640, 0xd678, 0xd6f0, 0xd706, 0xd70c, 0xd718, 0xd730, 0xd73e, 0xd760, 0xd77c, 0xd78e, 0xd79c, 0xd7b8, 0xd7c2, 0xd7c4, 0xd7c8, 0xd7d0, 0xd7de, 0xd7e6, 0xd7ec, 0xd826, 0xd82c, 0xd83a, 0xd846, 0xd84c, 0xd858, 0xd872, 0xd874, 0xd886, 0xd88c, 0xd898, 0xd8b0, 0xd8be, 0xd8ce, 0xd8e2, 0xd8e4, 0xd8e8, 0xd8f6, 0xd90c, 0xd918, 0xd930, 0xd93e, 0xd960, 0xd97c, 0xd99c, 0xd9c2, 0xd9c4, 0xd9c8, 0xd9d0, 0xd9e6, 0xd9fa, 0xda0c, 0xda18, 0xda30, 0xda3e, 0xda60, 0xda7c, 0xdac0, 0xdaf8, 0xdb38, 0xdb82, 0xdb84, 0xdb88, 0xdb90, 0xdb9e, 0xdba0, 0xdbcc, 0xdbf2, 0xdbf4, 0xdc22, 0xdc42, 0xdc44, 0xdc48, 0xdc50, 0xdc5e, 0xdc66, 0xdc7a, 0xdc82, 0xdc84, 0xdc88, 0xdc90, 0xdc9e, 0xdca0, 0xdcbc, 0xdccc, 0xdcf2, 0xdcf4, 0xdd04, 0xdd08, 0xdd10, 0xdd1e, 0xdd20, 0xdd3c, 0xdd40, 0xdd78, 0xdd86, 0xdd98, 0xddce, 0xdde2, 0xdde4, 0xdde8, 0xde2e, 0xde32, 0xde34, 0xde4e, 0xde5c, 0xde62, 0xde64, 0xde68, 0xde8e, 0xde9c, 0xdeb8, 0xdec2, 0xdec4, 0xdec8, 0xded0, 0xdee6, 0xdefa, 0xdf16, 0xdf26, 0xdf2c, 0xdf46, 0xdf4c, 0xdf58, 0xdf72, 0xdf74, 0xdf8a, 0xdf92, 0xdf94, 0xdfa2, 0xdfa4, 0xdfa8, 0xe08a, 0xe092, 0xe094, 0xe0a2, 0xe0a4, 0xe0a8, 0xe0b6, 0xe0da, 0xe10a, 0xe112, 0xe114, 0xe122, 0xe124, 0xe128, 0xe136, 0xe142, 0xe144, 0xe148, 0xe150, 0xe166, 0xe16c, 0xe17a, 0xe19a, 0xe1b2, 0xe1b4, 0xe20a, 0xe212, 0xe214, 0xe222, 0xe224, 0xe228, 0xe236, 0xe242, 0xe248, 0xe250, 0xe25e, 0xe266, 0xe26c, 0xe27a, 0xe282, 0xe284, 0xe288, 0xe290, 0xe2a0, 0xe2bc, 0xe2c6, 0xe2cc, 0xe2d8, 0xe2ee, 0xe2f2, 0xe2f4, 0xe31a, 0xe332, 0xe334, 0xe35c, 0xe362, 0xe364, 0xe368, 0xe3ba, 0xe40a, 0xe412, 0xe414, 0xe422, 0xe428, 0xe436, 0xe442, 0xe448, 0xe450, 0xe45e, 0xe466, 0xe46c, 0xe47a, 0xe482, 0xe484, 0xe490, 0xe49e, 0xe4a0, 0xe4bc, 0xe4c6, 0xe4cc, 0xe4d8, 0xe4ee, 0xe4f2, 0xe4f4, 0xe502, 0xe504, 0xe508, 0xe510, 0xe51e, 0xe520, 0xe53c, 0xe540, 0xe578, 0xe586, 0xe58c, 0xe598, 0xe5b0, 0xe5be, 0xe5ce, 0xe5dc, 0xe5e2, 0xe5e4, 0xe5e8, 0xe5f6, 0xe61a, 0xe62e, 0xe632, 0xe634, 0xe64e, 0xe65c, 0xe662, 0xe668, 0xe68e, 0xe69c, 0xe6b8, 0xe6c2, 0xe6c4, 0xe6c8, 0xe6d0, 0xe6e6, 0xe6fa, 0xe716, 0xe726, 0xe72c, 0xe73a, 0xe746, 0xe74c, 0xe758, 0xe772, 0xe774, 0xe792, 0xe794, 0xe7a2, 0xe7a4, 0xe7a8, 0xe7b6, 0xe812, 0xe814, 0xe822, 0xe824, 0xe828, 0xe836, 0xe842, 0xe844, 0xe848, 0xe850, 0xe85e, 0xe866, 0xe86c, 0xe87a, 0xe882, 0xe884, 0xe888, 0xe890, 0xe89e, 0xe8a0, 0xe8bc, 0xe8c6, 0xe8cc, 0xe8d8, 0xe8ee, 0xe8f2, 0xe8f4, 0xe902, 0xe904, 0xe908, 0xe910, 0xe920, 0xe93c, 0xe940, 0xe978, 0xe986, 0xe98c, 0xe998, 0xe9b0, 0xe9be, 0xe9ce, 0xe9dc, 0xe9e2, 0xe9e4, 0xe9e8, 0xe9f6, 0xea04, 0xea08, 0xea10, 0xea20, 0xea40, 0xea78, 0xeaf0, 0xeb06, 0xeb0c, 0xeb18, 0xeb30, 0xeb3e, 0xeb60, 0xeb7c, 0xeb8e, 0xeb9c, 0xebb8, 0xebc2, 0xebc4, 0xebc8, 0xebd0, 0xebde, 0xebe6, 0xebec, 0xec1a, 0xec2e, 0xec32, 0xec34, 0xec4e, 0xec5c, 0xec62, 0xec64, 0xec68, 0xec8e, 0xec9c, 0xecb8, 0xecc2, 0xecc4, 0xecc8, 0xecd0, 0xece6, 0xecfa, 0xed0e, 0xed1c, 0xed38, 0xed70, 0xed7e, 0xed82, 0xed84, 0xed88, 0xed90, 0xed9e, 0xeda0, 0xedcc, 0xedf2, 0xedf4, 0xee16, 0xee26, 0xee2c, 0xee3a, 0xee46, 0xee4c, 0xee58, 0xee6e, 0xee72, 0xee74, 0xee86, 0xee8c, 0xee98, 0xeeb0, 0xeebe, 0xeece, 0xeedc, 0xeee2, 0xeee4, 0xeee8, 0xef12, 0xef22, 0xef24, 0xef28, 0xef36, 0xef42, 0xef44, 0xef48, 0xef50, 0xef5e, 0xef66, 0xef6c, 0xef7a, 0xefae, 0xefb2, 0xefb4, 0xefd6, 0xf096, 0xf0a6, 0xf0ac, 0xf0ba, 0xf0ca, 0xf0d2, 0xf0d4, 0xf116, 0xf126, 0xf12c, 0xf13a, 0xf146, 0xf14c, 0xf158, 0xf16e, 0xf172, 0xf174, 0xf18a, 0xf192, 0xf194, 0xf1a2, 0xf1a4, 0xf1a8, 0xf1da, 0xf216, 0xf226, 0xf22c, 0xf23a, 0xf246, 0xf258, 0xf26e, 0xf272, 0xf274, 0xf286, 0xf28c, 0xf298, 0xf2b0, 0xf2be, 0xf2ce, 0xf2dc, 0xf2e2, 0xf2e4, 0xf2e8, 0xf2f6, 0xf30a, 0xf312, 0xf314, 0xf322, 0xf328, 0xf342, 0xf344, 0xf348, 0xf350, 0xf35e, 0xf366, 0xf37a, 0xf39a, 0xf3ae, 0xf3b2, 0xf3b4, 0xf416, 0xf426, 0xf42c, 0xf43a, 0xf446, 0xf44c, 0xf458, 0xf46e, 0xf472, 0xf474, 0xf486, 0xf48c, 0xf498, 0xf4b0, 0xf4be, 0xf4ce, 0xf4dc, 0xf4e2, 0xf4e4, 0xf4e8, 0xf4f6, 0xf506, 0xf50c, 0xf518, 0xf530, 0xf53e, 0xf560, 0xf57c, 0xf58e, 0xf59c, 0xf5b8, 0xf5c2, 0xf5c4, 0xf5c8, 0xf5d0, 0xf5de, 0xf5e6, 0xf5ec, 0xf5fa, 0xf60a, 0xf612, 0xf614, 0xf622, 0xf624, 0xf628, 0xf636, 0xf642, 0xf644, 0xf648, 0xf650, 0xf65e, 0xf666, 0xf67a, 0xf682, 0xf684, 0xf688, 0xf690, 0xf69e, 0xf6a0, 0xf6bc, 0xf6cc, 0xf6f2, 0xf6f4, 0xf71a, 0xf72e, 0xf732, 0xf734, 0xf74e, 0xf75c, 0xf762, 0xf764, 0xf768, 0xf776, 0xf796, 0xf7a6, 0xf7ac, 0xf7ba, 0xf7d2, 0xf7d4, 0xf89a, 0xf8ae, 0xf8b2, 0xf8b4, 0xf8d6, 0xf8ea, 0xf91a, 0xf92e, 0xf932, 0xf934, 0xf94e, 0xf95c, 0xf962, 0xf964, 0xf968, 0xf976, 0xf996, 0xf9a6, 0xf9ac, 0xf9ba, 0xf9ca, 0xf9d2, 0xf9d4, 0xfa1a, 0xfa2e, 0xfa32, 0xfa34, 0xfa4e, 0xfa5c, 0xfa62, 0xfa64, 0xfa68, 0xfa76, 0xfa8e, 0xfa9c, 0xfab8, 0xfac2, 0xfac4, 0xfac8, 0xfad0, 0xfade, 0xfae6, 0xfaec, 0xfb16, 0xfb26, 0xfb2c, 0xfb3a, 0xfb46, 0xfb4c, 0xfb58, 0xfb6e, 0xfb72, 0xfb74, 0xfb8a, 0xfb92, 0xfb94, 0xfba2, 0xfba4, 0xfba8, 0xfbb6, 0xfbda }; /** * This table contains to codewords for all symbols. */ static constexpr const std::array<uint16_t, 2787> CODEWORD_TABLE = { 2627, 1819, 2622, 2621, 1813, 1812, 2729, 2724, 2723, 2779, 2774, 2773, 902, 896, 908, 868, 865, 861, 859, 2511, 873, 871, 1780, 835, 2493, 825, 2491, 842, 837, 844, 1764, 1762, 811, 810, 809, 2483, 807, 2482, 806, 2480, 815, 814, 813, 812, 2484, 817, 816, 1745, 1744, 1742, 1746, 2655, 2637, 2635, 2626, 2625, 2623, 2628, 1820, 2752, 2739, 2737, 2728, 2727, 2725, 2730, 2785, 2783, 2778, 2777, 2775, 2780, 787, 781, 747, 739, 736, 2413, 754, 752, 1719, 692, 689, 681, 2371, 678, 2369, 700, 697, 694, 703, 1688, 1686, 642, 638, 2343, 631, 2341, 627, 2338, 651, 646, 643, 2345, 654, 652, 1652, 1650, 1647, 1654, 601, 599, 2322, 596, 2321, 594, 2319, 2317, 611, 610, 608, 606, 2324, 603, 2323, 615, 614, 612, 1617, 1616, 1614, 1612, 616, 1619, 1618, 2575, 2538, 2536, 905, 901, 898, 909, 2509, 2507, 2504, 870, 867, 864, 860, 2512, 875, 872, 1781, 2490, 2489, 2487, 2485, 1748, 836, 834, 832, 830, 2494, 827, 2492, 843, 841, 839, 845, 1765, 1763, 2701, 2676, 2674, 2653, 2648, 2656, 2634, 2633, 2631, 2629, 1821, 2638, 2636, 2770, 2763, 2761, 2750, 2745, 2753, 2736, 2735, 2733, 2731, 1848, 2740, 2738, 2786, 2784, 591, 588, 576, 569, 566, 2296, 1590, 537, 534, 526, 2276, 522, 2274, 545, 542, 539, 548, 1572, 1570, 481, 2245, 466, 2242, 462, 2239, 492, 485, 482, 2249, 496, 494, 1534, 1531, 1528, 1538, 413, 2196, 406, 2191, 2188, 425, 419, 2202, 415, 2199, 432, 430, 427, 1472, 1467, 1464, 433, 1476, 1474, 368, 367, 2160, 365, 2159, 362, 2157, 2155, 2152, 378, 377, 375, 2166, 372, 2165, 369, 2162, 383, 381, 379, 2168, 1419, 1418, 1416, 1414, 385, 1411, 384, 1423, 1422, 1420, 1424, 2461, 802, 2441, 2439, 790, 786, 783, 794, 2409, 2406, 2403, 750, 742, 738, 2414, 756, 753, 1720, 2367, 2365, 2362, 2359, 1663, 693, 691, 684, 2373, 680, 2370, 702, 699, 696, 704, 1690, 1687, 2337, 2336, 2334, 2332, 1624, 2329, 1622, 640, 637, 2344, 634, 2342, 630, 2340, 650, 648, 645, 2346, 655, 653, 1653, 1651, 1649, 1655, 2612, 2597, 2595, 2571, 2568, 2565, 2576, 2534, 2529, 2526, 1787, 2540, 2537, 907, 904, 900, 910, 2503, 2502, 2500, 2498, 1768, 2495, 1767, 2510, 2508, 2506, 869, 866, 863, 2513, 876, 874, 1782, 2720, 2713, 2711, 2697, 2694, 2691, 2702, 2672, 2670, 2664, 1828, 2678, 2675, 2647, 2646, 2644, 2642, 1823, 2639, 1822, 2654, 2652, 2650, 2657, 2771, 1855, 2765, 2762, 1850, 1849, 2751, 2749, 2747, 2754, 353, 2148, 344, 342, 336, 2142, 332, 2140, 345, 1375, 1373, 306, 2130, 299, 2128, 295, 2125, 319, 314, 311, 2132, 1354, 1352, 1349, 1356, 262, 257, 2101, 253, 2096, 2093, 274, 273, 267, 2107, 263, 2104, 280, 278, 275, 1316, 1311, 1308, 1320, 1318, 2052, 202, 2050, 2044, 2040, 219, 2063, 212, 2060, 208, 2055, 224, 221, 2066, 1260, 1258, 1252, 231, 1248, 229, 1266, 1264, 1261, 1268, 155, 1998, 153, 1996, 1994, 1991, 1988, 165, 164, 2007, 162, 2006, 159, 2003, 2000, 172, 171, 169, 2012, 166, 2010, 1186, 1184, 1182, 1179, 175, 1176, 173, 1192, 1191, 1189, 1187, 176, 1194, 1193, 2313, 2307, 2305, 592, 589, 2294, 2292, 2289, 578, 572, 568, 2297, 580, 1591, 2272, 2267, 2264, 1547, 538, 536, 529, 2278, 525, 2275, 547, 544, 541, 1574, 1571, 2237, 2235, 2229, 1493, 2225, 1489, 478, 2247, 470, 2244, 465, 2241, 493, 488, 484, 2250, 498, 495, 1536, 1533, 1530, 1539, 2187, 2186, 2184, 2182, 1432, 2179, 1430, 2176, 1427, 414, 412, 2197, 409, 2195, 405, 2193, 2190, 426, 424, 421, 2203, 418, 2201, 431, 429, 1473, 1471, 1469, 1466, 434, 1477, 1475, 2478, 2472, 2470, 2459, 2457, 2454, 2462, 803, 2437, 2432, 2429, 1726, 2443, 2440, 792, 789, 785, 2401, 2399, 2393, 1702, 2389, 1699, 2411, 2408, 2405, 745, 741, 2415, 758, 755, 1721, 2358, 2357, 2355, 2353, 1661, 2350, 1660, 2347, 1657, 2368, 2366, 2364, 2361, 1666, 690, 687, 2374, 683, 2372, 701, 698, 705, 1691, 1689, 2619, 2617, 2610, 2608, 2605, 2613, 2593, 2588, 2585, 1803, 2599, 2596, 2563, 2561, 2555, 1797, 2551, 1795, 2573, 2570, 2567, 2577, 2525, 2524, 2522, 2520, 1786, 2517, 1785, 2514, 1783, 2535, 2533, 2531, 2528, 1788, 2541, 2539, 906, 903, 911, 2721, 1844, 2715, 2712, 1838, 1836, 2699, 2696, 2693, 2703, 1827, 1826, 1824, 2673, 2671, 2669, 2666, 1829, 2679, 2677, 1858, 1857, 2772, 1854, 1853, 1851, 1856, 2766, 2764, 143, 1987, 139, 1986, 135, 133, 131, 1984, 128, 1983, 125, 1981, 138, 137, 136, 1985, 1133, 1132, 1130, 112, 110, 1974, 107, 1973, 104, 1971, 1969, 122, 121, 119, 117, 1977, 114, 1976, 124, 1115, 1114, 1112, 1110, 1117, 1116, 84, 83, 1953, 81, 1952, 78, 1950, 1948, 1945, 94, 93, 91, 1959, 88, 1958, 85, 1955, 99, 97, 95, 1961, 1086, 1085, 1083, 1081, 1078, 100, 1090, 1089, 1087, 1091, 49, 47, 1917, 44, 1915, 1913, 1910, 1907, 59, 1926, 56, 1925, 53, 1922, 1919, 66, 64, 1931, 61, 1929, 1042, 1040, 1038, 71, 1035, 70, 1032, 68, 1048, 1047, 1045, 1043, 1050, 1049, 12, 10, 1869, 1867, 1864, 1861, 21, 1880, 19, 1877, 1874, 1871, 28, 1888, 25, 1886, 22, 1883, 982, 980, 977, 974, 32, 30, 991, 989, 987, 984, 34, 995, 994, 992, 2151, 2150, 2147, 2146, 2144, 356, 355, 354, 2149, 2139, 2138, 2136, 2134, 1359, 343, 341, 338, 2143, 335, 2141, 348, 347, 346, 1376, 1374, 2124, 2123, 2121, 2119, 1326, 2116, 1324, 310, 308, 305, 2131, 302, 2129, 298, 2127, 320, 318, 316, 313, 2133, 322, 321, 1355, 1353, 1351, 1357, 2092, 2091, 2089, 2087, 1276, 2084, 1274, 2081, 1271, 259, 2102, 256, 2100, 252, 2098, 2095, 272, 269, 2108, 266, 2106, 281, 279, 277, 1317, 1315, 1313, 1310, 282, 1321, 1319, 2039, 2037, 2035, 2032, 1203, 2029, 1200, 1197, 207, 2053, 205, 2051, 201, 2049, 2046, 2043, 220, 218, 2064, 215, 2062, 211, 2059, 228, 226, 223, 2069, 1259, 1257, 1254, 232, 1251, 230, 1267, 1265, 1263, 2316, 2315, 2312, 2311, 2309, 2314, 2304, 2303, 2301, 2299, 1593, 2308, 2306, 590, 2288, 2287, 2285, 2283, 1578, 2280, 1577, 2295, 2293, 2291, 579, 577, 574, 571, 2298, 582, 581, 1592, 2263, 2262, 2260, 2258, 1545, 2255, 1544, 2252, 1541, 2273, 2271, 2269, 2266, 1550, 535, 532, 2279, 528, 2277, 546, 543, 549, 1575, 1573, 2224, 2222, 2220, 1486, 2217, 1485, 2214, 1482, 1479, 2238, 2236, 2234, 2231, 1496, 2228, 1492, 480, 477, 2248, 473, 2246, 469, 2243, 490, 487, 2251, 497, 1537, 1535, 1532, 2477, 2476, 2474, 2479, 2469, 2468, 2466, 2464, 1730, 2473, 2471, 2453, 2452, 2450, 2448, 1729, 2445, 1728, 2460, 2458, 2456, 2463, 805, 804, 2428, 2427, 2425, 2423, 1725, 2420, 1724, 2417, 1722, 2438, 2436, 2434, 2431, 1727, 2444, 2442, 793, 791, 788, 795, 2388, 2386, 2384, 1697, 2381, 1696, 2378, 1694, 1692, 2402, 2400, 2398, 2395, 1703, 2392, 1701, 2412, 2410, 2407, 751, 748, 744, 2416, 759, 757, 1807, 2620, 2618, 1806, 1805, 2611, 2609, 2607, 2614, 1802, 1801, 1799, 2594, 2592, 2590, 2587, 1804, 2600, 2598, 1794, 1793, 1791, 1789, 2564, 2562, 2560, 2557, 1798, 2554, 1796, 2574, 2572, 2569, 2578, 1847, 1846, 2722, 1843, 1842, 1840, 1845, 2716, 2714, 1835, 1834, 1832, 1830, 1839, 1837, 2700, 2698, 2695, 2704, 1817, 1811, 1810, 897, 862, 1777, 829, 826, 838, 1760, 1758, 808, 2481, 1741, 1740, 1738, 1743, 2624, 1818, 2726, 2776, 782, 740, 737, 1715, 686, 679, 695, 1682, 1680, 639, 628, 2339, 647, 644, 1645, 1643, 1640, 1648, 602, 600, 597, 595, 2320, 593, 2318, 609, 607, 604, 1611, 1610, 1608, 1606, 613, 1615, 1613, 2328, 926, 924, 892, 886, 899, 857, 850, 2505, 1778, 824, 823, 821, 819, 2488, 818, 2486, 833, 831, 828, 840, 1761, 1759, 2649, 2632, 2630, 2746, 2734, 2732, 2782, 2781, 570, 567, 1587, 531, 527, 523, 540, 1566, 1564, 476, 467, 463, 2240, 486, 483, 1524, 1521, 1518, 1529, 411, 403, 2192, 399, 2189, 423, 416, 1462, 1457, 1454, 428, 1468, 1465, 2210, 366, 363, 2158, 360, 2156, 357, 2153, 376, 373, 370, 2163, 1410, 1409, 1407, 1405, 382, 1402, 380, 1417, 1415, 1412, 1421, 2175, 2174, 777, 774, 771, 784, 732, 725, 722, 2404, 743, 1716, 676, 674, 668, 2363, 665, 2360, 685, 1684, 1681, 626, 624, 622, 2335, 620, 2333, 617, 2330, 641, 635, 649, 1646, 1644, 1642, 2566, 928, 925, 2530, 2527, 894, 891, 888, 2501, 2499, 2496, 858, 856, 854, 851, 1779, 2692, 2668, 2665, 2645, 2643, 2640, 2651, 2768, 2759, 2757, 2744, 2743, 2741, 2748, 352, 1382, 340, 337, 333, 1371, 1369, 307, 300, 296, 2126, 315, 312, 1347, 1342, 1350, 261, 258, 250, 2097, 246, 2094, 271, 268, 264, 1306, 1301, 1298, 276, 1312, 1309, 2115, 203, 2048, 195, 2045, 191, 2041, 213, 209, 2056, 1246, 1244, 1238, 225, 1234, 222, 1256, 1253, 1249, 1262, 2080, 2079, 154, 1997, 150, 1995, 147, 1992, 1989, 163, 160, 2004, 156, 2001, 1175, 1174, 1172, 1170, 1167, 170, 1164, 167, 1185, 1183, 1180, 1177, 174, 1190, 1188, 2025, 2024, 2022, 587, 586, 564, 559, 556, 2290, 573, 1588, 520, 518, 512, 2268, 508, 2265, 530, 1568, 1565, 461, 457, 2233, 450, 2230, 446, 2226, 479, 471, 489, 1526, 1523, 1520, 397, 395, 2185, 392, 2183, 389, 2180, 2177, 410, 2194, 402, 422, 1463, 1461, 1459, 1456, 1470, 2455, 799, 2433, 2430, 779, 776, 773, 2397, 2394, 2390, 734, 728, 724, 746, 1717, 2356, 2354, 2351, 2348, 1658, 677, 675, 673, 670, 667, 688, 1685, 1683, 2606, 2589, 2586, 2559, 2556, 2552, 927, 2523, 2521, 2518, 2515, 1784, 2532, 895, 893, 890, 2718, 2709, 2707, 2689, 2687, 2684, 2663, 2662, 2660, 2658, 1825, 2667, 2769, 1852, 2760, 2758, 142, 141, 1139, 1138, 134, 132, 129, 126, 1982, 1129, 1128, 1126, 1131, 113, 111, 108, 105, 1972, 101, 1970, 120, 118, 115, 1109, 1108, 1106, 1104, 123, 1113, 1111, 82, 79, 1951, 75, 1949, 72, 1946, 92, 89, 86, 1956, 1077, 1076, 1074, 1072, 98, 1069, 96, 1084, 1082, 1079, 1088, 1968, 1967, 48, 45, 1916, 42, 1914, 39, 1911, 1908, 60, 57, 54, 1923, 50, 1920, 1031, 1030, 1028, 1026, 67, 1023, 65, 1020, 62, 1041, 1039, 1036, 1033, 69, 1046, 1044, 1944, 1943, 1941, 11, 9, 1868, 7, 1865, 1862, 1859, 20, 1878, 16, 1875, 13, 1872, 970, 968, 966, 963, 29, 960, 26, 23, 983, 981, 978, 975, 33, 971, 31, 990, 988, 985, 1906, 1904, 1902, 993, 351, 2145, 1383, 331, 330, 328, 326, 2137, 323, 2135, 339, 1372, 1370, 294, 293, 291, 289, 2122, 286, 2120, 283, 2117, 309, 303, 317, 1348, 1346, 1344, 245, 244, 242, 2090, 239, 2088, 236, 2085, 2082, 260, 2099, 249, 270, 1307, 1305, 1303, 1300, 1314, 189, 2038, 186, 2036, 183, 2033, 2030, 2026, 206, 198, 2047, 194, 216, 1247, 1245, 1243, 1240, 227, 1237, 1255, 2310, 2302, 2300, 2286, 2284, 2281, 565, 563, 561, 558, 575, 1589, 2261, 2259, 2256, 2253, 1542, 521, 519, 517, 514, 2270, 511, 533, 1569, 1567, 2223, 2221, 2218, 2215, 1483, 2211, 1480, 459, 456, 453, 2232, 449, 474, 491, 1527, 1525, 1522, 2475, 2467, 2465, 2451, 2449, 2446, 801, 800, 2426, 2424, 2421, 2418, 1723, 2435, 780, 778, 775, 2387, 2385, 2382, 2379, 1695, 2375, 1693, 2396, 735, 733, 730, 727, 749, 1718, 2616, 2615, 2604, 2603, 2601, 2584, 2583, 2581, 2579, 1800, 2591, 2550, 2549, 2547, 2545, 1792, 2542, 1790, 2558, 929, 2719, 1841, 2710, 2708, 1833, 1831, 2690, 2688, 2686, 1815, 1809, 1808, 1774, 1756, 1754, 1737, 1736, 1734, 1739, 1816, 1711, 1676, 1674, 633, 629, 1638, 1636, 1633, 1641, 598, 1605, 1604, 1602, 1600, 605, 1609, 1607, 2327, 887, 853, 1775, 822, 820, 1757, 1755, 1584, 524, 1560, 1558, 468, 464, 1514, 1511, 1508, 1519, 408, 404, 400, 1452, 1447, 1444, 417, 1458, 1455, 2208, 364, 361, 358, 2154, 1401, 1400, 1398, 1396, 374, 1393, 371, 1408, 1406, 1403, 1413, 2173, 2172, 772, 726, 723, 1712, 672, 669, 666, 682, 1678, 1675, 625, 623, 621, 618, 2331, 636, 632, 1639, 1637, 1635, 920, 918, 884, 880, 889, 849, 848, 847, 846, 2497, 855, 852, 1776, 2641, 2742, 2787, 1380, 334, 1367, 1365, 301, 297, 1340, 1338, 1335, 1343, 255, 251, 247, 1296, 1291, 1288, 265, 1302, 1299, 2113, 204, 196, 192, 2042, 1232, 1230, 1224, 214, 1220, 210, 1242, 1239, 1235, 1250, 2077, 2075, 151, 148, 1993, 144, 1990, 1163, 1162, 1160, 1158, 1155, 161, 1152, 157, 1173, 1171, 1168, 1165, 168, 1181, 1178, 2021, 2020, 2018, 2023, 585, 560, 557, 1585, 516, 509, 1562, 1559, 458, 447, 2227, 472, 1516, 1513, 1510, 398, 396, 393, 390, 2181, 386, 2178, 407, 1453, 1451, 1449, 1446, 420, 1460, 2209, 769, 764, 720, 712, 2391, 729, 1713, 664, 663, 661, 659, 2352, 656, 2349, 671, 1679, 1677, 2553, 922, 919, 2519, 2516, 885, 883, 881, 2685, 2661, 2659, 2767, 2756, 2755, 140, 1137, 1136, 130, 127, 1125, 1124, 1122, 1127, 109, 106, 102, 1103, 1102, 1100, 1098, 116, 1107, 1105, 1980, 80, 76, 73, 1947, 1068, 1067, 1065, 1063, 90, 1060, 87, 1075, 1073, 1070, 1080, 1966, 1965, 46, 43, 40, 1912, 36, 1909, 1019, 1018, 1016, 1014, 58, 1011, 55, 1008, 51, 1029, 1027, 1024, 1021, 63, 1037, 1034, 1940, 1939, 1937, 1942, 8, 1866, 4, 1863, 1, 1860, 956, 954, 952, 949, 946, 17, 14, 969, 967, 964, 961, 27, 957, 24, 979, 976, 972, 1901, 1900, 1898, 1896, 986, 1905, 1903, 350, 349, 1381, 329, 327, 324, 1368, 1366, 292, 290, 287, 284, 2118, 304, 1341, 1339, 1337, 1345, 243, 240, 237, 2086, 233, 2083, 254, 1297, 1295, 1293, 1290, 1304, 2114, 190, 187, 184, 2034, 180, 2031, 177, 2027, 199, 1233, 1231, 1229, 1226, 217, 1223, 1241, 2078, 2076, 584, 555, 554, 552, 550, 2282, 562, 1586, 507, 506, 504, 502, 2257, 499, 2254, 515, 1563, 1561, 445, 443, 441, 2219, 438, 2216, 435, 2212, 460, 454, 475, 1517, 1515, 1512, 2447, 798, 797, 2422, 2419, 770, 768, 766, 2383, 2380, 2376, 721, 719, 717, 714, 731, 1714, 2602, 2582, 2580, 2548, 2546, 2543, 923, 921, 2717, 2706, 2705, 2683, 2682, 2680, 1771, 1752, 1750, 1733, 1732, 1731, 1735, 1814, 1707, 1670, 1668, 1631, 1629, 1626, 1634, 1599, 1598, 1596, 1594, 1603, 1601, 2326, 1772, 1753, 1751, 1581, 1554, 1552, 1504, 1501, 1498, 1509, 1442, 1437, 1434, 401, 1448, 1445, 2206, 1392, 1391, 1389, 1387, 1384, 359, 1399, 1397, 1394, 1404, 2171, 2170, 1708, 1672, 1669, 619, 1632, 1630, 1628, 1773, 1378, 1363, 1361, 1333, 1328, 1336, 1286, 1281, 1278, 248, 1292, 1289, 2111, 1218, 1216, 1210, 197, 1206, 193, 1228, 1225, 1221, 1236, 2073, 2071, 1151, 1150, 1148, 1146, 152, 1143, 149, 1140, 145, 1161, 1159, 1156, 1153, 158, 1169, 1166, 2017, 2016, 2014, 2019, 1582, 510, 1556, 1553, 452, 448, 1506, 1500, 394, 391, 387, 1443, 1441, 1439, 1436, 1450, 2207, 765, 716, 713, 1709, 662, 660, 657, 1673, 1671, 916, 914, 879, 878, 877, 882, 1135, 1134, 1121, 1120, 1118, 1123, 1097, 1096, 1094, 1092, 103, 1101, 1099, 1979, 1059, 1058, 1056, 1054, 77, 1051, 74, 1066, 1064, 1061, 1071, 1964, 1963, 1007, 1006, 1004, 1002, 999, 41, 996, 37, 1017, 1015, 1012, 1009, 52, 1025, 1022, 1936, 1935, 1933, 1938, 942, 940, 938, 935, 932, 5, 2, 955, 953, 950, 947, 18, 943, 15, 965, 962, 958, 1895, 1894, 1892, 1890, 973, 1899, 1897, 1379, 325, 1364, 1362, 288, 285, 1334, 1332, 1330, 241, 238, 234, 1287, 1285, 1283, 1280, 1294, 2112, 188, 185, 181, 178, 2028, 1219, 1217, 1215, 1212, 200, 1209, 1227, 2074, 2072, 583, 553, 551, 1583, 505, 503, 500, 513, 1557, 1555, 444, 442, 439, 436, 2213, 455, 451, 1507, 1505, 1502, 796, 763, 762, 760, 767, 711, 710, 708, 706, 2377, 718, 715, 1710, 2544, 917, 915, 2681, 1627, 1597, 1595, 2325, 1769, 1749, 1747, 1499, 1438, 1435, 2204, 1390, 1388, 1385, 1395, 2169, 2167, 1704, 1665, 1662, 1625, 1623, 1620, 1770, 1329, 1282, 1279, 2109, 1214, 1207, 1222, 2068, 2065, 1149, 1147, 1144, 1141, 146, 1157, 1154, 2013, 2011, 2008, 2015, 1579, 1549, 1546, 1495, 1487, 1433, 1431, 1428, 1425, 388, 1440, 2205, 1705, 658, 1667, 1664, 1119, 1095, 1093, 1978, 1057, 1055, 1052, 1062, 1962, 1960, 1005, 1003, 1000, 997, 38, 1013, 1010, 1932, 1930, 1927, 1934, 941, 939, 936, 933, 6, 930, 3, 951, 948, 944, 1889, 1887, 1884, 1881, 959, 1893, 1891, 35, 1377, 1360, 1358, 1327, 1325, 1322, 1331, 1277, 1275, 1272, 1269, 235, 1284, 2110, 1205, 1204, 1201, 1198, 182, 1195, 179, 1213, 2070, 2067, 1580, 501, 1551, 1548, 440, 437, 1497, 1494, 1490, 1503, 761, 709, 707, 1706, 913, 912, 2198, 1386, 2164, 2161, 1621, 1766, 2103, 1208, 2058, 2054, 1145, 1142, 2005, 2002, 1999, 2009, 1488, 1429, 1426, 2200, 1698, 1659, 1656, 1975, 1053, 1957, 1954, 1001, 998, 1924, 1921, 1918, 1928, 937, 934, 931, 1879, 1876, 1873, 1870, 945, 1885, 1882, 1323, 1273, 1270, 2105, 1202, 1199, 1196, 1211, 2061, 2057, 1576, 1543, 1540, 1484, 1481, 1478, 1491, 1700 }; using ModuleBitCountType = std::array<int, CodewordDecoder::BARS_IN_MODULE>; static ModuleBitCountType SampleBitCounts(const ModuleBitCountType& moduleBitCount) { float bitCountSum = static_cast<float>(Reduce(moduleBitCount)); ModuleBitCountType result; result.fill(0); int bitCountIndex = 0; int sumPreviousBits = 0; for (int i = 0; i < CodewordDecoder::MODULES_IN_CODEWORD; i++) { float sampleIndex = bitCountSum / (2 * CodewordDecoder::MODULES_IN_CODEWORD) + (i * bitCountSum) / CodewordDecoder::MODULES_IN_CODEWORD; if (sumPreviousBits + moduleBitCount[bitCountIndex] <= sampleIndex) { sumPreviousBits += moduleBitCount[bitCountIndex]; bitCountIndex++; if (bitCountIndex == Size(moduleBitCount)) { // this check is not done in original code, so I guess this should not happen? break; } } result[bitCountIndex]++; } return result; } static int GetBitValue(const ModuleBitCountType& moduleBitCount) { int result = 0; for (size_t i = 0; i < moduleBitCount.size(); i++) for (int bit = 0; bit < moduleBitCount[i]; bit++) AppendBit(result, i % 2 == 0); return result; } static int GetDecodedCodewordValue(const ModuleBitCountType& moduleBitCount) { int decodedValue = GetBitValue(moduleBitCount); return CodewordDecoder::GetCodeword(decodedValue) == -1 ? -1 : decodedValue; } static constexpr int getSymbol(int idx) { return SYMBOL_TABLE[idx] | 0x10000; } static int GetClosestDecodedValue(const ModuleBitCountType& moduleBitCount) { #if 1 // put 87kB on heap and calucate per process on first use -> 7% smaller binary static const auto ratioTable = []() { auto table = std::vector<std::array<float, CodewordDecoder::BARS_IN_MODULE>>(SYMBOL_COUNT); #else // put 87kB in .rodata shared by all processes and calcuate during compilation static constexpr const auto ratioTable = []() constexpr { auto table = std::array<std::array<float, CodewordDecoder::BARS_IN_MODULE>, SYMBOL_COUNT>(); #endif for (int i = 0; i < SYMBOL_COUNT; i++) { int currentSymbol = getSymbol(i); int currentBit = currentSymbol & 0x1; for (int j = 0; j < CodewordDecoder::BARS_IN_MODULE; j++) { int8_t size = 0; while ((currentSymbol & 0x1) == currentBit) { size += 1; currentSymbol >>= 1; } currentBit = currentSymbol & 0x1; table[i][CodewordDecoder::BARS_IN_MODULE - j - 1] = size / 17.f; // MODULES_IN_CODEWORD } } return table; }(); int bitCountSum = Reduce(moduleBitCount); std::array<float, CodewordDecoder::BARS_IN_MODULE> bitCountRatios = {}; if (bitCountSum > 1) { for (int i = 0; i < CodewordDecoder::BARS_IN_MODULE; i++) { bitCountRatios[i] = moduleBitCount[i] / (float)bitCountSum; } } float bestMatchError = std::numeric_limits<float>::max(); int bestMatch = -1; for (size_t j = 0; j < ratioTable.size(); j++) { float error = 0.0f; auto& ratioTableRow = ratioTable[j]; for (int k = 0; k < CodewordDecoder::BARS_IN_MODULE; k++) { float diff = ratioTableRow[k] - bitCountRatios[k]; error += diff * diff; if (error >= bestMatchError) { break; } } if (error < bestMatchError) { bestMatchError = error; bestMatch = getSymbol(j); } } return bestMatch; } int CodewordDecoder::GetDecodedValue(const std::array<int, BARS_IN_MODULE>& moduleBitCount) { int decodedValue = GetDecodedCodewordValue(SampleBitCounts(moduleBitCount)); if (decodedValue != -1) { return decodedValue; } return GetClosestDecodedValue(moduleBitCount); } /** * @param symbol encoded symbol to translate to a codeword * @return the codeword corresponding to the symbol. */ int CodewordDecoder::GetCodeword(int symbol) { if ((symbol & 0xFFFF0000) != 0x10000) return -1; symbol &= 0xFFFF; auto it = std::lower_bound(SYMBOL_TABLE.begin(), SYMBOL_TABLE.end(), symbol); if (it != SYMBOL_TABLE.end() && *it == symbol) { return (CODEWORD_TABLE[it - SYMBOL_TABLE.begin()] - 1) % NUMBER_OF_CODEWORDS; } return -1; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFCodewordDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
28,877
```objective-c /* */ #pragma once #include "ResultPoint.h" #include "ZXNullable.h" #include <list> #include <array> #include <memory> namespace ZXing { class BitMatrix; class BinaryBitmap; namespace Pdf417 { /** * <p>Encapsulates logic that can detect a PDF417 Code in an image, even if the * PDF417 Code is rotated or skewed, or partially obscured.< / p> * * @author SITA Lab(kevin.osullivan@sita.aero) * @author dswitkin@google.com(Daniel Switkin) * @author Guenther Grau */ class Detector { public: struct Result { std::shared_ptr<const BitMatrix> bits; std::list<std::array<Nullable<ResultPoint>, 8>> points; int rotation = -1; }; static Result Detect(const BinaryBitmap& image, bool multiple, bool tryRotate); }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDetector.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
204
```objective-c /* */ #pragma once #include <map> #include <vector> namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau */ class BarcodeValue { std::map<int, int> _values; public: /** * Add an occurrence of a value */ void setValue(int value); /** * Determines the maximum occurrence of a set value and returns all values which were set with this occurrence. * @return an array of int, containing the values with the highest occurrence, or null, if no value was set */ std::vector<int> value() const; int confidence(int value) const; }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFBarcodeValue.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
146
```objective-c /* */ #pragma once namespace ZXing { class CustomData { public: virtual ~CustomData() = default; protected: CustomData() = default; }; } // ZXing ```
/content/code_sandbox/core/src/pdf417/CustomData.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
40
```objective-c /* */ #pragma once #include "Reader.h" #include <list> namespace ZXing::Pdf417 { /** * This implementation can detect and decode PDF417 codes in an image. * * @author Guenther Grau */ class Reader : public ZXing::Reader { public: using ZXing::Reader::Reader; Barcode decode(const BinaryBitmap& image) const override; Barcodes decode(const BinaryBitmap& image, int maxSymbols) const override; }; } // namespace ZXing::Pdf417 ```
/content/code_sandbox/core/src/pdf417/PDFReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
107
```c++ /* */ #include "PDFDetector.h" #include "BinaryBitmap.h" #include "BitMatrix.h" #include "ZXNullable.h" #include "Pattern.h" #include <algorithm> #include <array> #include <cstdlib> #include <limits> #include <list> #include <vector> namespace ZXing { namespace Pdf417 { static const int INDEXES_START_PATTERN[] = { 0, 4, 1, 5 }; static const int INDEXES_STOP_PATTERN[] = { 6, 2, 7, 3 }; static const float MAX_AVG_VARIANCE = 0.42f; static const float MAX_INDIVIDUAL_VARIANCE = 0.8f; static const int MAX_PIXEL_DRIFT = 3; static const int MAX_PATTERN_DRIFT = 5; // if we set the value too low, then we don't detect the correct height of the bar if the start patterns are damaged. // if we set the value too high, then we might detect the start pattern from a neighbor barcode. static const int SKIPPED_ROW_COUNT_MAX = 25; // A PDF471 barcode should have at least 3 rows, with each row being >= 3 times the module width. Therefore it should be at least // 9 pixels tall. To be conservative, we use about half the size to ensure we don't miss it. static const int ROW_STEP = 8; // used to be 5, but 8 is enough for conforming symbols static const int BARCODE_MIN_HEIGHT = 10; /** * Determines how closely a set of observed counts of runs of black/white * values matches a given target pattern. This is reported as the ratio of * the total variance from the expected pattern proportions across all * pattern elements, to the length of the pattern. * * @param counters observed counters * @param pattern expected pattern * @param maxIndividualVariance The most any counter can differ before we give up * @return ratio of total variance between counters and pattern compared to total pattern size */ static float PatternMatchVariance(const std::vector<int>& counters, const std::vector<int>& pattern, float maxIndividualVariance) { int total = 0; int patternLength = 0; for (size_t i = 0; i < counters.size(); i++) { total += counters[i]; patternLength += pattern[i]; } if (total < patternLength) { // If we don't even have one pixel per unit of bar width, assume this // is too small to reliably match, so fail: return std::numeric_limits<float>::max(); } // We're going to fake floating-point math in integers. We just need to use more bits. // Scale up patternLength so that intermediate values below like scaledCounter will have // more "significant digits". float unitBarWidth = (float)total / patternLength; maxIndividualVariance *= unitBarWidth; float totalVariance = 0.0f; for (size_t x = 0; x < counters.size(); x++) { int counter = counters[x]; float scaledPattern = pattern[x] * unitBarWidth; float variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; if (variance > maxIndividualVariance) { return std::numeric_limits<float>::max(); } totalVariance += variance; } return totalVariance / total; } /** * @param matrix row of black/white values to search * @param column x position to start search * @param row y position to start search * @param width the number of pixels to search on this row * @param pattern pattern of counts of number of black and white pixels that are * being searched for as a pattern * @param counters array of counters, as long as pattern, to re-use * @return start/end horizontal offset of guard pattern, as an array of two ints. */ static bool FindGuardPattern(const BitMatrix& matrix, int column, int row, int width, bool whiteFirst, const std::vector<int>& pattern, std::vector<int>& counters, int& startPos, int& endPos) { std::fill(counters.begin(), counters.end(), 0); int patternLength = Size(pattern); bool isWhite = whiteFirst; int patternStart = column; int pixelDrift = 0; // if there are black pixels left of the current pixel shift to the left, but only for MAX_PIXEL_DRIFT pixels while (matrix.get(patternStart, row) && patternStart > 0 && pixelDrift++ < MAX_PIXEL_DRIFT) { patternStart--; } int x = patternStart; int counterPosition = 0; for (; x < width; x++) { bool pixel = matrix.get(x, row); if (pixel != isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (PatternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { startPos = patternStart; endPos = x; return true; } patternStart += counters[0] + counters[1]; std::copy(counters.begin() + 2, counters.end(), counters.begin()); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } if (counterPosition == patternLength - 1) { if (PatternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { startPos = patternStart; endPos = x - 1; return true; } } return false; } static std::array<Nullable<ResultPoint>, 4>& FindRowsWithPattern(const BitMatrix& matrix, int height, int width, int startRow, int startColumn, const std::vector<int>& pattern, std::array<Nullable<ResultPoint>, 4>& result) { bool found = false; int startPos, endPos; int minStartRow = startRow; std::vector<int> counters(pattern.size(), 0); for (; startRow < height; startRow += ROW_STEP) { if (FindGuardPattern(matrix, startColumn, startRow, width, false, pattern, counters, startPos, endPos)) { while (startRow > minStartRow + 1) { if (!FindGuardPattern(matrix, startColumn, --startRow, width, false, pattern, counters, startPos, endPos)) { startRow++; break; } } result[0] = ResultPoint(startPos, startRow); result[1] = ResultPoint(endPos, startRow); found = true; break; } } int stopRow = startRow + 1; // Last row of the current symbol that contains pattern if (found) { int skippedRowCount = 0; int previousRowStart = static_cast<int>(result[0].value().x()); int previousRowEnd = static_cast<int>(result[1].value().x()); for (; stopRow < height; stopRow++) { int startPos, endPos; found = FindGuardPattern(matrix, previousRowStart, stopRow, width, false, pattern, counters, startPos, endPos); // a found pattern is only considered to belong to the same barcode if the start and end positions // don't differ too much. Pattern drift should be not bigger than two for consecutive rows. With // a higher number of skipped rows drift could be larger. To keep it simple for now, we allow a slightly // larger drift and don't check for skipped rows. if (found && std::abs(previousRowStart - startPos) < MAX_PATTERN_DRIFT && std::abs(previousRowEnd - endPos) < MAX_PATTERN_DRIFT) { previousRowStart = startPos; previousRowEnd = endPos; skippedRowCount = 0; } else if (skippedRowCount > SKIPPED_ROW_COUNT_MAX) { break; } else { skippedRowCount++; } } stopRow -= skippedRowCount + 1; result[2] = ResultPoint(previousRowStart, stopRow); result[3] = ResultPoint(previousRowEnd, stopRow); } if (stopRow - startRow < BARCODE_MIN_HEIGHT) { std::fill(result.begin(), result.end(), nullptr); } return result; } static void CopyToResult(std::array<Nullable<ResultPoint>, 8>& result, const std::array<Nullable<ResultPoint>, 4>& tmpResult, const int destinationIndexes[4]) { for (int i = 0; i < 4; i++) { result[destinationIndexes[i]] = tmpResult[i]; } } /** * Locate the vertices and the codewords area of a black blob using the Start * and Stop patterns as locators. * * @param matrix the scanned barcode image. * @return an array containing the vertices: * vertices[0] x, y top left barcode * vertices[1] x, y bottom left barcode * vertices[2] x, y top right barcode * vertices[3] x, y bottom right barcode * vertices[4] x, y top left codeword area * vertices[5] x, y bottom left codeword area * vertices[6] x, y top right codeword area * vertices[7] x, y bottom right codeword area */ static std::array<Nullable<ResultPoint>, 8> FindVertices(const BitMatrix& matrix, int startRow, int startColumn) { // B S B S B S B S Bar/Space pattern // 11111111 0 1 0 1 0 1 000 static const std::vector<int> START_PATTERN = { 8, 1, 1, 1, 1, 1, 1, 3 }; // 1111111 0 1 000 1 0 1 00 1 static const std::vector<int> STOP_PATTERN = { 7, 1, 1, 3, 1, 1, 1, 2, 1 }; int width = matrix.width(); int height = matrix.height(); std::array<Nullable<ResultPoint>, 4> tmp; std::array<Nullable<ResultPoint>, 8> result; CopyToResult(result, FindRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN, tmp), INDEXES_START_PATTERN); if (result[4] != nullptr) { startColumn = static_cast<int>(result[4].value().x()); startRow = static_cast<int>(result[4].value().y()); #if 1 // 2x speed improvement for images with no PDF417 symbol by not looking for symbols without start guard (which are not conforming to spec anyway) CopyToResult(result, FindRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN, tmp), INDEXES_STOP_PATTERN); } #else } CopyToResult(result, FindRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN, tmp), INDEXES_STOP_PATTERN); #endif return result; } /** * Detects PDF417 codes in an image. Only checks 0 degree rotation * @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will * be found and returned * @param bitMatrix bit matrix to detect barcodes in * @return List of ResultPoint arrays containing the coordinates of found barcodes */ static std::list<std::array<Nullable<ResultPoint>, 8>> DetectBarcode(const BitMatrix& bitMatrix, bool multiple) { int row = 0; int column = 0; bool foundBarcodeInRow = false; std::list<std::array<Nullable<ResultPoint>, 8>> barcodeCoordinates; while (row < bitMatrix.height()) { auto vertices = FindVertices(bitMatrix, row, column); if (vertices[0] == nullptr && vertices[3] == nullptr) { if (!foundBarcodeInRow) { // we didn't find any barcode so that's the end of searching break; } // we didn't find a barcode starting at the given column and row. Try again from the first column and slightly // below the lowest barcode we found so far. foundBarcodeInRow = false; column = 0; for (auto& barcodeCoordinate : barcodeCoordinates) { if (barcodeCoordinate[1] != nullptr) { row = std::max(row, static_cast<int>(barcodeCoordinate[1].value().y())); } if (barcodeCoordinate[3] != nullptr) { row = std::max(row, static_cast<int>(barcodeCoordinate[3].value().y())); } } row += ROW_STEP; continue; } foundBarcodeInRow = true; barcodeCoordinates.push_back(vertices); if (!multiple) { break; } // if we didn't find a right row indicator column, then continue the search for the next barcode after the // start pattern of the barcode just found. if (vertices[2] != nullptr) { column = static_cast<int>(vertices[2].value().x()); row = static_cast<int>(vertices[2].value().y()); } else { column = static_cast<int>(vertices[4].value().x()); row = static_cast<int>(vertices[4].value().y()); } } return barcodeCoordinates; } bool HasStartPattern(const BitMatrix& m, bool rotate90) { constexpr FixedPattern<8, 17> START_PATTERN = { 8, 1, 1, 1, 1, 1, 1, 3 }; constexpr int minSymbolWidth = 3*8+1; // compact symbol PatternRow row; int end = rotate90 ? m.width() : m.height(); for (int r = ROW_STEP; r < end; r += ROW_STEP) { GetPatternRow(m, r, row, rotate90); if (FindLeftGuard(row, minSymbolWidth, START_PATTERN, 2).isValid()) return true; std::reverse(row.begin(), row.end()); if (FindLeftGuard(row, minSymbolWidth, START_PATTERN, 2).isValid()) return true; } return false; } /** * <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p> * * @param image barcode image to decode * @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will * be found and returned */ Detector::Result Detector::Detect(const BinaryBitmap& image, bool multiple, bool tryRotate) { // construct a 'dummy' shared pointer, just be able to pass it up the call chain in DetectorResult // TODO: reimplement PDF Detector auto binImg = std::shared_ptr<const BitMatrix>(image.getBitMatrix(), [](const BitMatrix*){}); if (!binImg) return {}; Result result; for (int rotate90 = 0; rotate90 <= static_cast<int>(tryRotate); ++rotate90) { if (!HasStartPattern(*binImg, rotate90)) continue; result.rotation = 90 * rotate90; if (rotate90) { auto newBits = std::make_shared<BitMatrix>(binImg->copy()); newBits->rotate90(); binImg = newBits; } result.points = DetectBarcode(*binImg, multiple); result.bits = binImg; if (result.points.empty()) { auto newBits = std::make_shared<BitMatrix>(binImg->copy()); newBits->rotate180(); result.points = DetectBarcode(*newBits, multiple); result.rotation += 180; result.bits = newBits; } if (!result.points.empty()) return result; } return {}; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDetector.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,565
```c++ /* */ #include "PDFModulusGF.h" #include <stdexcept> namespace ZXing { namespace Pdf417 { ModulusGF::ModulusGF(int modulus, int generator) : _modulus(modulus), _zero(*this, { 0 }), _one(*this, { 1 }) { #ifdef ZX_REED_SOLOMON_USE_MORE_MEMORY_FOR_SPEED _expTable.resize(modulus * 2, 0); #else _expTable.resize(modulus, 0); #endif _logTable.resize(modulus, 0); int x = 1; for (int i = 0; i < modulus; i++) { _expTable[i] = x; x = (x * generator) % modulus; } #ifdef ZX_REED_SOLOMON_USE_MORE_MEMORY_FOR_SPEED for (int i = modulus - 1; i < modulus * 2; ++i) _expTable[i] = _expTable[i - (modulus - 1)]; #endif for (int i = 0; i < modulus - 1; i++) { _logTable[_expTable[i]] = i; } // logTable[0] == 0 but this should never be used } ModulusPoly ModulusGF::buildMonomial(int degree, int coefficient) const { if (degree < 0) { throw std::invalid_argument("degree < 0"); } if (coefficient == 0) { return _zero; } std::vector<int> coefficients(degree + 1, 0); coefficients[0] = coefficient; return ModulusPoly(*this, coefficients); } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFModulusGF.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
361
```objective-c /* */ #pragma once #include "PDFBarcodeMetadata.h" #include "PDFBoundingBox.h" #include "PDFDetectionResultColumn.h" #include "ZXNullable.h" #include <vector> namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau */ class DetectionResult { BarcodeMetadata _barcodeMetadata; std::vector<Nullable<DetectionResultColumn>> _detectionResultColumns; Nullable<BoundingBox> _boundingBox; public: DetectionResult() = default; DetectionResult(const BarcodeMetadata& barcodeMetadata, const Nullable<BoundingBox>& boundingBox); void init(const BarcodeMetadata& barcodeMetadata, const Nullable<BoundingBox>& boundingBox); const std::vector<Nullable<DetectionResultColumn>> & allColumns(); int barcodeColumnCount() const { return _barcodeMetadata.columnCount(); } int barcodeRowCount() const { return _barcodeMetadata.rowCount(); } int barcodeECLevel() const { return _barcodeMetadata.errorCorrectionLevel(); } void setBoundingBox(const BoundingBox& boundingBox) { _boundingBox = boundingBox; } const Nullable<BoundingBox> & getBoundingBox() const { return _boundingBox; } void setBoundingBox(const Nullable<BoundingBox>& box) { _boundingBox = box; } void setColumn(int barcodeColumn, const Nullable<DetectionResultColumn>& detectionResultColumn) { _detectionResultColumns[barcodeColumn] = detectionResultColumn; } const Nullable<DetectionResultColumn>& column(int barcodeColumn) const { return _detectionResultColumns[barcodeColumn]; } Nullable<DetectionResultColumn>& column(int barcodeColumn) { return _detectionResultColumns[barcodeColumn]; } }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDetectionResult.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
362
```objective-c /* */ #pragma once #include <array> namespace ZXing { namespace Pdf417 { /** * @author Guenther Grau * @author creatale GmbH (christoph.schulz@creatale.de) */ class CodewordDecoder { public: static constexpr const int NUMBER_OF_CODEWORDS = 929; // Maximum Codewords (Data + Error). static constexpr const int MAX_CODEWORDS_IN_BARCODE = NUMBER_OF_CODEWORDS - 1; // One left row indication column + max 30 data columns + one right row indicator column //public static final int MAX_CODEWORDS_IN_ROW = 32; static constexpr const int MODULES_IN_CODEWORD = 17; static constexpr const int BARS_IN_MODULE = 8; /** * @param symbol encoded symbol to translate to a codeword * @return the codeword corresponding to the symbol. */ static int GetCodeword(int symbol); static int GetDecodedValue(const std::array<int, BARS_IN_MODULE>& moduleBitCount); }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFCodewordDecoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
233
```objective-c /* */ #pragma once #include <stdexcept> #include <utility> namespace ZXing { template <typename T> class Nullable final { bool m_hasValue = false; T m_value; public: Nullable() = default; Nullable(const T &value) : m_hasValue(true), m_value(value) {} Nullable(T &&value) noexcept : m_hasValue(true), m_value(std::move(value)) {} Nullable(std::nullptr_t) {} Nullable<T> & operator=(const T &value) { m_hasValue = true; m_value = value; return *this; } Nullable<T> & operator=(T &&value) noexcept { m_hasValue = true; m_value = std::move(value); return *this; } Nullable<T> & operator=(std::nullptr_t) { m_hasValue = false; m_value = T(); return *this; } operator T() const { if (!m_hasValue) { throw std::logic_error("Access empty value"); } return m_value; } bool hasValue() const { return m_hasValue; } const T & value() const { return m_value; } T & value() { return m_value; } friend inline bool operator==(const Nullable &a, const Nullable &b) { return a.m_hasValue == b.m_hasValue && (!a.m_hasValue || a.m_value == b.m_value); } friend inline bool operator!=(const Nullable &a, const Nullable &b) { return !(a == b); } friend inline bool operator==(const Nullable &a, const T &v) { return a.m_hasValue && a.m_value == v; } friend inline bool operator!=(const Nullable &a, const T &v) { return !(a == v); } friend inline bool operator==(const T &v, const Nullable &a) { return a.m_hasValue && a.m_value == v; } friend inline bool operator!=(const T &v, const Nullable &a) { return !(v == a); } friend inline bool operator==(const Nullable &a, std::nullptr_t) { return !a.m_hasValue; } friend inline bool operator!=(const Nullable &a, std::nullptr_t) { return a.m_hasValue; } friend inline bool operator==(std::nullptr_t, const Nullable &a) { return !a.m_hasValue; } friend inline bool operator!=(std::nullptr_t, const Nullable &a) { return a.m_hasValue; } friend inline void swap(Nullable &a, Nullable &b) { using std::swap; swap(a.m_value, b.m_value); swap(a.m_hasValue, b.m_hasValue); } }; } // ZXing ```
/content/code_sandbox/core/src/pdf417/ZXNullable.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
607
```c++ /* */ #include "PDFReader.h" #include "PDFDetector.h" #include "PDFScanningDecoder.h" #include "PDFCodewordDecoder.h" #include "ReaderOptions.h" #include "DecoderResult.h" #include "DetectorResult.h" #include "Barcode.h" #include "BitMatrixCursor.h" #include "BinaryBitmap.h" #include "BitArray.h" #include "Pattern.h" #include <vector> #include <cstdlib> #include <algorithm> #include <limits> #include <utility> #ifdef PRINT_DEBUG #include "BitMatrixIO.h" #include <cstdio> #endif namespace ZXing { namespace Pdf417 { static const int MODULES_IN_STOP_PATTERN = 18; static int GetMinWidth(const Nullable<ResultPoint>& p1, const Nullable<ResultPoint>& p2) { if (p1 == nullptr || p2 == nullptr) { // the division prevents an integer overflow (see below). 120 million is still sufficiently large. return std::numeric_limits<int>::max() / CodewordDecoder::MODULES_IN_CODEWORD; } return std::abs(static_cast<int>(p1.value().x()) - static_cast<int>(p2.value().x())); } static int GetMinCodewordWidth(const std::array<Nullable<ResultPoint>, 8>& p) { return std::min(std::min(GetMinWidth(p[0], p[4]), GetMinWidth(p[6], p[2]) * CodewordDecoder::MODULES_IN_CODEWORD / MODULES_IN_STOP_PATTERN), std::min(GetMinWidth(p[1], p[5]), GetMinWidth(p[7], p[3]) * CodewordDecoder::MODULES_IN_CODEWORD / MODULES_IN_STOP_PATTERN)); } static int GetMaxWidth(const Nullable<ResultPoint>& p1, const Nullable<ResultPoint>& p2) { if (p1 == nullptr || p2 == nullptr) { return 0; } return std::abs(static_cast<int>(p1.value().x()) - static_cast<int>(p2.value().x())); } static int GetMaxCodewordWidth(const std::array<Nullable<ResultPoint>, 8>& p) { return std::max(std::max(GetMaxWidth(p[0], p[4]), GetMaxWidth(p[6], p[2]) * CodewordDecoder::MODULES_IN_CODEWORD / MODULES_IN_STOP_PATTERN), std::max(GetMaxWidth(p[1], p[5]), GetMaxWidth(p[7], p[3]) * CodewordDecoder::MODULES_IN_CODEWORD / MODULES_IN_STOP_PATTERN)); } static Barcodes DoDecode(const BinaryBitmap& image, bool multiple, bool tryRotate, bool returnErrors) { Detector::Result detectorResult = Detector::Detect(image, multiple, tryRotate); if (detectorResult.points.empty()) return {}; auto rotate = [res = detectorResult](PointI p) { switch(res.rotation) { case 90: return PointI(res.bits->height() - p.y - 1, p.x); case 180: return PointI(res.bits->width() - p.x - 1, res.bits->height() - p.y - 1); case 270: return PointI(p.y, res.bits->width() - p.x - 1); } return p; }; Barcodes res; for (const auto& points : detectorResult.points) { DecoderResult decoderResult = ScanningDecoder::Decode(*detectorResult.bits, points[4], points[5], points[6], points[7], GetMinCodewordWidth(points), GetMaxCodewordWidth(points)); if (decoderResult.isValid(returnErrors)) { auto point = [&](int i) { return rotate(PointI(points[i].value())); }; res.emplace_back(std::move(decoderResult), DetectorResult{{}, {point(0), point(2), point(3), point(1)}}, BarcodeFormat::PDF417); if (!multiple) return res; } } return res; } // new implementation (only for isPure use case atm.) using Pattern417 = std::array<uint16_t, 8>; struct CodeWord { int cluster = -1; int code = -1; operator bool() const noexcept { return code != -1; } }; struct SymbolInfo { int width = 0, height = 0; int nRows = 0, nCols = 0, firstRow = -1, lastRow = -1; int ecLevel = -1; int colWidth = 0; float rowHeight = 0; operator bool() const noexcept { return nRows >= 3 && nCols >= 1 && ecLevel != -1; } }; template<typename POINT> CodeWord ReadCodeWord(BitMatrixCursor<POINT>& cur, int expectedCluster = -1) { auto readCodeWord = [expectedCluster](auto& cur) -> CodeWord { auto np = NormalizedPattern<8, 17>(cur.template readPattern<Pattern417>()); int cluster = (np[0] - np[2] + np[4] - np[6] + 9) % 9; int code = expectedCluster == -1 || cluster == expectedCluster ? CodewordDecoder::GetCodeword(ToInt(np)) : -1; return {cluster, code}; }; auto curBackup = cur; auto cw = readCodeWord(cur); if (!cw) { for (auto offset : {curBackup.left(), curBackup.right()}) { auto curAlt = curBackup.movedBy(offset); if (!curAlt.isIn()) // curBackup might be the first or last image row continue; if (auto cwAlt = readCodeWord(curAlt)) { cur = curAlt; return cwAlt; } } } return cw; } static int Row(CodeWord rowIndicator) { return (rowIndicator.code / 30) * 3 + rowIndicator.cluster / 3; } constexpr FixedPattern<8, 17> START_PATTERN = { 8, 1, 1, 1, 1, 1, 1, 3 }; #ifndef PRINT_DEBUG #define printf(...){} #endif template<typename POINT> SymbolInfo ReadSymbolInfo(BitMatrixCursor<POINT> topCur, POINT rowSkip, int colWidth, int width, int height) { SymbolInfo res = {width, height}; res.colWidth = colWidth; int clusterMask = 0; int rows0 = 0, rows1 = 0; // Suppress GNUC -Wmaybe-uninitialized topCur.p += .5f * rowSkip; for (auto startCur = topCur; clusterMask != 0b111 && maxAbsComponent(topCur.p - startCur.p) < height / 2; startCur.p += rowSkip) { auto cur = startCur; if (!IsPattern(cur.template readPatternFromBlack<Pattern417>(1, colWidth + 2), START_PATTERN)) break; auto cw = ReadCodeWord(cur); #ifdef PRINT_DEBUG printf("%3dx%3d:%2d: %4d.%d \n", int(cur.p.x), int(cur.p.y), Row(cw), cw.code, cw.cluster); fflush(stdout); #endif if (!cw) continue; if (res.firstRow == -1) res.firstRow = Row(cw); switch (cw.cluster) { case 0: rows0 = cw.code % 30; break; case 3: rows1 = cw.code % 3, res.ecLevel = (cw.code % 30) / 3; break; case 6: res.nCols = (cw.code % 30) + 1; break; default: continue; } clusterMask |= (1 << cw.cluster / 3); } if ((clusterMask & 0b11) == 0b11) res.nRows = 3 * rows0 + rows1 + 1; return res; } template<typename POINT> SymbolInfo DetectSymbol(BitMatrixCursor<POINT> topCur, int width, int height) { auto pat = topCur.movedBy(height / 2 * topCur.right()).template readPatternFromBlack<Pattern417>(1, width / 3); if (!IsPattern(pat, START_PATTERN)) return {}; int colWidth = Reduce(pat); auto rowSkip = std::max(colWidth / 17.f, 1.f) * bresenhamDirection(topCur.right()); auto botCur = topCur.movedBy((height - 1) * topCur.right()); auto topSI = ReadSymbolInfo(topCur, rowSkip, colWidth, width, height); auto botSI = ReadSymbolInfo(botCur, -rowSkip, colWidth, width, height); SymbolInfo res = topSI; res.lastRow = botSI.firstRow; res.rowHeight = float(height) / (std::abs(res.lastRow - res.firstRow) + 1); if (topSI.nCols != botSI.nCols) // if there is something fishy with the number of cols (aliasing), guess them from the width res.nCols = (width + res.colWidth / 2) / res.colWidth - 4; return res; } template<typename POINT> std::vector<int> ReadCodeWords(BitMatrixCursor<POINT> topCur, SymbolInfo info) { printf("rows: %d, cols: %d, rowHeight: %.1f, colWidth: %d, firstRow: %d, lastRow: %d, ecLevel: %d\n", info.nRows, info.nCols, info.rowHeight, info.colWidth, info.firstRow, info.lastRow, info.ecLevel); auto print = [](CodeWord c [[maybe_unused]]) { printf("%4d.%d ", c.code, c.cluster); }; auto rowSkip = topCur.right(); if (info.firstRow > info.lastRow) { topCur.p += (info.height - 1) * rowSkip; rowSkip = -rowSkip; std::swap(info.firstRow, info.lastRow); } int maxColWidth = info.colWidth * 3 / 2; std::vector<int> codeWords(info.nRows * info.nCols, -1); for (int row = info.firstRow; row < std::min(info.nRows, info.lastRow + 1); ++row) { int cluster = (row % 3) * 3; auto cur = topCur.movedBy(int((row - info.firstRow + 0.5f) * info.rowHeight) * rowSkip); // skip start pattern cur.stepToEdge(8 + cur.isWhite(), maxColWidth); // read off left row indicator column auto cw [[maybe_unused]] = ReadCodeWord(cur, cluster); printf("%3dx%3d:%2d: ", int(cur.p.x), int(cur.p.y), Row(cw)); print(cw); for (int col = 0; col < info.nCols && cur.isIn(); ++col) { auto cw = ReadCodeWord(cur, cluster); codeWords[row * info.nCols + col] = cw.code; print(cw); } #ifdef PRINT_DEBUG print(ReadCodeWord(cur)); printf("\n"); fflush(stdout); #endif } return codeWords; } static Barcode DecodePure(const BinaryBitmap& image_) { auto pimage = image_.getBitMatrix(); if (!pimage) return {}; auto& image = *pimage; #ifdef PRINT_DEBUG SaveAsPBM(image, "weg.pbm"); #endif int left, top, width, height; if (!image.findBoundingBox(left, top, width, height, 9) || (width < 3 * 17 && height < 3 * 17)) return {}; int right = left + width - 1; int bottom = top + height - 1; // counter intuitively, using a floating point cursor is about twice as fast an integer one (on an AVX architecture) BitMatrixCursorF cur(image, centered(PointI{left, top}), PointF{1, 0}); SymbolInfo info; // try all 4 orientations for (int a = 0; a < 4; ++a) { info = DetectSymbol(cur, width, height); if (info) break; cur.step(width - 1); cur.turnRight(); std::swap(width, height); } if (!info) return {}; auto codeWords = ReadCodeWords(cur, info); auto res = DecodeCodewords(codeWords, NumECCodeWords(info.ecLevel)); return Barcode(std::move(res), {{}, {{left, top}, {right, top}, {right, bottom}, {left, bottom}}}, BarcodeFormat::PDF417); } Barcode Reader::decode(const BinaryBitmap& image) const { if (_opts.isPure()) { auto res = DecodePure(image); if (res.error() != Error::Checksum) return res; // This falls through and tries the non-pure code path if we have a checksum error. This approach is // currently the best option to deal with 'aliased' input like e.g. 03-aliased.png } return FirstOrDefault(DoDecode(image, false, _opts.tryRotate(), _opts.returnErrors())); } Barcodes Reader::decode(const BinaryBitmap& image, [[maybe_unused]] int maxSymbols) const { return DoDecode(image, true, _opts.tryRotate(), _opts.returnErrors()); } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,926
```c++ /* */ #include "PDFBoundingBox.h" #include <algorithm> namespace ZXing { namespace Pdf417 { BoundingBox::BoundingBox() { _imgWidth = _imgHeight = _minX = _maxX = _minY = _maxY = 0; } bool BoundingBox::Create(int imgWidth, int imgHeight, const Nullable<ResultPoint>& topLeft, const Nullable<ResultPoint>& bottomLeft, const Nullable<ResultPoint>& topRight, const Nullable<ResultPoint>& bottomRight, BoundingBox& result) { if ((topLeft == nullptr && topRight == nullptr) || (bottomLeft == nullptr && bottomRight == nullptr) || (topLeft != nullptr && bottomLeft == nullptr) || (topRight != nullptr && bottomRight == nullptr)) { return false; } result._imgWidth = imgWidth; result._imgHeight = imgHeight; result._topLeft = topLeft; result._bottomLeft = bottomLeft; result._topRight = topRight; result._bottomRight = bottomRight; result.calculateMinMaxValues(); return true; } void BoundingBox::calculateMinMaxValues() { if (_topLeft == nullptr) { _topLeft = ResultPoint(0.f, _topRight.value().y()); _bottomLeft = ResultPoint(0.f, _bottomRight.value().y()); } else if (_topRight == nullptr) { _topRight = ResultPoint(static_cast<float>(_imgWidth - 1), _topLeft.value().y()); _bottomRight = ResultPoint(static_cast<float>(_imgWidth - 1), _bottomLeft.value().y()); } _minX = static_cast<int>(std::min(_topLeft.value().x(), _bottomLeft.value().x())); _maxX = static_cast<int>(std::max(_topRight.value().x(), _bottomRight.value().x())); _minY = static_cast<int>(std::min(_topLeft.value().y(), _topRight.value().y())); _maxY = static_cast<int>(std::max(_bottomLeft.value().y(), _bottomRight.value().y())); } bool BoundingBox::Merge(const Nullable<BoundingBox>& leftBox, const Nullable<BoundingBox>& rightBox, Nullable<BoundingBox>& result) { if (leftBox == nullptr) { result = rightBox; return true; } if (rightBox == nullptr) { result = leftBox; return true; } BoundingBox box; if (Create(leftBox.value()._imgWidth, leftBox.value()._imgHeight, leftBox.value()._topLeft, leftBox.value()._bottomLeft, rightBox.value()._topRight, rightBox.value()._bottomRight, box)) { result = box; return true; } return false; } bool BoundingBox::AddMissingRows(const BoundingBox& box, int missingStartRows, int missingEndRows, bool isLeft, BoundingBox& result) { auto newTopLeft = box._topLeft; auto newBottomLeft = box._bottomLeft; auto newTopRight = box._topRight; auto newBottomRight = box._bottomRight; if (missingStartRows > 0) { auto top = isLeft ? box._topLeft : box._topRight; int newMinY = static_cast<int>(top.value().y()) - missingStartRows; if (newMinY < 0) { newMinY = 0; } ResultPoint newTop(top.value().x(), static_cast<float>(newMinY)); if (isLeft) { newTopLeft = newTop; } else { newTopRight = newTop; } } if (missingEndRows > 0) { auto bottom = isLeft ? box._bottomLeft : box._bottomRight; int newMaxY = (int)bottom.value().y() + missingEndRows; if (newMaxY >= box._imgHeight) { newMaxY = box._imgHeight - 1; } ResultPoint newBottom(bottom.value().x(), static_cast<float>(newMaxY)); if (isLeft) { newBottomLeft = newBottom; } else { newBottomRight = newBottom; } } return Create(box._imgWidth, box._imgHeight, newTopLeft, newBottomLeft, newTopRight, newBottomRight, result); } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFBoundingBox.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
926
```c++ /* */ #include "PDFDecoder.h" #include "CharacterSet.h" #include "DecoderResult.h" #include "PDFDecoderResultExtra.h" #include "ZXAlgorithms.h" #include "ZXBigInteger.h" #include "ZXTestSupport.h" #include <array> #include <cassert> #include <sstream> #include <utility> namespace ZXing::Pdf417 { enum class Mode { ALPHA, LOWER, MIXED, PUNCT, ALPHA_SHIFT, PUNCT_SHIFT }; constexpr int TEXT_COMPACTION_MODE_LATCH = 900; constexpr int BYTE_COMPACTION_MODE_LATCH = 901; constexpr int NUMERIC_COMPACTION_MODE_LATCH = 902; // 903-912 reserved constexpr int MODE_SHIFT_TO_BYTE_COMPACTION_MODE = 913; // 914-917 reserved constexpr int LINKAGE_OTHER = 918; // 919 reserved constexpr int LINKAGE_EANUCC = 920; // GS1 Composite constexpr int READER_INIT = 921; // Reader Initialisation/Programming constexpr int MACRO_PDF417_TERMINATOR = 922; constexpr int BEGIN_MACRO_PDF417_OPTIONAL_FIELD = 923; constexpr int BYTE_COMPACTION_MODE_LATCH_6 = 924; constexpr int ECI_USER_DEFINED = 925; // 810900-811799 (1 codeword) constexpr int ECI_GENERAL_PURPOSE = 926; // 900-810899 (2 codewords) constexpr int ECI_CHARSET = 927; // 0-899 (1 codeword) constexpr int BEGIN_MACRO_PDF417_CONTROL_BLOCK = 928; constexpr int MAX_NUMERIC_CODEWORDS = 15; constexpr int MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME = 0; constexpr int MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT = 1; constexpr int MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP = 2; constexpr int MACRO_PDF417_OPTIONAL_FIELD_SENDER = 3; constexpr int MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE = 4; constexpr int MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE = 5; constexpr int MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM = 6; static const char* PUNCT_CHARS = ";<>@[\\]_`~!\r\t,:\n-.$/\"|*()?{}'"; static const char* MIXED_CHARS = "0123456789&\r\t,:#-.$/+%*=^"; constexpr int NUMBER_OF_SEQUENCE_CODEWORDS = 2; inline bool IsECI(int code) { return code >= ECI_USER_DEFINED && code <= ECI_CHARSET; } /** * Whether a codeword terminates a Compaction mode. * * See ISO/IEC 15438:2015 5.4.2.5 (Text), 5.4.3.4 (Byte), 5.4.4.3 (Numeric) */ static bool TerminatesCompaction(int code) { switch (code) { case TEXT_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH: case NUMERIC_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH_6: case BEGIN_MACRO_PDF417_CONTROL_BLOCK: case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case MACRO_PDF417_TERMINATOR: return true; } return false; } /** * Helper to process ECIs. **/ static int ProcessECI(const std::vector<int>& codewords, int codeIndex, const int length, const int code, Content& result) { if (codeIndex < length && IsECI(code)) { if (code == ECI_CHARSET) result.switchEncoding(ECI(codewords[codeIndex++])); else codeIndex += code == ECI_GENERAL_PURPOSE ? 2 : 1; // Don't currently handle non-character set ECIs so just ignore } return codeIndex; } /** * The Text Compaction mode includes all the printable ASCII characters * (i.e. values from 32 to 126) and three ASCII control characters: HT or tab * (ASCII value 9), LF or line feed (ASCII value 10), and CR or carriage * return (ASCII value 13). The Text Compaction mode also includes various latch * and shift characters which are used exclusively within the mode. The Text * Compaction mode encodes up to 2 characters per codeword. The compaction rules * for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode * switches are defined in 5.4.2.3. * * @param textCompactionData The text compaction data. * @param length The size of the text compaction data. * @param result The data in the character set encoding. */ static void DecodeTextCompaction(const std::vector<int>& textCompactionData, int length, Content& result) { // Beginning from an initial state of the Alpha sub-mode // The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text // Compaction mode Alpha sub-mode (uppercase alphabetic). A latch codeword from another mode to the Text // Compaction mode shall always switch to the Text Compaction Alpha sub-mode. Mode subMode = Mode::ALPHA; Mode priorToShiftMode = Mode::ALPHA; int i = 0; while (i < length) { int subModeCh = textCompactionData[i]; // Note only have ECI and MODE_SHIFT_TO_BYTE_COMPACTION_MODE function codewords in text compaction array if (IsECI(subModeCh)) { i = ProcessECI(textCompactionData, i + 1, length, subModeCh, result); continue; } if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) { i++; while (i < length && IsECI(textCompactionData[i])) i = ProcessECI(textCompactionData, i + 1, length, textCompactionData[i], result); if (i < length) result.push_back((uint8_t)textCompactionData[i++]); continue; } char ch = 0; switch (subMode) { case Mode::ALPHA: case Mode::LOWER: // Alpha (uppercase alphabetic) or Lower (lowercase alphabetic) if (subModeCh < 26) { // Upper/lowercase character ch = (char)((subMode == Mode::ALPHA ? 'A' : 'a') + subModeCh); } else if (subModeCh == 26) { // Space ch = ' '; } else if (subModeCh == 27 && subMode == Mode::ALPHA) { // LL subMode = Mode::LOWER; } else if (subModeCh == 27 && subMode == Mode::LOWER) { // AS // Shift to alpha priorToShiftMode = subMode; subMode = Mode::ALPHA_SHIFT; } else if (subModeCh == 28) { // ML subMode = Mode::MIXED; } // 29 PS - ignore if last or followed by Shift to Byte, 5.4.2.4 (b) (1) else if (i + 1 < length && textCompactionData[i + 1] != MODE_SHIFT_TO_BYTE_COMPACTION_MODE) { // Shift to punctuation priorToShiftMode = subMode; subMode = Mode::PUNCT_SHIFT; } break; case Mode::MIXED: // Mixed (numeric and some punctuation) if (subModeCh < 25) { ch = MIXED_CHARS[subModeCh]; } else if (subModeCh == 25) { // PL subMode = Mode::PUNCT; } else if (subModeCh == 26) { // Space ch = ' '; } else if (subModeCh == 27) { // LL subMode = Mode::LOWER; } else if (subModeCh == 28) { // AL subMode = Mode::ALPHA; } // 29 PS - ignore if last or followed by Shift to Byte, 5.4.2.4 (b) (1) else if (i + 1 < length && textCompactionData[i + 1] != MODE_SHIFT_TO_BYTE_COMPACTION_MODE) { // Shift to punctuation priorToShiftMode = subMode; subMode = Mode::PUNCT_SHIFT; } break; case Mode::PUNCT: // Punctuation if (subModeCh < 29) ch = PUNCT_CHARS[subModeCh]; else // 29 AL - note not ignored if followed by Shift to Byte, 5.4.2.4 (b) (2) subMode = Mode::ALPHA; break; case Mode::ALPHA_SHIFT: // Restore sub-mode subMode = priorToShiftMode; if (subModeCh < 26) ch = (char)('A' + subModeCh); else if (subModeCh == 26) // Space ch = ' '; // 27 LL, 28 ML, 29 PS used as padding break; case Mode::PUNCT_SHIFT: // Restore sub-mode subMode = priorToShiftMode; if (subModeCh < 29) ch = PUNCT_CHARS[subModeCh]; else // 29 AL subMode = Mode::ALPHA; break; } if (ch != 0) result.push_back(ch); // Append decoded character to result i++; } } /* * Helper to put ECI codewords into Text Compaction array. */ static int ProcessTextECI(std::vector<int>& textCompactionData, int& index, const std::vector<int>& codewords, int codeIndex, const int code) { textCompactionData[index++] = code; if (codeIndex < codewords[0]) { textCompactionData[index++] = codewords[codeIndex++]; if (codeIndex < codewords[0] && code == ECI_GENERAL_PURPOSE) { textCompactionData[index++] = codewords[codeIndex++]; } } return codeIndex; } /** * Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be * encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as * well as selected control characters. * * @param codewords The array of codewords (data + error) * @param codeIndex The current index into the codeword array. * @param result The data in the character set encoding. * @return The next index into the codeword array. */ static int TextCompaction(const std::vector<int>& codewords, int codeIndex, Content& result) { // 2 characters per codeword std::vector<int> textCompactionData((codewords[0] - codeIndex) * 2, 0); int index = 0; bool end = false; while ((codeIndex < codewords[0]) && !end) { int code = codewords[codeIndex++]; if (code < TEXT_COMPACTION_MODE_LATCH) { textCompactionData[index] = code / 30; textCompactionData[index + 1] = code % 30; index += 2; } else { switch (code) { case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // The Mode Shift codeword 913 shall cause a temporary // switch from Text Compaction mode to Byte Compaction mode. // This switch shall be in effect for only the next codeword, // after which the mode shall revert to the prevailing sub-mode // of the Text Compaction mode. Codeword 913 is only available // in Text Compaction mode; its use is described in 5.4.2.4. textCompactionData[index++] = MODE_SHIFT_TO_BYTE_COMPACTION_MODE; // 5.5.3.1 allows ECIs anywhere in Text Compaction, including after a Shift to Byte while (codeIndex < codewords[0] && IsECI(codewords[codeIndex])) { codeIndex = ProcessTextECI(textCompactionData, index, codewords, codeIndex + 1, codewords[codeIndex]); } if (codeIndex < codewords[0]) textCompactionData[index++] = codewords[codeIndex++]; // Byte to shift break; case ECI_CHARSET: case ECI_GENERAL_PURPOSE: case ECI_USER_DEFINED: codeIndex = ProcessTextECI(textCompactionData, index, codewords, codeIndex, code); break; default: if (!TerminatesCompaction(code)) throw FormatError(); codeIndex--; end = true; break; } } } DecodeTextCompaction(textCompactionData, index, result); return codeIndex; } /* * Helper for Byte Compaction to look ahead and count 5-codeword batches and trailing bytes, with some checking of * format errors. */ static int CountByteBatches(int mode, const std::vector<int>& codewords, int codeIndex, int& trailingCount) { int count = 0; trailingCount = 0; while (codeIndex < codewords[0]) { int code = codewords[codeIndex++]; if (code >= TEXT_COMPACTION_MODE_LATCH) { if (mode == BYTE_COMPACTION_MODE_LATCH_6 && count && count % 5) throw FormatError(); if (IsECI(code)) { codeIndex += code == ECI_GENERAL_PURPOSE ? 2 : 1; continue; } if (!TerminatesCompaction(code)) throw FormatError(); break; } count++; } if (codeIndex > codewords[0]) throw FormatError(); if (count == 0) return 0; if (mode == BYTE_COMPACTION_MODE_LATCH) { trailingCount = count % 5; if (trailingCount == 0) { trailingCount = 5; count -= 5; } } else { // BYTE_COMPACTION_MODE_LATCH_6 if (count % 5 != 0) throw FormatError(); } return count / 5; } /* * Helper to handle Byte Compaction ECIs. */ static int ProcessByteECIs(const std::vector<int>& codewords, int codeIndex, Content& result) { while (codeIndex < codewords[0] && codewords[codeIndex] >= TEXT_COMPACTION_MODE_LATCH && !TerminatesCompaction(codewords[codeIndex])) { int code = codewords[codeIndex++]; if (IsECI(code)) codeIndex = ProcessECI(codewords, codeIndex, codewords[0], code, result); } return codeIndex; } /** * Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded. * This includes all ASCII characters value 0 to 127 inclusive and provides for international * character set support. * * @param mode The byte compaction mode i.e. 901 or 924 * @param codewords The array of codewords (data + error) * @param codeIndex The current index into the codeword array. * @param result The data in the character set encoding. * @return The next index into the codeword array. */ static int ByteCompaction(int mode, const std::vector<int>& codewords, int codeIndex, Content& result) { // Count number of 5-codeword batches and trailing bytes int trailingCount; int batches = CountByteBatches(mode, codewords, codeIndex, trailingCount); // Deal with initial ECIs codeIndex = ProcessByteECIs(codewords, codeIndex, result); for (int batch = 0; batch < batches; batch++) { int64_t value = 0; for (int count = 0; count < 5; count++) value = 900 * value + codewords[codeIndex++]; for (int j = 0; j < 6; ++j) result.push_back((uint8_t)(value >> (8 * (5 - j)))); // Deal with inter-batch ECIs codeIndex = ProcessByteECIs(codewords, codeIndex, result); } for (int i = 0; i < trailingCount; i++) { result.push_back((uint8_t)codewords[codeIndex++]); // Deal with inter-byte ECIs codeIndex = ProcessByteECIs(codewords, codeIndex, result); } return codeIndex; } /** * Convert a list of Numeric Compacted codewords from Base 900 to Base 10. * * @param codewords The array of codewords * @param count The number of codewords * @return The decoded string representing the Numeric data. */ /* EXAMPLE Encode the fifteen digit numeric string 000213298174000 Prefix the numeric string with a 1 and set the initial value of t = 1 000 213 298 174 000 Calculate codeword 0 d0 = 1 000 213 298 174 000 mod 900 = 200 t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082 Calculate codeword 1 d1 = 1 111 348 109 082 mod 900 = 282 t = 1 111 348 109 082 div 900 = 1 234 831 232 Calculate codeword 2 d2 = 1 234 831 232 mod 900 = 632 t = 1 234 831 232 div 900 = 1 372 034 Calculate codeword 3 d3 = 1 372 034 mod 900 = 434 t = 1 372 034 div 900 = 1 524 Calculate codeword 4 d4 = 1 524 mod 900 = 624 t = 1 524 div 900 = 1 Calculate codeword 5 d5 = 1 mod 900 = 1 t = 1 div 900 = 0 Codeword sequence is: 1, 624, 434, 632, 282, 200 Decode the above codewords involves 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 + 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000 Remove leading 1 => Result is 000213298174000 */ static std::string DecodeBase900toBase10(const std::vector<int>& codewords, int endIndex, int count) { // Table containing values for the exponent of 900. static const auto EXP900 = []() { std::array<BigInteger, 16> table = {1, 900}; for (size_t i = 2; i < table.size(); ++i) table[i] = table[i - 1] * 900; return table; }(); assert(count <= 16); BigInteger result; for (int i = 0; i < count; i++) result += EXP900[count - i - 1] * codewords[endIndex - count + i]; std::string resultString = result.toString(); if (!resultString.empty() && resultString.front() == '1') return resultString.substr(1); throw FormatError(); } /** * Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings. * * @param codewords The array of codewords (data + error) * @param codeIndex The current index into the codeword array. * @param result The decoded data is appended to the result. * @return The next index into the codeword array. */ static int NumericCompaction(const std::vector<int>& codewords, int codeIndex, Content& result) { int count = 0; while (codeIndex < codewords[0]) { int code = codewords[codeIndex]; if (code < TEXT_COMPACTION_MODE_LATCH) { count++; codeIndex++; } if (count > 0 && (count == MAX_NUMERIC_CODEWORDS || codeIndex == codewords[0] || code >= TEXT_COMPACTION_MODE_LATCH)) { result += DecodeBase900toBase10(codewords, codeIndex, count); count = 0; } if (code >= TEXT_COMPACTION_MODE_LATCH) { if (IsECI(code)) { // As operating in Basic Channel Mode (i.e. not embedding backslashed ECIs and doubling backslashes) // allow ECIs anywhere in Numeric Compaction (i.e. ISO/IEC 15438:2015 5.5.3.4 doesn't apply). codeIndex = ProcessECI(codewords, codeIndex + 1, codewords[0], code, result); } else if (TerminatesCompaction(code)) { break; } else { throw FormatError(); } } } return codeIndex; } /* * Helper to deal with optional text fields in Macros. */ static int DecodeMacroOptionalTextField(const std::vector<int>& codewords, int codeIndex, std::string& field) { Content result; // Each optional field begins with an implied reset to ECI 2 (Annex H.2.3). ECI 2 is ASCII for 0-127, and Cp437 // for non-ASCII (128-255). Text optional fields can contain ECIs. result.defaultCharset = CharacterSet::Cp437; codeIndex = TextCompaction(codewords, codeIndex, result); // Converting to UTF-8 (backward-incompatible change for non-ASCII chars) field = result.utf8(); return codeIndex; } /* * Helper to deal with optional numeric fields in Macros. */ static int DecodeMacroOptionalNumericField(const std::vector<int>& codewords, int codeIndex, uint64_t& field) { Content result; // Each optional field begins with an implied reset to ECI 2 (Annex H.2.3). ECI 2 is ASCII for 0-127, and Cp437 // for non-ASCII (128-255). Text optional fields can contain ECIs. result.defaultCharset = CharacterSet::Cp437; codeIndex = NumericCompaction(codewords, codeIndex, result); field = std::stoll(result.utf8()); return codeIndex; } ZXING_EXPORT_TEST_ONLY int DecodeMacroBlock(const std::vector<int>& codewords, int codeIndex, DecoderResultExtra& resultMetadata) { // we must have at least two codewords left for the segment index if (codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0]) throw FormatError(); std::string strBuf = DecodeBase900toBase10(codewords, codeIndex += NUMBER_OF_SEQUENCE_CODEWORDS, NUMBER_OF_SEQUENCE_CODEWORDS); resultMetadata.setSegmentIndex(std::stoi(strBuf)); // Decoding the fileId codewords as 0-899 numbers, each 0-filled to width 3. This follows the spec // (See ISO/IEC 15438:2015 Annex H.6) and preserves all info, but some generators (e.g. TEC-IT) write // the fileId using text compaction, so in those cases the fileId will appear mangled. std::ostringstream fileId; for (; codeIndex < codewords[0] && codewords[codeIndex] != MACRO_PDF417_TERMINATOR && codewords[codeIndex] != BEGIN_MACRO_PDF417_OPTIONAL_FIELD; codeIndex++) { fileId << ToString(codewords[codeIndex], 3); } resultMetadata.setFileId(fileId.str()); int optionalFieldsStart = -1; if (codeIndex < codewords[0] && codewords[codeIndex] == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) optionalFieldsStart = codeIndex + 1; while (codeIndex < codewords[0]) { switch (codewords[codeIndex]) { case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: { codeIndex++; if (codeIndex >= codewords[0]) break; switch (codewords[codeIndex]) { case MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME: { std::string fileName; codeIndex = DecodeMacroOptionalTextField(codewords, codeIndex + 1, fileName); resultMetadata.setFileName(fileName); break; } case MACRO_PDF417_OPTIONAL_FIELD_SENDER: { std::string sender; codeIndex = DecodeMacroOptionalTextField(codewords, codeIndex + 1, sender); resultMetadata.setSender(sender); break; } case MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE: { std::string addressee; codeIndex = DecodeMacroOptionalTextField(codewords, codeIndex + 1, addressee); resultMetadata.setAddressee(addressee); break; } case MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT: { uint64_t segmentCount; codeIndex = DecodeMacroOptionalNumericField(codewords, codeIndex + 1, segmentCount); resultMetadata.setSegmentCount(narrow_cast<int>(segmentCount)); break; } case MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP: { uint64_t timestamp; codeIndex = DecodeMacroOptionalNumericField(codewords, codeIndex + 1, timestamp); resultMetadata.setTimestamp(timestamp); break; } case MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM: { uint64_t checksum; codeIndex = DecodeMacroOptionalNumericField(codewords, codeIndex + 1, checksum); resultMetadata.setChecksum(narrow_cast<int>(checksum)); break; } case MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE: { uint64_t fileSize; codeIndex = DecodeMacroOptionalNumericField(codewords, codeIndex + 1, fileSize); resultMetadata.setFileSize(fileSize); break; } default: throw FormatError(); } break; } case MACRO_PDF417_TERMINATOR: { codeIndex++; resultMetadata.setLastSegment(true); break; } default: throw FormatError(); } } // copy optional fields to additional options if (optionalFieldsStart != -1) { int optionalFieldsLength = codeIndex - optionalFieldsStart; if (resultMetadata.isLastSegment()) optionalFieldsLength--; // do not include terminator resultMetadata.setOptionalData( std::vector<int>(codewords.begin() + optionalFieldsStart, codewords.begin() + optionalFieldsStart + optionalFieldsLength)); } return codeIndex; } DecoderResult Decode(const std::vector<int>& codewords) { Content result; result.symbology = {'L', '2', char(-1)}; bool readerInit = false; auto resultMetadata = std::make_shared<DecoderResultExtra>(); try { for (int codeIndex = 1; codeIndex < codewords[0];) { int code = codewords[codeIndex++]; switch (code) { case TEXT_COMPACTION_MODE_LATCH: codeIndex = TextCompaction(codewords, codeIndex, result); break; // This should only be encountered once in this loop, when default Text Compaction mode applies // (see default case below) case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: codeIndex = TextCompaction(codewords, codeIndex - 1, result); break; case BYTE_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH_6: codeIndex = ByteCompaction(code, codewords, codeIndex, result); break; case NUMERIC_COMPACTION_MODE_LATCH: codeIndex = NumericCompaction(codewords, codeIndex, result); break; case ECI_CHARSET: case ECI_GENERAL_PURPOSE: case ECI_USER_DEFINED: codeIndex = ProcessECI(codewords, codeIndex, codewords[0], code, result); break; case BEGIN_MACRO_PDF417_CONTROL_BLOCK: codeIndex = DecodeMacroBlock(codewords, codeIndex, *resultMetadata); break; case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case MACRO_PDF417_TERMINATOR: // Should not see these outside a macro block throw FormatError(); break; case READER_INIT: if (codeIndex != 2) // Must be first codeword after symbol length (ISO/IEC 15438:2015 5.4.1.4) throw FormatError(); else readerInit = true; break; case LINKAGE_EANUCC: if (codeIndex != 2) // Must be first codeword after symbol length (GS1 Composite ISO/IEC 24723:2010 4.3) throw FormatError(); // TODO: handle else case break; case LINKAGE_OTHER: // Allowed to treat as invalid by ISO/IEC 24723:2010 5.4.1.5 and 5.4.6.1 when in Basic Channel Mode throw UnsupportedError("LINKAGE_OTHER, see ISO/IEC 15438:2015 5.4.1.5"); break; default: if (code >= TEXT_COMPACTION_MODE_LATCH) { // Reserved codewords (all others in switch) // Allowed to treat as invalid by ISO/IEC 24723:2010 5.4.6.1 when in Basic Channel Mode throw UnsupportedError("Reserved codeword, see ISO/IEC 15438:2015 5.4.6.1"); } else { // Default mode is Text Compaction mode Alpha sub-mode (ISO/IEC 15438:2015 5.4.2.1) codeIndex = TextCompaction(codewords, codeIndex - 1, result); } break; } } } catch (std::exception& e) { return FormatError(e.what()); } catch (Error e) { return e; } if (result.empty() && resultMetadata->segmentIndex() == -1) return FormatError(); StructuredAppendInfo sai; if (resultMetadata->segmentIndex() > -1) { sai.count = resultMetadata->segmentCount() != -1 ? resultMetadata->segmentCount() : (resultMetadata->isLastSegment() ? resultMetadata->segmentIndex() + 1 : 0); sai.index = resultMetadata->segmentIndex(); sai.id = resultMetadata->fileId(); } return DecoderResult(std::move(result)) .setStructuredAppend(sai) .setReaderInit(readerInit) .setExtra(resultMetadata); } } // namespace ZXing::Pdf417 ```
/content/code_sandbox/core/src/pdf417/PDFDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
7,007
```c++ /* */ #include "ZXBigInteger.h" #include "BitHacks.h" #include "ZXAlgorithms.h" #include <algorithm> #include <cassert> #include <cctype> #include <cstdint> #include <utility> namespace ZXing { using Block = BigInteger::Block; using Magnitude = std::vector<Block>; static const size_t NB_BITS = 8 * sizeof(Block); static void AddMag(const Magnitude& a, const Magnitude& b, Magnitude& c) { // a2 points to the longer input, b2 points to the shorter const Magnitude& a2 = a.size() >= b.size() ? a : b; const Magnitude& b2 = a.size() >= b.size() ? b : a; // need to store the old sizes of a and b, in case c aliases either of them const size_t a2Size = a2.size(), b2Size = b2.size(); c.resize(a2Size + 1); size_t i = 0; bool carryIn = false; for (; i < b2Size; ++i) { auto temp = a2[i] + b2[i]; bool carryOut = (temp < a2[i]); if (carryIn) { ++temp; carryOut |= (temp == 0); } c[i] = temp; carryIn = carryOut; } // If there is a carry left over, increase blocks until one does not roll over. for (; i < a2Size && carryIn; ++i) { auto temp = a2[i] + 1; carryIn = (temp == 0); c[i] = temp; } // If the carry was resolved but the larger number still has blocks, copy them over. for (; i < a2Size; ++i) { c[i] = a2[i]; } // Set the extra block if there's still a carry, decrease length otherwise if (carryIn) { c[i] = 1; } else { c.pop_back(); } } // Note that we DO NOT support the case where b is greater than a. static void SubMag(const Magnitude& a, const Magnitude& b, Magnitude& c) { assert(a.size() >= b.size()); // need to store the old sizes of a and b, in case c aliases either of them const size_t aSize = a.size(), bSize = b.size(); c.resize(aSize); size_t i = 0; bool borrowIn = false; for (; i < bSize; ++i) { auto temp = a[i] - b[i]; // If a reverse rollover occurred, the result is greater than the block from a. bool borrowOut = (temp > a[i]); if (borrowIn) { borrowOut |= (temp == 0); temp--; } c[i] = temp; borrowIn = borrowOut; } // If there is a borrow left over, decrease blocks until one does not reverse rollover. for (; i < aSize && borrowIn; ++i) { borrowIn = (a[i] == 0); c[i] = a[i] - 1; } //if (borrowIn) { //throw error; //} // Copy over the rest of the blocks for (; i < aSize; ++i) { c[i] = a[i]; } // Zap leading zeros while (!c.empty() && c.back() == 0) { c.pop_back(); } } static Block GetShiftedBlock(const Magnitude& num, size_t x, size_t y) { Block part1 = (x == 0 || y == 0) ? Block(0) : (num[x - 1] >> (NB_BITS - y)); Block part2 = (x == num.size()) ? Block(0) : (num[x] << y); return part1 | part2; } static void MulMag(const Magnitude& a, const Magnitude& b, Magnitude& c) { // If either a or b is zero, set to zero. if (a.empty() || b.empty()) { c.clear(); return; } Magnitude tmp; Magnitude& r = &c == &a || &c == &b ? tmp : c; /* * Overall method: * * Set this = 0. * For each 1-bit of `a' (say the `i2'th bit of block `i'): * Add `b << (i blocks and i2 bits)' to *this. */ r.clear(); r.resize(a.size() + b.size(), 0); // For each block of the first number... for (size_t i = 0; i < a.size(); ++i) { // For each 1-bit of that block... for (size_t i2 = 0; i2 < NB_BITS; ++i2) { if ((a[i] & (Block(1) << i2)) == 0) continue; /* * Add b to this, shifted left i blocks and i2 bits. * j is the index in b, and k = i + j is the index in this. * * `getShiftedBlock', a short inline function defined above, * is now used for the bit handling. It replaces the more * complex `bHigh' code, in which each run of the loop dealt * immediately with the low bits and saved the high bits to * be picked up next time. The last run of the loop used to * leave leftover high bits, which were handled separately. * Instead, this loop runs an additional time with j == b.len. * These changes were made on 2005.01.11. */ size_t k = i; bool carryIn = false; for (size_t j = 0; j <= b.size(); ++j, ++k) { /* * The body of this loop is very similar to the body of the first loop * in `add', except that this loop does a `+=' instead of a `+'. */ auto temp = r[k] + GetShiftedBlock(b, j, i2); auto carryOut = (temp < r[k]); if (carryIn) { temp++; carryOut |= (temp == 0); } r[k] = temp; carryIn = carryOut; } // No more extra iteration to deal with `bHigh'. // Roll-over a carry as necessary. for (; carryIn; k++) { r[k]++; carryIn = (r[k] == 0); } } } // Zap possible leading zero if (r.back() == 0) { r.pop_back(); } if (&c != &r) c = std::move(r); } /* * DIVISION WITH REMAINDER * This monstrous function mods *this by the given divisor b while storing the * quotient in the given object q; at the end, *this contains the remainder. * The seemingly bizarre pattern of inputs and outputs was chosen so that the * function copies as little as possible (since it is implemented by repeated * subtraction of multiples of b from *this). * * "modWithQuotient" might be a better name for this function, but I would * rather not change the name now. */ static void DivideWithRemainder(const Magnitude& a, const Magnitude& b, Magnitude& qq, Magnitude& rr) { /* Defending against aliased calls is more complex than usual because we * are writing to both r and q. * * It would be silly to try to write quotient and remainder to the * same variable. Rule that out right away. */ assert(&rr != &qq); Magnitude tmp, tmp2; Magnitude& q = &qq == &a || &qq == &b ? tmp : qq; Magnitude& r = &rr == &b ? tmp2 : rr; /* * Knuth's definition of mod (which this function uses) is somewhat * different from the C++ definition of % in case of division by 0. * * We let a / 0 == 0 (it doesn't matter much) and a % 0 == a, no * exceptions thrown. This allows us to preserve both Knuth's demand * that a mod 0 == a and the useful property that * (a / b) * b + (a % b) == a. */ /* * If a.len < b.len, then a < b, and we can be sure that b doesn't go into * a at all. The quotient is 0 and *this is already the remainder (so leave it alone). */ if (b.empty() || a.size() < b.size()) { qq.clear(); rr = a; return; } // At this point we know a.len >= b.len > 0. (Whew!) /* * Overall method: * * For each appropriate i and i2, decreasing: * Subtract (b << (i blocks and i2 bits)) from *this, storing the * result in subtractBuf. * If the subtraction succeeds with a nonnegative result: * Turn on bit i2 of block i of the quotient q. * Copy subtractBuf back into *this. * Otherwise bit i2 of block i remains off, and *this is unchanged. * * Eventually q will contain the entire quotient, and *this will * be left with the remainder. * * subtractBuf[x] corresponds to blk[x], not blk[x+i], since 2005.01.11. * But on a single iteration, we don't touch the i lowest blocks of blk * (and don't use those of subtractBuf) because these blocks are * unaffected by the subtraction: we are subtracting * (b << (i blocks and i2 bits)), which ends in at least `i' zero * blocks. */ /* * Make sure we have an extra zero block just past the value. * * When we attempt a subtraction, we might shift `b' so * its first block begins a few bits left of the dividend, * and then we'll try to compare these extra bits with * a nonexistent block to the left of the dividend. The * extra zero block ensures sensible behavior; we need * an extra block in `subtractBuf' for exactly the same reason. */ if (&r != &a) { r.reserve(a.size() + 1); r = a; } r.push_back(0); Magnitude subtractBuf(r.size()); // Set preliminary length for quotient and make room q.resize(a.size() - b.size() + 1); // For each possible left-shift of b in blocks... size_t i = q.size(); while (i > 0) { i--; // For each possible left-shift of b in bits... // (Remember, N is the number of bits in a Blk.) q[i] = 0; size_t i2 = NB_BITS; while (i2 > 0) { i2--; /* * Subtract b, shifted left i blocks and i2 bits, from *this, * and store the answer in subtractBuf. In the for loop, `k == i + j'. * * Compare this to the middle section of `multiply'. They * are in many ways analogous. See especially the discussion * of `getShiftedBlock'. */ size_t k = i; bool borrowIn = false; for (size_t j = 0; j <= b.size(); ++j, ++k) { auto temp = r[k] - GetShiftedBlock(b, j, i2); bool borrowOut = (temp > r[k]); if (borrowIn) { borrowOut |= (temp == 0); temp--; } // Since 2005.01.11, indices of `subtractBuf' directly match those of `blk', so use `k'. subtractBuf[k] = temp; borrowIn = borrowOut; } // No more extra iteration to deal with `bHigh'. // Roll-over a borrow as necessary. for (; k < a.size() && borrowIn; k++) { borrowIn = (r[k] == 0); subtractBuf[k] = r[k] - 1; } /* * If the subtraction was performed successfully (!borrowIn), * set bit i2 in block i of the quotient. * * Then, copy the portion of subtractBuf filled by the subtraction * back to *this. This portion starts with block i and ends-- * where? Not necessarily at block `i + b.len'! Well, we * increased k every time we saved a block into subtractBuf, so * the region of subtractBuf we copy is just [i, k). */ if (!borrowIn) { q[i] |= (Block(1) << i2); while (k > i) { k--; r[k] = subtractBuf[k]; } } } } // Zap possible leading zero in quotient if (q.back() == 0) q.pop_back(); // Zap any/all leading zeros in remainder while (!r.empty() && r.back() == 0) { r.pop_back(); } if (&qq != &q) qq = std::move(q); if (&rr != &r) rr = std::move(r); } static int CompareMag(const Magnitude& a, const Magnitude& b) { // A bigger length implies a bigger number. if (a.size() < b.size()) { return -1; } else if (a.size() > b.size()) { return 1; } else { // Compare blocks one by one from left to right. auto p = std::mismatch(a.rbegin(), a.rend(), b.rbegin()); if (p.first != a.rend()) { return *p.first < *p.second ? -1 : 1; // note: cannot use subtraction here } return 0; } } template <typename StrT> static bool ParseFromString(const StrT& str, std::vector<Block>& mag, bool& negative) { auto iter = str.begin(); auto end = str.end(); while (iter != end && std::isspace(*iter)) ++iter; if (iter != end) { mag.clear(); negative = false; if (*iter == '-') { negative = true; ++iter; } else if (*iter == '+') { ++iter; } Magnitude ten{10}; Magnitude tmp{0}; for (int c; iter != end && std::isdigit(c = *iter); ++iter) { tmp[0] = c - '0'; MulMag(mag, ten, mag); AddMag(mag, tmp, mag); } return !mag.empty(); } return false; } bool BigInteger::TryParse(const std::string& str, BigInteger& result) { return ParseFromString(str, result.mag, result.negative); } bool BigInteger::TryParse(const std::wstring& str, BigInteger& result) { return ParseFromString(str, result.mag, result.negative); } void BigInteger::Add(const BigInteger& a, const BigInteger &b, BigInteger& c) { // If one argument is zero, copy the other. if (a.mag.empty()) { c = b; return; } if (b.mag.empty()) { c = a; return; } // If the arguments have the same sign, take the // common sign and add their magnitudes. if (a.negative == b.negative) { c.negative = a.negative; AddMag(a.mag, b.mag, c.mag); } else { // Otherwise, their magnitudes must be compared. int cmp = CompareMag(a.mag, b.mag); if (cmp < 0) { c.negative = b.negative; SubMag(b.mag, a.mag, c.mag); } else if (cmp > 0) { c.negative = a.negative; SubMag(a.mag, b.mag, c.mag); } else { c.negative = false; c.mag.clear(); } } } void BigInteger::Subtract(const BigInteger &a, const BigInteger &b, BigInteger& c) { if (a.mag.empty()) { c.negative = !b.negative; c.mag = b.mag; return; } if (b.mag.empty()) { c = a; return; } // If their signs differ, take a.sign and add the magnitudes. if (a.negative != b.negative) { c.negative = a.negative; AddMag(a.mag, b.mag, c.mag); } else { int cmp = CompareMag(a.mag, b.mag); if (cmp < 0) { c.negative = !b.negative; SubMag(b.mag, a.mag, c.mag); } else if (cmp > 0) { c.negative = a.negative; SubMag(a.mag, b.mag, c.mag); } else { c.negative = false; c.mag.clear(); } } } void BigInteger::Multiply(const BigInteger &a, const BigInteger &b, BigInteger& c) { if (a.mag.empty() || b.mag.empty()) { c.negative = false; c.mag.clear(); return; } c.negative = a.negative != b.negative; MulMag(a.mag, b.mag, c.mag); } /* * DIVISION WITH REMAINDER * Please read the comments before the definition of * `BigUnsigned::divideWithRemainder' in `BigUnsigned.cc' for lots of * information you should know before reading this function. * * Following Knuth, I decree that x / y is to be * 0 if y==0 and floor(real-number x / y) if y!=0. * Then x % y shall be x - y*(integer x / y). * * Note that x = y * (x / y) + (x % y) always holds. * In addition, (x % y) is from 0 to y - 1 if y > 0, * and from -(|y| - 1) to 0 if y < 0. (x % y) = x if y = 0. * * Examples: (q = a / b, r = a % b) * a b q r * === === === === * 4 3 1 1 * -4 3 -2 2 * 4 -3 -2 -2 * -4 -3 1 -1 */ void BigInteger::Divide(const BigInteger &a, const BigInteger &b, BigInteger &quotient, BigInteger& remainder) { if (b.mag.empty() || a.mag.size() < b.mag.size()) { quotient.mag.clear(); quotient.negative = false; remainder = a; return; } // Do the operands have the same sign? if (a.negative == b.negative) { // Yes: easy case. Quotient is zero or positive. quotient.negative = false; DivideWithRemainder(a.mag, b.mag, quotient.mag, remainder.mag); } else { // No: harder case. Quotient is negative. quotient.negative = true; // Decrease the magnitude of the dividend by one. Magnitude one{ 1 }; Magnitude aa; SubMag(a.mag, one, aa); /* * We tinker with the dividend before and with the * quotient and remainder after so that the result * comes out right. To see why it works, consider the following * list of examples, where A is the magnitude-decreased * a, Q and R are the results of BigUnsigned division * with remainder on A and |b|, and q and r are the * final results we want: * * a A b Q R q r * -3 -2 3 0 2 -1 0 * -4 -3 3 1 0 -2 2 * -5 -4 3 1 1 -2 1 * -6 -5 3 1 2 -2 0 * * It appears that we need a total of 3 corrections: * Decrease the magnitude of a to get A. Increase the * magnitude of Q to get q (and make it negative). * Find r = (b - 1) - R and give it the desired sign. */ DivideWithRemainder(aa, b.mag, quotient.mag, remainder.mag); AddMag(quotient.mag, one, quotient.mag); // Modify the remainder. SubMag(b.mag, remainder.mag, remainder.mag); SubMag(remainder.mag, one, remainder.mag); } // Sign of the remainder is always the sign of the divisor b. remainder.negative = b.negative; // Set signs to zero as necessary. (Thanks David Allen!) if (remainder.mag.empty()) remainder.negative = false; if (quotient.mag.empty()) quotient.negative = false; } size_t ceilingDiv(size_t a, size_t b) { return (a + b - 1) / b; } std::string BigInteger::toString() const { if (mag.empty()) { return "0"; } std::string result; if (negative) { result.push_back('-'); } static const uint32_t base = 10; auto maxBitLenOfX = static_cast<uint32_t>(mag.size()) * NB_BITS; int minBitsPerDigit = BitHacks::HighestBitSet(base); auto maxDigitLenOfX = (maxBitLenOfX + minBitsPerDigit - 1) / minBitsPerDigit; // ceilingDiv std::vector<uint8_t> buffer; buffer.reserve(maxDigitLenOfX); Magnitude x2 = mag; Magnitude buBase{base}; Magnitude lastDigit; lastDigit.reserve(1); while (!x2.empty()) { // Get last digit. This is like `lastDigit = x2 % buBase, x2 /= buBase'. DivideWithRemainder(x2, buBase, x2, lastDigit); // Save the digit. buffer.push_back(static_cast<uint8_t>(lastDigit.empty() ? 0 : lastDigit.front())); } size_t offset = result.size(); result.resize(offset + buffer.size()); std::transform(buffer.rbegin(), buffer.rend(), result.begin() + offset, ToDigit<char>); return result; } int BigInteger::toInt() const { if (mag.empty()) return 0; else if (negative) return -static_cast<int>(mag.back()); else return static_cast<int>(mag.back()); } } // ZXing ```
/content/code_sandbox/core/src/pdf417/ZXBigInteger.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
5,259
```objective-c /* */ #pragma once #include "ZXAlgorithms.h" #include <utility> #include <vector> namespace ZXing { namespace Pdf417 { class ModulusGF; /** * @author Sean Owen * @see com.google.zxing.common.reedsolomon.GenericGFPoly */ class ModulusPoly { const ModulusGF* _field = nullptr; std::vector<int> _coefficients; public: // Build a invalid object, so that this can be used in container or return by reference, // any access to invalid object is undefined behavior. ModulusPoly() = default; ModulusPoly(const ModulusGF& field, const std::vector<int>& coefficients); const std::vector<int>& coefficients() const { return _coefficients; } /** * @return degree of this polynomial */ int degree() const { return Size(_coefficients) - 1; } /** * @return true iff this polynomial is the monomial "0" */ bool isZero() const { return _coefficients.at(0) == 0; } /** * @return coefficient of x^degree term in this polynomial */ int coefficient(int degree) const { return _coefficients.at(_coefficients.size() - 1 - degree); } /** * @return evaluation of this polynomial at a given point */ int evaluateAt(int a) const; ModulusPoly add(const ModulusPoly& other) const; ModulusPoly subtract(const ModulusPoly& other) const; ModulusPoly multiply(const ModulusPoly& other) const; ModulusPoly negative() const; ModulusPoly multiply(int scalar) const; ModulusPoly multiplyByMonomial(int degree, int coefficient) const; void divide(const ModulusPoly& other, ModulusPoly& quotient, ModulusPoly& remainder) const; friend void swap(ModulusPoly& a, ModulusPoly& b) { std::swap(a._field, b._field); std::swap(a._coefficients, b._coefficients); } }; } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFModulusPoly.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
457
```c++ /* */ #include "PDFDetectionResult.h" #include "PDFCodewordDecoder.h" #include "ZXAlgorithms.h" #include <algorithm> #include <array> namespace ZXing { namespace Pdf417 { static const int ADJUST_ROW_NUMBER_SKIP = 2; DetectionResult::DetectionResult(const BarcodeMetadata& barcodeMetadata, const Nullable<BoundingBox>& boundingBox) : _barcodeMetadata(barcodeMetadata), _detectionResultColumns(barcodeMetadata.columnCount() + 2), _boundingBox(boundingBox) { } void DetectionResult::init(const BarcodeMetadata& barcodeMetadata, const Nullable<BoundingBox>& boundingBox) { _barcodeMetadata = barcodeMetadata; _boundingBox = boundingBox; _detectionResultColumns.resize(barcodeMetadata.columnCount() + 2); std::fill(_detectionResultColumns.begin(), _detectionResultColumns.end(), nullptr); } static void AdjustIndicatorColumnRowNumbers(Nullable<DetectionResultColumn>& detectionResultColumn, const BarcodeMetadata& barcodeMetadata) { if (detectionResultColumn != nullptr) { detectionResultColumn.value().adjustCompleteIndicatorColumnRowNumbers(barcodeMetadata); } } static void AdjustRowNumbersFromBothRI(std::vector<Nullable<DetectionResultColumn>>& detectionResultColumns) { if (detectionResultColumns.front() == nullptr || detectionResultColumns.back() == nullptr) { return; } auto& LRIcodewords = detectionResultColumns.front().value().allCodewords(); auto& RRIcodewords = detectionResultColumns.back().value().allCodewords(); for (size_t codewordsRow = 0; codewordsRow < LRIcodewords.size(); codewordsRow++) { if (LRIcodewords[codewordsRow] != nullptr && RRIcodewords[codewordsRow] != nullptr && LRIcodewords[codewordsRow].value().rowNumber() == RRIcodewords[codewordsRow].value().rowNumber()) { auto lastColumn = detectionResultColumns.end() - 1; for (auto columnIter = detectionResultColumns.begin() + 1; columnIter != lastColumn; ++columnIter) { if (!columnIter->hasValue()) { continue; } auto& codeword = columnIter->value().allCodewords()[codewordsRow]; if (codeword != nullptr) { codeword.value().setRowNumber(LRIcodewords[codewordsRow].value().rowNumber()); if (!codeword.value().hasValidRowNumber()) { columnIter->value().allCodewords()[codewordsRow] = nullptr; } } } } } } static int AdjustRowNumberIfValid(int rowIndicatorRowNumber, int invalidRowCounts, Codeword& codeword) { if (!codeword.hasValidRowNumber()) { if (codeword.isValidRowNumber(rowIndicatorRowNumber)) { codeword.setRowNumber(rowIndicatorRowNumber); invalidRowCounts = 0; } else { ++invalidRowCounts; } } return invalidRowCounts; } static int AdjustRowNumbersFromLRI(std::vector<Nullable<DetectionResultColumn>>& detectionResultColumns) { if (detectionResultColumns.front() == nullptr) { return 0; } int unadjustedCount = 0; auto& codewords = detectionResultColumns.front().value().allCodewords(); for (size_t codewordsRow = 0; codewordsRow < codewords.size(); codewordsRow++) { if (codewords[codewordsRow] == nullptr) { continue; } int rowIndicatorRowNumber = codewords[codewordsRow].value().rowNumber(); int invalidRowCounts = 0; auto lastColumn = detectionResultColumns.end() - 1; for (auto columnIter = detectionResultColumns.begin() + 1; columnIter != lastColumn && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP; ++columnIter) { if (!columnIter->hasValue()) { continue; } auto& codeword = columnIter->value().allCodewords()[codewordsRow]; if (codeword != nullptr) { invalidRowCounts = AdjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword.value()); if (!codeword.value().hasValidRowNumber()) { unadjustedCount++; } } } } return unadjustedCount; } static int AdjustRowNumbersFromRRI(std::vector<Nullable<DetectionResultColumn>>& detectionResultColumns) { if (detectionResultColumns.back() == nullptr) { return 0; } int unadjustedCount = 0; auto& codewords = detectionResultColumns.back().value().allCodewords(); for (size_t codewordsRow = 0; codewordsRow < codewords.size(); codewordsRow++) { if (codewords[codewordsRow] == nullptr) { continue; } int rowIndicatorRowNumber = codewords[codewordsRow].value().rowNumber(); int invalidRowCounts = 0; auto lastColumn = detectionResultColumns.end() - 1; for (auto columnIter = detectionResultColumns.begin() + 1; columnIter != lastColumn && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP; ++columnIter) { if (!columnIter->hasValue()) { continue; } auto& codeword = columnIter->value().allCodewords()[codewordsRow]; if (codeword != nullptr) { invalidRowCounts = AdjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword.value()); if (!codeword.value().hasValidRowNumber()) { unadjustedCount++; } } } } return unadjustedCount; } static int AdjustRowNumbersByRow(std::vector<Nullable<DetectionResultColumn>>& detectionResultColumns) { AdjustRowNumbersFromBothRI(detectionResultColumns); // TODO we should only do full row adjustments if row numbers of left and right row indicator column match. // Maybe it's even better to calculated the height (in codeword rows) and divide it by the number of barcode // rows. This, together with the LRI and RRI row numbers should allow us to get a good estimate where a row // number starts and ends. int unadjustedCount = AdjustRowNumbersFromLRI(detectionResultColumns); return unadjustedCount + AdjustRowNumbersFromRRI(detectionResultColumns); } /** * @return true, if row number was adjusted, false otherwise */ static bool AdjustRowNumber(Nullable<Codeword>& codeword, const Nullable<Codeword>& otherCodeword) { if (codeword != nullptr && otherCodeword != nullptr && otherCodeword.value().hasValidRowNumber() && otherCodeword.value().bucket() == codeword.value().bucket()) { codeword.value().setRowNumber(otherCodeword.value().rowNumber()); return true; } return false; } static void AdjustRowNumbers(const std::vector<Nullable<DetectionResultColumn>>& detectionResultColumns, int barcodeColumn, int codewordsRow, std::vector<Nullable<Codeword>>& codewords) { auto& codeword = codewords[codewordsRow]; auto& previousColumnCodewords = detectionResultColumns[barcodeColumn - 1].value().allCodewords(); auto& nextColumnCodewords = detectionResultColumns[barcodeColumn + 1] != nullptr ? detectionResultColumns[barcodeColumn + 1].value().allCodewords() : previousColumnCodewords; std::array<Nullable<Codeword>, 14> otherCodewords; otherCodewords[2] = previousColumnCodewords[codewordsRow]; otherCodewords[3] = nextColumnCodewords[codewordsRow]; if (codewordsRow > 0) { otherCodewords[0] = codewords[codewordsRow - 1]; otherCodewords[4] = previousColumnCodewords[codewordsRow - 1]; otherCodewords[5] = nextColumnCodewords[codewordsRow - 1]; } if (codewordsRow > 1) { otherCodewords[8] = codewords[codewordsRow - 2]; otherCodewords[10] = previousColumnCodewords[codewordsRow - 2]; otherCodewords[11] = nextColumnCodewords[codewordsRow - 2]; } if (codewordsRow < Size(codewords) - 1) { otherCodewords[1] = codewords[codewordsRow + 1]; otherCodewords[6] = previousColumnCodewords[codewordsRow + 1]; otherCodewords[7] = nextColumnCodewords[codewordsRow + 1]; } if (codewordsRow < Size(codewords) - 2) { otherCodewords[9] = codewords[codewordsRow + 2]; otherCodewords[12] = previousColumnCodewords[codewordsRow + 2]; otherCodewords[13] = nextColumnCodewords[codewordsRow + 2]; } for (const auto& otherCodeword : otherCodewords) { if (AdjustRowNumber(codeword, otherCodeword)) { return; } } } // TODO ensure that no detected codewords with unknown row number are left // we should be able to estimate the row height and use it as a hint for the row number // we should also fill the rows top to bottom and bottom to top /** * @return number of codewords which don't have a valid row number. Note that the count is not accurate as codewords * will be counted several times. It just serves as an indicator to see when we can stop adjusting row numbers */ static int AdjustRowNumbers(std::vector<Nullable<DetectionResultColumn>>& detectionResultColumns) { int unadjustedCount = AdjustRowNumbersByRow(detectionResultColumns); if (unadjustedCount == 0) { return 0; } for (int barcodeColumn = 1; barcodeColumn < Size(detectionResultColumns) - 1; barcodeColumn++) { if (detectionResultColumns[barcodeColumn] == nullptr) { continue; } auto& codewords = detectionResultColumns[barcodeColumn].value().allCodewords(); for (int codewordsRow = 0; codewordsRow < Size(codewords); codewordsRow++) { if (codewords[codewordsRow] == nullptr) { continue; } if (!codewords[codewordsRow].value().hasValidRowNumber()) { AdjustRowNumbers(detectionResultColumns, barcodeColumn, codewordsRow, codewords); } } } return unadjustedCount; } const std::vector<Nullable<DetectionResultColumn>> & DetectionResult::allColumns() { AdjustIndicatorColumnRowNumbers(_detectionResultColumns.front(), _barcodeMetadata); AdjustIndicatorColumnRowNumbers(_detectionResultColumns.back(), _barcodeMetadata); int unadjustedCodewordCount = CodewordDecoder::MAX_CODEWORDS_IN_BARCODE; int previousUnadjustedCount; do { previousUnadjustedCount = unadjustedCodewordCount; unadjustedCodewordCount = AdjustRowNumbers(_detectionResultColumns); } while (unadjustedCodewordCount > 0 && unadjustedCodewordCount < previousUnadjustedCount); return _detectionResultColumns; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFDetectionResult.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,632
```c #include "common.h" #define STUB_PIXEL_PLOT(NAME) \ INTERNAL int NAME(struct zint_symbol* symbol, const unsigned char* pixelbuf) \ { \ (void)symbol; \ (void)pixelbuf; \ return ZINT_ERROR_ENCODING_PROBLEM; \ } #define STUB_FUNC_CHAR(NAME) \ INTERNAL int NAME(struct zint_symbol* symbol, unsigned char source[], int length) \ { \ (void)symbol; \ (void)source; \ (void)length; \ return ZINT_ERROR_ENCODING_PROBLEM; \ } #define STUB_FUNC_SEGS(NAME) \ INTERNAL int NAME(struct zint_symbol* symbol, struct zint_seg segs[], const int seg_count) \ { \ (void)symbol; \ (void)segs; \ (void)seg_count; \ return ZINT_ERROR_ENCODING_PROBLEM; \ } STUB_PIXEL_PLOT(png_pixel_plot) STUB_PIXEL_PLOT(bmp_pixel_plot) STUB_PIXEL_PLOT(pcx_pixel_plot) STUB_PIXEL_PLOT(gif_pixel_plot) STUB_PIXEL_PLOT(tif_pixel_plot) INTERNAL int ps_plot(struct zint_symbol* symbol) { (void)symbol; return ZINT_ERROR_ENCODING_PROBLEM; } INTERNAL int emf_plot(struct zint_symbol* symbol, int rotate_angle) { (void)symbol; (void)rotate_angle; return ZINT_ERROR_ENCODING_PROBLEM; } // STUB_FUNC_CHAR(pzn) // STUB_FUNC_CHAR(c25ind) // STUB_FUNC_CHAR(c25iata) // STUB_FUNC_CHAR(c25inter) // STUB_FUNC_CHAR(c25logic) // STUB_FUNC_CHAR(itf14) // STUB_FUNC_CHAR(dpleit) // STUB_FUNC_CHAR(dpident) // STUB_FUNC_CHAR(code11) STUB_FUNC_CHAR(msi_plessey) STUB_FUNC_CHAR(telepen) STUB_FUNC_CHAR(telepen_num) STUB_FUNC_CHAR(plessey) // STUB_FUNC_CHAR(pharma) STUB_FUNC_CHAR(flat) STUB_FUNC_CHAR(fim) // STUB_FUNC_CHAR(pharma_two) STUB_FUNC_CHAR(postnet) STUB_FUNC_CHAR(planet) STUB_FUNC_CHAR(usps_imail) STUB_FUNC_CHAR(rm4scc) STUB_FUNC_CHAR(auspost) STUB_FUNC_CHAR(code16k) STUB_FUNC_CHAR(composite) STUB_FUNC_CHAR(kix) // STUB_FUNC_CHAR(code32) STUB_FUNC_CHAR(daft) // STUB_FUNC_CHAR(nve18) STUB_FUNC_CHAR(koreapost) STUB_FUNC_CHAR(japanpost) STUB_FUNC_CHAR(code49) // STUB_FUNC_CHAR(channel) STUB_FUNC_SEGS(codeone) STUB_FUNC_SEGS(gridmatrix) STUB_FUNC_SEGS(hanxin) STUB_FUNC_SEGS(dotcode) STUB_FUNC_SEGS(codablockf) // STUB_FUNC_CHAR(vin) STUB_FUNC_CHAR(mailmark_2d) STUB_FUNC_CHAR(mailmark_4s) // STUB_FUNC_CHAR(upu_s10) STUB_FUNC_SEGS(ultra) // STUB_FUNC_CHAR(dpd) STUB_FUNC_CHAR(bc412) ```
/content/code_sandbox/core/src/libzint/stubs.c
c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
680
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitArray; namespace Aztec { class Token { public: void appendTo(BitArray& bitArray, const std::string& text) const; static Token CreateSimple(int value, int bitCount) { return {value, -bitCount}; } static Token CreateBinaryShift(int start, int byteCount) { return {start, byteCount}; } private: short _value; short _count; // is simple token if negative, public: Token(int value, int count) : _value((short)value), _count((short)count) {} }; } // Aztec } // ZXing ```
/content/code_sandbox/core/src/aztec/AZToken.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
147
```objective-c /* */ #pragma once #include "DetectorResult.h" #include <utility> namespace ZXing::Aztec { class DetectorResult : public ZXing::DetectorResult { bool _compact = false; int _nbDatablocks = 0; int _nbLayers = 0; bool _readerInit = false; bool _isMirrored = false; int _runeValue = -1; DetectorResult(const DetectorResult&) = delete; DetectorResult& operator=(const DetectorResult&) = delete; public: DetectorResult() = default; DetectorResult(DetectorResult&&) noexcept = default; DetectorResult& operator=(DetectorResult&&) noexcept = default; DetectorResult(ZXing::DetectorResult&& result, bool isCompact, int nbDatablocks, int nbLayers, bool readerInit, bool isMirrored, int runeValue) : ZXing::DetectorResult{std::move(result)}, _compact(isCompact), _nbDatablocks(nbDatablocks), _nbLayers(nbLayers), _readerInit(readerInit), _isMirrored(isMirrored), _runeValue(runeValue) {} bool isCompact() const { return _compact; } int nbDatablocks() const { return _nbDatablocks; } int nbLayers() const { return _nbLayers; } bool readerInit() const { return _readerInit; } bool isMirrored() const { return _isMirrored; } // Only meaningful is nbDatablocks == 0 int runeValue() const { return _runeValue; } }; } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZDetectorResult.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
353
```c++ /* */ #include "AZToken.h" #include "BitArray.h" #include <algorithm> namespace ZXing::Aztec { void Token::appendTo(BitArray& bitArray, const std::string& text) const { if (_count < 0) { bitArray.appendBits(_value, -_count); } else { for (int i = 0; i < _count; i++) { if (i == 0 || (i == 31 && _count <= 62)) { // We need a header before the first character, and before // character 31 when the total byte code is <= 62 bitArray.appendBits(31, 5); // BINARY_SHIFT if (_count > 62) { bitArray.appendBits(_count - 31, 16); } else if (i == 0) { // 1 <= binaryShiftByteCode <= 62 bitArray.appendBits(std::min((int)_count, 31), 5); } else { // 32 <= binaryShiftCount <= 62 and i == 31 bitArray.appendBits(_count - 31, 5); } } bitArray.appendBits(text[_value + i], 8); } } } } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZToken.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
299
```c++ /* */ #include "AZReader.h" #include "AZDecoder.h" #include "AZDetector.h" #include "AZDetectorResult.h" #include "BinaryBitmap.h" #include "ReaderOptions.h" #include "DecoderResult.h" #include "Barcode.h" #include <utility> namespace ZXing::Aztec { Barcode Reader::decode(const BinaryBitmap& image) const { auto binImg = image.getBitMatrix(); if (binImg == nullptr) return {}; DetectorResult detectorResult = Detect(*binImg, _opts.isPure(), _opts.tryHarder()); if (!detectorResult.isValid()) return {}; auto decodeResult = Decode(detectorResult) .setReaderInit(detectorResult.readerInit()) .setIsMirrored(detectorResult.isMirrored()) .setVersionNumber(detectorResult.nbLayers()); return Barcode(std::move(decodeResult), std::move(detectorResult), BarcodeFormat::Aztec); } Barcodes Reader::decode(const BinaryBitmap& image, int maxSymbols) const { auto binImg = image.getBitMatrix(); if (binImg == nullptr) return {}; auto detRess = Detect(*binImg, _opts.isPure(), _opts.tryHarder(), maxSymbols); Barcodes baracodes; for (auto&& detRes : detRess) { auto decRes = Decode(detRes).setReaderInit(detRes.readerInit()).setIsMirrored(detRes.isMirrored()).setVersionNumber(detRes.nbLayers()); if (decRes.isValid(_opts.returnErrors())) { baracodes.emplace_back(std::move(decRes), std::move(detRes), BarcodeFormat::Aztec); if (maxSymbols > 0 && Size(baracodes) >= maxSymbols) break; } } return baracodes; } } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
389
```objective-c /* */ #pragma once #include "CharacterSet.h" #include <string> namespace ZXing { class BitMatrix; namespace Aztec { class Writer { public: Writer(); Writer& setMargin(int margin) { _margin = margin; return *this; } Writer& setEncoding(CharacterSet encoding) { _encoding = encoding; return *this; } Writer& setEccPercent(int percent) { _eccPercent = percent; return *this; } Writer& setLayers(int layers) { _layers = layers; return *this; } BitMatrix encode(const std::wstring& contents, int width, int height) const; BitMatrix encode(const std::string& contents, int width, int height) const; private: CharacterSet _encoding; int _eccPercent; int _layers; int _margin = 0; }; } // Aztec } // ZXing ```
/content/code_sandbox/core/src/aztec/AZWriter.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
201
```c++ /* */ #include "AZHighLevelEncoder.h" #include "AZEncodingState.h" #include "AZToken.h" #include "BitArray.h" #include "ZXAlgorithms.h" #include <algorithm> #include <array> #include <cstdint> #include <list> #include <vector> namespace ZXing::Aztec { // Do not change these constants static const int MODE_UPPER = 0; // 5 bits static const int MODE_LOWER = 1; // 5 bits static const int MODE_DIGIT = 2; // 4 bits static const int MODE_MIXED = 3; // 5 bits static const int MODE_PUNCT = 4; // 5 bits // The Latch Table shows, for each pair of Modes, the optimal method for // getting from one mode to another. In the worst possible case, this can // be up to 14 bits. In the best possible case, we are already there! // The high half-word of each entry gives the number of bits. // The low half-word of each entry are the actual bits necessary to change static const std::array<std::array<int, 5>, 5> LATCH_TABLE = { 0, (5 << 16) + 28, // UPPER -> LOWER (5 << 16) + 30, // UPPER -> DIGIT (5 << 16) + 29, // UPPER -> MIXED (10 << 16) + (29 << 5) + 30, // UPPER -> MIXED -> PUNCT (9 << 16) + (30 << 4) + 14, // LOWER -> DIGIT -> UPPER 0, (5 << 16) + 30, // LOWER -> DIGIT (5 << 16) + 29, // LOWER -> MIXED (10 << 16) + (29 << 5) + 30, // LOWER -> MIXED -> PUNCT (4 << 16) + 14, // DIGIT -> UPPER (9 << 16) + (14 << 5) + 28, // DIGIT -> UPPER -> LOWER 0, (9 << 16) + (14 << 5) + 29, // DIGIT -> UPPER -> MIXED (14 << 16) + (14 << 10) + (29 << 5) + 30, // DIGIT -> UPPER -> MIXED -> PUNCT (5 << 16) + 29, // MIXED -> UPPER (5 << 16) + 28, // MIXED -> LOWER (10 << 16) + (29 << 5) + 30, // MIXED -> UPPER -> DIGIT 0, (5 << 16) + 30, // MIXED -> PUNCT (5 << 16) + 31, // PUNCT -> UPPER (10 << 16) + (31 << 5) + 28, // PUNCT -> UPPER -> LOWER (10 << 16) + (31 << 5) + 30, // PUNCT -> UPPER -> DIGIT (10 << 16) + (31 << 5) + 29, // PUNCT -> UPPER -> MIXED 0, }; // A reverse mapping from [mode][char] to the encoding for that character // in that mode. An entry of 0 indicates no mapping exists. static const std::array<std::array<int8_t, 256>, 5>& InitCharMap() { static std::array<std::array<int8_t, 256>, 5> charmap = {}; charmap[MODE_UPPER][' '] = 1; for (int c = 'A'; c <= 'Z'; c++) { charmap[MODE_UPPER][c] = c - 'A' + 2; } charmap[MODE_LOWER][' '] = 1; for (int c = 'a'; c <= 'z'; c++) { charmap[MODE_LOWER][c] = c - 'a' + 2; } charmap[MODE_DIGIT][' '] = 1; for (int c = '0'; c <= '9'; c++) { charmap[MODE_DIGIT][c] = c - '0' + 2; } charmap[MODE_DIGIT][','] = 12; charmap[MODE_DIGIT]['.'] = 13; const int8_t mixedTable[] = { 0x00, 0x20, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x40, 0x5c, 0x5e, 0x5f, 0x60, 0x7c, 0x7d, 0x7f, }; for (uint8_t i = 0; i < Size(mixedTable); i++) { charmap[MODE_MIXED][mixedTable[i]] = i; } const char punctTable[] = {'\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}'}; for (uint8_t i = 0; i < Size(punctTable); i++) { if (punctTable[i] > 0) { charmap[MODE_PUNCT][punctTable[i]] = i; } } return charmap; } const std::array<std::array<int8_t, 256>, 5>& CHAR_MAP = InitCharMap(); // A map showing the available shift codes. (The shifts to BINARY are not shown static const std::array<std::array<int8_t, 6>, 6>& InitShiftTable() { static std::array<std::array<int8_t, 6>, 6> table; for (auto& row : table) { std::fill(row.begin(), row.end(), -1); } table[MODE_UPPER][MODE_PUNCT] = 0; table[MODE_LOWER][MODE_PUNCT] = 0; table[MODE_LOWER][MODE_UPPER] = 28; table[MODE_MIXED][MODE_PUNCT] = 0; table[MODE_DIGIT][MODE_PUNCT] = 0; table[MODE_DIGIT][MODE_UPPER] = 15; return table; } const std::array<std::array<int8_t, 6>, 6>& SHIFT_TABLE = InitShiftTable(); // Create a new state representing this state with a latch to a (not // necessary different) mode, and then a code. static EncodingState LatchAndAppend(const EncodingState& state, int mode, int value) { //assert binaryShiftByteCount == 0; int bitCount = state.bitCount; auto tokens = state.tokens; if (mode != state.mode) { int latch = LATCH_TABLE[state.mode][mode]; tokens.push_back(Token::CreateSimple(latch & 0xFFFF, latch >> 16)); bitCount += latch >> 16; } int latchModeBitCount = mode == MODE_DIGIT ? 4 : 5; tokens.push_back(Token::CreateSimple(value, latchModeBitCount)); return EncodingState{ tokens, mode, 0, bitCount + latchModeBitCount }; } // Create a new state representing this state, with a temporary shift // to a different mode to output a single value. static EncodingState ShiftAndAppend(const EncodingState& state, int mode, int value) { //assert binaryShiftByteCount == 0 && this.mode != mode; int thisModeBitCount = state.mode == MODE_DIGIT ? 4 : 5; // Shifts exist only to UPPER and PUNCT, both with tokens size 5. auto tokens = state.tokens; tokens.push_back(Token::CreateSimple(SHIFT_TABLE[state.mode][mode], thisModeBitCount)); tokens.push_back(Token::CreateSimple(value, 5)); return EncodingState{ tokens, state.mode, 0, state.bitCount + thisModeBitCount + 5 }; } // Create the state identical to this one, but we are no longer in // Binary Shift mode. static EncodingState EndBinaryShift(const EncodingState& state, int index) { if (state.binaryShiftByteCount == 0) { return state; } auto tokens = state.tokens; tokens.push_back(Token::CreateBinaryShift(index - state.binaryShiftByteCount, state.binaryShiftByteCount)); //assert token.getTotalBitCount() == this.bitCount; return EncodingState{ tokens, state.mode, 0, state.bitCount }; } // Create a new state representing this state, but an additional character // output in Binary Shift mode. static EncodingState AddBinaryShiftChar(const EncodingState& state, int index) { auto tokens = state.tokens; int mode = state.mode; int bitCount = state.bitCount; if (state.mode == MODE_PUNCT || state.mode == MODE_DIGIT) { //assert binaryShiftByteCount == 0; int latch = LATCH_TABLE[mode][MODE_UPPER]; tokens.push_back(Token::CreateSimple(latch & 0xFFFF, latch >> 16)); bitCount += latch >> 16; mode = MODE_UPPER; } int deltaBitCount = (state.binaryShiftByteCount == 0 || state.binaryShiftByteCount == 31) ? 18 : (state.binaryShiftByteCount == 62) ? 9 : 8; EncodingState result{ tokens, mode, state.binaryShiftByteCount + 1, bitCount + deltaBitCount }; if (result.binaryShiftByteCount == 2047 + 31) { // The string is as long as it's allowed to be. We should end it. result = EndBinaryShift(result, index + 1); } return result; } static int CalculateBinaryShiftCost(const EncodingState& state) { if (state.binaryShiftByteCount > 62) { return 21; // B/S with extended length } if (state.binaryShiftByteCount > 31) { return 20; // two B/S } if (state.binaryShiftByteCount > 0) { return 10; // one B/S } return 0; } // Returns true if "this" state is better (or equal) to be in than "that" // state under all possible circumstances. static bool IsBetterThanOrEqualTo(const EncodingState& state, const EncodingState& other) { int newModeBitCount = state.bitCount + (LATCH_TABLE[state.mode][other.mode] >> 16); if (state.binaryShiftByteCount < other.binaryShiftByteCount) { // add additional B/S encoding cost of other, if any newModeBitCount += CalculateBinaryShiftCost(other) - CalculateBinaryShiftCost(state); } else if (state.binaryShiftByteCount > other.binaryShiftByteCount && other.binaryShiftByteCount > 0) { // maximum possible additional cost (we end up exceeding the 31 byte boundary and other state can stay beneath it) newModeBitCount += 10; } return newModeBitCount <= other.bitCount; } static BitArray ToBitArray(const EncodingState& state, const std::string& text) { auto endState = EndBinaryShift(state, Size(text)); BitArray bits; // Add each token to the result. for (const Token& symbol : endState.tokens) { symbol.appendTo(bits, text); } //assert bitArray.getSize() == this.bitCount; return bits; } static void UpdateStateForPair(const EncodingState& state, int index, int pairCode, std::list<EncodingState>& result) { EncodingState stateNoBinary = EndBinaryShift(state, index); // Possibility 1. Latch to MODE_PUNCT, and then append this code result.push_back(LatchAndAppend(stateNoBinary, MODE_PUNCT, pairCode)); if (state.mode != MODE_PUNCT) { // Possibility 2. Shift to MODE_PUNCT, and then append this code. // Every state except MODE_PUNCT (handled above) can shift result.push_back(ShiftAndAppend(stateNoBinary, MODE_PUNCT, pairCode)); } if (pairCode == 3 || pairCode == 4) { // both characters are in DIGITS. Sometimes better to just add two digits auto digitState = LatchAndAppend(stateNoBinary, MODE_DIGIT, 16 - pairCode); // period or comma in DIGIT result.push_back(LatchAndAppend(digitState, MODE_DIGIT, 1)); // space in DIGIT } if (state.binaryShiftByteCount > 0) { // It only makes sense to do the characters as binary if we're already // in binary mode. result.push_back(AddBinaryShiftChar(AddBinaryShiftChar(state, index), index + 1)); } } static std::list<EncodingState> SimplifyStates(const std::list<EncodingState>& states) { std::list<EncodingState> result; for (auto& newState : states) { bool add = true; for (auto iterator = result.begin(); iterator != result.end();) { auto& oldState = *iterator; if (IsBetterThanOrEqualTo(oldState, newState)) { add = false; break; } if (IsBetterThanOrEqualTo(newState, oldState)) { iterator = result.erase(iterator); } else { ++iterator; } } if (add) { result.push_back(newState); } } return result; } static std::list<EncodingState> UpdateStateListForPair(const std::list<EncodingState>& states, int index, int pairCode) { std::list<EncodingState> result; for (auto& state : states) { UpdateStateForPair(state, index, pairCode, result); } return SimplifyStates(result); } // Return a set of states that represent the possible ways of updating this // state for the next character. The resulting set of states are added to // the "result" list. static void UpdateStateForChar(const EncodingState& state, const std::string& text, int index, std::list<EncodingState>& result) { int ch = text[index] & 0xff; bool charInCurrentTable = CHAR_MAP[state.mode][ch] > 0; EncodingState stateNoBinary; bool firstTime = true; for (int mode = 0; mode <= MODE_PUNCT; mode++) { int charInMode = CHAR_MAP[mode][ch]; if (charInMode > 0) { if (firstTime) { // Only create stateNoBinary the first time it's required. stateNoBinary = EndBinaryShift(state, index); firstTime = false; } // Try generating the character by latching to its mode if (!charInCurrentTable || mode == state.mode || mode == MODE_DIGIT) { // If the character is in the current table, we don't want to latch to // any other mode except possibly digit (which uses only 4 bits). Any // other latch would be equally successful *after* this character, and // so wouldn't save any bits. result.push_back(LatchAndAppend(stateNoBinary, mode, charInMode)); } // Try generating the character by switching to its mode. if (!charInCurrentTable && SHIFT_TABLE[state.mode][mode] >= 0) { // It never makes sense to temporarily shift to another mode if the // character exists in the current mode. That can never save bits. result.push_back(ShiftAndAppend(stateNoBinary, mode, charInMode)); } } } if (state.binaryShiftByteCount > 0 || CHAR_MAP[state.mode][ch] == 0) { // It's never worthwhile to go into binary shift mode if you're not already // in binary shift mode, and the character exists in your current mode. // That can never save bits over just outputting the char in the current mode. result.push_back(AddBinaryShiftChar(state, index)); } } // We update a set of states for a new character by updating each state // for the new character, merging the results, and then removing the // non-optimal states. static std::list<EncodingState> UpdateStateListForChar(const std::list<EncodingState>& states, const std::string& text, int index) { std::list<EncodingState> result; for (auto& state : states) { UpdateStateForChar(state, text, index, result); } return result.size() > 1 ? SimplifyStates(result) : result; } /** * @return text represented by this encoder encoded as a {@link BitArray} */ BitArray HighLevelEncoder::Encode(const std::string& text) { std::list<EncodingState> states; states.push_back(EncodingState{ std::vector<Token>(), MODE_UPPER, 0, 0 }); for (int index = 0; index < Size(text); index++) { int pairCode; int nextChar = index + 1 < Size(text) ? text[index + 1] : 0; switch (text[index]) { case '\r': pairCode = nextChar == '\n' ? 2 : 0; break; case '.': pairCode = nextChar == ' ' ? 3 : 0; break; case ',': pairCode = nextChar == ' ' ? 4 : 0; break; case ':': pairCode = nextChar == ' ' ? 5 : 0; break; default: pairCode = 0; } if (pairCode > 0) { // We have one of the four special PUNCT pairs. Treat them specially. // Get a new set of states for the two new characters. states = UpdateStateListForPair(states, index, pairCode); index++; } else { // Get a new set of states for the new character. states = UpdateStateListForChar(states, text, index); } } // We are left with a set of states. Find the shortest one. EncodingState minState = *std::min_element(states.begin(), states.end(), [](const EncodingState& a, const EncodingState& b) { return a.bitCount < b.bitCount; }); // Convert it to a bit array, and return. return ToBitArray(minState, text); } } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZHighLevelEncoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
4,212
```objective-c /* */ #pragma once #include "AZToken.h" #include <vector> namespace ZXing::Aztec { class Token; /** * State represents all information about a sequence necessary to generate the current output. * Note that a state is immutable. */ class EncodingState { public: // The list of tokens that we output. If we are in Binary Shift mode, this // token list does *not* yet included the token for those bytes std::vector<Token> tokens; // The current mode of the encoding (or the mode to which we'll return if // we're in Binary Shift mode. int mode = 0; // If non-zero, the number of most recent bytes that should be output // in Binary Shift mode. int binaryShiftByteCount = 0; // The total number of bits generated (including Binary Shift). int bitCount = 0; }; } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZEncodingState.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
201
```c++ /* */ #include "PDFEncoder.h" #include "PDFHighLevelEncoder.h" #include <array> #include <cmath> #include <vector> #include <stdexcept> namespace ZXing { namespace Pdf417 { /** * The start pattern (17 bits) */ static const int START_PATTERN = 0x1fea8; /** * The stop pattern (18 bits) */ static const int STOP_PATTERN = 0x3fa29; /** * The codeword table from the Annex A of ISO/IEC 15438:2001(E). */ static const std::array<std::array<int, 929>, 3> CODEWORD_TABLE = { 0x1d5c0, 0x1eaf0, 0x1f57c, 0x1d4e0, 0x1ea78, 0x1f53e, 0x1a8c0, 0x1d470, 0x1a860, 0x15040, 0x1a830, 0x15020, 0x1adc0, 0x1d6f0, 0x1eb7c, 0x1ace0, 0x1d678, 0x1eb3e, 0x158c0, 0x1ac70, 0x15860, 0x15dc0, 0x1aef0, 0x1d77c, 0x15ce0, 0x1ae78, 0x1d73e, 0x15c70, 0x1ae3c, 0x15ef0, 0x1af7c, 0x15e78, 0x1af3e, 0x15f7c, 0x1f5fa, 0x1d2e0, 0x1e978, 0x1f4be, 0x1a4c0, 0x1d270, 0x1e93c, 0x1a460, 0x1d238, 0x14840, 0x1a430, 0x1d21c, 0x14820, 0x1a418, 0x14810, 0x1a6e0, 0x1d378, 0x1e9be, 0x14cc0, 0x1a670, 0x1d33c, 0x14c60, 0x1a638, 0x1d31e, 0x14c30, 0x1a61c, 0x14ee0, 0x1a778, 0x1d3be, 0x14e70, 0x1a73c, 0x14e38, 0x1a71e, 0x14f78, 0x1a7be, 0x14f3c, 0x14f1e, 0x1a2c0, 0x1d170, 0x1e8bc, 0x1a260, 0x1d138, 0x1e89e, 0x14440, 0x1a230, 0x1d11c, 0x14420, 0x1a218, 0x14410, 0x14408, 0x146c0, 0x1a370, 0x1d1bc, 0x14660, 0x1a338, 0x1d19e, 0x14630, 0x1a31c, 0x14618, 0x1460c, 0x14770, 0x1a3bc, 0x14738, 0x1a39e, 0x1471c, 0x147bc, 0x1a160, 0x1d0b8, 0x1e85e, 0x14240, 0x1a130, 0x1d09c, 0x14220, 0x1a118, 0x1d08e, 0x14210, 0x1a10c, 0x14208, 0x1a106, 0x14360, 0x1a1b8, 0x1d0de, 0x14330, 0x1a19c, 0x14318, 0x1a18e, 0x1430c, 0x14306, 0x1a1de, 0x1438e, 0x14140, 0x1a0b0, 0x1d05c, 0x14120, 0x1a098, 0x1d04e, 0x14110, 0x1a08c, 0x14108, 0x1a086, 0x14104, 0x141b0, 0x14198, 0x1418c, 0x140a0, 0x1d02e, 0x1a04c, 0x1a046, 0x14082, 0x1cae0, 0x1e578, 0x1f2be, 0x194c0, 0x1ca70, 0x1e53c, 0x19460, 0x1ca38, 0x1e51e, 0x12840, 0x19430, 0x12820, 0x196e0, 0x1cb78, 0x1e5be, 0x12cc0, 0x19670, 0x1cb3c, 0x12c60, 0x19638, 0x12c30, 0x12c18, 0x12ee0, 0x19778, 0x1cbbe, 0x12e70, 0x1973c, 0x12e38, 0x12e1c, 0x12f78, 0x197be, 0x12f3c, 0x12fbe, 0x1dac0, 0x1ed70, 0x1f6bc, 0x1da60, 0x1ed38, 0x1f69e, 0x1b440, 0x1da30, 0x1ed1c, 0x1b420, 0x1da18, 0x1ed0e, 0x1b410, 0x1da0c, 0x192c0, 0x1c970, 0x1e4bc, 0x1b6c0, 0x19260, 0x1c938, 0x1e49e, 0x1b660, 0x1db38, 0x1ed9e, 0x16c40, 0x12420, 0x19218, 0x1c90e, 0x16c20, 0x1b618, 0x16c10, 0x126c0, 0x19370, 0x1c9bc, 0x16ec0, 0x12660, 0x19338, 0x1c99e, 0x16e60, 0x1b738, 0x1db9e, 0x16e30, 0x12618, 0x16e18, 0x12770, 0x193bc, 0x16f70, 0x12738, 0x1939e, 0x16f38, 0x1b79e, 0x16f1c, 0x127bc, 0x16fbc, 0x1279e, 0x16f9e, 0x1d960, 0x1ecb8, 0x1f65e, 0x1b240, 0x1d930, 0x1ec9c, 0x1b220, 0x1d918, 0x1ec8e, 0x1b210, 0x1d90c, 0x1b208, 0x1b204, 0x19160, 0x1c8b8, 0x1e45e, 0x1b360, 0x19130, 0x1c89c, 0x16640, 0x12220, 0x1d99c, 0x1c88e, 0x16620, 0x12210, 0x1910c, 0x16610, 0x1b30c, 0x19106, 0x12204, 0x12360, 0x191b8, 0x1c8de, 0x16760, 0x12330, 0x1919c, 0x16730, 0x1b39c, 0x1918e, 0x16718, 0x1230c, 0x12306, 0x123b8, 0x191de, 0x167b8, 0x1239c, 0x1679c, 0x1238e, 0x1678e, 0x167de, 0x1b140, 0x1d8b0, 0x1ec5c, 0x1b120, 0x1d898, 0x1ec4e, 0x1b110, 0x1d88c, 0x1b108, 0x1d886, 0x1b104, 0x1b102, 0x12140, 0x190b0, 0x1c85c, 0x16340, 0x12120, 0x19098, 0x1c84e, 0x16320, 0x1b198, 0x1d8ce, 0x16310, 0x12108, 0x19086, 0x16308, 0x1b186, 0x16304, 0x121b0, 0x190dc, 0x163b0, 0x12198, 0x190ce, 0x16398, 0x1b1ce, 0x1638c, 0x12186, 0x16386, 0x163dc, 0x163ce, 0x1b0a0, 0x1d858, 0x1ec2e, 0x1b090, 0x1d84c, 0x1b088, 0x1d846, 0x1b084, 0x1b082, 0x120a0, 0x19058, 0x1c82e, 0x161a0, 0x12090, 0x1904c, 0x16190, 0x1b0cc, 0x19046, 0x16188, 0x12084, 0x16184, 0x12082, 0x120d8, 0x161d8, 0x161cc, 0x161c6, 0x1d82c, 0x1d826, 0x1b042, 0x1902c, 0x12048, 0x160c8, 0x160c4, 0x160c2, 0x18ac0, 0x1c570, 0x1e2bc, 0x18a60, 0x1c538, 0x11440, 0x18a30, 0x1c51c, 0x11420, 0x18a18, 0x11410, 0x11408, 0x116c0, 0x18b70, 0x1c5bc, 0x11660, 0x18b38, 0x1c59e, 0x11630, 0x18b1c, 0x11618, 0x1160c, 0x11770, 0x18bbc, 0x11738, 0x18b9e, 0x1171c, 0x117bc, 0x1179e, 0x1cd60, 0x1e6b8, 0x1f35e, 0x19a40, 0x1cd30, 0x1e69c, 0x19a20, 0x1cd18, 0x1e68e, 0x19a10, 0x1cd0c, 0x19a08, 0x1cd06, 0x18960, 0x1c4b8, 0x1e25e, 0x19b60, 0x18930, 0x1c49c, 0x13640, 0x11220, 0x1cd9c, 0x1c48e, 0x13620, 0x19b18, 0x1890c, 0x13610, 0x11208, 0x13608, 0x11360, 0x189b8, 0x1c4de, 0x13760, 0x11330, 0x1cdde, 0x13730, 0x19b9c, 0x1898e, 0x13718, 0x1130c, 0x1370c, 0x113b8, 0x189de, 0x137b8, 0x1139c, 0x1379c, 0x1138e, 0x113de, 0x137de, 0x1dd40, 0x1eeb0, 0x1f75c, 0x1dd20, 0x1ee98, 0x1f74e, 0x1dd10, 0x1ee8c, 0x1dd08, 0x1ee86, 0x1dd04, 0x19940, 0x1ccb0, 0x1e65c, 0x1bb40, 0x19920, 0x1eedc, 0x1e64e, 0x1bb20, 0x1dd98, 0x1eece, 0x1bb10, 0x19908, 0x1cc86, 0x1bb08, 0x1dd86, 0x19902, 0x11140, 0x188b0, 0x1c45c, 0x13340, 0x11120, 0x18898, 0x1c44e, 0x17740, 0x13320, 0x19998, 0x1ccce, 0x17720, 0x1bb98, 0x1ddce, 0x18886, 0x17710, 0x13308, 0x19986, 0x17708, 0x11102, 0x111b0, 0x188dc, 0x133b0, 0x11198, 0x188ce, 0x177b0, 0x13398, 0x199ce, 0x17798, 0x1bbce, 0x11186, 0x13386, 0x111dc, 0x133dc, 0x111ce, 0x177dc, 0x133ce, 0x1dca0, 0x1ee58, 0x1f72e, 0x1dc90, 0x1ee4c, 0x1dc88, 0x1ee46, 0x1dc84, 0x1dc82, 0x198a0, 0x1cc58, 0x1e62e, 0x1b9a0, 0x19890, 0x1ee6e, 0x1b990, 0x1dccc, 0x1cc46, 0x1b988, 0x19884, 0x1b984, 0x19882, 0x1b982, 0x110a0, 0x18858, 0x1c42e, 0x131a0, 0x11090, 0x1884c, 0x173a0, 0x13190, 0x198cc, 0x18846, 0x17390, 0x1b9cc, 0x11084, 0x17388, 0x13184, 0x11082, 0x13182, 0x110d8, 0x1886e, 0x131d8, 0x110cc, 0x173d8, 0x131cc, 0x110c6, 0x173cc, 0x131c6, 0x110ee, 0x173ee, 0x1dc50, 0x1ee2c, 0x1dc48, 0x1ee26, 0x1dc44, 0x1dc42, 0x19850, 0x1cc2c, 0x1b8d0, 0x19848, 0x1cc26, 0x1b8c8, 0x1dc66, 0x1b8c4, 0x19842, 0x1b8c2, 0x11050, 0x1882c, 0x130d0, 0x11048, 0x18826, 0x171d0, 0x130c8, 0x19866, 0x171c8, 0x1b8e6, 0x11042, 0x171c4, 0x130c2, 0x171c2, 0x130ec, 0x171ec, 0x171e6, 0x1ee16, 0x1dc22, 0x1cc16, 0x19824, 0x19822, 0x11028, 0x13068, 0x170e8, 0x11022, 0x13062, 0x18560, 0x10a40, 0x18530, 0x10a20, 0x18518, 0x1c28e, 0x10a10, 0x1850c, 0x10a08, 0x18506, 0x10b60, 0x185b8, 0x1c2de, 0x10b30, 0x1859c, 0x10b18, 0x1858e, 0x10b0c, 0x10b06, 0x10bb8, 0x185de, 0x10b9c, 0x10b8e, 0x10bde, 0x18d40, 0x1c6b0, 0x1e35c, 0x18d20, 0x1c698, 0x18d10, 0x1c68c, 0x18d08, 0x1c686, 0x18d04, 0x10940, 0x184b0, 0x1c25c, 0x11b40, 0x10920, 0x1c6dc, 0x1c24e, 0x11b20, 0x18d98, 0x1c6ce, 0x11b10, 0x10908, 0x18486, 0x11b08, 0x18d86, 0x10902, 0x109b0, 0x184dc, 0x11bb0, 0x10998, 0x184ce, 0x11b98, 0x18dce, 0x11b8c, 0x10986, 0x109dc, 0x11bdc, 0x109ce, 0x11bce, 0x1cea0, 0x1e758, 0x1f3ae, 0x1ce90, 0x1e74c, 0x1ce88, 0x1e746, 0x1ce84, 0x1ce82, 0x18ca0, 0x1c658, 0x19da0, 0x18c90, 0x1c64c, 0x19d90, 0x1cecc, 0x1c646, 0x19d88, 0x18c84, 0x19d84, 0x18c82, 0x19d82, 0x108a0, 0x18458, 0x119a0, 0x10890, 0x1c66e, 0x13ba0, 0x11990, 0x18ccc, 0x18446, 0x13b90, 0x19dcc, 0x10884, 0x13b88, 0x11984, 0x10882, 0x11982, 0x108d8, 0x1846e, 0x119d8, 0x108cc, 0x13bd8, 0x119cc, 0x108c6, 0x13bcc, 0x119c6, 0x108ee, 0x119ee, 0x13bee, 0x1ef50, 0x1f7ac, 0x1ef48, 0x1f7a6, 0x1ef44, 0x1ef42, 0x1ce50, 0x1e72c, 0x1ded0, 0x1ef6c, 0x1e726, 0x1dec8, 0x1ef66, 0x1dec4, 0x1ce42, 0x1dec2, 0x18c50, 0x1c62c, 0x19cd0, 0x18c48, 0x1c626, 0x1bdd0, 0x19cc8, 0x1ce66, 0x1bdc8, 0x1dee6, 0x18c42, 0x1bdc4, 0x19cc2, 0x1bdc2, 0x10850, 0x1842c, 0x118d0, 0x10848, 0x18426, 0x139d0, 0x118c8, 0x18c66, 0x17bd0, 0x139c8, 0x19ce6, 0x10842, 0x17bc8, 0x1bde6, 0x118c2, 0x17bc4, 0x1086c, 0x118ec, 0x10866, 0x139ec, 0x118e6, 0x17bec, 0x139e6, 0x17be6, 0x1ef28, 0x1f796, 0x1ef24, 0x1ef22, 0x1ce28, 0x1e716, 0x1de68, 0x1ef36, 0x1de64, 0x1ce22, 0x1de62, 0x18c28, 0x1c616, 0x19c68, 0x18c24, 0x1bce8, 0x19c64, 0x18c22, 0x1bce4, 0x19c62, 0x1bce2, 0x10828, 0x18416, 0x11868, 0x18c36, 0x138e8, 0x11864, 0x10822, 0x179e8, 0x138e4, 0x11862, 0x179e4, 0x138e2, 0x179e2, 0x11876, 0x179f6, 0x1ef12, 0x1de34, 0x1de32, 0x19c34, 0x1bc74, 0x1bc72, 0x11834, 0x13874, 0x178f4, 0x178f2, 0x10540, 0x10520, 0x18298, 0x10510, 0x10508, 0x10504, 0x105b0, 0x10598, 0x1058c, 0x10586, 0x105dc, 0x105ce, 0x186a0, 0x18690, 0x1c34c, 0x18688, 0x1c346, 0x18684, 0x18682, 0x104a0, 0x18258, 0x10da0, 0x186d8, 0x1824c, 0x10d90, 0x186cc, 0x10d88, 0x186c6, 0x10d84, 0x10482, 0x10d82, 0x104d8, 0x1826e, 0x10dd8, 0x186ee, 0x10dcc, 0x104c6, 0x10dc6, 0x104ee, 0x10dee, 0x1c750, 0x1c748, 0x1c744, 0x1c742, 0x18650, 0x18ed0, 0x1c76c, 0x1c326, 0x18ec8, 0x1c766, 0x18ec4, 0x18642, 0x18ec2, 0x10450, 0x10cd0, 0x10448, 0x18226, 0x11dd0, 0x10cc8, 0x10444, 0x11dc8, 0x10cc4, 0x10442, 0x11dc4, 0x10cc2, 0x1046c, 0x10cec, 0x10466, 0x11dec, 0x10ce6, 0x11de6, 0x1e7a8, 0x1e7a4, 0x1e7a2, 0x1c728, 0x1cf68, 0x1e7b6, 0x1cf64, 0x1c722, 0x1cf62, 0x18628, 0x1c316, 0x18e68, 0x1c736, 0x19ee8, 0x18e64, 0x18622, 0x19ee4, 0x18e62, 0x19ee2, 0x10428, 0x18216, 0x10c68, 0x18636, 0x11ce8, 0x10c64, 0x10422, 0x13de8, 0x11ce4, 0x10c62, 0x13de4, 0x11ce2, 0x10436, 0x10c76, 0x11cf6, 0x13df6, 0x1f7d4, 0x1f7d2, 0x1e794, 0x1efb4, 0x1e792, 0x1efb2, 0x1c714, 0x1cf34, 0x1c712, 0x1df74, 0x1cf32, 0x1df72, 0x18614, 0x18e34, 0x18612, 0x19e74, 0x18e32, 0x1bef4, 0x1f560, 0x1fab8, 0x1ea40, 0x1f530, 0x1fa9c, 0x1ea20, 0x1f518, 0x1fa8e, 0x1ea10, 0x1f50c, 0x1ea08, 0x1f506, 0x1ea04, 0x1eb60, 0x1f5b8, 0x1fade, 0x1d640, 0x1eb30, 0x1f59c, 0x1d620, 0x1eb18, 0x1f58e, 0x1d610, 0x1eb0c, 0x1d608, 0x1eb06, 0x1d604, 0x1d760, 0x1ebb8, 0x1f5de, 0x1ae40, 0x1d730, 0x1eb9c, 0x1ae20, 0x1d718, 0x1eb8e, 0x1ae10, 0x1d70c, 0x1ae08, 0x1d706, 0x1ae04, 0x1af60, 0x1d7b8, 0x1ebde, 0x15e40, 0x1af30, 0x1d79c, 0x15e20, 0x1af18, 0x1d78e, 0x15e10, 0x1af0c, 0x15e08, 0x1af06, 0x15f60, 0x1afb8, 0x1d7de, 0x15f30, 0x1af9c, 0x15f18, 0x1af8e, 0x15f0c, 0x15fb8, 0x1afde, 0x15f9c, 0x15f8e, 0x1e940, 0x1f4b0, 0x1fa5c, 0x1e920, 0x1f498, 0x1fa4e, 0x1e910, 0x1f48c, 0x1e908, 0x1f486, 0x1e904, 0x1e902, 0x1d340, 0x1e9b0, 0x1f4dc, 0x1d320, 0x1e998, 0x1f4ce, 0x1d310, 0x1e98c, 0x1d308, 0x1e986, 0x1d304, 0x1d302, 0x1a740, 0x1d3b0, 0x1e9dc, 0x1a720, 0x1d398, 0x1e9ce, 0x1a710, 0x1d38c, 0x1a708, 0x1d386, 0x1a704, 0x1a702, 0x14f40, 0x1a7b0, 0x1d3dc, 0x14f20, 0x1a798, 0x1d3ce, 0x14f10, 0x1a78c, 0x14f08, 0x1a786, 0x14f04, 0x14fb0, 0x1a7dc, 0x14f98, 0x1a7ce, 0x14f8c, 0x14f86, 0x14fdc, 0x14fce, 0x1e8a0, 0x1f458, 0x1fa2e, 0x1e890, 0x1f44c, 0x1e888, 0x1f446, 0x1e884, 0x1e882, 0x1d1a0, 0x1e8d8, 0x1f46e, 0x1d190, 0x1e8cc, 0x1d188, 0x1e8c6, 0x1d184, 0x1d182, 0x1a3a0, 0x1d1d8, 0x1e8ee, 0x1a390, 0x1d1cc, 0x1a388, 0x1d1c6, 0x1a384, 0x1a382, 0x147a0, 0x1a3d8, 0x1d1ee, 0x14790, 0x1a3cc, 0x14788, 0x1a3c6, 0x14784, 0x14782, 0x147d8, 0x1a3ee, 0x147cc, 0x147c6, 0x147ee, 0x1e850, 0x1f42c, 0x1e848, 0x1f426, 0x1e844, 0x1e842, 0x1d0d0, 0x1e86c, 0x1d0c8, 0x1e866, 0x1d0c4, 0x1d0c2, 0x1a1d0, 0x1d0ec, 0x1a1c8, 0x1d0e6, 0x1a1c4, 0x1a1c2, 0x143d0, 0x1a1ec, 0x143c8, 0x1a1e6, 0x143c4, 0x143c2, 0x143ec, 0x143e6, 0x1e828, 0x1f416, 0x1e824, 0x1e822, 0x1d068, 0x1e836, 0x1d064, 0x1d062, 0x1a0e8, 0x1d076, 0x1a0e4, 0x1a0e2, 0x141e8, 0x1a0f6, 0x141e4, 0x141e2, 0x1e814, 0x1e812, 0x1d034, 0x1d032, 0x1a074, 0x1a072, 0x1e540, 0x1f2b0, 0x1f95c, 0x1e520, 0x1f298, 0x1f94e, 0x1e510, 0x1f28c, 0x1e508, 0x1f286, 0x1e504, 0x1e502, 0x1cb40, 0x1e5b0, 0x1f2dc, 0x1cb20, 0x1e598, 0x1f2ce, 0x1cb10, 0x1e58c, 0x1cb08, 0x1e586, 0x1cb04, 0x1cb02, 0x19740, 0x1cbb0, 0x1e5dc, 0x19720, 0x1cb98, 0x1e5ce, 0x19710, 0x1cb8c, 0x19708, 0x1cb86, 0x19704, 0x19702, 0x12f40, 0x197b0, 0x1cbdc, 0x12f20, 0x19798, 0x1cbce, 0x12f10, 0x1978c, 0x12f08, 0x19786, 0x12f04, 0x12fb0, 0x197dc, 0x12f98, 0x197ce, 0x12f8c, 0x12f86, 0x12fdc, 0x12fce, 0x1f6a0, 0x1fb58, 0x16bf0, 0x1f690, 0x1fb4c, 0x169f8, 0x1f688, 0x1fb46, 0x168fc, 0x1f684, 0x1f682, 0x1e4a0, 0x1f258, 0x1f92e, 0x1eda0, 0x1e490, 0x1fb6e, 0x1ed90, 0x1f6cc, 0x1f246, 0x1ed88, 0x1e484, 0x1ed84, 0x1e482, 0x1ed82, 0x1c9a0, 0x1e4d8, 0x1f26e, 0x1dba0, 0x1c990, 0x1e4cc, 0x1db90, 0x1edcc, 0x1e4c6, 0x1db88, 0x1c984, 0x1db84, 0x1c982, 0x1db82, 0x193a0, 0x1c9d8, 0x1e4ee, 0x1b7a0, 0x19390, 0x1c9cc, 0x1b790, 0x1dbcc, 0x1c9c6, 0x1b788, 0x19384, 0x1b784, 0x19382, 0x1b782, 0x127a0, 0x193d8, 0x1c9ee, 0x16fa0, 0x12790, 0x193cc, 0x16f90, 0x1b7cc, 0x193c6, 0x16f88, 0x12784, 0x16f84, 0x12782, 0x127d8, 0x193ee, 0x16fd8, 0x127cc, 0x16fcc, 0x127c6, 0x16fc6, 0x127ee, 0x1f650, 0x1fb2c, 0x165f8, 0x1f648, 0x1fb26, 0x164fc, 0x1f644, 0x1647e, 0x1f642, 0x1e450, 0x1f22c, 0x1ecd0, 0x1e448, 0x1f226, 0x1ecc8, 0x1f666, 0x1ecc4, 0x1e442, 0x1ecc2, 0x1c8d0, 0x1e46c, 0x1d9d0, 0x1c8c8, 0x1e466, 0x1d9c8, 0x1ece6, 0x1d9c4, 0x1c8c2, 0x1d9c2, 0x191d0, 0x1c8ec, 0x1b3d0, 0x191c8, 0x1c8e6, 0x1b3c8, 0x1d9e6, 0x1b3c4, 0x191c2, 0x1b3c2, 0x123d0, 0x191ec, 0x167d0, 0x123c8, 0x191e6, 0x167c8, 0x1b3e6, 0x167c4, 0x123c2, 0x167c2, 0x123ec, 0x167ec, 0x123e6, 0x167e6, 0x1f628, 0x1fb16, 0x162fc, 0x1f624, 0x1627e, 0x1f622, 0x1e428, 0x1f216, 0x1ec68, 0x1f636, 0x1ec64, 0x1e422, 0x1ec62, 0x1c868, 0x1e436, 0x1d8e8, 0x1c864, 0x1d8e4, 0x1c862, 0x1d8e2, 0x190e8, 0x1c876, 0x1b1e8, 0x1d8f6, 0x1b1e4, 0x190e2, 0x1b1e2, 0x121e8, 0x190f6, 0x163e8, 0x121e4, 0x163e4, 0x121e2, 0x163e2, 0x121f6, 0x163f6, 0x1f614, 0x1617e, 0x1f612, 0x1e414, 0x1ec34, 0x1e412, 0x1ec32, 0x1c834, 0x1d874, 0x1c832, 0x1d872, 0x19074, 0x1b0f4, 0x19072, 0x1b0f2, 0x120f4, 0x161f4, 0x120f2, 0x161f2, 0x1f60a, 0x1e40a, 0x1ec1a, 0x1c81a, 0x1d83a, 0x1903a, 0x1b07a, 0x1e2a0, 0x1f158, 0x1f8ae, 0x1e290, 0x1f14c, 0x1e288, 0x1f146, 0x1e284, 0x1e282, 0x1c5a0, 0x1e2d8, 0x1f16e, 0x1c590, 0x1e2cc, 0x1c588, 0x1e2c6, 0x1c584, 0x1c582, 0x18ba0, 0x1c5d8, 0x1e2ee, 0x18b90, 0x1c5cc, 0x18b88, 0x1c5c6, 0x18b84, 0x18b82, 0x117a0, 0x18bd8, 0x1c5ee, 0x11790, 0x18bcc, 0x11788, 0x18bc6, 0x11784, 0x11782, 0x117d8, 0x18bee, 0x117cc, 0x117c6, 0x117ee, 0x1f350, 0x1f9ac, 0x135f8, 0x1f348, 0x1f9a6, 0x134fc, 0x1f344, 0x1347e, 0x1f342, 0x1e250, 0x1f12c, 0x1e6d0, 0x1e248, 0x1f126, 0x1e6c8, 0x1f366, 0x1e6c4, 0x1e242, 0x1e6c2, 0x1c4d0, 0x1e26c, 0x1cdd0, 0x1c4c8, 0x1e266, 0x1cdc8, 0x1e6e6, 0x1cdc4, 0x1c4c2, 0x1cdc2, 0x189d0, 0x1c4ec, 0x19bd0, 0x189c8, 0x1c4e6, 0x19bc8, 0x1cde6, 0x19bc4, 0x189c2, 0x19bc2, 0x113d0, 0x189ec, 0x137d0, 0x113c8, 0x189e6, 0x137c8, 0x19be6, 0x137c4, 0x113c2, 0x137c2, 0x113ec, 0x137ec, 0x113e6, 0x137e6, 0x1fba8, 0x175f0, 0x1bafc, 0x1fba4, 0x174f8, 0x1ba7e, 0x1fba2, 0x1747c, 0x1743e, 0x1f328, 0x1f996, 0x132fc, 0x1f768, 0x1fbb6, 0x176fc, 0x1327e, 0x1f764, 0x1f322, 0x1767e, 0x1f762, 0x1e228, 0x1f116, 0x1e668, 0x1e224, 0x1eee8, 0x1f776, 0x1e222, 0x1eee4, 0x1e662, 0x1eee2, 0x1c468, 0x1e236, 0x1cce8, 0x1c464, 0x1dde8, 0x1cce4, 0x1c462, 0x1dde4, 0x1cce2, 0x1dde2, 0x188e8, 0x1c476, 0x199e8, 0x188e4, 0x1bbe8, 0x199e4, 0x188e2, 0x1bbe4, 0x199e2, 0x1bbe2, 0x111e8, 0x188f6, 0x133e8, 0x111e4, 0x177e8, 0x133e4, 0x111e2, 0x177e4, 0x133e2, 0x177e2, 0x111f6, 0x133f6, 0x1fb94, 0x172f8, 0x1b97e, 0x1fb92, 0x1727c, 0x1723e, 0x1f314, 0x1317e, 0x1f734, 0x1f312, 0x1737e, 0x1f732, 0x1e214, 0x1e634, 0x1e212, 0x1ee74, 0x1e632, 0x1ee72, 0x1c434, 0x1cc74, 0x1c432, 0x1dcf4, 0x1cc72, 0x1dcf2, 0x18874, 0x198f4, 0x18872, 0x1b9f4, 0x198f2, 0x1b9f2, 0x110f4, 0x131f4, 0x110f2, 0x173f4, 0x131f2, 0x173f2, 0x1fb8a, 0x1717c, 0x1713e, 0x1f30a, 0x1f71a, 0x1e20a, 0x1e61a, 0x1ee3a, 0x1c41a, 0x1cc3a, 0x1dc7a, 0x1883a, 0x1987a, 0x1b8fa, 0x1107a, 0x130fa, 0x171fa, 0x170be, 0x1e150, 0x1f0ac, 0x1e148, 0x1f0a6, 0x1e144, 0x1e142, 0x1c2d0, 0x1e16c, 0x1c2c8, 0x1e166, 0x1c2c4, 0x1c2c2, 0x185d0, 0x1c2ec, 0x185c8, 0x1c2e6, 0x185c4, 0x185c2, 0x10bd0, 0x185ec, 0x10bc8, 0x185e6, 0x10bc4, 0x10bc2, 0x10bec, 0x10be6, 0x1f1a8, 0x1f8d6, 0x11afc, 0x1f1a4, 0x11a7e, 0x1f1a2, 0x1e128, 0x1f096, 0x1e368, 0x1e124, 0x1e364, 0x1e122, 0x1e362, 0x1c268, 0x1e136, 0x1c6e8, 0x1c264, 0x1c6e4, 0x1c262, 0x1c6e2, 0x184e8, 0x1c276, 0x18de8, 0x184e4, 0x18de4, 0x184e2, 0x18de2, 0x109e8, 0x184f6, 0x11be8, 0x109e4, 0x11be4, 0x109e2, 0x11be2, 0x109f6, 0x11bf6, 0x1f9d4, 0x13af8, 0x19d7e, 0x1f9d2, 0x13a7c, 0x13a3e, 0x1f194, 0x1197e, 0x1f3b4, 0x1f192, 0x13b7e, 0x1f3b2, 0x1e114, 0x1e334, 0x1e112, 0x1e774, 0x1e332, 0x1e772, 0x1c234, 0x1c674, 0x1c232, 0x1cef4, 0x1c672, 0x1cef2, 0x18474, 0x18cf4, 0x18472, 0x19df4, 0x18cf2, 0x19df2, 0x108f4, 0x119f4, 0x108f2, 0x13bf4, 0x119f2, 0x13bf2, 0x17af0, 0x1bd7c, 0x17a78, 0x1bd3e, 0x17a3c, 0x17a1e, 0x1f9ca, 0x1397c, 0x1fbda, 0x17b7c, 0x1393e, 0x17b3e, 0x1f18a, 0x1f39a, 0x1f7ba, 0x1e10a, 0x1e31a, 0x1e73a, 0x1ef7a, 0x1c21a, 0x1c63a, 0x1ce7a, 0x1defa, 0x1843a, 0x18c7a, 0x19cfa, 0x1bdfa, 0x1087a, 0x118fa, 0x139fa, 0x17978, 0x1bcbe, 0x1793c, 0x1791e, 0x138be, 0x179be, 0x178bc, 0x1789e, 0x1785e, 0x1e0a8, 0x1e0a4, 0x1e0a2, 0x1c168, 0x1e0b6, 0x1c164, 0x1c162, 0x182e8, 0x1c176, 0x182e4, 0x182e2, 0x105e8, 0x182f6, 0x105e4, 0x105e2, 0x105f6, 0x1f0d4, 0x10d7e, 0x1f0d2, 0x1e094, 0x1e1b4, 0x1e092, 0x1e1b2, 0x1c134, 0x1c374, 0x1c132, 0x1c372, 0x18274, 0x186f4, 0x18272, 0x186f2, 0x104f4, 0x10df4, 0x104f2, 0x10df2, 0x1f8ea, 0x11d7c, 0x11d3e, 0x1f0ca, 0x1f1da, 0x1e08a, 0x1e19a, 0x1e3ba, 0x1c11a, 0x1c33a, 0x1c77a, 0x1823a, 0x1867a, 0x18efa, 0x1047a, 0x10cfa, 0x11dfa, 0x13d78, 0x19ebe, 0x13d3c, 0x13d1e, 0x11cbe, 0x13dbe, 0x17d70, 0x1bebc, 0x17d38, 0x1be9e, 0x17d1c, 0x17d0e, 0x13cbc, 0x17dbc, 0x13c9e, 0x17d9e, 0x17cb8, 0x1be5e, 0x17c9c, 0x17c8e, 0x13c5e, 0x17cde, 0x17c5c, 0x17c4e, 0x17c2e, 0x1c0b4, 0x1c0b2, 0x18174, 0x18172, 0x102f4, 0x102f2, 0x1e0da, 0x1c09a, 0x1c1ba, 0x1813a, 0x1837a, 0x1027a, 0x106fa, 0x10ebe, 0x11ebc, 0x11e9e, 0x13eb8, 0x19f5e, 0x13e9c, 0x13e8e, 0x11e5e, 0x13ede, 0x17eb0, 0x1bf5c, 0x17e98, 0x1bf4e, 0x17e8c, 0x17e86, 0x13e5c, 0x17edc, 0x13e4e, 0x17ece, 0x17e58, 0x1bf2e, 0x17e4c, 0x17e46, 0x13e2e, 0x17e6e, 0x17e2c, 0x17e26, 0x10f5e, 0x11f5c, 0x11f4e, 0x13f58, 0x19fae, 0x13f4c, 0x13f46, 0x11f2e, 0x13f6e, 0x13f2c, 0x13f26, 0x1abe0, 0x1d5f8, 0x153c0, 0x1a9f0, 0x1d4fc, 0x151e0, 0x1a8f8, 0x1d47e, 0x150f0, 0x1a87c, 0x15078, 0x1fad0, 0x15be0, 0x1adf8, 0x1fac8, 0x159f0, 0x1acfc, 0x1fac4, 0x158f8, 0x1ac7e, 0x1fac2, 0x1587c, 0x1f5d0, 0x1faec, 0x15df8, 0x1f5c8, 0x1fae6, 0x15cfc, 0x1f5c4, 0x15c7e, 0x1f5c2, 0x1ebd0, 0x1f5ec, 0x1ebc8, 0x1f5e6, 0x1ebc4, 0x1ebc2, 0x1d7d0, 0x1ebec, 0x1d7c8, 0x1ebe6, 0x1d7c4, 0x1d7c2, 0x1afd0, 0x1d7ec, 0x1afc8, 0x1d7e6, 0x1afc4, 0x14bc0, 0x1a5f0, 0x1d2fc, 0x149e0, 0x1a4f8, 0x1d27e, 0x148f0, 0x1a47c, 0x14878, 0x1a43e, 0x1483c, 0x1fa68, 0x14df0, 0x1a6fc, 0x1fa64, 0x14cf8, 0x1a67e, 0x1fa62, 0x14c7c, 0x14c3e, 0x1f4e8, 0x1fa76, 0x14efc, 0x1f4e4, 0x14e7e, 0x1f4e2, 0x1e9e8, 0x1f4f6, 0x1e9e4, 0x1e9e2, 0x1d3e8, 0x1e9f6, 0x1d3e4, 0x1d3e2, 0x1a7e8, 0x1d3f6, 0x1a7e4, 0x1a7e2, 0x145e0, 0x1a2f8, 0x1d17e, 0x144f0, 0x1a27c, 0x14478, 0x1a23e, 0x1443c, 0x1441e, 0x1fa34, 0x146f8, 0x1a37e, 0x1fa32, 0x1467c, 0x1463e, 0x1f474, 0x1477e, 0x1f472, 0x1e8f4, 0x1e8f2, 0x1d1f4, 0x1d1f2, 0x1a3f4, 0x1a3f2, 0x142f0, 0x1a17c, 0x14278, 0x1a13e, 0x1423c, 0x1421e, 0x1fa1a, 0x1437c, 0x1433e, 0x1f43a, 0x1e87a, 0x1d0fa, 0x14178, 0x1a0be, 0x1413c, 0x1411e, 0x141be, 0x140bc, 0x1409e, 0x12bc0, 0x195f0, 0x1cafc, 0x129e0, 0x194f8, 0x1ca7e, 0x128f0, 0x1947c, 0x12878, 0x1943e, 0x1283c, 0x1f968, 0x12df0, 0x196fc, 0x1f964, 0x12cf8, 0x1967e, 0x1f962, 0x12c7c, 0x12c3e, 0x1f2e8, 0x1f976, 0x12efc, 0x1f2e4, 0x12e7e, 0x1f2e2, 0x1e5e8, 0x1f2f6, 0x1e5e4, 0x1e5e2, 0x1cbe8, 0x1e5f6, 0x1cbe4, 0x1cbe2, 0x197e8, 0x1cbf6, 0x197e4, 0x197e2, 0x1b5e0, 0x1daf8, 0x1ed7e, 0x169c0, 0x1b4f0, 0x1da7c, 0x168e0, 0x1b478, 0x1da3e, 0x16870, 0x1b43c, 0x16838, 0x1b41e, 0x1681c, 0x125e0, 0x192f8, 0x1c97e, 0x16de0, 0x124f0, 0x1927c, 0x16cf0, 0x1b67c, 0x1923e, 0x16c78, 0x1243c, 0x16c3c, 0x1241e, 0x16c1e, 0x1f934, 0x126f8, 0x1937e, 0x1fb74, 0x1f932, 0x16ef8, 0x1267c, 0x1fb72, 0x16e7c, 0x1263e, 0x16e3e, 0x1f274, 0x1277e, 0x1f6f4, 0x1f272, 0x16f7e, 0x1f6f2, 0x1e4f4, 0x1edf4, 0x1e4f2, 0x1edf2, 0x1c9f4, 0x1dbf4, 0x1c9f2, 0x1dbf2, 0x193f4, 0x193f2, 0x165c0, 0x1b2f0, 0x1d97c, 0x164e0, 0x1b278, 0x1d93e, 0x16470, 0x1b23c, 0x16438, 0x1b21e, 0x1641c, 0x1640e, 0x122f0, 0x1917c, 0x166f0, 0x12278, 0x1913e, 0x16678, 0x1b33e, 0x1663c, 0x1221e, 0x1661e, 0x1f91a, 0x1237c, 0x1fb3a, 0x1677c, 0x1233e, 0x1673e, 0x1f23a, 0x1f67a, 0x1e47a, 0x1ecfa, 0x1c8fa, 0x1d9fa, 0x191fa, 0x162e0, 0x1b178, 0x1d8be, 0x16270, 0x1b13c, 0x16238, 0x1b11e, 0x1621c, 0x1620e, 0x12178, 0x190be, 0x16378, 0x1213c, 0x1633c, 0x1211e, 0x1631e, 0x121be, 0x163be, 0x16170, 0x1b0bc, 0x16138, 0x1b09e, 0x1611c, 0x1610e, 0x120bc, 0x161bc, 0x1209e, 0x1619e, 0x160b8, 0x1b05e, 0x1609c, 0x1608e, 0x1205e, 0x160de, 0x1605c, 0x1604e, 0x115e0, 0x18af8, 0x1c57e, 0x114f0, 0x18a7c, 0x11478, 0x18a3e, 0x1143c, 0x1141e, 0x1f8b4, 0x116f8, 0x18b7e, 0x1f8b2, 0x1167c, 0x1163e, 0x1f174, 0x1177e, 0x1f172, 0x1e2f4, 0x1e2f2, 0x1c5f4, 0x1c5f2, 0x18bf4, 0x18bf2, 0x135c0, 0x19af0, 0x1cd7c, 0x134e0, 0x19a78, 0x1cd3e, 0x13470, 0x19a3c, 0x13438, 0x19a1e, 0x1341c, 0x1340e, 0x112f0, 0x1897c, 0x136f0, 0x11278, 0x1893e, 0x13678, 0x19b3e, 0x1363c, 0x1121e, 0x1361e, 0x1f89a, 0x1137c, 0x1f9ba, 0x1377c, 0x1133e, 0x1373e, 0x1f13a, 0x1f37a, 0x1e27a, 0x1e6fa, 0x1c4fa, 0x1cdfa, 0x189fa, 0x1bae0, 0x1dd78, 0x1eebe, 0x174c0, 0x1ba70, 0x1dd3c, 0x17460, 0x1ba38, 0x1dd1e, 0x17430, 0x1ba1c, 0x17418, 0x1ba0e, 0x1740c, 0x132e0, 0x19978, 0x1ccbe, 0x176e0, 0x13270, 0x1993c, 0x17670, 0x1bb3c, 0x1991e, 0x17638, 0x1321c, 0x1761c, 0x1320e, 0x1760e, 0x11178, 0x188be, 0x13378, 0x1113c, 0x17778, 0x1333c, 0x1111e, 0x1773c, 0x1331e, 0x1771e, 0x111be, 0x133be, 0x177be, 0x172c0, 0x1b970, 0x1dcbc, 0x17260, 0x1b938, 0x1dc9e, 0x17230, 0x1b91c, 0x17218, 0x1b90e, 0x1720c, 0x17206, 0x13170, 0x198bc, 0x17370, 0x13138, 0x1989e, 0x17338, 0x1b99e, 0x1731c, 0x1310e, 0x1730e, 0x110bc, 0x131bc, 0x1109e, 0x173bc, 0x1319e, 0x1739e, 0x17160, 0x1b8b8, 0x1dc5e, 0x17130, 0x1b89c, 0x17118, 0x1b88e, 0x1710c, 0x17106, 0x130b8, 0x1985e, 0x171b8, 0x1309c, 0x1719c, 0x1308e, 0x1718e, 0x1105e, 0x130de, 0x171de, 0x170b0, 0x1b85c, 0x17098, 0x1b84e, 0x1708c, 0x17086, 0x1305c, 0x170dc, 0x1304e, 0x170ce, 0x17058, 0x1b82e, 0x1704c, 0x17046, 0x1302e, 0x1706e, 0x1702c, 0x17026, 0x10af0, 0x1857c, 0x10a78, 0x1853e, 0x10a3c, 0x10a1e, 0x10b7c, 0x10b3e, 0x1f0ba, 0x1e17a, 0x1c2fa, 0x185fa, 0x11ae0, 0x18d78, 0x1c6be, 0x11a70, 0x18d3c, 0x11a38, 0x18d1e, 0x11a1c, 0x11a0e, 0x10978, 0x184be, 0x11b78, 0x1093c, 0x11b3c, 0x1091e, 0x11b1e, 0x109be, 0x11bbe, 0x13ac0, 0x19d70, 0x1cebc, 0x13a60, 0x19d38, 0x1ce9e, 0x13a30, 0x19d1c, 0x13a18, 0x19d0e, 0x13a0c, 0x13a06, 0x11970, 0x18cbc, 0x13b70, 0x11938, 0x18c9e, 0x13b38, 0x1191c, 0x13b1c, 0x1190e, 0x13b0e, 0x108bc, 0x119bc, 0x1089e, 0x13bbc, 0x1199e, 0x13b9e, 0x1bd60, 0x1deb8, 0x1ef5e, 0x17a40, 0x1bd30, 0x1de9c, 0x17a20, 0x1bd18, 0x1de8e, 0x17a10, 0x1bd0c, 0x17a08, 0x1bd06, 0x17a04, 0x13960, 0x19cb8, 0x1ce5e, 0x17b60, 0x13930, 0x19c9c, 0x17b30, 0x1bd9c, 0x19c8e, 0x17b18, 0x1390c, 0x17b0c, 0x13906, 0x17b06, 0x118b8, 0x18c5e, 0x139b8, 0x1189c, 0x17bb8, 0x1399c, 0x1188e, 0x17b9c, 0x1398e, 0x17b8e, 0x1085e, 0x118de, 0x139de, 0x17bde, 0x17940, 0x1bcb0, 0x1de5c, 0x17920, 0x1bc98, 0x1de4e, 0x17910, 0x1bc8c, 0x17908, 0x1bc86, 0x17904, 0x17902, 0x138b0, 0x19c5c, 0x179b0, 0x13898, 0x19c4e, 0x17998, 0x1bcce, 0x1798c, 0x13886, 0x17986, 0x1185c, 0x138dc, 0x1184e, 0x179dc, 0x138ce, 0x179ce, 0x178a0, 0x1bc58, 0x1de2e, 0x17890, 0x1bc4c, 0x17888, 0x1bc46, 0x17884, 0x17882, 0x13858, 0x19c2e, 0x178d8, 0x1384c, 0x178cc, 0x13846, 0x178c6, 0x1182e, 0x1386e, 0x178ee, 0x17850, 0x1bc2c, 0x17848, 0x1bc26, 0x17844, 0x17842, 0x1382c, 0x1786c, 0x13826, 0x17866, 0x17828, 0x1bc16, 0x17824, 0x17822, 0x13816, 0x17836, 0x10578, 0x182be, 0x1053c, 0x1051e, 0x105be, 0x10d70, 0x186bc, 0x10d38, 0x1869e, 0x10d1c, 0x10d0e, 0x104bc, 0x10dbc, 0x1049e, 0x10d9e, 0x11d60, 0x18eb8, 0x1c75e, 0x11d30, 0x18e9c, 0x11d18, 0x18e8e, 0x11d0c, 0x11d06, 0x10cb8, 0x1865e, 0x11db8, 0x10c9c, 0x11d9c, 0x10c8e, 0x11d8e, 0x1045e, 0x10cde, 0x11dde, 0x13d40, 0x19eb0, 0x1cf5c, 0x13d20, 0x19e98, 0x1cf4e, 0x13d10, 0x19e8c, 0x13d08, 0x19e86, 0x13d04, 0x13d02, 0x11cb0, 0x18e5c, 0x13db0, 0x11c98, 0x18e4e, 0x13d98, 0x19ece, 0x13d8c, 0x11c86, 0x13d86, 0x10c5c, 0x11cdc, 0x10c4e, 0x13ddc, 0x11cce, 0x13dce, 0x1bea0, 0x1df58, 0x1efae, 0x1be90, 0x1df4c, 0x1be88, 0x1df46, 0x1be84, 0x1be82, 0x13ca0, 0x19e58, 0x1cf2e, 0x17da0, 0x13c90, 0x19e4c, 0x17d90, 0x1becc, 0x19e46, 0x17d88, 0x13c84, 0x17d84, 0x13c82, 0x17d82, 0x11c58, 0x18e2e, 0x13cd8, 0x11c4c, 0x17dd8, 0x13ccc, 0x11c46, 0x17dcc, 0x13cc6, 0x17dc6, 0x10c2e, 0x11c6e, 0x13cee, 0x17dee, 0x1be50, 0x1df2c, 0x1be48, 0x1df26, 0x1be44, 0x1be42, 0x13c50, 0x19e2c, 0x17cd0, 0x13c48, 0x19e26, 0x17cc8, 0x1be66, 0x17cc4, 0x13c42, 0x17cc2, 0x11c2c, 0x13c6c, 0x11c26, 0x17cec, 0x13c66, 0x17ce6, 0x1be28, 0x1df16, 0x1be24, 0x1be22, 0x13c28, 0x19e16, 0x17c68, 0x13c24, 0x17c64, 0x13c22, 0x17c62, 0x11c16, 0x13c36, 0x17c76, 0x1be14, 0x1be12, 0x13c14, 0x17c34, 0x13c12, 0x17c32, 0x102bc, 0x1029e, 0x106b8, 0x1835e, 0x1069c, 0x1068e, 0x1025e, 0x106de, 0x10eb0, 0x1875c, 0x10e98, 0x1874e, 0x10e8c, 0x10e86, 0x1065c, 0x10edc, 0x1064e, 0x10ece, 0x11ea0, 0x18f58, 0x1c7ae, 0x11e90, 0x18f4c, 0x11e88, 0x18f46, 0x11e84, 0x11e82, 0x10e58, 0x1872e, 0x11ed8, 0x18f6e, 0x11ecc, 0x10e46, 0x11ec6, 0x1062e, 0x10e6e, 0x11eee, 0x19f50, 0x1cfac, 0x19f48, 0x1cfa6, 0x19f44, 0x19f42, 0x11e50, 0x18f2c, 0x13ed0, 0x19f6c, 0x18f26, 0x13ec8, 0x11e44, 0x13ec4, 0x11e42, 0x13ec2, 0x10e2c, 0x11e6c, 0x10e26, 0x13eec, 0x11e66, 0x13ee6, 0x1dfa8, 0x1efd6, 0x1dfa4, 0x1dfa2, 0x19f28, 0x1cf96, 0x1bf68, 0x19f24, 0x1bf64, 0x19f22, 0x1bf62, 0x11e28, 0x18f16, 0x13e68, 0x11e24, 0x17ee8, 0x13e64, 0x11e22, 0x17ee4, 0x13e62, 0x17ee2, 0x10e16, 0x11e36, 0x13e76, 0x17ef6, 0x1df94, 0x1df92, 0x19f14, 0x1bf34, 0x19f12, 0x1bf32, 0x11e14, 0x13e34, 0x11e12, 0x17e74, 0x13e32, 0x17e72, 0x1df8a, 0x19f0a, 0x1bf1a, 0x11e0a, 0x13e1a, 0x17e3a, 0x1035c, 0x1034e, 0x10758, 0x183ae, 0x1074c, 0x10746, 0x1032e, 0x1076e, 0x10f50, 0x187ac, 0x10f48, 0x187a6, 0x10f44, 0x10f42, 0x1072c, 0x10f6c, 0x10726, 0x10f66, 0x18fa8, 0x1c7d6, 0x18fa4, 0x18fa2, 0x10f28, 0x18796, 0x11f68, 0x18fb6, 0x11f64, 0x10f22, 0x11f62, 0x10716, 0x10f36, 0x11f76, 0x1cfd4, 0x1cfd2, 0x18f94, 0x19fb4, 0x18f92, 0x19fb2, 0x10f14, 0x11f34, 0x10f12, 0x13f74, 0x11f32, 0x13f72, 0x1cfca, 0x18f8a, 0x19f9a, 0x10f0a, 0x11f1a, 0x13f3a, 0x103ac, 0x103a6, 0x107a8, 0x183d6, 0x107a4, 0x107a2, 0x10396, 0x107b6, 0x187d4, 0x187d2, 0x10794, 0x10fb4, 0x10792, 0x10fb2, 0x1c7ea }; static const float PREFERRED_RATIO = 3.0f; static const float MODULE_RATIO = 0.25f; // keep in sync with Writer::encode() /** * PDF417 error correction code following the algorithm described in ISO/IEC 15438:2001(E) in * chapter 4.10. */ /** * Tables of coefficients for calculating error correction words * (see annex F, ISO/IEC 15438:2001(E)) */ static const short EC_COEFFICIENTS_L0[] = { 27, 917 }; static const short EC_COEFFICIENTS_L1[] = { 522, 568, 723, 809 }; static const short EC_COEFFICIENTS_L2[] = { 237, 308, 436, 284, 646, 653, 428, 379 }; static const short EC_COEFFICIENTS_L3[] = { 274, 562, 232, 755, 599, 524, 801, 132, 295, 116, 442, 428, 295, 42, 176, 65, }; static const short EC_COEFFICIENTS_L4[] = { 361, 575, 922, 525, 176, 586, 640, 321, 536, 742, 677, 742, 687, 284, 193, 517, 273, 494, 263, 147, 593, 800, 571, 320, 803, 133, 231, 390, 685, 330, 63, 410, }; static const short EC_COEFFICIENTS_L5[] = { 539, 422, 6, 93, 862, 771, 453, 106, 610, 287, 107, 505, 733, 877, 381, 612, 723, 476, 462, 172, 430, 609, 858, 822, 543, 376, 511, 400, 672, 762, 283, 184, 440, 35, 519, 31, 460, 594, 225, 535, 517, 352, 605, 158, 651, 201, 488, 502, 648, 733, 717, 83, 404, 97, 280, 771, 840, 629, 4, 381, 843, 623, 264, 543, }; static const short EC_COEFFICIENTS_L6[] = { 521, 310, 864, 547, 858, 580, 296, 379, 53, 779, 897, 444, 400, 925, 749, 415, 822, 93, 217, 208, 928, 244, 583, 620, 246, 148, 447, 631, 292, 908, 490, 704, 516, 258, 457, 907, 594, 723, 674, 292, 272, 96, 684, 432, 686, 606, 860, 569, 193, 219, 129, 186, 236, 287, 192, 775, 278, 173, 40, 379, 712, 463, 646, 776, 171, 491, 297, 763, 156, 732, 95, 270, 447, 90, 507, 48, 228, 821, 808, 898, 784, 663, 627, 378, 382, 262, 380, 602, 754, 336, 89, 614, 87, 432, 670, 616, 157, 374, 242, 726, 600, 269, 375, 898, 845, 454, 354, 130, 814, 587, 804, 34, 211, 330, 539, 297, 827, 865, 37, 517, 834, 315, 550, 86, 801, 4, 108, 539, }; static const short EC_COEFFICIENTS_L7[] = { 524, 894, 75, 766, 882, 857, 74, 204, 82, 586, 708, 250, 905, 786, 138, 720, 858, 194, 311, 913, 275, 190, 375, 850, 438, 733, 194, 280, 201, 280, 828, 757, 710, 814, 919, 89, 68, 569, 11, 204, 796, 605, 540, 913, 801, 700, 799, 137, 439, 418, 592, 668, 353, 859, 370, 694, 325, 240, 216, 257, 284, 549, 209, 884, 315, 70, 329, 793, 490, 274, 877, 162, 749, 812, 684, 461, 334, 376, 849, 521, 307, 291, 803, 712, 19, 358, 399, 908, 103, 511, 51, 8, 517, 225, 289, 470, 637, 731, 66, 255, 917, 269, 463, 830, 730, 433, 848, 585, 136, 538, 906, 90, 2, 290, 743, 199, 655, 903, 329, 49, 802, 580, 355, 588, 188, 462, 10, 134, 628, 320, 479, 130, 739, 71, 263, 318, 374, 601, 192, 605, 142, 673, 687, 234, 722, 384, 177, 752, 607, 640, 455, 193, 689, 707, 805, 641, 48, 60, 732, 621, 895, 544, 261, 852, 655, 309, 697, 755, 756, 60, 231, 773, 434, 421, 726, 528, 503, 118, 49, 795, 32, 144, 500, 238, 836, 394, 280, 566, 319, 9, 647, 550, 73, 914, 342, 126, 32, 681, 331, 792, 620, 60, 609, 441, 180, 791, 893, 754, 605, 383, 228, 749, 760, 213, 54, 297, 134, 54, 834, 299, 922, 191, 910, 532, 609, 829, 189, 20, 167, 29, 872, 449, 83, 402, 41, 656, 505, 579, 481, 173, 404, 251, 688, 95, 497, 555, 642, 543, 307, 159, 924, 558, 648, 55, 497, 10, }; static const short EC_COEFFICIENTS_L8[] = { 352, 77, 373, 504, 35, 599, 428, 207, 409, 574, 118, 498, 285, 380, 350, 492, 197, 265, 920, 155, 914, 299, 229, 643, 294, 871, 306, 88, 87, 193, 352, 781, 846, 75, 327, 520, 435, 543, 203, 666, 249, 346, 781, 621, 640, 268, 794, 534, 539, 781, 408, 390, 644, 102, 476, 499, 290, 632, 545, 37, 858, 916, 552, 41, 542, 289, 122, 272, 383, 800, 485, 98, 752, 472, 761, 107, 784, 860, 658, 741, 290, 204, 681, 407, 855, 85, 99, 62, 482, 180, 20, 297, 451, 593, 913, 142, 808, 684, 287, 536, 561, 76, 653, 899, 729, 567, 744, 390, 513, 192, 516, 258, 240, 518, 794, 395, 768, 848, 51, 610, 384, 168, 190, 826, 328, 596, 786, 303, 570, 381, 415, 641, 156, 237, 151, 429, 531, 207, 676, 710, 89, 168, 304, 402, 40, 708, 575, 162, 864, 229, 65, 861, 841, 512, 164, 477, 221, 92, 358, 785, 288, 357, 850, 836, 827, 736, 707, 94, 8, 494, 114, 521, 2, 499, 851, 543, 152, 729, 771, 95, 248, 361, 578, 323, 856, 797, 289, 51, 684, 466, 533, 820, 669, 45, 902, 452, 167, 342, 244, 173, 35, 463, 651, 51, 699, 591, 452, 578, 37, 124, 298, 332, 552, 43, 427, 119, 662, 777, 475, 850, 764, 364, 578, 911, 283, 711, 472, 420, 245, 288, 594, 394, 511, 327, 589, 777, 699, 688, 43, 408, 842, 383, 721, 521, 560, 644, 714, 559, 62, 145, 873, 663, 713, 159, 672, 729, 624, 59, 193, 417, 158, 209, 563, 564, 343, 693, 109, 608, 563, 365, 181, 772, 677, 310, 248, 353, 708, 410, 579, 870, 617, 841, 632, 860, 289, 536, 35, 777, 618, 586, 424, 833, 77, 597, 346, 269, 757, 632, 695, 751, 331, 247, 184, 45, 787, 680, 18, 66, 407, 369, 54, 492, 228, 613, 830, 922, 437, 519, 644, 905, 789, 420, 305, 441, 207, 300, 892, 827, 141, 537, 381, 662, 513, 56, 252, 341, 242, 797, 838, 837, 720, 224, 307, 631, 61, 87, 560, 310, 756, 665, 397, 808, 851, 309, 473, 795, 378, 31, 647, 915, 459, 806, 590, 731, 425, 216, 548, 249, 321, 881, 699, 535, 673, 782, 210, 815, 905, 303, 843, 922, 281, 73, 469, 791, 660, 162, 498, 308, 155, 422, 907, 817, 187, 62, 16, 425, 535, 336, 286, 437, 375, 273, 610, 296, 183, 923, 116, 667, 751, 353, 62, 366, 691, 379, 687, 842, 37, 357, 720, 742, 330, 5, 39, 923, 311, 424, 242, 749, 321, 54, 669, 316, 342, 299, 534, 105, 667, 488, 640, 672, 576, 540, 316, 486, 721, 610, 46, 656, 447, 171, 616, 464, 190, 531, 297, 321, 762, 752, 533, 175, 134, 14, 381, 433, 717, 45, 111, 20, 596, 284, 736, 138, 646, 411, 877, 669, 141, 919, 45, 780, 407, 164, 332, 899, 165, 726, 600, 325, 498, 655, 357, 752, 768, 223, 849, 647, 63, 310, 863, 251, 366, 304, 282, 738, 675, 410, 389, 244, 31, 121, 303, 263, }; static const short* EC_COEFFICIENTS[] = {EC_COEFFICIENTS_L0, EC_COEFFICIENTS_L1, EC_COEFFICIENTS_L2, EC_COEFFICIENTS_L3, EC_COEFFICIENTS_L4, EC_COEFFICIENTS_L5, EC_COEFFICIENTS_L6, EC_COEFFICIENTS_L7, EC_COEFFICIENTS_L8}; /** * Determines the number of error correction codewords for a specified error correction * level. * * @param errorCorrectionLevel the error correction level (0-8) * @return the number of codewords generated for error correction */ static int GetErrorCorrectionCodewordCount(int errorCorrectionLevel) { return 1 << (errorCorrectionLevel + 1); } /** * Generates the error correction codewords according to 4.10 in ISO/IEC 15438:2001(E). * * @param dataCodewords the data codewords (including error correction after return) * @param errorCorrectionLevel the error correction level (0-8) */ static void GenerateErrorCorrection(std::vector<int>& dataCodewords, int errorCorrectionLevel) { int k = GetErrorCorrectionCodewordCount(errorCorrectionLevel); std::vector<int> e(k, 0); int sld = Size(dataCodewords); for (int i = 0; i < sld; i++) { int t1 = (dataCodewords[i] + e[k - 1]) % 929; int t2; int t3; for (int j = k - 1; j >= 1; j--) { t2 = (t1 * EC_COEFFICIENTS[errorCorrectionLevel][j]) % 929; t3 = 929 - t2; e[j] = (e[j - 1] + t3) % 929; } t2 = (t1 * EC_COEFFICIENTS[errorCorrectionLevel][0]) % 929; t3 = 929 - t2; e[0] = t3 % 929; } for (int j = 0; j < k; ++j) { if (e[j] != 0) { e[j] = 929 - e[j]; } } dataCodewords.insert(dataCodewords.end(), e.rbegin(), e.rend()); } /** * Calculates the necessary number of rows as described in annex Q of ISO/IEC 15438:2001(E). * * @param m the number of source codewords prior to the additional of the Symbol Length * Descriptor and any pad codewords * @param k the number of error correction codewords * @param c the number of columns in the symbol in the data region (excluding start, stop and * row indicator codewords) * @return the number of rows in the symbol (r) */ static int CalculateNumberOfRows(int m, int k, int c) { int r = ((m + 1 + k) / c) + 1; if (c * r >= (m + 1 + k + c)) { r--; } return r; } /** * Calculates the number of pad codewords as described in 4.9.2 of ISO/IEC 15438:2001(E). * * @param m the number of source codewords prior to the additional of the Symbol Length * Descriptor and any pad codewords * @param k the number of error correction codewords * @param c the number of columns in the symbol in the data region (excluding start, stop and * row indicator codewords) * @param r the number of rows in the symbol * @return the number of pad codewords */ static int GetNumberOfPadCodewords(int m, int k, int c, int r) { int n = c * r - k; return n > m + 1 ? n - m - 1 : 0; } static void EncodeChar(int pattern, int len, BarcodeRow& logic) { int map = 1 << (len - 1); bool last = (pattern & map) != 0; //Initialize to inverse of first bit int width = 0; for (int i = 0; i < len; i++) { bool black = (pattern & map) != 0; if (last == black) { width++; } else { logic.addBar(last, width); last = black; width = 1; } map >>= 1; } logic.addBar(last, width); } static BarcodeMatrix EncodeLowLevel(const std::vector<int>& fullCodewords, int c, int r, int errorCorrectionLevel, bool compact) { BarcodeMatrix logic; logic.init(r, c); int idx = 0; for (int y = 0; y < r; y++) { int cluster = y % 3; logic.startRow(); EncodeChar(START_PATTERN, 17, logic.currentRow()); int left; int right; if (cluster == 0) { left = (30 * (y / 3)) + ((r - 1) / 3); right = (30 * (y / 3)) + (c - 1); } else if (cluster == 1) { left = (30 * (y / 3)) + (errorCorrectionLevel * 3) + ((r - 1) % 3); right = (30 * (y / 3)) + ((r - 1) / 3); } else { left = (30 * (y / 3)) + (c - 1); right = (30 * (y / 3)) + (errorCorrectionLevel * 3) + ((r - 1) % 3); } int pattern = CODEWORD_TABLE[cluster][left]; EncodeChar(pattern, 17, logic.currentRow()); for (int x = 0; x < c; x++) { pattern = CODEWORD_TABLE[cluster][fullCodewords[idx]]; EncodeChar(pattern, 17, logic.currentRow()); idx++; } if (compact) { EncodeChar(STOP_PATTERN, 1, logic.currentRow()); // encodes stop line for compact pdf417 } else { pattern = CODEWORD_TABLE[cluster][right]; EncodeChar(pattern, 17, logic.currentRow()); EncodeChar(STOP_PATTERN, 18, logic.currentRow()); } } return logic; } /** * Determine optimal nr of columns and rows for the specified number of * codewords. * * @param sourceCodeWords number of code words * @param errorCorrectionCodeWords number of error correction code words */ static void DetermineDimensions(int minCols, int maxCols, int minRows, int maxRows, int sourceCodeWords, int errorCorrectionCodeWords, int& outCols, int& outRows) { float ratio = 0.0f; bool haveDimension = false; for (int cols = minCols; cols <= maxCols; cols++) { int rows = CalculateNumberOfRows(sourceCodeWords, errorCorrectionCodeWords, cols); if (rows < minRows) { break; } if (rows > maxRows) { continue; } float newRatio = ((17 * cols + 69) / rows) * MODULE_RATIO; // ignore if previous ratio is closer to preferred ratio if (haveDimension && std::abs(newRatio - PREFERRED_RATIO) > std::abs(ratio - PREFERRED_RATIO)) { continue; } ratio = newRatio; outCols = cols; outRows = rows; haveDimension = true; } // Handle case when min values were larger than necessary if (!haveDimension) { int rows = CalculateNumberOfRows(sourceCodeWords, errorCorrectionCodeWords, minCols); if (rows < minRows) { outCols = minCols; outRows = minRows; } else { throw std::invalid_argument("Unable to fit message in columns"); } } } /** * @param msg message to encode * @param errorCorrectionLevel PDF417 error correction level to use * @throws WriterException if the contents cannot be encoded in this format */ BarcodeMatrix Encoder::generateBarcodeLogic(const std::wstring& msg, int errorCorrectionLevel) const { if (errorCorrectionLevel < 0 || errorCorrectionLevel > 8) { throw std::invalid_argument("Error correction level must be between 0 and 8!"); } //1. step: High-level encoding int errorCorrectionCodeWords = GetErrorCorrectionCodewordCount(errorCorrectionLevel); std::vector<int> highLevel = HighLevelEncoder::EncodeHighLevel(msg, _compaction, _encoding); int sourceCodeWords = Size(highLevel); int cols, rows; DetermineDimensions(_minCols, _maxCols, _minRows, _maxRows, sourceCodeWords, errorCorrectionCodeWords, cols, rows); int pad = GetNumberOfPadCodewords(sourceCodeWords, errorCorrectionCodeWords, cols, rows); //2. step: construct data codewords if (sourceCodeWords + errorCorrectionCodeWords + 1 > 929) { // +1 for symbol length CW throw std::invalid_argument("Encoded message contains to many code words, message too big"); } int n = sourceCodeWords + pad + 1; std::vector<int> dataCodewords; dataCodewords.reserve(n); dataCodewords.push_back(n); dataCodewords.insert(dataCodewords.end(), highLevel.begin(), highLevel.end()); for (int i = 0; i < pad; i++) { dataCodewords.push_back(900); //PAD characters } //3. step: Error correction GenerateErrorCorrection(dataCodewords, errorCorrectionLevel); //4. step: low-level encoding return EncodeLowLevel(dataCodewords, cols, rows, errorCorrectionLevel, _compact); } /** * Returns the recommended minimum error correction level as described in annex E of * ISO/IEC 15438:2001(E). * * @param n the number of data codewords * @return the recommended minimum error correction level */ int Encoder::GetRecommendedMinimumErrorCorrectionLevel(int n) { if (n <= 40) { return 2; } if (n <= 160) { return 3; } if (n <= 320) { return 4; } if (n <= 863) { return 5; } return 6; } } // Pdf417 } // ZXing ```
/content/code_sandbox/core/src/pdf417/PDFEncoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
25,894
```objective-c /* */ #pragma once #include <string> namespace ZXing { class BitArray; namespace Aztec { /** * This produces nearly optimal encodings of text into the first-level of * encoding used by Aztec code. * * It uses a dynamic algorithm. For each prefix of the string, it determines * a set of encodings that could lead to this prefix. We repeatedly add a * character and generate a new set of optimal encodings until we have read * through the entire input. * * @author Frank Yellin * @author Rustam Abdullaev */ class HighLevelEncoder { public: static BitArray Encode(const std::string& text); }; } // Aztec } // ZXing ```
/content/code_sandbox/core/src/aztec/AZHighLevelEncoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
155
```c++ /* */ #include "AZWriter.h" #include "AZEncoder.h" #include "CharacterSet.h" #include "TextEncoder.h" #include "Utf.h" #include <utility> namespace ZXing::Aztec { Writer::Writer() : _encoding(CharacterSet::ISO8859_1), _eccPercent(Encoder::DEFAULT_EC_PERCENT), _layers(Encoder::DEFAULT_AZTEC_LAYERS) { } BitMatrix Writer::encode(const std::wstring& contents, int width, int height) const { std::string bytes = TextEncoder::FromUnicode(contents, _encoding); EncodeResult aztec = Encoder::Encode(bytes, _eccPercent, _layers); return Inflate(std::move(aztec.matrix), width, height, _margin); } BitMatrix Writer::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
201
```c++ /* */ #include "AZDecoder.h" #include "AZDetectorResult.h" #include "BitArray.h" #include "BitMatrix.h" #include "DecoderResult.h" #include "GenericGF.h" #include "ReedSolomonDecoder.h" #include "ZXTestSupport.h" #include "ZXAlgorithms.h" #include <cctype> #include <cstring> #include <numeric> #include <string> #include <utility> #include <vector> namespace ZXing::Aztec { enum class Table { UPPER, LOWER, MIXED, DIGIT, PUNCT, BINARY }; static const char* UPPER_TABLE[] = { "CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS" }; static const char* LOWER_TABLE[] = { "CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS" }; static const char* MIXED_TABLE[] = { "CTRL_PS", " ", "\1", "\2", "\3", "\4", "\5", "\6", "\7", "\b", "\t", "\n", "\13", "\f", "\r", "\33", "\34", "\35", "\36", "\37", "@", "\\", "^", "_", "`", "|", "~", "\177", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS" }; static const char* PUNCT_TABLE[] = { "FLGN", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL" }; static const char* DIGIT_TABLE[] = { "CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US" }; static int TotalBitsInLayer(int layers, bool compact) { return ((compact ? 88 : 112) + 16 * layers) * layers; } /** * Gets the array of bits from an Aztec Code matrix * * @return the array of bits */ static BitArray ExtractBits(const DetectorResult& ddata) { bool compact = ddata.isCompact(); int layers = ddata.nbLayers(); int baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines std::vector<int> map(baseMatrixSize, 0); if (compact) { std::iota(map.begin(), map.end(), 0); } else { int matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15); int origCenter = baseMatrixSize / 2; int center = matrixSize / 2; for (int i = 0; i < origCenter; i++) { int newOffset = i + i / 15; map[origCenter - i - 1] = center - newOffset - 1; map[origCenter + i] = center + newOffset + 1; } } auto& matrix = ddata.bits(); BitArray rawbits(TotalBitsInLayer(layers, compact)); for (int i = 0, rowOffset = 0; i < layers; i++) { int rowSize = (layers - i) * 4 + (compact ? 9 : 12); // The top-left most point of this layer is <low, low> (not including alignment lines) int low = i * 2; // The bottom-right most point of this layer is <high, high> (not including alignment lines) int high = baseMatrixSize - 1 - low; // We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows for (int j = 0; j < rowSize; j++) { int colOffset = j * 2; for (int k = 0; k < 2; k++) { // left column rawbits.set(rowOffset + 0 * rowSize + colOffset + k, matrix.get(map[low + k], map[low + j])); // bottom row rawbits.set(rowOffset + 2 * rowSize + colOffset + k, matrix.get(map[low + j], map[high - k])); // right column rawbits.set(rowOffset + 4 * rowSize + colOffset + k, matrix.get(map[high - k], map[high - j])); // top row rawbits.set(rowOffset + 6 * rowSize + colOffset + k, matrix.get(map[high - j], map[low + k])); } } rowOffset += rowSize * 8; } return rawbits; } /** * @brief Performs RS error correction on an array of bits. */ static BitArray CorrectBits(const DetectorResult& ddata, const BitArray& rawbits) { const GenericGF* gf = nullptr; int codewordSize; if (ddata.nbLayers() <= 2) { codewordSize = 6; gf = &GenericGF::AztecData6(); } else if (ddata.nbLayers() <= 8) { codewordSize = 8; gf = &GenericGF::AztecData8(); } else if (ddata.nbLayers() <= 22) { codewordSize = 10; gf = &GenericGF::AztecData10(); } else { codewordSize = 12; gf = &GenericGF::AztecData12(); } int numCodewords = Size(rawbits) / codewordSize; int numDataCodewords = ddata.nbDatablocks(); int numECCodewords = numCodewords - numDataCodewords; if (numCodewords < numDataCodewords) throw FormatError("Invalid number of code words"); auto dataWords = ToInts<int>(rawbits, codewordSize, numCodewords, Size(rawbits) % codewordSize); if (!ReedSolomonDecode(*gf, dataWords, numECCodewords)) throw ChecksumError(); // drop the ECCodewords from the dataWords array dataWords.resize(numDataCodewords); // Now perform the unstuffing operation. BitArray correctedBits; // correctedBits.reserve(numDataCodewords * codewordSize - stuffedBits); for (int dataWord : dataWords) { if (dataWord == 0 || dataWord == (1 << codewordSize) - 1) return {}; else if (dataWord == 1) // next codewordSize-1 bits are all zeros or all ones correctedBits.appendBits(0, codewordSize - 1); else if (dataWord == (1 << codewordSize) - 2) correctedBits.appendBits(0xffffffff, codewordSize - 1); else correctedBits.appendBits(dataWord, codewordSize); } return correctedBits; } /** * gets the table corresponding to the char passed */ static Table GetTable(char t) { switch (t) { case 'L': return Table::LOWER; case 'P': return Table::PUNCT; case 'M': return Table::MIXED; case 'D': return Table::DIGIT; case 'B': return Table::BINARY; case 'U': default: return Table::UPPER; } } /** * Gets the character (or string) corresponding to the passed code in the given table * * @param table the table used * @param code the code of the character */ static const char* GetCharacter(Table table, int code) { switch (table) { case Table::UPPER: return UPPER_TABLE[code]; case Table::LOWER: return LOWER_TABLE[code]; case Table::MIXED: return MIXED_TABLE[code]; case Table::PUNCT: return PUNCT_TABLE[code]; case Table::DIGIT: return DIGIT_TABLE[code]; case Table::BINARY: return nullptr; // should not happen } // silence gcc warning/error (this code can not be reached) return nullptr; } /** * See ISO/IEC 24778:2008 Section 10.1 */ static ECI ParseECIValue(BitArrayView& bits, const int flg) { int eci = 0; for (int i = 0; i < flg; i++) eci = 10 * eci + bits.readBits(4) - 2; return ECI(eci); } /** * See ISO/IEC 24778:2008 Section 8 */ static StructuredAppendInfo ParseStructuredAppend(ByteArray& bytes) { std::string text(bytes.begin(), bytes.end()); StructuredAppendInfo sai; std::string::size_type i = 0; if (text[0] == ' ') { // Space-delimited id std::string::size_type sp = text.find(' ', 1); if (sp == std::string::npos) return {}; sai.id = text.substr(1, sp - 1); // Strip space delimiters i = sp + 1; } if (i + 1 >= text.size() || !std::isupper(text[i]) || !std::isupper(text[i + 1])) return {}; sai.index = text[i] - 'A'; sai.count = text[i + 1] - 'A' + 1; if (sai.count == 1 || sai.count <= sai.index) // If info doesn't make sense sai.count = 0; // Choose to mark count as unknown text.erase(0, i + 2); // Remove bytes = ByteArray(text); return sai; } static void DecodeContent(const BitArray& bits, Content& res) { Table latchTable = Table::UPPER; // table most recently latched to Table shiftTable = Table::UPPER; // table to use for the next read auto remBits = BitArrayView(bits); while (remBits.size() >= (shiftTable == Table::DIGIT ? 4 : 5)) { // see ISO/IEC 24778:2008 7.3.1.2 regarding padding bits if (shiftTable == Table::BINARY) { if (remBits.size() <= 6) // padding bits break; int length = remBits.readBits(5); if (length == 0) length = remBits.readBits(11) + 31; for (int i = 0; i < length; i++) res.push_back(remBits.readBits(8)); // Go back to whatever mode we had been in shiftTable = latchTable; } else { int size = shiftTable == Table::DIGIT ? 4 : 5; int code = remBits.readBits(size); const char* str = GetCharacter(shiftTable, code); if (std::strncmp(str, "CTRL_", 5) == 0) { // Table changes // ISO/IEC 24778:2008 prescibes ending a shift sequence in the mode from which it was invoked. // That's including when that mode is a shift. // Our test case dlusbs.png for issue #642 exercises that. latchTable = shiftTable; // Latch the current mode, so as to return to Upper after U/S B/S shiftTable = GetTable(str[5]); if (str[6] == 'L') latchTable = shiftTable; } else if (std::strcmp(str, "FLGN") == 0) { int flg = remBits.readBits(3); if (flg == 0) { // FNC1 res.push_back(29); // May be removed at end if first/second FNC1 } else if (flg <= 6) { // FLG(1) to FLG(6) ECI res.switchEncoding(ParseECIValue(remBits, flg)); } else { // FLG(7) is invalid } shiftTable = latchTable; } else { res.append(str); // Go back to whatever mode we had been in shiftTable = latchTable; } } } } ZXING_EXPORT_TEST_ONLY DecoderResult Decode(const BitArray& bits) { Content res; res.symbology = {'z', '0', 3}; try { DecodeContent(bits, res); } catch (const std::exception&) { // see BitArrayView::readBits return FormatError(); } if (res.bytes.empty()) return FormatError("Empty symbol content"); // Check for Structured Append - need 4 5-bit words, beginning with ML UL, ending with index and count bool haveStructuredAppend = Size(bits) > 20 && ToInt(bits, 0, 5) == 29 // latch to MIXED (from UPPER) && ToInt(bits, 5, 5) == 29; // latch back to UPPER (from MIXED) StructuredAppendInfo sai = haveStructuredAppend ? ParseStructuredAppend(res.bytes) : StructuredAppendInfo(); // As converting character set ECIs ourselves and ignoring/skipping non-character ECIs, not using // modifiers that indicate ECI protocol (ISO/IEC 24778:2008 Annex F Table F.1) if (res.bytes.size() > 1 && res.bytes[0] == 29) { res.symbology.modifier = '1'; // GS1 res.symbology.aiFlag = AIFlag::GS1; res.erase(0, 1); // Remove FNC1 } else if (res.bytes.size() > 2 && std::isupper(res.bytes[0]) && res.bytes[1] == 29) { // FNC1 following single uppercase letter (the AIM Application Indicator) res.symbology.modifier = '2'; // AIM res.symbology.aiFlag = AIFlag::AIM; res.erase(1, 1); // Remove FNC1, // The AIM Application Indicator character "A"-"Z" is left in the stream (ISO/IEC 24778:2008 16.2) } else if (res.bytes.size() > 3 && std::isdigit(res.bytes[0]) && std::isdigit(res.bytes[1]) && res.bytes[2] == 29) { // FNC1 following 2 digits (the AIM Application Indicator) res.symbology.modifier = '2'; // AIM res.symbology.aiFlag = AIFlag::AIM; res.erase(2, 1); // Remove FNC1 // The AIM Application Indicator characters "00"-"99" are left in the stream (ISO/IEC 24778:2008 16.2) } if (sai.index != -1) res.symbology.modifier += 6; // TODO: this is wrong as long as we remove the sai info from the content in ParseStructuredAppend return DecoderResult(std::move(res)).setStructuredAppend(sai); } DecoderResult DecodeRune(const DetectorResult& detectorResult) { Content res; res.symbology = {'z', 'C', 0}; // Runes cannot have ECI // Bizarrely, this is what it says to do in the spec auto runeString = ToString(detectorResult.runeValue(), 3); res.append(runeString); return DecoderResult(std::move(res)); } DecoderResult Decode(const DetectorResult& detectorResult) { try { if (detectorResult.nbLayers() == 0) { // This is a rune - just return the rune value return DecodeRune(detectorResult); } auto bits = CorrectBits(detectorResult, ExtractBits(detectorResult)); return Decode(bits); } catch (Error e) { return e; } } } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,746
```objective-c /* */ #pragma once #include <vector> namespace ZXing { class BitMatrix; namespace Aztec { class DetectorResult; DetectorResult Detect(const BitMatrix& image, bool isPure, bool tryHarder = true); using DetectorResults = std::vector<DetectorResult>; DetectorResults Detect(const BitMatrix& image, bool isPure, bool tryHarder, int maxSymbols); } // Aztec } // ZXing ```
/content/code_sandbox/core/src/aztec/AZDetector.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
89
```objective-c /* */ #pragma once namespace ZXing { class DecoderResult; namespace Aztec { class DetectorResult; DecoderResult Decode(const DetectorResult& detectorResult); } // Aztec } // ZXing ```
/content/code_sandbox/core/src/aztec/AZDecoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
42
```objective-c /* */ #pragma once #include "Reader.h" namespace ZXing::Aztec { class Reader : public ZXing::Reader { public: using ZXing::Reader::Reader; Barcode decode(const BinaryBitmap& image) const override; Barcodes decode(const BinaryBitmap& image, int maxSymbols) const override; }; } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
77
```objective-c /* */ #pragma once #include "BitMatrix.h" #include <string> namespace ZXing::Aztec { /** * Aztec 2D code representation * * @author Rustam Abdullaev */ struct EncodeResult { bool compact; int size; int layers; int codeWords; BitMatrix matrix; }; /** * Generates Aztec 2D barcodes. * * @author Rustam Abdullaev */ class Encoder { public: static const int DEFAULT_EC_PERCENT = 33; // default minimal percentage of error check words static const int DEFAULT_AZTEC_LAYERS = 0; static const int AZTEC_RUNE_LAYERS = 0xFF; static EncodeResult Encode(const std::string& data, int minECCPercent, int userSpecifiedLayers); }; } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZEncoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
179
```c++ /* */ #include "AZDetector.h" #include "AZDetectorResult.h" #include "BitArray.h" #include "BitHacks.h" #include "BitMatrix.h" #include "ConcentricFinder.h" #include "GenericGF.h" #include "GridSampler.h" #include "LogMatrix.h" #include "Pattern.h" #include "ReedSolomonDecoder.h" #include "ZXAlgorithms.h" #include <algorithm> #include <optional> #include <vector> namespace ZXing::Aztec { static bool IsAztecCenterPattern(const PatternView& view) { // find min/max of all subsequent black/white pairs and check that they 'close together' auto m = view[0] + view[1]; auto M = m; for (int i = 1; i < Size(view) - 1; ++i) { int v = view[i] + view[i + 1]; UpdateMinMax(m, M, v); } return M <= m * 4 / 3 + 1 && view[-1] >= view[Size(view) / 2] - 2 && view[Size(view)] >= view[Size(view) / 2] - 2; }; // specialized version of FindLeftGuard to find the '1,1,1,1,1,1,1' pattern of a compact Aztec center pattern static PatternView FindAztecCenterPattern(const PatternView& view) { constexpr int minSize = 8; // Aztec runes auto window = view.subView(0, 7); for (auto end = view.end() - minSize; window.data() < end; window.skipPair()) if (IsAztecCenterPattern(window)) return window; return {}; }; static int CheckSymmetricAztecCenterPattern(BitMatrixCursorI& cur, int range, bool updatePosition) { range *= 2; // tilted symbols may have a larger vertical than horizontal range FastEdgeToEdgeCounter curFwd(cur), curBwd(cur.turnedBack()); int centerFwd = curFwd.stepToNextEdge(range / 7); if (!centerFwd) return 0; int centerBwd = curBwd.stepToNextEdge(range / 7); if (!centerBwd) return 0; int center = centerFwd + centerBwd - 1; // -1 because the starting pixel is counted twice if (center > range / 7 || center < range / (4 * 7)) return 0; int spread = center; int m = 0; int M = 0; for (auto c : {&curFwd, &curBwd}) { int lastS = center; for (int i = 0; i < 3; ++i) { int s = c->stepToNextEdge(range - spread); if (s == 0) return 0; int v = s + lastS; if (m == 0) m = M = v; else UpdateMinMax(m, M, v); if (M > m * 4 / 3 + 1) return 0; spread += s; lastS = s; } } if (updatePosition) cur.step(centerFwd - centerBwd); return spread; } static std::optional<ConcentricPattern> LocateAztecCenter(const BitMatrix& image, PointF center, int spreadH) { auto cur = BitMatrixCursor(image, PointI(center), {}); int minSpread = spreadH, maxSpread = 0; for (auto d : {PointI{0, 1}, {1, 0}, {1, 1}, {1, -1}}) { int spread = CheckSymmetricAztecCenterPattern(cur.setDirection(d), spreadH, d.x == 0); if (!spread) return {}; UpdateMinMax(minSpread, maxSpread, spread); } return ConcentricPattern{centered(cur.p), (maxSpread + minSpread) / 2}; } static std::vector<ConcentricPattern> FindPureFinderPattern(const BitMatrix& image) { int left, top, width, height; if (!image.findBoundingBox(left, top, width, height, 11)) { // 11 is the size of an Aztec Rune, see ISO/IEC 24778:2008(E) Annex A // Runes 68 and 223 have none of their bits set on the bottom row if (image.findBoundingBox(left, top, width, height, 10) && (width == 11) && (height == 10)) height = 11; else return {}; } PointF p(left + width / 2, top + height / 2); constexpr auto PATTERN = FixedPattern<7, 7>{1, 1, 1, 1, 1, 1, 1}; if (auto pattern = LocateConcentricPattern(image, PATTERN, p, width)) return {*pattern}; else return {}; } static std::vector<ConcentricPattern> FindFinderPatterns(const BitMatrix& image, bool tryHarder) { std::vector<ConcentricPattern> res; [[maybe_unused]] int N = 0; #if 0 // reference algorithm for finding aztec center candidates constexpr auto PATTERN = FixedPattern<7, 7>{1, 1, 1, 1, 1, 1, 1}; auto l0 = image.row(0); std::vector<uint8_t> line(l0.begin(), l0.end()); const int width = image.width(); int skip = tryHarder ? 1 : std::clamp(image.height() / 100, 1, 3); int margin = skip; for (int y = margin; y < image.height() - margin; y += skip) { auto lc = image.row(y).begin() + 1; auto lp = image.row(y - skip).begin() + 1; line.front() = image.get(0, y); // update line and swipe right for (int x = 1; x < image.width(); ++x) { line[x] += *lc++ != *lp++; while (line[x] > line[x - 1] + 1) line[x] -= 2; } // swipe left line.back() = image.get(width - 1, y); for (int x = width - 2; x > 0; --x) while (line[x] > line[x + 1] + 1) line[x] -= 2; int first = 0, last = 0; for (int x = 1; x < width - 5; ++x) { if (line[x] > line[x - 1] && line[x] >= 5 && line[x] % 2 == 1) first = x; else continue; while (line[x] == line[x + 1]) ++x; last = x; if (line[last + 1] < line[last]) { auto p = centered(PointI((first + last) / 2, y)); // make sure p is not 'inside' an already found pattern area if (FindIf(res, [p](const auto& old) { return distance(p, old) < old.size / 2; }) == res.end()) { ++N; auto pattern = LocateConcentricPattern(image, PATTERN, p, image.width() / 3); if (pattern){ log(*pattern, 2); res.push_back(*pattern); } } } } } #else // own algorithm based on PatternRow processing (between 0% and 100% faster than reference algo depending on input) int skip = tryHarder ? 1 : std::clamp(image.height() / 2 / 100, 1, 5); int margin = tryHarder ? 5 : image.height() / 4; PatternRow row; for (int y = margin; y < image.height() - margin; y += skip) { GetPatternRow(image, y, row, false); PatternView next = row; next.shift(1); // the center pattern we are looking for starts with white and is 7 wide (compact code) #if 1 while (next = FindAztecCenterPattern(next), next.isValid()) { #else constexpr auto PATTERN = FixedPattern<7, 7>{1, 1, 1, 1, 1, 1, 1}; while (next = FindLeftGuard(next, 0, PATTERN, 0.5), next.isValid()) { #endif PointF p(next.pixelsInFront() + next[0] + next[1] + next[2] + next[3] / 2.0, y + 0.5); // make sure p is not 'inside' an already found pattern area bool found = false; for (auto old = res.rbegin(); old != res.rend(); ++old) { // search from back to front, stop once we are out of range due to the y-coordinate if (p.y - old->y > old->size / 2) break; if (distance(p, *old) < old->size / 2) { found = true; break; } } if (!found) { ++N; log(p, 1); auto pattern = LocateAztecCenter(image, p, next.sum()); if (pattern) { log(*pattern, 3); assert(image.get(*pattern)); res.push_back(*pattern); } } next.skipPair(); next.extend(); } } #endif #ifdef PRINT_DEBUG printf("\n# checked centeres: %d, # found centers: %d\n", N, Size(res)); #endif return res; } static int FindRotation(uint32_t bits, bool mirror) { const uint32_t mask = mirror ? 0b111'000'001'110 : 0b111'011'100'000; for (int i = 0; i < 4; ++i) { if (BitHacks::CountBitsSet(mask ^ bits) <= 2) // at most 2 bits may be wrong (24778:2008(E) 14.3.3 sais 3 but that is wrong) return i; bits = ((bits << 3) & 0xfff) | ((bits >> 9) & 0b111); // left shift/rotate, see RotatedCorners(Quadrilateral) } return -1; } // read 4*3=12 bits from the 4 corners of the finder pattern at radius static uint32_t SampleOrientationBits(const BitMatrix& image, const PerspectiveTransform& mod2Pix, int radius) { uint32_t bits = 0; for (auto d : {PointI{-1, -1}, {1, -1}, {1, 1}, {-1, 1}}) { auto corner = radius * d; auto cornerL = corner + PointI{0, -d.y}; auto cornerR = corner + PointI{-d.x, 0}; if (d.x != d.y) std::swap(cornerL, cornerR); for (auto ps : {cornerL, corner, cornerR}) { auto p = mod2Pix(PointF(ps)); if (!image.isIn(p)) return 0; log(p); AppendBit(bits, image.get(p)); } } return bits; } static int ModeMessage(const BitMatrix& image, const PerspectiveTransform& mod2Pix, int radius, bool& isRune) { const bool compact = radius == 5; isRune = false; // read the bits between the corner bits along the 4 edges uint64_t bits = 0; for (auto d : {PointI{-1, -1}, {1, -1}, {1, 1}, {-1, 1}}) { auto corner = radius * d; auto next = (d.x == d.y) ? PointI{-d.x, 0} : PointI{0, -d.y}; for (int i = 2; i <= 2 * radius - 2; ++i) { if (!compact && i == 7) continue; // skip the timing pattern auto p = mod2Pix(PointF(corner + i * next)); log(p); if (!image.isIn(p)) return -1; AppendBit(bits, image.get(p)); } } // error correct bits int numCodewords = compact ? 7 : 10; int numDataCodewords = compact ? 2 : 4; int numECCodewords = numCodewords - numDataCodewords; std::vector<int> words(numCodewords); for (int i = numCodewords - 1; i >= 0; --i) { words[i] = narrow_cast<int>(bits & 0xF); bits >>= 4; } bool decodeResult = ReedSolomonDecode(GenericGF::AztecParam(), words, numECCodewords); if ((!decodeResult) && compact) { // Is this a Rune? for (auto& word : words) word ^= 0b1010; decodeResult = ReedSolomonDecode(GenericGF::AztecParam(), words, numECCodewords); if (decodeResult) isRune = true; } if (!decodeResult) return -1; int res = 0; for (int i = 0; i < numDataCodewords; i++) res = (res << 4) + words[i]; return res; } static void ExtractParameters(int modeMessage, bool compact, int& nbLayers, int& nbDataBlocks, bool& readerInit) { readerInit = false; if (compact) { // 8 bits: 2 bits layers and 6 bits data blocks nbLayers = (modeMessage >> 6) + 1; if (nbLayers == 1 && (modeMessage & 0x20)) { // ISO/IEC 24778:2008 Section 9 MSB artificially set readerInit = true; modeMessage &= ~0x20; } nbDataBlocks = (modeMessage & 0x3F) + 1; } else { // 16 bits: 5 bits layers and 11 bits data blocks nbLayers = (modeMessage >> 11) + 1; if (nbLayers <= 22 && (modeMessage & 0x400)) { // ISO/IEC 24778:2008 Section 9 MSB artificially set readerInit = true; modeMessage &= ~0x400; } nbDataBlocks = (modeMessage & 0x7FF) + 1; } } DetectorResult Detect(const BitMatrix& image, bool isPure, bool tryHarder) { return FirstOrDefault(Detect(image, isPure, tryHarder, 1)); } DetectorResults Detect(const BitMatrix& image, bool isPure, bool tryHarder, int maxSymbols) { #ifdef PRINT_DEBUG LogMatrixWriter lmw(log, image, 5, "az-log.pnm"); #endif DetectorResults res; auto fps = isPure ? FindPureFinderPattern(image) : FindFinderPatterns(image, tryHarder); for (const auto& fp : fps) { auto fpQuad = FindConcentricPatternCorners(image, fp, fp.size, 3); if (!fpQuad) continue; auto srcQuad = CenteredSquare(7); auto mod2Pix = PerspectiveTransform(srcQuad, *fpQuad); if (!mod2Pix.isValid()) continue; int radius; // 5 or 7 (compact vs. full) int mirror; // 0 or 1 int rotate; // [0..3] int modeMessage = -1; bool isRune = false; [&]() { // 24778:2008(E) 14.3.3 reads: // In the outer layer of the Core Symbol, the 12 orientation bits at the corners are bitwise compared against the specified // pattern in each of four possible orientations and their four mirror inverse orientations as well. If in any of the 8 // cases checked as many as 9 of the 12 bits correctly match, that is deemed to be the correct orientation, otherwise // decoding fails. // Unfortunately, this seems to be wrong: there are 12-bit patterns in those 8 cases that differ only in 4 bits like // 011'100'000'111 (rot90 && !mirror) and 111'000'001'110 (rot0 && mirror), meaning if two of those are wrong, both cases // have a hamming distance of 2, meaning only 1 bit errors can be relyable recovered from. The following code therefore // incorporates the complete set of mode message bits to help determine the orientation of the symbol. This is still not // sufficient for the ErrorInModeMessageZero test case in AZDecoderTest.cpp but good enough for the author. for (radius = 5; radius <= 7; radius += 2) { uint32_t bits = SampleOrientationBits(image, mod2Pix, radius); if (bits == 0) continue; for (mirror = 0; mirror <= 1; ++mirror) { rotate = FindRotation(bits, mirror); if (rotate == -1) continue; modeMessage = ModeMessage(image, PerspectiveTransform(srcQuad, RotatedCorners(*fpQuad, rotate, mirror)), radius, isRune); if (modeMessage != -1) return; } } }(); if (modeMessage == -1) continue; #if 1 // improve prescision of sample grid by extrapolating from outer square of white pixels (5 edges away from center) if (radius == 7) { if (auto fpQuad5 = FindConcentricPatternCorners(image, fp, fp.size * 5 / 3, 5)) { if (auto mod2Pix = PerspectiveTransform(CenteredSquare(11), *fpQuad5); mod2Pix.isValid()) { int rotate5 = FindRotation(SampleOrientationBits(image, mod2Pix, radius), mirror); if (rotate5 != -1) { srcQuad = CenteredSquare(11); fpQuad = fpQuad5; rotate = rotate5; } } } } #endif *fpQuad = RotatedCorners(*fpQuad, rotate, mirror); int nbLayers = 0; int nbDataBlocks = 0; bool readerInit = false; if (!isRune) { ExtractParameters(modeMessage, radius == 5, nbLayers, nbDataBlocks, readerInit); } int dim = radius == 5 ? 4 * nbLayers + 11 : 4 * nbLayers + 2 * ((2 * nbLayers + 6) / 15) + 15; double low = dim / 2.0 + srcQuad[0].x; double high = dim / 2.0 + srcQuad[2].x; auto bits = SampleGrid(image, dim, dim, PerspectiveTransform{{PointF{low, low}, {high, low}, {high, high}, {low, high}}, *fpQuad}); if (!bits.isValid()) continue; res.emplace_back(std::move(bits), radius == 5, nbDataBlocks, nbLayers, readerInit, mirror != 0, isRune ? modeMessage : -1); if (Size(res) == maxSymbols) break; } return res; } } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZDetector.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
4,419
```c++ /* */ #include "AZEncoder.h" #include "AZHighLevelEncoder.h" #include "BitArray.h" #include "GenericGF.h" #include "ReedSolomonEncoder.h" #include "ZXTestSupport.h" #include <cstdlib> #include <stdexcept> #include <vector> namespace ZXing::Aztec { static const int MAX_NB_BITS = 32; static const int MAX_NB_BITS_COMPACT = 4; static const int WORD_SIZE[] = {4, 6, 6, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12}; static void DrawBullsEye(BitMatrix& matrix, int center, int size) { for (int i = 0; i < size; i += 2) { for (int j = center - i; j <= center + i; j++) { matrix.set(j, center - i); matrix.set(j, center + i); matrix.set(center - i, j); matrix.set(center + i, j); } } matrix.set(center - size, center - size); matrix.set(center - size + 1, center - size); matrix.set(center - size, center - size + 1); matrix.set(center + size, center - size); matrix.set(center + size, center - size + 1); matrix.set(center + size, center + size - 1); } static const GenericGF& GetGFFromWordSize(int wordSize) { switch (wordSize) { case 4: return GenericGF::AztecParam(); case 6: return GenericGF::AztecData6(); case 8: return GenericGF::AztecData8(); case 10: return GenericGF::AztecData10(); case 12: return GenericGF::AztecData12(); default: throw std::invalid_argument("Unsupported word size " + std::to_string(wordSize)); } } static void GenerateCheckWords(const BitArray& bitArray, int totalBits, int wordSize, BitArray& messageBits) { // bitArray is guaranteed to be a multiple of the wordSize, so no padding needed std::vector<int> messageWords = ToInts(bitArray, wordSize, totalBits / wordSize); ReedSolomonEncode(GetGFFromWordSize(wordSize), messageWords, (totalBits - bitArray.size()) / wordSize); int startPad = totalBits % wordSize; messageBits = BitArray(); messageBits.appendBits(0, startPad); for (int messageWord : messageWords) messageBits.appendBits(messageWord, wordSize); } ZXING_EXPORT_TEST_ONLY void GenerateModeMessage(bool compact, int layers, int messageSizeInWords, BitArray& modeMessage) { modeMessage = BitArray(); if (compact) { modeMessage.appendBits(layers - 1, 2); modeMessage.appendBits(messageSizeInWords - 1, 6); GenerateCheckWords(modeMessage, 28, 4, modeMessage); } else { modeMessage.appendBits(layers - 1, 5); modeMessage.appendBits(messageSizeInWords - 1, 11); GenerateCheckWords(modeMessage, 40, 4, modeMessage); } } ZXING_EXPORT_TEST_ONLY void GenerateRuneMessage(uint8_t word, BitArray& runeMessage) { runeMessage = BitArray(); runeMessage.appendBits(word, 8); GenerateCheckWords(runeMessage, 28, 4, runeMessage); // Now flip every other bit BitArray xorBits; xorBits.appendBits(0xAAAAAAAA, 28); runeMessage.bitwiseXOR(xorBits); } static void DrawModeMessage(BitMatrix& matrix, bool compact, int matrixSize, const BitArray& modeMessage) { int center = matrixSize / 2; if (compact) { for (int i = 0; i < 7; i++) { int offset = center - 3 + i; if (modeMessage.get(i)) { matrix.set(offset, center - 5); } if (modeMessage.get(i + 7)) { matrix.set(center + 5, offset); } if (modeMessage.get(20 - i)) { matrix.set(offset, center + 5); } if (modeMessage.get(27 - i)) { matrix.set(center - 5, offset); } } } else { for (int i = 0; i < 10; i++) { int offset = center - 5 + i + i / 5; if (modeMessage.get(i)) { matrix.set(offset, center - 7); } if (modeMessage.get(i + 10)) { matrix.set(center + 7, offset); } if (modeMessage.get(29 - i)) { matrix.set(offset, center + 7); } if (modeMessage.get(39 - i)) { matrix.set(center - 7, offset); } } } } ZXING_EXPORT_TEST_ONLY void StuffBits(const BitArray& bits, int wordSize, BitArray& out) { out = BitArray(); int n = bits.size(); int mask = (1 << wordSize) - 2; for (int i = 0; i < n; i += wordSize) { int word = 0; for (int j = 0; j < wordSize; j++) { if (i + j >= n || bits.get(i + j)) { word |= 1 << (wordSize - 1 - j); } } if ((word & mask) == mask) { out.appendBits(word & mask, wordSize); i--; } else if ((word & mask) == 0) { out.appendBits(word | 1, wordSize); i--; } else { out.appendBits(word, wordSize); } } } static int TotalBitsInLayer(int layers, bool compact) { return ((compact ? 88 : 112) + 16 * layers) * layers; } /** * Encodes the given binary content as an Aztec symbol * * @param data input data string * @param minECCPercent minimal percentage of error check words (According to ISO/IEC 24778:2008, * a minimum of 23% + 3 words is recommended) * @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers * @return Aztec symbol matrix with metadata */ EncodeResult Encoder::Encode(const std::string& data, int minECCPercent, int userSpecifiedLayers) { // High-level encode BitArray bits = HighLevelEncoder::Encode(data); // stuff bits and choose symbol size int eccBits = bits.size() * minECCPercent / 100 + 11; int totalSizeBits = bits.size() + eccBits; bool compact; int layers; int totalBitsInLayer; int wordSize; BitArray stuffedBits; if (userSpecifiedLayers == AZTEC_RUNE_LAYERS) { compact = true; layers = 0; totalBitsInLayer = 0; wordSize = 0; stuffedBits = BitArray(0); } else if (userSpecifiedLayers != DEFAULT_AZTEC_LAYERS) { compact = userSpecifiedLayers < 0; layers = std::abs(userSpecifiedLayers); if (layers > (compact ? MAX_NB_BITS_COMPACT : MAX_NB_BITS)) { throw std::invalid_argument("Illegal value for layers: " + std::to_string(userSpecifiedLayers)); } totalBitsInLayer = TotalBitsInLayer(layers, compact); wordSize = WORD_SIZE[layers]; int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize); StuffBits(bits, wordSize, stuffedBits); if (stuffedBits.size() + eccBits > usableBitsInLayers) { throw std::invalid_argument("Data to large for user specified layer"); } if (compact && stuffedBits.size() > wordSize * 64) { // Compact format only allows 64 data words, though C4 can hold more words than that throw std::invalid_argument("Data to large for user specified layer"); } } else { wordSize = 0; // We look at the possible table sizes in the order Compact1, Compact2, Compact3, // Compact4, Normal4,... Normal(i) for i < 4 isn't typically used since Compact(i+1) // is the same size, but has more data. for (int i = 0; ; i++) { if (i > MAX_NB_BITS) { throw std::invalid_argument("Data too large for an Aztec code"); } compact = i <= 3; layers = compact ? i + 1 : i; totalBitsInLayer = TotalBitsInLayer(layers, compact); if (totalSizeBits > totalBitsInLayer) { continue; } // [Re]stuff the bits if this is the first opportunity, or if the // wordSize has changed if (wordSize != WORD_SIZE[layers]) { wordSize = WORD_SIZE[layers]; StuffBits(bits, wordSize, stuffedBits); } int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize); if (compact && stuffedBits.size() > wordSize * 64) { // Compact format only allows 64 data words, though C4 can hold more words than that continue; } if (stuffedBits.size() + eccBits <= usableBitsInLayers) { break; } } } BitArray messageBits; BitArray modeMessage; int messageSizeInWords; if (layers == 0) { // This is a rune, and messageBits should be empty messageBits = BitArray(0); messageSizeInWords = 0; GenerateRuneMessage(data[0], modeMessage); } else { GenerateCheckWords(stuffedBits, totalBitsInLayer, wordSize, messageBits); messageSizeInWords = stuffedBits.size() / wordSize; GenerateModeMessage(compact, layers, messageSizeInWords, modeMessage); } // allocate symbol int baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines std::vector<int> alignmentMap(baseMatrixSize, 0); int matrixSize; if (compact) { // no alignment marks in compact mode, alignmentMap is a no-op matrixSize = baseMatrixSize; std::iota(alignmentMap.begin(), alignmentMap.end(), 0); } else { matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15); int origCenter = baseMatrixSize / 2; int center = matrixSize / 2; for (int i = 0; i < origCenter; i++) { int newOffset = i + i / 15; alignmentMap[origCenter - i - 1] = center - newOffset - 1; alignmentMap[origCenter + i] = center + newOffset + 1; } } EncodeResult output{compact, matrixSize, layers, messageSizeInWords, BitMatrix(matrixSize)}; BitMatrix& matrix = output.matrix; // draw data bits for (int i = 0, rowOffset = 0; i < layers; i++) { int rowSize = (layers - i) * 4 + (compact ? 9 : 12); for (int j = 0; j < rowSize; j++) { int columnOffset = j * 2; for (int k = 0; k < 2; k++) { if (messageBits.get(rowOffset + columnOffset + k)) { matrix.set(alignmentMap[i * 2 + k], alignmentMap[i * 2 + j]); } if (messageBits.get(rowOffset + rowSize * 2 + columnOffset + k)) { matrix.set(alignmentMap[i * 2 + j], alignmentMap[baseMatrixSize - 1 - i * 2 - k]); } if (messageBits.get(rowOffset + rowSize * 4 + columnOffset + k)) { matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - k], alignmentMap[baseMatrixSize - 1 - i * 2 - j]); } if (messageBits.get(rowOffset + rowSize * 6 + columnOffset + k)) { matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - j], alignmentMap[i * 2 + k]); } } } rowOffset += rowSize * 8; } // draw mode message DrawModeMessage(matrix, compact, matrixSize, modeMessage); // draw alignment marks if (compact) { DrawBullsEye(matrix, matrixSize / 2, 5); } else { DrawBullsEye(matrix, matrixSize / 2, 7); for (int i = 0, j = 0; i < baseMatrixSize / 2 - 1; i += 15, j += 16) { for (int k = (matrixSize / 2) & 1; k < matrixSize; k += 2) { matrix.set(matrixSize / 2 - j, k); matrix.set(matrixSize / 2 + j, k); matrix.set(k, matrixSize / 2 - j); matrix.set(k, matrixSize / 2 + j); } } } return output; } } // namespace ZXing::Aztec ```
/content/code_sandbox/core/src/aztec/AZEncoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,151
```objective-c /* */ #pragma once namespace ZXing { class DecoderResult; class BitMatrix; namespace DataMatrix { DecoderResult Decode(const BitMatrix& bits); } // DataMatrix } // ZXing ```
/content/code_sandbox/core/src/datamatrix/DMDecoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
41
```c++ /* */ #include "DMDecoder.h" #include "BitMatrix.h" #include "BitSource.h" #include "DMBitLayout.h" #include "DMDataBlock.h" #include "DMVersion.h" #include "DecoderResult.h" #include "GenericGF.h" #include "ReedSolomonDecoder.h" #include "ZXAlgorithms.h" #include "ZXTestSupport.h" #include <algorithm> #include <array> #include <optional> #include <string> #include <utility> #include <vector> namespace ZXing::DataMatrix { /** * <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes * in one Data Matrix Code. This class decodes the bits back into text.</p> * * <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p> * * @author bbrown@google.com (Brian Brown) * @author Sean Owen */ namespace DecodedBitStreamParser { /** * See ISO 16022:2006, Annex C Table C.1 * The C40 Basic Character Set (*'s used for placeholders for the shift values) */ static const char C40_BASIC_SET_CHARS[] = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; static const char C40_SHIFT2_SET_CHARS[] = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', 29 // FNC1->29 }; /** * See ISO 16022:2006, Annex C Table C.2 * The Text Basic Character Set (*'s used for placeholders for the shift values) */ static const char TEXT_BASIC_SET_CHARS[] = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; // Shift 2 for Text is the same encoding as C40 #define TEXT_SHIFT2_SET_CHARS C40_SHIFT2_SET_CHARS static const char TEXT_SHIFT3_SET_CHARS[] = { '`', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', 127 }; struct Shift128 { bool set = false; char operator()(int val) { return static_cast<char>(val + std::exchange(set, false) * 128); } }; /** * See ISO 16022:2006, 5.4.1, Table 6 */ static ECI ParseECIValue(BitSource& bits) { int firstByte = bits.readBits(8); if (firstByte <= 127) return ECI(firstByte - 1); int secondByte = bits.readBits(8); if (firstByte <= 191) return ECI((firstByte - 128) * 254 + 127 + secondByte - 1); int thirdByte = bits.readBits(8); return ECI((firstByte - 192) * 64516 + 16383 + (secondByte - 1) * 254 + thirdByte - 1); } /** * See ISO 16022:2006, 5.6 */ static void ParseStructuredAppend(BitSource& bits, StructuredAppendInfo& sai) { // 5.6.2 Table 8 int symbolSequenceIndicator = bits.readBits(8); sai.index = symbolSequenceIndicator >> 4; sai.count = 17 - (symbolSequenceIndicator & 0x0F); // 2-16 permitted, 17 invalid if (sai.count == 17 || sai.count <= sai.index) // If info doesn't make sense sai.count = 0; // Choose to mark count as unknown int fileId1 = bits.readBits(8); // File identification 1 int fileId2 = bits.readBits(8); // File identification 2 // There's no conversion method or meaning given to the 2 file id codewords in Section 5.6.3, apart from // saying that each value should be 1-254. Choosing here to represent them as base 256. sai.id = std::to_string((fileId1 << 8) | fileId2); } std::optional<std::array<int, 3>> DecodeNextTriple(BitSource& bits) { // Values are encoded in a 16-bit value as (1600 * C1) + (40 * C2) + C3 + 1 // If there is less than 2 bytes left or the next byte is the unlatch codeword then the current segment has ended if (bits.available() < 16) return {}; int firstByte = bits.readBits(8); if (firstByte == 254) // Unlatch codeword return {}; int fullBitValue = (firstByte << 8) + bits.readBits(8) - 1; int a = fullBitValue / 1600; fullBitValue -= a * 1600; int b = fullBitValue / 40; int c = fullBitValue - b * 40; return {{a, b, c}}; } enum class Mode {C40, TEXT}; /** * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 (C40) * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 (Text) */ static void DecodeC40OrTextSegment(BitSource& bits, Content& result, Mode mode) { // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time Shift128 upperShift; int shift = 0; const char* BASIC_SET_CHARS = mode == Mode::C40 ? C40_BASIC_SET_CHARS : TEXT_BASIC_SET_CHARS; const char* SHIFT_SET_CHARS = mode == Mode::C40 ? C40_SHIFT2_SET_CHARS : TEXT_SHIFT2_SET_CHARS; while (auto triple = DecodeNextTriple(bits)) { for (int cValue : *triple) { switch (std::exchange(shift, 0)) { case 0: if (cValue < 3) shift = cValue + 1; else if (cValue < 40) // Size(BASIC_SET_CHARS) result.push_back(upperShift(BASIC_SET_CHARS[cValue])); else throw FormatError("invalid value in C40 or Text segment"); break; case 1: result.push_back(upperShift(cValue)); break; case 2: if (cValue < 28) // Size(SHIFT_SET_CHARS)) result.push_back(upperShift(SHIFT_SET_CHARS[cValue])); else if (cValue == 30) // Upper Shift upperShift.set = true; else throw FormatError("invalid value in C40 or Text segment"); break; case 3: if (mode == Mode::C40) result.push_back(upperShift(cValue + 96)); else if (cValue < Size(TEXT_SHIFT3_SET_CHARS)) result.push_back(upperShift(TEXT_SHIFT3_SET_CHARS[cValue])); else throw FormatError("invalid value in C40 or Text segment"); break; default: throw FormatError("invalid value in C40 or Text segment"); ; } } } } /** * See ISO 16022:2006, 5.2.7 */ static void DecodeAnsiX12Segment(BitSource& bits, Content& result) { while (auto triple = DecodeNextTriple(bits)) { for (int cValue : *triple) { // X12 segment terminator <CR>, separator *, sub-element separator >, space static const char segChars[4] = {'\r', '*', '>', ' '}; if (cValue < 0) throw FormatError("invalid value in AnsiX12 segment"); else if (cValue < 4) result.push_back(segChars[cValue]); else if (cValue < 14) // 0 - 9 result.push_back((char)(cValue + 44)); else if (cValue < 40) // A - Z result.push_back((char)(cValue + 51)); else throw FormatError("invalid value in AnsiX12 segment"); } } } /** * See ISO 16022:2006, 5.2.8 and Annex C Table C.3 */ static void DecodeEdifactSegment(BitSource& bits, Content& result) { // If there are less than 3 bytes left then it will be encoded as ASCII while (bits.available() >= 24) { for (int i = 0; i < 4; i++) { char edifactValue = bits.readBits(6); // Check for the unlatch character if (edifactValue == 0x1F) { // 011111 // Read rest of byte, which should be 0, and stop if (bits.bitOffset()) bits.readBits(8 - bits.bitOffset()); return; } if ((edifactValue & 0x20) == 0) // no 1 in the leading (6th) bit edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value result.push_back(edifactValue); } } } /** * See ISO 16022:2006, Annex B, B.2 */ static int Unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition) { int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; return tempVariable >= 0 ? tempVariable : tempVariable + 256; } /** * See ISO 16022:2006, 5.2.9 and Annex B, B.2 */ static void DecodeBase256Segment(BitSource& bits, Content& result) { // Figure out how long the Base 256 Segment is. int codewordPosition = 1 + bits.byteOffset(); // position is 1-indexed int d1 = Unrandomize255State(bits.readBits(8), codewordPosition++); int count; if (d1 == 0) // Read the remainder of the symbol count = bits.available() / 8; else if (d1 < 250) count = d1; else count = 250 * (d1 - 249) + Unrandomize255State(bits.readBits(8), codewordPosition++); // We're seeing NegativeArraySizeException errors from users. if (count < 0) throw FormatError("invalid count in Base256 segment"); result.reserve(count); for (int i = 0; i < count; i++) { // readBits(8) may fail, have seen this particular error in the wild, such as at // path_to_url result += narrow_cast<uint8_t>(Unrandomize255State(bits.readBits(8), codewordPosition++)); } } ZXING_EXPORT_TEST_ONLY DecoderResult Decode(ByteArray&& bytes, const bool isDMRE) { BitSource bits(bytes); Content result; Error error; result.symbology = {'d', '1', 3}; // ECC 200 (ISO 16022:2006 Annex N Table N.1) std::string resultTrailer; struct StructuredAppendInfo sai; bool readerInit = false; bool firstCodeword = true; bool done = false; int firstFNC1Position = 1; Shift128 upperShift; auto setError = [&error](Error&& e) { // return only the first error but keep on decoding if possible if (!error) error = std::move(e); }; // See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 try { while (!done && bits.available() >= 8) { int oneByte = bits.readBits(8); switch (oneByte) { case 0: setError(FormatError("invalid 0 code word")); break; case 129: done = true; break; // Pad -> we are done, ignore the rest of the bits case 230: DecodeC40OrTextSegment(bits, result, Mode::C40); break; case 231: DecodeBase256Segment(bits, result); break; case 232: // FNC1 // Only recognizing an FNC1 as first/second by codeword position (aka symbol character position), not // by decoded character position, i.e. not recognizing a C40/Text encoded FNC1 (which requires a latch // and a shift) if (bits.byteOffset() == firstFNC1Position) result.symbology.modifier = '2'; // GS1 else if (bits.byteOffset() == firstFNC1Position + 1) result.symbology.modifier = '3'; // AIM, note no AIM Application Indicator format defined, ISO 16022:2006 11.2 else result.push_back((char)29); // translate as ASCII 29 <GS> break; case 233: // Structured Append if (!firstCodeword) // Must be first ISO 16022:2006 5.6.1 setError(FormatError("structured append tag must be first code word")); ParseStructuredAppend(bits, sai); firstFNC1Position = 5; break; case 234: // Reader Programming if (!firstCodeword) // Must be first ISO 16022:2006 5.2.4.9 setError(FormatError("reader programming tag must be first code word")); readerInit = true; break; case 235: upperShift.set = true; break; // Upper Shift (shift to Extended ASCII) case 236: // ISO 15434 format "05" Macro result.append("[)>\x1E" "05\x1D"); resultTrailer.insert(0, "\x1E\x04"); break; case 237: // ISO 15434 format "06" Macro result.append("[)>\x1E" "06\x1D"); resultTrailer.insert(0, "\x1E\x04"); break; case 238: DecodeAnsiX12Segment(bits, result); break; case 239: DecodeC40OrTextSegment(bits, result, Mode::TEXT); break; case 240: DecodeEdifactSegment(bits, result); break; case 241: result.switchEncoding(ParseECIValue(bits)); break; default: if (oneByte <= 128) { // ASCII data (ASCII value + 1) result.push_back(upperShift(oneByte) - 1); } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) result.append(ToString(oneByte - 130, 2)); } else if (oneByte >= 242) { // Not to be used in ASCII encodation // work around encoders that use unlatch to ASCII as last code word (ask upstream) if (oneByte == 254 && bits.available() == 0) break; setError(FormatError("invalid code word")); break; } } firstCodeword = false; } } catch (Error e) { setError(std::move(e)); } result.append(resultTrailer); result.symbology.aiFlag = result.symbology.modifier == '2' ? AIFlag::GS1 : AIFlag::None; result.symbology.modifier += isDMRE * 6; return DecoderResult(std::move(result)) .setError(std::move(error)) .setStructuredAppend(sai) .setReaderInit(readerInit); } } // namespace DecodedBitStreamParser /** * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to * correct the errors in-place using Reed-Solomon error correction.</p> * * @param codewordBytes data and error correction codewords * @param numDataCodewords number of codewords that are data bytes * @return false if error correction fails */ static bool CorrectErrors(ByteArray& codewordBytes, int numDataCodewords) { // First read into an array of ints std::vector<int> codewordsInts(codewordBytes.begin(), codewordBytes.end()); int numECCodewords = Size(codewordBytes) - numDataCodewords; if (!ReedSolomonDecode(GenericGF::DataMatrixField256(), codewordsInts, numECCodewords)) return false; // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords std::copy_n(codewordsInts.begin(), numDataCodewords, codewordBytes.begin()); return true; } static DecoderResult DoDecode(const BitMatrix& bits) { // Construct a parser and read version, error-correction level const Version* version = VersionForDimensionsOf(bits); if (version == nullptr) return FormatError("Invalid matrix dimension"); // Read codewords ByteArray codewords = CodewordsFromBitMatrix(bits, *version); if (codewords.empty()) return FormatError("Invalid number of code words"); bool fix259 = false; // see path_to_url retry: // Separate into data blocks std::vector<DataBlock> dataBlocks = GetDataBlocks(codewords, *version, fix259); if (dataBlocks.empty()) return FormatError("Invalid number of data blocks"); // Count total number of data bytes ByteArray resultBytes(TransformReduce(dataBlocks, 0, [](const auto& db) { return db.numDataCodewords; })); // Error-correct and copy data blocks together into a stream of bytes const int dataBlocksCount = Size(dataBlocks); for (int j = 0; j < dataBlocksCount; j++) { auto& [numDataCodewords, codewords] = dataBlocks[j]; if (!CorrectErrors(codewords, numDataCodewords)) { if(version->versionNumber == 24 && !fix259) { fix259 = true; goto retry; } return ChecksumError(); } for (int i = 0; i < numDataCodewords; i++) { // De-interlace data blocks. resultBytes[i * dataBlocksCount + j] = codewords[i]; } } #ifdef PRINT_DEBUG if (fix259) printf("-> needed retry with fix259 for 144x144 symbol\n"); #endif // Decode the contents of that stream of bytes return DecodedBitStreamParser::Decode(std::move(resultBytes), version->isDMRE()) .setVersionNumber(version->versionNumber); } static BitMatrix FlippedL(const BitMatrix& bits) { BitMatrix res(bits.height(), bits.width()); for (int y = 0; y < res.height(); ++y) for (int x = 0; x < res.width(); ++x) res.set(x, y, bits.get(bits.width() - 1 - y, bits.height() - 1 - x)); return res; } DecoderResult Decode(const BitMatrix& bits) { auto res = DoDecode(bits); if (res.isValid()) return res; //TODO: // * unify bit mirroring helper code with QRReader? // * rectangular symbols with the a size of 8 x Y are not supported a.t.m. if (auto mirroredRes = DoDecode(FlippedL(bits)); mirroredRes.error().type() != Error::Checksum) { mirroredRes.setIsMirrored(true); return mirroredRes; } return res; } } // namespace ZXing::DataMatrix ```
/content/code_sandbox/core/src/datamatrix/DMDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
4,681
```objective-c /* */ #pragma once namespace ZXing { class ByteArray; namespace DataMatrix { class SymbolInfo; /** * Creates and interleaves the ECC200 error correction for an encoded message. * * @param codewords the codewords (with interleaved error correction after function return) * @param symbolInfo information about the symbol to be encoded */ void EncodeECC200(ByteArray& codewords, const SymbolInfo& symbolInfo); } // DataMatrix } // ZXing ```
/content/code_sandbox/core/src/datamatrix/DMECEncoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
102
```objective-c /* */ #pragma once namespace ZXing::DataMatrix { /** * The Version object encapsulates attributes about a particular Data Matrix Symbol size. */ class Version { public: /** * Encapsulates a set of error-correction blocks in one symbol version. Most versions will * use blocks of differing sizes within one version, so, this encapsulates the parameters for * each set of blocks. It also holds the number of error-correction codewords per block since it * will be the same across all blocks within one version. */ struct ECBlocks { int codewordsPerBlock; /* Encapsulates the parameters for one error-correction block in one symbol version. * This includes the number of data codewords, and the number of times a block with these * parameters is used consecutively in the Data Matrix code version's format. */ struct { int count; int dataCodewords; } const blocks[2]; int numBlocks() const { return blocks[0].count + blocks[1].count; } int totalDataCodewords() const { return blocks[0].count * (blocks[0].dataCodewords + codewordsPerBlock) + blocks[1].count * (blocks[1].dataCodewords + codewordsPerBlock); } }; const int versionNumber; const int symbolHeight; const int symbolWidth; const int dataBlockHeight; const int dataBlockWidth; const ECBlocks ecBlocks; int totalCodewords() const { return ecBlocks.totalDataCodewords(); } int dataWidth() const { return (symbolWidth / dataBlockWidth) * dataBlockWidth; } int dataHeight() const { return (symbolHeight / dataBlockHeight) * dataBlockHeight; } bool isDMRE() const { return versionNumber >= 31 && versionNumber <= 48; } }; /** * @brief Looks up Version information based on symbol dimensions. * * @param height Number of rows in modules * @param width Number of columns in modules * @return Version for a Data Matrix Code of those dimensions, nullputr for invalid dimensions */ const Version* VersionForDimensions(int height, int width); template<typename MAT> const Version* VersionForDimensionsOf(const MAT& mat) { return VersionForDimensions(mat.height(), mat.width()); } } // namespace ZXing::DataMatrix ```
/content/code_sandbox/core/src/datamatrix/DMVersion.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
523
```objective-c /* */ #pragma once #include "ByteArray.h" #include <vector> namespace ZXing::DataMatrix { class Version; /** * <p>Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into * multiple blocks, each of which is a unit of data and error-correction codewords. Each * is represented by an instance of this class.</p> */ struct DataBlock { const int numDataCodewords = 0; ByteArray codewords; }; /** * <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This * method will separate the data into original blocks.</p> * * @param rawCodewords bytes as read directly from the Data Matrix Code * @param version version of the Data Matrix Code * @param fix259 see path_to_url * @return DataBlocks containing original bytes, "de-interleaved" from representation in the * Data Matrix Code */ std::vector<DataBlock> GetDataBlocks(const ByteArray& rawCodewords, const Version& version, bool fix259 = false); } // namespace ZXing::DataMatrix ```
/content/code_sandbox/core/src/datamatrix/DMDataBlock.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
277
```c++ /* */ #include "DMReader.h" #include "BinaryBitmap.h" #include "DMDecoder.h" #include "DMDetector.h" #include "ReaderOptions.h" #include "DecoderResult.h" #include "DetectorResult.h" #include "Barcode.h" #include <utility> namespace ZXing::DataMatrix { Barcode Reader::decode(const BinaryBitmap& image) const { #ifdef __cpp_impl_coroutine return FirstOrDefault(decode(image, 1)); #else auto binImg = image.getBitMatrix(); if (binImg == nullptr) return {}; auto detectorResult = Detect(*binImg, _opts.tryHarder(), _opts.tryRotate(), _opts.isPure()); if (!detectorResult.isValid()) return {}; return Barcode(Decode(detectorResult.bits()), std::move(detectorResult), BarcodeFormat::DataMatrix); #endif } #ifdef __cpp_impl_coroutine Barcodes Reader::decode(const BinaryBitmap& image, int maxSymbols) const { auto binImg = image.getBitMatrix(); if (binImg == nullptr) return {}; Barcodes res; for (auto&& detRes : Detect(*binImg, _opts.tryHarder(), _opts.tryRotate(), _opts.isPure())) { auto decRes = Decode(detRes.bits()); if (decRes.isValid(_opts.returnErrors())) { res.emplace_back(std::move(decRes), std::move(detRes), BarcodeFormat::DataMatrix); if (maxSymbols > 0 && Size(res) >= maxSymbols) break; } } return res; } #endif } // namespace ZXing::DataMatrix ```
/content/code_sandbox/core/src/datamatrix/DMReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
335
```objective-c /* */ #pragma once namespace ZXing { class BitMatrix; class ByteArray; namespace DataMatrix { class Version; BitMatrix BitMatrixFromCodewords(const ByteArray& codewords, int width, int height); ByteArray CodewordsFromBitMatrix(const BitMatrix& bits, const Version& version); } // namespace DataMatrix } // namespace ZXing ```
/content/code_sandbox/core/src/datamatrix/DMBitLayout.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
75
```objective-c /* */ #pragma once #include "ByteArray.h" #include "DMSymbolInfo.h" #include "ZXAlgorithms.h" #include <stdexcept> #include <string> #include <utility> namespace ZXing::DataMatrix { class EncoderContext { std::string _msg; SymbolShape _shape = SymbolShape::NONE; int _minWidth = -1; int _minHeight = -1; int _maxWidth = -1; int _maxHeight = -1; ByteArray _codewords; int _pos = 0; int _newEncoding = -1; const SymbolInfo* _symbolInfo = nullptr; int _skipAtEnd = 0; public: explicit EncoderContext(std::string&& msg) : _msg(std::move(msg)) { _codewords.reserve(_msg.length()); } EncoderContext(const EncoderContext &) = delete; // avoid copy by mistake void setSymbolShape(SymbolShape shape) { _shape = shape; } void setSizeConstraints(int minWidth, int minHeight, int maxWidth, int maxHeight) { _minWidth = minWidth; _minHeight = minHeight; _maxWidth = maxWidth; _maxHeight = maxHeight; } const std::string& message() const { return _msg; } void setSkipAtEnd(int count) { _skipAtEnd = count; } int currentPos() const { return _pos; } void setCurrentPos(int pos) { _pos = pos; } int currentChar() const { return _msg.at(_pos) & 0xff; } int nextChar() const { return _msg.at(_pos + 1) & 0xff; } const ByteArray& codewords() const { return _codewords; } int codewordCount() const { return Size(_codewords); } void addCodeword(uint8_t codeword) { _codewords.push_back(codeword); } void setNewEncoding(int encoding) { _newEncoding = encoding; } void clearNewEncoding() { _newEncoding = -1; } int newEncoding() const { return _newEncoding; } bool hasMoreCharacters() const { return _pos < totalMessageCharCount(); } int totalMessageCharCount() const { return narrow_cast<int>(_msg.length() - _skipAtEnd); } int remainingCharacters() const { return totalMessageCharCount() - _pos; } const SymbolInfo* updateSymbolInfo(int len) { if (_symbolInfo == nullptr || len > _symbolInfo->dataCapacity()) { _symbolInfo = SymbolInfo::Lookup(len, _shape, _minWidth, _minHeight, _maxWidth, _maxHeight); if (_symbolInfo == nullptr) { throw std::invalid_argument("Can't find a symbol arrangement that matches the message. Data codewords: " + std::to_string(len)); } } return _symbolInfo; } void resetSymbolInfo() { _symbolInfo = nullptr; } const SymbolInfo* symbolInfo() const { return _symbolInfo; } }; } // namespace ZXing::DataMatrix ```
/content/code_sandbox/core/src/datamatrix/DMEncoderContext.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
688
```objective-c /* */ #pragma once #include "CharacterSet.h" #include <string> namespace ZXing { class ByteArray; namespace DataMatrix { enum class SymbolShape; /** * DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in * annex S. */ ByteArray Encode(const std::wstring& msg); ByteArray Encode(const std::wstring& msg, CharacterSet encoding, SymbolShape shape, int minWidth, int minHeight, int maxWidth, int maxHeight); } // DataMatrix } // ZXing ```
/content/code_sandbox/core/src/datamatrix/DMHighLevelEncoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
111
```c++ /* */ #include "DMHighLevelEncoder.h" #include "ByteArray.h" #include "CharacterSet.h" #include "DMEncoderContext.h" #include "TextEncoder.h" #include "ZXAlgorithms.h" #include <algorithm> #include <array> #include <cmath> #include <cstddef> #include <cstdint> #include <functional> #include <limits> #include <stdexcept> #include <string> namespace ZXing::DataMatrix { static const uint8_t PAD = 129; static const uint8_t UPPER_SHIFT = 235; static const uint8_t MACRO_05 = 236; static const uint8_t MACRO_06 = 237; static const uint8_t C40_UNLATCH = 254; static const uint8_t X12_UNLATCH = 254; enum { ASCII_ENCODATION, C40_ENCODATION, TEXT_ENCODATION, X12_ENCODATION, EDIFACT_ENCODATION, BASE256_ENCODATION, }; static const uint8_t LATCHES[] = { 0, // ASCII mode, no latch needed 230, // LATCH_TO_C40 239, // LATCH_TO_TEXT 238, // LATCH_TO_ANSIX12 240, // LATCH_TO_EDIFACT 231, // LATCH_TO_BASE256, }; static bool IsDigit(int ch) { return ch >= '0' && ch <= '9'; } static bool IsExtendedASCII(int ch) { return ch >= 128 && ch <= 255; } static bool IsNativeC40(int ch) { return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); } static bool IsNativeText(int ch) { return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z'); } static bool IsX12TermSep(int ch) { return (ch == '\r') //CR || (ch == '*') || (ch == '>'); } static bool IsNativeX12(int ch) { return IsX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); } static bool IsNativeEDIFACT(int ch) { return ch >= ' ' && ch <= '^'; } static bool IsSpecialB256(int /*ch*/) { return false; //TODO NOT IMPLEMENTED YET!!! } /* * Converts the message to a byte array using the default encoding (cp437) as defined by the * specification * * @param msg the message * @return the byte array of the message */ /* public static byte[] getBytesForMessage(String msg) { return msg.getBytes(Charset.forName("cp437")); //See 4.4.3 and annex B of ISO/IEC 15438:2001(E) } */ static uint8_t Randomize253State(uint8_t ch, int codewordPosition) { int pseudoRandom = ((149 * codewordPosition) % 253) + 1; int tempVariable = ch + pseudoRandom; return narrow_cast<uint8_t>(tempVariable <= 254 ? tempVariable : (tempVariable - 254)); } static int FindMinimums(const std::array<int, 6>& intCharCounts, int min, std::array<int, 6>& mins) { mins.fill(0); for (int i = 0; i < 6; i++) { int current = intCharCounts[i]; if (min > current) { min = current; mins.fill(0); } if (min == current) { mins[i]++; } } return min; } static int LookAheadTest(const std::string& msg, size_t startpos, int currentMode) { if (startpos >= msg.length()) { return currentMode; } std::array<float, 6> charCounts; //step J if (currentMode == ASCII_ENCODATION) { charCounts = { 0, 1, 1, 1, 1, 1.25f }; } else { charCounts = { 1, 2, 2, 2, 2, 2.25f }; charCounts[currentMode] = 0; } std::array<int, 6> mins; std::array<int, 6> intCharCounts; int charsProcessed = 0; while (true) { //step K if ((startpos + charsProcessed) == msg.length()) { int min = std::numeric_limits<int>::max(); std::transform(charCounts.begin(), charCounts.end(), intCharCounts.begin(), [](float x) { return static_cast<int>(std::ceil(x)); }); min = FindMinimums(intCharCounts, min, mins); int minCount = Reduce(mins); if (intCharCounts[ASCII_ENCODATION] == min) { return ASCII_ENCODATION; } if (minCount == 1 && mins[BASE256_ENCODATION] > 0) { return BASE256_ENCODATION; } if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) { return EDIFACT_ENCODATION; } if (minCount == 1 && mins[TEXT_ENCODATION] > 0) { return TEXT_ENCODATION; } if (minCount == 1 && mins[X12_ENCODATION] > 0) { return X12_ENCODATION; } return C40_ENCODATION; } int c = (uint8_t)msg.at(startpos + charsProcessed); charsProcessed++; //step L if (IsDigit(c)) { charCounts[ASCII_ENCODATION] += 0.5f; } else if (IsExtendedASCII(c)) { charCounts[ASCII_ENCODATION] = std::ceil(charCounts[ASCII_ENCODATION]); charCounts[ASCII_ENCODATION] += 2.0f; } else { charCounts[ASCII_ENCODATION] = std::ceil(charCounts[ASCII_ENCODATION]); charCounts[ASCII_ENCODATION] += 1.0f; } //step M if (IsNativeC40(c)) { charCounts[C40_ENCODATION] += 2.0f / 3.0f; } else if (IsExtendedASCII(c)) { charCounts[C40_ENCODATION] += 8.0f / 3.0f; } else { charCounts[C40_ENCODATION] += 4.0f / 3.0f; } //step N if (IsNativeText(c)) { charCounts[TEXT_ENCODATION] += 2.0f / 3.0f; } else if (IsExtendedASCII(c)) { charCounts[TEXT_ENCODATION] += 8.0f / 3.0f; } else { charCounts[TEXT_ENCODATION] += 4.0f / 3.0f; } //step O if (IsNativeX12(c)) { charCounts[X12_ENCODATION] += 2.0f / 3.0f; } else if (IsExtendedASCII(c)) { charCounts[X12_ENCODATION] += 13.0f / 3.0f; } else { charCounts[X12_ENCODATION] += 10.0f / 3.0f; } //step P if (IsNativeEDIFACT(c)) { charCounts[EDIFACT_ENCODATION] += 3.0f / 4.0f; } else if (IsExtendedASCII(c)) { charCounts[EDIFACT_ENCODATION] += 17.0f / 4.0f; } else { charCounts[EDIFACT_ENCODATION] += 13.0f / 4.0f; } // step Q if (IsSpecialB256(c)) { charCounts[BASE256_ENCODATION] += 4.0f; } else { charCounts[BASE256_ENCODATION] += 1.0f; } //step R if (charsProcessed >= 4) { std::transform(charCounts.begin(), charCounts.end(), intCharCounts.begin(), [](float x) { return static_cast<int>(std::ceil(x)); }); FindMinimums(intCharCounts, std::numeric_limits<int>::max(), mins); int minCount = Reduce(mins); if (intCharCounts[ASCII_ENCODATION] < intCharCounts[BASE256_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[C40_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[TEXT_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[X12_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[EDIFACT_ENCODATION]) { return ASCII_ENCODATION; } if (intCharCounts[BASE256_ENCODATION] < intCharCounts[ASCII_ENCODATION] || (mins[C40_ENCODATION] + mins[TEXT_ENCODATION] + mins[X12_ENCODATION] + mins[EDIFACT_ENCODATION]) == 0) { return BASE256_ENCODATION; } if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) { return EDIFACT_ENCODATION; } if (minCount == 1 && mins[TEXT_ENCODATION] > 0) { return TEXT_ENCODATION; } if (minCount == 1 && mins[X12_ENCODATION] > 0) { return X12_ENCODATION; } if (intCharCounts[C40_ENCODATION] + 1 < intCharCounts[ASCII_ENCODATION] && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[BASE256_ENCODATION] && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[EDIFACT_ENCODATION] && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[TEXT_ENCODATION]) { if (intCharCounts[C40_ENCODATION] < intCharCounts[X12_ENCODATION]) { return C40_ENCODATION; } if (intCharCounts[C40_ENCODATION] == intCharCounts[X12_ENCODATION]) { size_t p = startpos + charsProcessed + 1; while (p < msg.length()) { int tc = msg.at(p); if (IsX12TermSep(tc)) { return X12_ENCODATION; } if (!IsNativeX12(tc)) { break; } p++; } return C40_ENCODATION; } } } } } static std::string ToHexString(int c) { const char* digits = "0123456789abcdef"; std::string val(4, '0'); val[1] = 'x'; val[2] = digits[(c >> 4) & 0xf]; val[3] = digits[c & 0xf]; return val; } namespace ASCIIEncoder { /** * Determines the number of consecutive characters that are encodable using numeric compaction. * * @param msg the message * @param startpos the start position within the message * @return the requested character count */ static int DetermineConsecutiveDigitCount(const std::string& msg, int startpos) { auto begin = msg.begin() + startpos; return narrow_cast<int>(std::find_if_not(begin, msg.end(), IsDigit) - begin); } static uint8_t EncodeASCIIDigits(int digit1, int digit2) { if (IsDigit(digit1) && IsDigit(digit2)) { int num = (digit1 - '0') * 10 + (digit2 - '0'); return static_cast<uint8_t>(num + 130); } return '?'; } static void EncodeASCII(EncoderContext& context) { //step B int n = DetermineConsecutiveDigitCount(context.message(), context.currentPos()); if (n >= 2) { context.addCodeword(EncodeASCIIDigits(context.currentChar(), context.nextChar())); context.setCurrentPos(context.currentPos() + 2); } else { int c = context.currentChar(); int newMode = LookAheadTest(context.message(), context.currentPos(), ASCII_ENCODATION); if (newMode != ASCII_ENCODATION) { // the order here is the same as ENCODATION; context.addCodeword(LATCHES[newMode]); context.setNewEncoding(newMode); } else if (IsExtendedASCII(c)) { context.addCodeword(UPPER_SHIFT); context.addCodeword(static_cast<uint8_t>(c - 128 + 1)); context.setCurrentPos(context.currentPos() + 1); } else { context.addCodeword(static_cast<uint8_t>(c + 1)); context.setCurrentPos(context.currentPos() + 1); } } } } // ASCIIEncoder namespace C40Encoder { static int EncodeChar(int c, std::string& sb) { if (c == ' ') { sb.push_back('\3'); return 1; } if (c >= '0' && c <= '9') { sb.push_back((char)(c - 48 + 4)); return 1; } if (c >= 'A' && c <= 'Z') { sb.push_back((char)(c - 65 + 14)); return 1; } if (c >= '\0' && c <= '\x1f') { sb.push_back('\0'); //Shift 1 Set sb.push_back(c); return 2; } if (c <= '/') { sb.push_back('\1'); //Shift 2 Set sb.push_back((char)(c - 33)); return 2; } if (c <= '@') { sb.push_back('\1'); //Shift 2 Set sb.push_back((char)(c - 58 + 15)); return 2; } if (c <= '_') { sb.push_back('\1'); //Shift 2 Set sb.push_back((char)(c - 91 + 22)); return 2; } if (c <= '\x7f') { sb.push_back('\2'); //Shift 3 Set sb.push_back((char)(c - 96)); return 2; } sb.append("\1\x1e"); //Shift 2, Upper Shift int len = 2; len += EncodeChar((char)(c - 0x80), sb); return len; } static int BacktrackOneCharacter(EncoderContext& context, std::string& buffer, std::string& removed, int lastCharSize, std::function<int(int, std::string&)> encodeChar) { buffer.resize(buffer.size() - lastCharSize); context.setCurrentPos(context.currentPos() - 1); int c = context.currentChar(); lastCharSize = encodeChar(c, removed); context.resetSymbolInfo(); //Deal with possible reduction in symbol size return lastCharSize; } static void EncodeToCodewords(EncoderContext& context, const std::string& sb, int startPos) { int c1 = sb.at(startPos); int c2 = sb.at(startPos + 1); int c3 = sb.at(startPos + 2); int v = (1600 * c1) + (40 * c2) + c3 + 1; context.addCodeword(narrow_cast<uint8_t>(v / 256)); context.addCodeword(narrow_cast<uint8_t>(v % 256)); } static void WriteNextTriplet(EncoderContext& context, std::string& buffer) { EncodeToCodewords(context, buffer, 0); buffer.erase(0, 3); } /** * Handle "end of data" situations * * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ static void HandleEOD(EncoderContext& context, std::string& buffer) { int unwritten = (Size(buffer) / 3) * 2; int rest = Size(buffer) % 3; int curCodewordCount = context.codewordCount() + unwritten; auto symbolInfo = context.updateSymbolInfo(curCodewordCount); int available = symbolInfo->dataCapacity() - curCodewordCount; if (rest == 2) { buffer.push_back('\0'); //Shift 1 while (buffer.length() >= 3) { WriteNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.addCodeword(C40_UNLATCH); } } else if (available == 1 && rest == 1) { while (buffer.length() >= 3) { WriteNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.addCodeword(C40_UNLATCH); } // else no unlatch context.setCurrentPos(context.currentPos() - 1); } else if (rest == 0) { while (buffer.length() >= 3) { WriteNextTriplet(context, buffer); } if (available > 0 || context.hasMoreCharacters()) { context.addCodeword(C40_UNLATCH); } } else { throw std::logic_error("Unexpected case. Please report!"); } context.setNewEncoding(ASCII_ENCODATION); } static void EncodeC40(EncoderContext& context, std::function<int (int, std::string&)> encodeChar, int encodingMode) { //step C std::string buffer; while (context.hasMoreCharacters()) { int c = context.currentChar(); context.setCurrentPos(context.currentPos() + 1); int lastCharSize = encodeChar(c, buffer); int unwritten = narrow_cast<int>(buffer.length() / 3) * 2; int curCodewordCount = context.codewordCount() + unwritten; auto symbolInfo = context.updateSymbolInfo(curCodewordCount); int available = symbolInfo->dataCapacity() - curCodewordCount; if (!context.hasMoreCharacters()) { //Avoid having a single C40 value in the last triplet std::string removed; if ((buffer.length() % 3) == 2 && available != 2) { lastCharSize = BacktrackOneCharacter(context, buffer, removed, lastCharSize, encodeChar); } while ((buffer.length() % 3) == 1 && ((lastCharSize <= 3 && available != 1) || lastCharSize > 3)) { lastCharSize = BacktrackOneCharacter(context, buffer, removed, lastCharSize, encodeChar); } break; } if ((buffer.length() % 3) == 0) { int newMode = LookAheadTest(context.message(), context.currentPos(), encodingMode); if (newMode != encodingMode) { // Return to ASCII encodation, which will actually handle latch to new mode context.setNewEncoding(ASCII_ENCODATION); break; } } } return HandleEOD(context, buffer); } static void EncodeC40(EncoderContext& context) { EncodeC40(context, EncodeChar, C40_ENCODATION); } } // C40Encoder namespace DMTextEncoder { static int EncodeChar(int c, std::string& sb) { if (c == ' ') { sb.push_back('\3'); return 1; } if (c >= '0' && c <= '9') { sb.push_back((char)(c - 48 + 4)); return 1; } if (c >= 'a' && c <= 'z') { sb.push_back((char)(c - 97 + 14)); return 1; } if (c >= '\0' && c <= '\x1f') { sb.push_back('\0'); //Shift 1 Set sb.push_back(c); return 2; } if (c <= '/') { sb.push_back('\1'); //Shift 2 Set sb.push_back((char)(c - 33)); return 2; } if (c <= '@') { sb.push_back('\1'); //Shift 2 Set sb.push_back((char)(c - 58 + 15)); return 2; } if (c >= '[' && c <= '_') { sb.push_back('\1'); //Shift 2 Set sb.push_back((char)(c - 91 + 22)); return 2; } if (c == '\x60') { sb.push_back('\2'); //Shift 3 Set sb.push_back((char)(c - 96)); return 2; } if (c <= 'Z') { sb.push_back('\2'); //Shift 3 Set sb.push_back((char)(c - 65 + 1)); return 2; } if (c <= '\x7f') { sb.push_back('\2'); //Shift 3 Set sb.push_back((char)(c - 123 + 27)); return 2; } sb.append("\1\x1e"); //Shift 2, Upper Shift int len = 2; len += EncodeChar(c - 128, sb); return len; } static void EncodeText(EncoderContext& context) { C40Encoder::EncodeC40(context, EncodeChar, TEXT_ENCODATION); } } // DMTextEncoder namespace X12Encoder { static int EncodeChar(int c, std::string& sb) { switch (c) { case '\r': sb.push_back('\0'); break; case '*': sb.push_back('\1'); break; case '>': sb.push_back('\2'); break; case ' ': sb.push_back('\3'); break; default: if (c >= '0' && c <= '9') { sb.push_back((char)(c - 48 + 4)); } else if (c >= 'A' && c <= 'Z') { sb.push_back((char)(c - 65 + 14)); } else { throw std::invalid_argument("Illegal character: " + ToHexString(c)); } break; } return 1; } static void HandleEOD(EncoderContext& context, std::string& buffer) { int codewordCount = context.codewordCount(); auto symbolInfo = context.updateSymbolInfo(codewordCount); int available = symbolInfo->dataCapacity() - codewordCount; context.setCurrentPos(context.currentPos() - Size(buffer)); if (context.remainingCharacters() > 1 || available > 1 || context.remainingCharacters() != available) { context.addCodeword(X12_UNLATCH); } if (context.newEncoding() < 0) { context.setNewEncoding(ASCII_ENCODATION); } } static void EncodeX12(EncoderContext& context) { //step C std::string buffer; while (context.hasMoreCharacters()) { int c = context.currentChar(); context.setCurrentPos(context.currentPos() + 1); EncodeChar(c, buffer); size_t count = buffer.length(); if ((count % 3) == 0) { C40Encoder::WriteNextTriplet(context, buffer); int newMode = LookAheadTest(context.message(), context.currentPos(), X12_ENCODATION); if (newMode != X12_ENCODATION) { // Return to ASCII encodation, which will actually handle latch to new mode context.setNewEncoding(ASCII_ENCODATION); break; } } } HandleEOD(context, buffer); } } // X12Encoder namespace EdifactEncoder { static void EncodeChar(int c, std::string& sb) { if (c >= ' ' && c <= '?') { sb.push_back(c); } else if (c >= '@' && c <= '^') { sb.push_back((char)(c - 64)); } else { throw std::invalid_argument("Illegal character: " + ToHexString(c)); } } static ByteArray EncodeToCodewords(const std::string& sb, int startPos) { int len = Size(sb) - startPos; if (len == 0) { throw std::invalid_argument("buffer must not be empty"); } int c1 = sb.at(startPos); int c2 = len >= 2 ? sb.at(startPos + 1) : 0; int c3 = len >= 3 ? sb.at(startPos + 2) : 0; int c4 = len >= 4 ? sb.at(startPos + 3) : 0; int v = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4; uint8_t cw1 = (v >> 16) & 255; uint8_t cw2 = (v >> 8) & 255; uint8_t cw3 = v & 255; ByteArray res; res.reserve(3); res.push_back(cw1); if (len >= 2) { res.push_back(cw2); } if (len >= 3) { res.push_back(cw3); } return res; } /** * Handle "end of data" situations * * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ static void HandleEOD(EncoderContext& context, std::string& buffer) { try { size_t count = buffer.length(); if (count == 0) { return; //Already finished } if (count == 1) { //Only an unlatch at the end int codewordCount = context.codewordCount(); auto symbolInfo = context.updateSymbolInfo(codewordCount); int available = symbolInfo->dataCapacity() - codewordCount; int remaining = context.remainingCharacters(); // The following two lines are a hack inspired by the 'fix' from path_to_url if (remaining > available) available = context.updateSymbolInfo(codewordCount+1)->dataCapacity() - codewordCount; if (remaining <= available && available <= 2) { return; //No unlatch } } if (count > 4) { throw std::invalid_argument("Count must not exceed 4"); } int restChars = static_cast<int>(count - 1); auto encoded = EncodeToCodewords(buffer, 0); bool endOfSymbolReached = !context.hasMoreCharacters(); bool restInAscii = endOfSymbolReached && restChars <= 2; if (restChars <= 2) { int codewordCount = context.codewordCount(); auto symbolInfo = context.updateSymbolInfo(codewordCount + restChars); int available = symbolInfo->dataCapacity() - codewordCount; if (available >= 3) { restInAscii = false; context.updateSymbolInfo(codewordCount + Size(encoded)); //available = context.symbolInfo.dataCapacity - context.getCodewordCount(); } } if (restInAscii) { context.resetSymbolInfo(); context.setCurrentPos(context.currentPos() - restChars); } else { for (uint8_t cw : encoded) { context.addCodeword(cw); } } } catch (...) { context.setNewEncoding(ASCII_ENCODATION); throw; } context.setNewEncoding(ASCII_ENCODATION); } static void EncodeEdifact(EncoderContext& context) { //step F std::string buffer; while (context.hasMoreCharacters()) { int c = context.currentChar(); EncodeChar(c, buffer); context.setCurrentPos(context.currentPos() + 1); if (buffer.length() >= 4) { auto codewords = EncodeToCodewords(buffer, 0); for (uint8_t cw : codewords) { context.addCodeword(cw); } buffer.erase(0, 4); int newMode = LookAheadTest(context.message(), context.currentPos(), EDIFACT_ENCODATION); if (newMode != EDIFACT_ENCODATION) { // Return to ASCII encodation, which will actually handle latch to new mode context.setNewEncoding(ASCII_ENCODATION); break; } } } buffer.push_back(31); //Unlatch HandleEOD(context, buffer); } } // EdifactEncoder namespace Base256Encoder { static int Randomize255State(int ch, int codewordPosition) { int pseudoRandom = ((149 * codewordPosition) % 255) + 1; int tempVariable = ch + pseudoRandom; if (tempVariable <= 255) { return tempVariable; } else { return tempVariable - 256; } } static void EncodeBase256(EncoderContext& context) { std::string buffer; buffer.push_back('\0'); //Initialize length field while (context.hasMoreCharacters()) { int c = context.currentChar(); buffer.push_back(c); context.setCurrentPos(context.currentPos() + 1); int newMode = LookAheadTest(context.message(), context.currentPos(), BASE256_ENCODATION); if (newMode != BASE256_ENCODATION) { // Return to ASCII encodation, which will actually handle latch to new mode context.setNewEncoding(ASCII_ENCODATION); break; } } int dataCount = Size(buffer) - 1; int lengthFieldSize = 1; int currentSize = context.codewordCount() + dataCount + lengthFieldSize; auto symbolInfo = context.updateSymbolInfo(currentSize); bool mustPad = (symbolInfo->dataCapacity() - currentSize) > 0; if (context.hasMoreCharacters() || mustPad) { if (dataCount <= 249) { buffer.at(0) = (char)dataCount; } else if (dataCount <= 1555) { buffer.at(0) = (char)((dataCount / 250) + 249); buffer.insert(1, 1, (char)(dataCount % 250)); } else { throw std::invalid_argument("Message length not in valid ranges: " + std::to_string(dataCount)); } } for (char c : buffer) { context.addCodeword(Randomize255State(c, context.codewordCount() + 1)); } } } // Base256Encoder //TODO: c++20 static bool StartsWith(std::wstring_view s, std::wstring_view ss) { return s.length() > ss.length() && s.compare(0, ss.length(), ss) == 0; } static bool EndsWith(std::wstring_view s, std::wstring_view ss) { return s.length() > ss.length() && s.compare(s.length() - ss.length(), ss.length(), ss) == 0; } ByteArray Encode(const std::wstring& msg) { return Encode(msg, CharacterSet::ISO8859_1, SymbolShape::NONE, -1, -1, -1, -1); } /** * Performs message encoding of a DataMatrix message using the algorithm described in annex P * of ISO/IEC 16022:2000(E). * * @param msg the message * @param shape requested shape. May be {@code SymbolShapeHint.FORCE_NONE}, * {@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}. * @param minSize the minimum symbol size constraint or null for no constraint * @param maxSize the maximum symbol size constraint or null for no constraint * @return the encoded message (the char values range from 0 to 255) */ ByteArray Encode(const std::wstring& msg, CharacterSet charset, SymbolShape shape, int minWidth, int minHeight, int maxWidth, int maxHeight) { //the codewords 0..255 are encoded as Unicode characters //Encoder[] encoders = { // new ASCIIEncoder(), new C40Encoder(), new TextEncoder(), // new X12Encoder(), new EdifactEncoder(), new Base256Encoder() //}; if (charset == CharacterSet::Unknown) { charset = CharacterSet::ISO8859_1; } EncoderContext context(TextEncoder::FromUnicode(msg, charset)); context.setSymbolShape(shape); context.setSizeConstraints(minWidth, minHeight, maxWidth, maxHeight); constexpr std::wstring_view MACRO_05_HEADER = L"[)>\x1E""05\x1D"; constexpr std::wstring_view MACRO_06_HEADER = L"[)>\x1E""06\x1D"; constexpr std::wstring_view MACRO_TRAILER = L"\x1E\x04"; if (StartsWith(msg, MACRO_05_HEADER) && EndsWith(msg, MACRO_TRAILER)) { context.addCodeword(MACRO_05); context.setSkipAtEnd(2); context.setCurrentPos(Size(MACRO_05_HEADER)); } else if (StartsWith(msg, MACRO_06_HEADER) && EndsWith(msg, MACRO_TRAILER)) { context.addCodeword(MACRO_06); context.setSkipAtEnd(2); context.setCurrentPos(Size(MACRO_06_HEADER)); } int encodingMode = ASCII_ENCODATION; //Default mode while (context.hasMoreCharacters()) { switch (encodingMode) { case ASCII_ENCODATION: ASCIIEncoder::EncodeASCII(context); break; case C40_ENCODATION: C40Encoder::EncodeC40(context); break; case TEXT_ENCODATION: DMTextEncoder::EncodeText(context); break; case X12_ENCODATION: X12Encoder::EncodeX12(context); break; case EDIFACT_ENCODATION: EdifactEncoder::EncodeEdifact(context); break; case BASE256_ENCODATION: Base256Encoder::EncodeBase256(context); break; } if (context.newEncoding() >= 0) { encodingMode = context.newEncoding(); context.clearNewEncoding(); } } int len = context.codewordCount(); auto symbolInfo = context.updateSymbolInfo(len); int capacity = symbolInfo->dataCapacity(); if (len < capacity) { if (encodingMode != ASCII_ENCODATION && encodingMode != BASE256_ENCODATION && encodingMode != EDIFACT_ENCODATION) { context.addCodeword('\xfe'); //Unlatch (254) } } //Padding if (context.codewordCount() < capacity) { context.addCodeword(PAD); } while (context.codewordCount() < capacity) { context.addCodeword(Randomize253State(PAD, context.codewordCount() + 1)); } return context.codewords(); } } // namespace ZXing::DataMatrix ```
/content/code_sandbox/core/src/datamatrix/DMHighLevelEncoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
7,954
```objective-c /* */ #pragma once #ifdef __cpp_impl_coroutine #include <Generator.h> #include <DetectorResult.h> #endif namespace ZXing { class BitMatrix; class DetectorResult; namespace DataMatrix { #ifdef __cpp_impl_coroutine using DetectorResults = Generator<DetectorResult>; #else using DetectorResults = DetectorResult; #endif DetectorResults Detect(const BitMatrix& image, bool tryHarder, bool tryRotate, bool isPure); } // DataMatrix } // ZXing ```
/content/code_sandbox/core/src/datamatrix/DMDetector.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
101
```c++ /* */ #include "DMBitLayout.h" #include "BitArray.h" #include "BitMatrix.h" #include "ByteArray.h" #include "DMVersion.h" #include <array> #include <cstddef> namespace ZXing::DataMatrix { struct BitPos { int row, col; }; using BitPosArray = std::array<BitPos, 8>; /** * VisitMatrix gets a functor/callback that is responsible for processing/visiting the bits in the matrix. * The return value contains a BitMatrix where each bit that has been visited is set. */ template <typename VisitFunc> BitMatrix VisitMatrix(int numRows, int numCols, VisitFunc visit) { // <p>See ISO 16022:2006, Figure F.3 to F.6</p> const BitPosArray CORNER1 = {{{-1, 0}, {-1, 1}, {-1, 2}, {0, -2}, {0, -1}, {1, -1}, {2, -1}, {3, -1}}}; const BitPosArray CORNER2 = {{{-3, 0}, {-2, 0}, {-1, 0}, {0, -4}, {0, -3}, {0, -2}, {0, -1}, {1, -1}}}; const BitPosArray CORNER3 = {{{-1, 0}, {-1,-1}, {0, -3}, {0, -2}, {0, -1}, {1, -3}, {1, -2}, {1, -1}}}; const BitPosArray CORNER4 = {{{-3, 0}, {-2, 0}, {-1, 0}, {0, -2}, {0, -1}, {1, -1}, {2, -1}, {3, -1}}}; BitMatrix visited(numCols, numRows); auto logAccess = [&visited](BitPos p){ visited.set(p.col, p.row); }; int row = 4; int col = 0; auto corner = [&numRows, &numCols, logAccess](const BitPosArray& corner) { auto clamp = [](int i, int max) { return i < 0 ? i + max : i; }; BitPosArray result; for (size_t bit = 0; bit < 8; ++bit) { result[bit] = {clamp(corner[bit].row, numRows), clamp(corner[bit].col, numCols)}; logAccess(result[bit]); } return result; }; auto utah = [&numRows, &numCols, logAccess](int row, int col) { const BitPosArray delta = {{{-2, -2}, {-2, -1}, {-1, -2}, {-1, -1}, {-1, 0}, {0, -2}, {0, -1}, {0, 0}}}; BitPosArray result; for (size_t bit = 0; bit < 8; ++bit) { int r = row + delta[bit].row; int c = col + delta[bit].col; if (r < 0) { r += numRows; c += 4 - ((numRows + 4) % 8); } if (c < 0) { c += numCols; r += 4 - ((numCols + 4) % 8); } if (r >= numRows) { r -= numRows; } result[bit] = {r, c}; logAccess(result[bit]); } return result; }; do { // Check the four corner cases if ((row == numRows) && (col == 0)) visit(corner(CORNER1)); else if ((row == numRows - 2) && (col == 0) && (numCols % 4 != 0)) visit(corner(CORNER2)); else if ((row == numRows + 4) && (col == 2) && (numCols % 8 == 0)) visit(corner(CORNER3)); else if ((row == numRows - 2) && (col == 0) && (numCols % 8 == 4)) visit(corner(CORNER4)); // Sweep upward diagonally to the right do { if ((row < numRows) && (col >= 0) && !visited.get(col, row)) visit(utah(row, col)); row -= 2; col += 2; } while (row >= 0 && col < numCols); row += 1; col += 3; // Sweep downward diagonally to the left do { if ((row >= 0) && (col < numCols) && !visited.get(col, row)) visit(utah(row, col)); row += 2; col -= 2; } while ((row < numRows) && (col >= 0)); row += 3; col += 1; } while ((row < numRows) || (col < numCols)); return visited; } /** * Symbol Character Placement Program. Adapted from Annex M.1 in ISO/IEC 16022:2000(E). */ BitMatrix BitMatrixFromCodewords(const ByteArray& codewords, int width, int height) { BitMatrix result(width, height); auto codeword = codewords.begin(); auto visited = VisitMatrix(height, width, [&codeword, &result](const BitPosArray& bitPos) { // Places the 8 bits of a corner or the utah-shaped symbol character in the result matrix uint8_t mask = 0x80; for (auto& p : bitPos) { if (*codeword & mask) result.set(p.col, p.row); mask >>= 1; } ++codeword; }); if (codeword != codewords.end()) return {}; // Lastly, if the lower righthand corner is untouched, fill in fixed pattern if (!visited.get(width - 1, height - 1)) { result.set(width - 1, height - 1); result.set(width - 2, height - 2); } return result; } // Extracts the data bits from a BitMatrix that contains alignment patterns. static BitMatrix ExtractDataBits(const Version& version, const BitMatrix& bits) { BitMatrix res(version.dataWidth(), version.dataHeight()); for (int y = 0; y < res.height(); ++y) for (int x = 0; x < res.width(); ++x) { int ix = x + 1 + (x / version.dataBlockWidth) * 2; int iy = y + 1 + (y / version.dataBlockHeight) * 2; res.set(x, y, bits.get(ix, iy)); } return res; } /** * <p>Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns) * in the correct order in order to reconstitute the codewords bytes contained within the * Data Matrix Code.</p> * * @return bytes encoded within the Data Matrix Code */ ByteArray CodewordsFromBitMatrix(const BitMatrix& bits, const Version& version) { BitMatrix dataBits = ExtractDataBits(version, bits); ByteArray result(version.totalCodewords()); auto codeword = result.begin(); VisitMatrix(dataBits.height(), dataBits.width(), [&codeword, &dataBits](const BitPosArray& bitPos) { // Read the 8 bits of one of the special corner/utah symbols into the current codeword *codeword = 0; for (auto& p : bitPos) AppendBit(*codeword, dataBits.get(p.col, p.row)); ++codeword; }); if (codeword != result.end()) return {}; return result; } } // namespace ZXing::DataMatrix ```
/content/code_sandbox/core/src/datamatrix/DMBitLayout.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,773