QrCode.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*
  2. * QR Code generator library (C++)
  3. *
  4. * Copyright (c) Project Nayuki. (MIT License)
  5. * https://www.nayuki.io/page/qr-code-generator-library
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. * this software and associated documentation files (the "Software"), to deal in
  9. * the Software without restriction, including without limitation the rights to
  10. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. * the Software, and to permit persons to whom the Software is furnished to do so,
  12. * subject to the following conditions:
  13. * - The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. * - The Software is provided "as is", without warranty of any kind, express or
  16. * implied, including but not limited to the warranties of merchantability,
  17. * fitness for a particular purpose and noninfringement. In no event shall the
  18. * authors or copyright holders be liable for any claim, damages or other
  19. * liability, whether in an action of contract, tort or otherwise, arising from,
  20. * out of or in connection with the Software or the use or other dealings in the
  21. * Software.
  22. */
  23. #pragma once
  24. #include <array>
  25. #include <cstdint>
  26. #include <stdexcept>
  27. #include <string>
  28. #include <vector>
  29. namespace qrcodegen {
  30. /*
  31. * A segment of character/binary/control data in a QR Code symbol.
  32. * Instances of this class are immutable.
  33. * The mid-level way to create a segment is to take the payload data
  34. * and call a static factory function such as QrSegment::makeNumeric().
  35. * The low-level way to create a segment is to custom-make the bit buffer
  36. * and call the QrSegment() constructor with appropriate values.
  37. * This segment class imposes no length restrictions, but QR Codes have restrictions.
  38. * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
  39. * Any segment longer than this is meaningless for the purpose of generating QR Codes.
  40. */
  41. class QrSegment final {
  42. /*---- Public helper enumeration ----*/
  43. /*
  44. * Describes how a segment's data bits are interpreted. Immutable.
  45. */
  46. public: class Mode final {
  47. /*-- Constants --*/
  48. public: static const Mode NUMERIC;
  49. public: static const Mode ALPHANUMERIC;
  50. public: static const Mode BYTE;
  51. public: static const Mode KANJI;
  52. public: static const Mode ECI;
  53. /*-- Fields --*/
  54. // The mode indicator bits, which is a uint4 value (range 0 to 15).
  55. private: int modeBits;
  56. // Number of character count bits for three different version ranges.
  57. private: int numBitsCharCount[3];
  58. /*-- Constructor --*/
  59. private: Mode(int mode, int cc0, int cc1, int cc2);
  60. /*-- Methods --*/
  61. /*
  62. * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15).
  63. */
  64. public: int getModeBits() const;
  65. /*
  66. * (Package-private) Returns the bit width of the character count field for a segment in
  67. * this mode in a QR Code at the given version number. The result is in the range [0, 16].
  68. */
  69. public: int numCharCountBits(int ver) const;
  70. };
  71. /*---- Static factory functions (mid level) ----*/
  72. /*
  73. * Returns a segment representing the given binary data encoded in
  74. * byte mode. All input byte vectors are acceptable. Any text string
  75. * can be converted to UTF-8 bytes and encoded as a byte mode segment.
  76. */
  77. public: static QrSegment makeBytes(const std::vector<std::uint8_t> &data);
  78. /*
  79. * Returns a segment representing the given string of decimal digits encoded in numeric mode.
  80. */
  81. public: static QrSegment makeNumeric(const char *digits);
  82. /*
  83. * Returns a segment representing the given text string encoded in alphanumeric mode.
  84. * The characters allowed are: 0 to 9, A to Z (uppercase only), space,
  85. * dollar, percent, asterisk, plus, hyphen, period, slash, colon.
  86. */
  87. public: static QrSegment makeAlphanumeric(const char *text);
  88. /*
  89. * Returns a list of zero or more segments to represent the given text string. The result
  90. * may use various segment modes and switch modes to optimize the length of the bit stream.
  91. */
  92. public: static std::vector<QrSegment> makeSegments(const char *text);
  93. /*
  94. * Returns a segment representing an Extended Channel Interpretation
  95. * (ECI) designator with the given assignment value.
  96. */
  97. public: static QrSegment makeEci(long assignVal);
  98. /*---- Public static helper functions ----*/
  99. /*
  100. * Tests whether the given string can be encoded as a segment in alphanumeric mode.
  101. * A string is encodable iff each character is in the following set: 0 to 9, A to Z
  102. * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
  103. */
  104. public: static bool isAlphanumeric(const char *text);
  105. /*
  106. * Tests whether the given string can be encoded as a segment in numeric mode.
  107. * A string is encodable iff each character is in the range 0 to 9.
  108. */
  109. public: static bool isNumeric(const char *text);
  110. /*---- Instance fields ----*/
  111. /* The mode indicator of this segment. Accessed through getMode(). */
  112. private: Mode mode;
  113. /* The length of this segment's unencoded data. Measured in characters for
  114. * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
  115. * Always zero or positive. Not the same as the data's bit length.
  116. * Accessed through getNumChars(). */
  117. private: int numChars;
  118. /* The data bits of this segment. Accessed through getData(). */
  119. private: std::vector<bool> data;
  120. /*---- Constructors (low level) ----*/
  121. /*
  122. * Creates a new QR Code segment with the given attributes and data.
  123. * The character count (numCh) must agree with the mode and the bit buffer length,
  124. * but the constraint isn't checked. The given bit buffer is copied and stored.
  125. */
  126. public: QrSegment(Mode md, int numCh, const std::vector<bool> &dt);
  127. /*
  128. * Creates a new QR Code segment with the given parameters and data.
  129. * The character count (numCh) must agree with the mode and the bit buffer length,
  130. * but the constraint isn't checked. The given bit buffer is moved and stored.
  131. */
  132. public: QrSegment(Mode md, int numCh, std::vector<bool> &&dt);
  133. /*---- Methods ----*/
  134. /*
  135. * Returns the mode field of this segment.
  136. */
  137. public: Mode getMode() const;
  138. /*
  139. * Returns the character count field of this segment.
  140. */
  141. public: int getNumChars() const;
  142. /*
  143. * Returns the data bits of this segment.
  144. */
  145. public: const std::vector<bool> &getData() const;
  146. // (Package-private) Calculates the number of bits needed to encode the given segments at
  147. // the given version. Returns a non-negative number if successful. Otherwise returns -1 if a
  148. // segment has too many characters to fit its length field, or the total bits exceeds INT_MAX.
  149. public: static int getTotalBits(const std::vector<QrSegment> &segs, int version);
  150. /*---- Private constant ----*/
  151. /* The set of all legal characters in alphanumeric mode, where
  152. * each character value maps to the index in the string. */
  153. private: static const char *ALPHANUMERIC_CHARSET;
  154. };
  155. /*
  156. * A QR Code symbol, which is a type of two-dimension barcode.
  157. * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
  158. * Instances of this class represent an immutable square grid of black and white cells.
  159. * The class provides static factory functions to create a QR Code from text or binary data.
  160. * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
  161. * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
  162. *
  163. * Ways to create a QR Code object:
  164. * - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary().
  165. * - Mid level: Custom-make the list of segments and call QrCode::encodeSegments().
  166. * - Low level: Custom-make the array of data codeword bytes (including
  167. * segment headers and final padding, excluding error correction codewords),
  168. * supply the appropriate version number, and call the QrCode() constructor.
  169. * (Note that all ways require supplying the desired error correction level.)
  170. */
  171. class QrCode final {
  172. /*---- Public helper enumeration ----*/
  173. /*
  174. * The error correction level in a QR Code symbol.
  175. */
  176. public: enum class Ecc {
  177. LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords
  178. MEDIUM , // The QR Code can tolerate about 15% erroneous codewords
  179. QUARTILE, // The QR Code can tolerate about 25% erroneous codewords
  180. HIGH , // The QR Code can tolerate about 30% erroneous codewords
  181. };
  182. // Returns a value in the range 0 to 3 (unsigned 2-bit integer).
  183. private: static int getFormatBits(Ecc ecl);
  184. /*---- Static factory functions (high level) ----*/
  185. /*
  186. * Returns a QR Code representing the given Unicode text string at the given error correction level.
  187. * As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer
  188. * UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible
  189. * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than
  190. * the ecl argument if it can be done without increasing the version.
  191. */
  192. public: static QrCode encodeText(const char *text, Ecc ecl);
  193. /*
  194. * Returns a QR Code representing the given binary data at the given error correction level.
  195. * This function always encodes using the binary segment mode, not any text mode. The maximum number of
  196. * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
  197. * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
  198. */
  199. public: static QrCode encodeBinary(const std::vector<std::uint8_t> &data, Ecc ecl);
  200. /*---- Static factory functions (mid level) ----*/
  201. /*
  202. * Returns a QR Code representing the given segments with the given encoding parameters.
  203. * The smallest possible QR Code version within the given range is automatically
  204. * chosen for the output. Iff boostEcl is true, then the ECC level of the result
  205. * may be higher than the ecl argument if it can be done without increasing the
  206. * version. The mask number is either between 0 to 7 (inclusive) to force that
  207. * mask, or -1 to automatically choose an appropriate mask (which may be slow).
  208. * This function allows the user to create a custom sequence of segments that switches
  209. * between modes (such as alphanumeric and byte) to encode text in less space.
  210. * This is a mid-level API; the high-level API is encodeText() and encodeBinary().
  211. */
  212. public: static QrCode encodeSegments(const std::vector<QrSegment> &segs, Ecc ecl,
  213. int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters
  214. /*---- Instance fields ----*/
  215. // Immutable scalar parameters:
  216. /* The version number of this QR Code, which is between 1 and 40 (inclusive).
  217. * This determines the size of this barcode. */
  218. private: int version;
  219. /* The width and height of this QR Code, measured in modules, between
  220. * 21 and 177 (inclusive). This is equal to version * 4 + 17. */
  221. private: int size;
  222. /* The error correction level used in this QR Code. */
  223. private: Ecc errorCorrectionLevel;
  224. /* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
  225. * Even if a QR Code is created with automatic masking requested (mask = -1),
  226. * the resulting object still has a mask value between 0 and 7. */
  227. private: int mask;
  228. // Private grids of modules/pixels, with dimensions of size*size:
  229. // The modules of this QR Code (false = white, true = black).
  230. // Immutable after constructor finishes. Accessed through getModule().
  231. private: std::vector<std::vector<bool> > modules;
  232. // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
  233. private: std::vector<std::vector<bool> > isFunction;
  234. /*---- Constructor (low level) ----*/
  235. /*
  236. * Creates a new QR Code with the given version number,
  237. * error correction level, data codeword bytes, and mask number.
  238. * This is a low-level API that most users should not use directly.
  239. * A mid-level API is the encodeSegments() function.
  240. */
  241. public: QrCode(int ver, Ecc ecl, const std::vector<std::uint8_t> &dataCodewords, int msk);
  242. /*---- Public instance methods ----*/
  243. /*
  244. * Returns this QR Code's version, in the range [1, 40].
  245. */
  246. public: int getVersion() const;
  247. /*
  248. * Returns this QR Code's size, in the range [21, 177].
  249. */
  250. public: int getSize() const;
  251. /*
  252. * Returns this QR Code's error correction level.
  253. */
  254. public: Ecc getErrorCorrectionLevel() const;
  255. /*
  256. * Returns this QR Code's mask, in the range [0, 7].
  257. */
  258. public: int getMask() const;
  259. /*
  260. * Returns the color of the module (pixel) at the given coordinates, which is false
  261. * for white or true for black. The top left corner has the coordinates (x=0, y=0).
  262. * If the given coordinates are out of bounds, then false (white) is returned.
  263. */
  264. public: bool getModule(int x, int y) const;
  265. /*
  266. * Returns a string of SVG code for an image depicting this QR Code, with the given number
  267. * of border modules. The string always uses Unix newlines (\n), regardless of the platform.
  268. */
  269. public: std::string toSvgString(int border) const;
  270. /*---- Private helper methods for constructor: Drawing function modules ----*/
  271. // Reads this object's version field, and draws and marks all function modules.
  272. private: void drawFunctionPatterns();
  273. // Draws two copies of the format bits (with its own error correction code)
  274. // based on the given mask and this object's error correction level field.
  275. private: void drawFormatBits(int msk);
  276. // Draws two copies of the version bits (with its own error correction code),
  277. // based on this object's version field, iff 7 <= version <= 40.
  278. private: void drawVersion();
  279. // Draws a 9*9 finder pattern including the border separator,
  280. // with the center module at (x, y). Modules can be out of bounds.
  281. private: void drawFinderPattern(int x, int y);
  282. // Draws a 5*5 alignment pattern, with the center module
  283. // at (x, y). All modules must be in bounds.
  284. private: void drawAlignmentPattern(int x, int y);
  285. // Sets the color of a module and marks it as a function module.
  286. // Only used by the constructor. Coordinates must be in bounds.
  287. private: void setFunctionModule(int x, int y, bool isBlack);
  288. // Returns the color of the module at the given coordinates, which must be in range.
  289. private: bool module(int x, int y) const;
  290. /*---- Private helper methods for constructor: Codewords and masking ----*/
  291. // Returns a new byte string representing the given data with the appropriate error correction
  292. // codewords appended to it, based on this object's version and error correction level.
  293. private: std::vector<std::uint8_t> addEccAndInterleave(const std::vector<std::uint8_t> &data) const;
  294. // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
  295. // data area of this QR Code. Function modules need to be marked off before this is called.
  296. private: void drawCodewords(const std::vector<std::uint8_t> &data);
  297. // XORs the codeword modules in this QR Code with the given mask pattern.
  298. // The function modules must be marked and the codeword bits must be drawn
  299. // before masking. Due to the arithmetic of XOR, calling applyMask() with
  300. // the same mask value a second time will undo the mask. A final well-formed
  301. // QR Code needs exactly one (not zero, two, etc.) mask applied.
  302. private: void applyMask(int msk);
  303. // Calculates and returns the penalty score based on state of this QR Code's current modules.
  304. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
  305. private: long getPenaltyScore() const;
  306. /*---- Private helper functions ----*/
  307. // Returns an ascending list of positions of alignment patterns for this version number.
  308. // Each position is in the range [0,177), and are used on both the x and y axes.
  309. // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
  310. private: std::vector<int> getAlignmentPatternPositions() const;
  311. // Returns the number of data bits that can be stored in a QR Code of the given version number, after
  312. // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
  313. // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
  314. private: static int getNumRawDataModules(int ver);
  315. // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
  316. // QR Code of the given version number and error correction level, with remainder bits discarded.
  317. // This stateless pure function could be implemented as a (40*4)-cell lookup table.
  318. private: static int getNumDataCodewords(int ver, Ecc ecl);
  319. // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
  320. // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
  321. private: static std::vector<std::uint8_t> reedSolomonComputeDivisor(int degree);
  322. // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
  323. private: static std::vector<std::uint8_t> reedSolomonComputeRemainder(const std::vector<std::uint8_t> &data, const std::vector<std::uint8_t> &divisor);
  324. // Returns the product of the two given field elements modulo GF(2^8/0x11D).
  325. // All inputs are valid. This could be implemented as a 256*256 lookup table.
  326. private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y);
  327. // Can only be called immediately after a white run is added, and
  328. // returns either 0, 1, or 2. A helper function for getPenaltyScore().
  329. private: int finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const;
  330. // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
  331. private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const;
  332. // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
  333. private: void finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const;
  334. // Returns true iff the i'th bit of x is set to 1.
  335. private: static bool getBit(long x, int i);
  336. /*---- Constants and tables ----*/
  337. // The minimum version number supported in the QR Code Model 2 standard.
  338. public: static constexpr int MIN_VERSION = 1;
  339. // The maximum version number supported in the QR Code Model 2 standard.
  340. public: static constexpr int MAX_VERSION = 40;
  341. // For use in getPenaltyScore(), when evaluating which mask is best.
  342. private: static const int PENALTY_N1;
  343. private: static const int PENALTY_N2;
  344. private: static const int PENALTY_N3;
  345. private: static const int PENALTY_N4;
  346. private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41];
  347. private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41];
  348. };
  349. /*---- Public exception class ----*/
  350. /*
  351. * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include:
  352. * - Decrease the error correction level if it was greater than Ecc::LOW.
  353. * - If the encodeSegments() function was called with a maxVersion argument, then increase
  354. * it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other
  355. * factory functions because they search all versions up to QrCode::MAX_VERSION.)
  356. * - Split the text data into better or optimal segments in order to reduce the number of bits required.
  357. * - Change the text or binary data to be shorter.
  358. * - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).
  359. * - Propagate the error upward to the caller/user.
  360. */
  361. class data_too_long : public std::length_error {
  362. public: explicit data_too_long(const std::string &msg);
  363. };
  364. /*
  365. * An appendable sequence of bits (0s and 1s). Mainly used by QrSegment.
  366. */
  367. class BitBuffer final : public std::vector<bool> {
  368. /*---- Constructor ----*/
  369. // Creates an empty bit buffer (length 0).
  370. public: BitBuffer();
  371. /*---- Method ----*/
  372. // Appends the given number of low-order bits of the given value
  373. // to this buffer. Requires 0 <= len <= 31 and val < 2^len.
  374. public: void appendBits(std::uint32_t val, int len);
  375. };
  376. }