qrcodegen.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. #include <algorithm>
  24. #include <cassert>
  25. #include <climits>
  26. #include <cstddef>
  27. #include <cstdlib>
  28. #include <cstring>
  29. #include <sstream>
  30. #include <utility>
  31. #include "qrcodegen.hpp"
  32. using std::int8_t;
  33. using std::uint8_t;
  34. using std::size_t;
  35. using std::vector;
  36. namespace qrcodegen {
  37. /*---- Class QrSegment ----*/
  38. QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) :
  39. modeBits(mode) {
  40. numBitsCharCount[0] = cc0;
  41. numBitsCharCount[1] = cc1;
  42. numBitsCharCount[2] = cc2;
  43. }
  44. int QrSegment::Mode::getModeBits() const {
  45. return modeBits;
  46. }
  47. int QrSegment::Mode::numCharCountBits(int ver) const {
  48. return numBitsCharCount[(ver + 7) / 17];
  49. }
  50. const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14);
  51. const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13);
  52. const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16);
  53. const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12);
  54. const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0);
  55. QrSegment QrSegment::makeBytes(const vector<uint8_t> &data) {
  56. if (data.size() > static_cast<unsigned int>(INT_MAX))
  57. throw std::length_error("Data too long");
  58. BitBuffer bb;
  59. for (uint8_t b : data)
  60. bb.appendBits(b, 8);
  61. return QrSegment(Mode::BYTE, static_cast<int>(data.size()), std::move(bb));
  62. }
  63. QrSegment QrSegment::makeNumeric(const char *digits) {
  64. BitBuffer bb;
  65. int accumData = 0;
  66. int accumCount = 0;
  67. int charCount = 0;
  68. for (; *digits != '\0'; digits++, charCount++) {
  69. char c = *digits;
  70. if (c < '0' || c > '9')
  71. throw std::domain_error("String contains non-numeric characters");
  72. accumData = accumData * 10 + (c - '0');
  73. accumCount++;
  74. if (accumCount == 3) {
  75. bb.appendBits(static_cast<uint32_t>(accumData), 10);
  76. accumData = 0;
  77. accumCount = 0;
  78. }
  79. }
  80. if (accumCount > 0) // 1 or 2 digits remaining
  81. bb.appendBits(static_cast<uint32_t>(accumData), accumCount * 3 + 1);
  82. return QrSegment(Mode::NUMERIC, charCount, std::move(bb));
  83. }
  84. QrSegment QrSegment::makeAlphanumeric(const char *text) {
  85. BitBuffer bb;
  86. int accumData = 0;
  87. int accumCount = 0;
  88. int charCount = 0;
  89. for (; *text != '\0'; text++, charCount++) {
  90. const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text);
  91. if (temp == nullptr)
  92. throw std::domain_error("String contains unencodable characters in alphanumeric mode");
  93. accumData = accumData * 45 + static_cast<int>(temp - ALPHANUMERIC_CHARSET);
  94. accumCount++;
  95. if (accumCount == 2) {
  96. bb.appendBits(static_cast<uint32_t>(accumData), 11);
  97. accumData = 0;
  98. accumCount = 0;
  99. }
  100. }
  101. if (accumCount > 0) // 1 character remaining
  102. bb.appendBits(static_cast<uint32_t>(accumData), 6);
  103. return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb));
  104. }
  105. vector<QrSegment> QrSegment::makeSegments(const char *text) {
  106. // Select the most efficient segment encoding automatically
  107. vector<QrSegment> result;
  108. if (*text == '\0'); // Leave result empty
  109. else if (isNumeric(text))
  110. result.push_back(makeNumeric(text));
  111. else if (isAlphanumeric(text))
  112. result.push_back(makeAlphanumeric(text));
  113. else {
  114. vector<uint8_t> bytes;
  115. for (; *text != '\0'; text++)
  116. bytes.push_back(static_cast<uint8_t>(*text));
  117. result.push_back(makeBytes(bytes));
  118. }
  119. return result;
  120. }
  121. QrSegment QrSegment::makeEci(long assignVal) {
  122. BitBuffer bb;
  123. if (assignVal < 0)
  124. throw std::domain_error("ECI assignment value out of range");
  125. else if (assignVal < (1 << 7))
  126. bb.appendBits(static_cast<uint32_t>(assignVal), 8);
  127. else if (assignVal < (1 << 14)) {
  128. bb.appendBits(2, 2);
  129. bb.appendBits(static_cast<uint32_t>(assignVal), 14);
  130. } else if (assignVal < 1000000L) {
  131. bb.appendBits(6, 3);
  132. bb.appendBits(static_cast<uint32_t>(assignVal), 21);
  133. } else
  134. throw std::domain_error("ECI assignment value out of range");
  135. return QrSegment(Mode::ECI, 0, std::move(bb));
  136. }
  137. QrSegment::QrSegment(const Mode &md, int numCh, const std::vector<bool> &dt) :
  138. mode(&md),
  139. numChars(numCh),
  140. data(dt) {
  141. if (numCh < 0)
  142. throw std::domain_error("Invalid value");
  143. }
  144. QrSegment::QrSegment(const Mode &md, int numCh, std::vector<bool> &&dt) :
  145. mode(&md),
  146. numChars(numCh),
  147. data(std::move(dt)) {
  148. if (numCh < 0)
  149. throw std::domain_error("Invalid value");
  150. }
  151. int QrSegment::getTotalBits(const vector<QrSegment> &segs, int version) {
  152. int result = 0;
  153. for (const QrSegment &seg : segs) {
  154. int ccbits = seg.mode->numCharCountBits(version);
  155. if (seg.numChars >= (1L << ccbits))
  156. return -1; // The segment's length doesn't fit the field's bit width
  157. if (4 + ccbits > INT_MAX - result)
  158. return -1; // The sum will overflow an int type
  159. result += 4 + ccbits;
  160. if (seg.data.size() > static_cast<unsigned int>(INT_MAX - result))
  161. return -1; // The sum will overflow an int type
  162. result += static_cast<int>(seg.data.size());
  163. }
  164. return result;
  165. }
  166. bool QrSegment::isNumeric(const char *text) {
  167. for (; *text != '\0'; text++) {
  168. char c = *text;
  169. if (c < '0' || c > '9')
  170. return false;
  171. }
  172. return true;
  173. }
  174. bool QrSegment::isAlphanumeric(const char *text) {
  175. for (; *text != '\0'; text++) {
  176. if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr)
  177. return false;
  178. }
  179. return true;
  180. }
  181. const QrSegment::Mode &QrSegment::getMode() const {
  182. return *mode;
  183. }
  184. int QrSegment::getNumChars() const {
  185. return numChars;
  186. }
  187. const std::vector<bool> &QrSegment::getData() const {
  188. return data;
  189. }
  190. const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
  191. /*---- Class QrCode ----*/
  192. int QrCode::getFormatBits(Ecc ecl) {
  193. switch (ecl) {
  194. case Ecc::LOW : return 1;
  195. case Ecc::MEDIUM : return 0;
  196. case Ecc::QUARTILE: return 3;
  197. case Ecc::HIGH : return 2;
  198. default: throw std::logic_error("Unreachable");
  199. }
  200. }
  201. QrCode QrCode::encodeText(const char *text, Ecc ecl) {
  202. vector<QrSegment> segs = QrSegment::makeSegments(text);
  203. return encodeSegments(segs, ecl);
  204. }
  205. QrCode QrCode::encodeBinary(const vector<uint8_t> &data, Ecc ecl) {
  206. vector<QrSegment> segs{QrSegment::makeBytes(data)};
  207. return encodeSegments(segs, ecl);
  208. }
  209. QrCode QrCode::encodeSegments(const vector<QrSegment> &segs, Ecc ecl,
  210. int minVersion, int maxVersion, int mask, bool boostEcl) {
  211. if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7)
  212. throw std::invalid_argument("Invalid value");
  213. // Find the minimal version number to use
  214. int version, dataUsedBits;
  215. for (version = minVersion; ; version++) {
  216. int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available
  217. dataUsedBits = QrSegment::getTotalBits(segs, version);
  218. if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
  219. break; // This version number is found to be suitable
  220. if (version >= maxVersion) { // All versions in the range could not fit the given data
  221. std::ostringstream sb;
  222. if (dataUsedBits == -1)
  223. sb << "Segment too long";
  224. else {
  225. sb << "Data length = " << dataUsedBits << " bits, ";
  226. sb << "Max capacity = " << dataCapacityBits << " bits";
  227. }
  228. throw data_too_long(sb.str());
  229. }
  230. }
  231. assert(dataUsedBits != -1);
  232. // Increase the error correction level while the data still fits in the current version number
  233. for (Ecc newEcl : {Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high
  234. if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
  235. ecl = newEcl;
  236. }
  237. // Concatenate all segments to create the data bit string
  238. BitBuffer bb;
  239. for (const QrSegment &seg : segs) {
  240. bb.appendBits(static_cast<uint32_t>(seg.getMode().getModeBits()), 4);
  241. bb.appendBits(static_cast<uint32_t>(seg.getNumChars()), seg.getMode().numCharCountBits(version));
  242. bb.insert(bb.end(), seg.getData().begin(), seg.getData().end());
  243. }
  244. assert(bb.size() == static_cast<unsigned int>(dataUsedBits));
  245. // Add terminator and pad up to a byte if applicable
  246. size_t dataCapacityBits = static_cast<size_t>(getNumDataCodewords(version, ecl)) * 8;
  247. assert(bb.size() <= dataCapacityBits);
  248. bb.appendBits(0, std::min(4, static_cast<int>(dataCapacityBits - bb.size())));
  249. bb.appendBits(0, (8 - static_cast<int>(bb.size() % 8)) % 8);
  250. assert(bb.size() % 8 == 0);
  251. // Pad with alternating bytes until data capacity is reached
  252. for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
  253. bb.appendBits(padByte, 8);
  254. // Pack bits into bytes in big endian
  255. vector<uint8_t> dataCodewords(bb.size() / 8);
  256. for (size_t i = 0; i < bb.size(); i++)
  257. dataCodewords.at(i >> 3) |= (bb.at(i) ? 1 : 0) << (7 - (i & 7));
  258. // Create the QR Code object
  259. return QrCode(version, ecl, dataCodewords, mask);
  260. }
  261. QrCode::QrCode(int ver, Ecc ecl, const vector<uint8_t> &dataCodewords, int msk) :
  262. // Initialize fields and check arguments
  263. version(ver),
  264. errorCorrectionLevel(ecl) {
  265. if (ver < MIN_VERSION || ver > MAX_VERSION)
  266. throw std::domain_error("Version value out of range");
  267. if (msk < -1 || msk > 7)
  268. throw std::domain_error("Mask value out of range");
  269. size = ver * 4 + 17;
  270. size_t sz = static_cast<size_t>(size);
  271. modules = vector<vector<bool> >(sz, vector<bool>(sz)); // Initially all light
  272. isFunction = vector<vector<bool> >(sz, vector<bool>(sz));
  273. // Compute ECC, draw modules
  274. drawFunctionPatterns();
  275. const vector<uint8_t> allCodewords = addEccAndInterleave(dataCodewords);
  276. drawCodewords(allCodewords);
  277. // Do masking
  278. if (msk == -1) { // Automatically choose best mask
  279. long minPenalty = LONG_MAX;
  280. for (int i = 0; i < 8; i++) {
  281. applyMask(i);
  282. drawFormatBits(i);
  283. long penalty = getPenaltyScore();
  284. if (penalty < minPenalty) {
  285. msk = i;
  286. minPenalty = penalty;
  287. }
  288. applyMask(i); // Undoes the mask due to XOR
  289. }
  290. }
  291. assert(0 <= msk && msk <= 7);
  292. mask = msk;
  293. applyMask(msk); // Apply the final choice of mask
  294. drawFormatBits(msk); // Overwrite old format bits
  295. isFunction.clear();
  296. isFunction.shrink_to_fit();
  297. }
  298. int QrCode::getVersion() const {
  299. return version;
  300. }
  301. int QrCode::getSize() const {
  302. return size;
  303. }
  304. QrCode::Ecc QrCode::getErrorCorrectionLevel() const {
  305. return errorCorrectionLevel;
  306. }
  307. int QrCode::getMask() const {
  308. return mask;
  309. }
  310. bool QrCode::getModule(int x, int y) const {
  311. return 0 <= x && x < size && 0 <= y && y < size && module(x, y);
  312. }
  313. void QrCode::drawFunctionPatterns() {
  314. // Draw horizontal and vertical timing patterns
  315. for (int i = 0; i < size; i++) {
  316. setFunctionModule(6, i, i % 2 == 0);
  317. setFunctionModule(i, 6, i % 2 == 0);
  318. }
  319. // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
  320. drawFinderPattern(3, 3);
  321. drawFinderPattern(size - 4, 3);
  322. drawFinderPattern(3, size - 4);
  323. // Draw numerous alignment patterns
  324. const vector<int> alignPatPos = getAlignmentPatternPositions();
  325. size_t numAlign = alignPatPos.size();
  326. for (size_t i = 0; i < numAlign; i++) {
  327. for (size_t j = 0; j < numAlign; j++) {
  328. // Don't draw on the three finder corners
  329. if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
  330. drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j));
  331. }
  332. }
  333. // Draw configuration data
  334. drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
  335. drawVersion();
  336. }
  337. void QrCode::drawFormatBits(int msk) {
  338. // Calculate error correction code and pack bits
  339. int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3
  340. int rem = data;
  341. for (int i = 0; i < 10; i++)
  342. rem = (rem << 1) ^ ((rem >> 9) * 0x537);
  343. int bits = (data << 10 | rem) ^ 0x5412; // uint15
  344. assert(bits >> 15 == 0);
  345. // Draw first copy
  346. for (int i = 0; i <= 5; i++)
  347. setFunctionModule(8, i, getBit(bits, i));
  348. setFunctionModule(8, 7, getBit(bits, 6));
  349. setFunctionModule(8, 8, getBit(bits, 7));
  350. setFunctionModule(7, 8, getBit(bits, 8));
  351. for (int i = 9; i < 15; i++)
  352. setFunctionModule(14 - i, 8, getBit(bits, i));
  353. // Draw second copy
  354. for (int i = 0; i < 8; i++)
  355. setFunctionModule(size - 1 - i, 8, getBit(bits, i));
  356. for (int i = 8; i < 15; i++)
  357. setFunctionModule(8, size - 15 + i, getBit(bits, i));
  358. setFunctionModule(8, size - 8, true); // Always dark
  359. }
  360. void QrCode::drawVersion() {
  361. if (version < 7)
  362. return;
  363. // Calculate error correction code and pack bits
  364. int rem = version; // version is uint6, in the range [7, 40]
  365. for (int i = 0; i < 12; i++)
  366. rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
  367. long bits = static_cast<long>(version) << 12 | rem; // uint18
  368. assert(bits >> 18 == 0);
  369. // Draw two copies
  370. for (int i = 0; i < 18; i++) {
  371. bool bit = getBit(bits, i);
  372. int a = size - 11 + i % 3;
  373. int b = i / 3;
  374. setFunctionModule(a, b, bit);
  375. setFunctionModule(b, a, bit);
  376. }
  377. }
  378. void QrCode::drawFinderPattern(int x, int y) {
  379. for (int dy = -4; dy <= 4; dy++) {
  380. for (int dx = -4; dx <= 4; dx++) {
  381. int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm
  382. int xx = x + dx, yy = y + dy;
  383. if (0 <= xx && xx < size && 0 <= yy && yy < size)
  384. setFunctionModule(xx, yy, dist != 2 && dist != 4);
  385. }
  386. }
  387. }
  388. void QrCode::drawAlignmentPattern(int x, int y) {
  389. for (int dy = -2; dy <= 2; dy++) {
  390. for (int dx = -2; dx <= 2; dx++)
  391. setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1);
  392. }
  393. }
  394. void QrCode::setFunctionModule(int x, int y, bool isDark) {
  395. size_t ux = static_cast<size_t>(x);
  396. size_t uy = static_cast<size_t>(y);
  397. modules .at(uy).at(ux) = isDark;
  398. isFunction.at(uy).at(ux) = true;
  399. }
  400. bool QrCode::module(int x, int y) const {
  401. return modules.at(static_cast<size_t>(y)).at(static_cast<size_t>(x));
  402. }
  403. vector<uint8_t> QrCode::addEccAndInterleave(const vector<uint8_t> &data) const {
  404. if (data.size() != static_cast<unsigned int>(getNumDataCodewords(version, errorCorrectionLevel)))
  405. throw std::invalid_argument("Invalid argument");
  406. // Calculate parameter numbers
  407. int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(errorCorrectionLevel)][version];
  408. int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast<int>(errorCorrectionLevel)][version];
  409. int rawCodewords = getNumRawDataModules(version) / 8;
  410. int numShortBlocks = numBlocks - rawCodewords % numBlocks;
  411. int shortBlockLen = rawCodewords / numBlocks;
  412. // Split data into blocks and append ECC to each block
  413. vector<vector<uint8_t> > blocks;
  414. const vector<uint8_t> rsDiv = reedSolomonComputeDivisor(blockEccLen);
  415. for (int i = 0, k = 0; i < numBlocks; i++) {
  416. vector<uint8_t> dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)));
  417. k += static_cast<int>(dat.size());
  418. const vector<uint8_t> ecc = reedSolomonComputeRemainder(dat, rsDiv);
  419. if (i < numShortBlocks)
  420. dat.push_back(0);
  421. dat.insert(dat.end(), ecc.cbegin(), ecc.cend());
  422. blocks.push_back(std::move(dat));
  423. }
  424. // Interleave (not concatenate) the bytes from every block into a single sequence
  425. vector<uint8_t> result;
  426. for (size_t i = 0; i < blocks.at(0).size(); i++) {
  427. for (size_t j = 0; j < blocks.size(); j++) {
  428. // Skip the padding byte in short blocks
  429. if (i != static_cast<unsigned int>(shortBlockLen - blockEccLen) || j >= static_cast<unsigned int>(numShortBlocks))
  430. result.push_back(blocks.at(j).at(i));
  431. }
  432. }
  433. assert(result.size() == static_cast<unsigned int>(rawCodewords));
  434. return result;
  435. }
  436. void QrCode::drawCodewords(const vector<uint8_t> &data) {
  437. if (data.size() != static_cast<unsigned int>(getNumRawDataModules(version) / 8))
  438. throw std::invalid_argument("Invalid argument");
  439. size_t i = 0; // Bit index into the data
  440. // Do the funny zigzag scan
  441. for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
  442. if (right == 6)
  443. right = 5;
  444. for (int vert = 0; vert < size; vert++) { // Vertical counter
  445. for (int j = 0; j < 2; j++) {
  446. size_t x = static_cast<size_t>(right - j); // Actual x coordinate
  447. bool upward = ((right + 1) & 2) == 0;
  448. size_t y = static_cast<size_t>(upward ? size - 1 - vert : vert); // Actual y coordinate
  449. if (!isFunction.at(y).at(x) && i < data.size() * 8) {
  450. modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast<int>(i & 7));
  451. i++;
  452. }
  453. // If this QR Code has any remainder bits (0 to 7), they were assigned as
  454. // 0/false/light by the constructor and are left unchanged by this method
  455. }
  456. }
  457. }
  458. assert(i == data.size() * 8);
  459. }
  460. void QrCode::applyMask(int msk) {
  461. if (msk < 0 || msk > 7)
  462. throw std::domain_error("Mask value out of range");
  463. size_t sz = static_cast<size_t>(size);
  464. for (size_t y = 0; y < sz; y++) {
  465. for (size_t x = 0; x < sz; x++) {
  466. bool invert;
  467. switch (msk) {
  468. case 0: invert = (x + y) % 2 == 0; break;
  469. case 1: invert = y % 2 == 0; break;
  470. case 2: invert = x % 3 == 0; break;
  471. case 3: invert = (x + y) % 3 == 0; break;
  472. case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
  473. case 5: invert = x * y % 2 + x * y % 3 == 0; break;
  474. case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
  475. case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
  476. default: throw std::logic_error("Unreachable");
  477. }
  478. modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x));
  479. }
  480. }
  481. }
  482. long QrCode::getPenaltyScore() const {
  483. long result = 0;
  484. // Adjacent modules in row having same color, and finder-like patterns
  485. for (int y = 0; y < size; y++) {
  486. bool runColor = false;
  487. int runX = 0;
  488. std::array<int,7> runHistory = {};
  489. for (int x = 0; x < size; x++) {
  490. if (module(x, y) == runColor) {
  491. runX++;
  492. if (runX == 5)
  493. result += PENALTY_N1;
  494. else if (runX > 5)
  495. result++;
  496. } else {
  497. finderPenaltyAddHistory(runX, runHistory);
  498. if (!runColor)
  499. result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
  500. runColor = module(x, y);
  501. runX = 1;
  502. }
  503. }
  504. result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3;
  505. }
  506. // Adjacent modules in column having same color, and finder-like patterns
  507. for (int x = 0; x < size; x++) {
  508. bool runColor = false;
  509. int runY = 0;
  510. std::array<int,7> runHistory = {};
  511. for (int y = 0; y < size; y++) {
  512. if (module(x, y) == runColor) {
  513. runY++;
  514. if (runY == 5)
  515. result += PENALTY_N1;
  516. else if (runY > 5)
  517. result++;
  518. } else {
  519. finderPenaltyAddHistory(runY, runHistory);
  520. if (!runColor)
  521. result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
  522. runColor = module(x, y);
  523. runY = 1;
  524. }
  525. }
  526. result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3;
  527. }
  528. // 2*2 blocks of modules having same color
  529. for (int y = 0; y < size - 1; y++) {
  530. for (int x = 0; x < size - 1; x++) {
  531. bool color = module(x, y);
  532. if ( color == module(x + 1, y) &&
  533. color == module(x, y + 1) &&
  534. color == module(x + 1, y + 1))
  535. result += PENALTY_N2;
  536. }
  537. }
  538. // Balance of dark and light modules
  539. int dark = 0;
  540. for (const vector<bool> &row : modules) {
  541. for (bool color : row) {
  542. if (color)
  543. dark++;
  544. }
  545. }
  546. int total = size * size; // Note that size is odd, so dark/total != 1/2
  547. // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
  548. int k = static_cast<int>((std::abs(dark * 20L - total * 10L) + total - 1) / total) - 1;
  549. assert(0 <= k && k <= 9);
  550. result += k * PENALTY_N4;
  551. assert(0 <= result && result <= 2568888L); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
  552. return result;
  553. }
  554. vector<int> QrCode::getAlignmentPatternPositions() const {
  555. if (version == 1)
  556. return vector<int>();
  557. else {
  558. int numAlign = version / 7 + 2;
  559. int step = (version == 32) ? 26 :
  560. (version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2;
  561. vector<int> result;
  562. for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step)
  563. result.insert(result.begin(), pos);
  564. result.insert(result.begin(), 6);
  565. return result;
  566. }
  567. }
  568. int QrCode::getNumRawDataModules(int ver) {
  569. if (ver < MIN_VERSION || ver > MAX_VERSION)
  570. throw std::domain_error("Version number out of range");
  571. int result = (16 * ver + 128) * ver + 64;
  572. if (ver >= 2) {
  573. int numAlign = ver / 7 + 2;
  574. result -= (25 * numAlign - 10) * numAlign - 55;
  575. if (ver >= 7)
  576. result -= 36;
  577. }
  578. assert(208 <= result && result <= 29648);
  579. return result;
  580. }
  581. int QrCode::getNumDataCodewords(int ver, Ecc ecl) {
  582. return getNumRawDataModules(ver) / 8
  583. - ECC_CODEWORDS_PER_BLOCK [static_cast<int>(ecl)][ver]
  584. * NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(ecl)][ver];
  585. }
  586. vector<uint8_t> QrCode::reedSolomonComputeDivisor(int degree) {
  587. if (degree < 1 || degree > 255)
  588. throw std::domain_error("Degree out of range");
  589. // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
  590. // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
  591. vector<uint8_t> result(static_cast<size_t>(degree));
  592. result.at(result.size() - 1) = 1; // Start off with the monomial x^0
  593. // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
  594. // and drop the highest monomial term which is always 1x^degree.
  595. // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
  596. uint8_t root = 1;
  597. for (int i = 0; i < degree; i++) {
  598. // Multiply the current product by (x - r^i)
  599. for (size_t j = 0; j < result.size(); j++) {
  600. result.at(j) = reedSolomonMultiply(result.at(j), root);
  601. if (j + 1 < result.size())
  602. result.at(j) ^= result.at(j + 1);
  603. }
  604. root = reedSolomonMultiply(root, 0x02);
  605. }
  606. return result;
  607. }
  608. vector<uint8_t> QrCode::reedSolomonComputeRemainder(const vector<uint8_t> &data, const vector<uint8_t> &divisor) {
  609. vector<uint8_t> result(divisor.size());
  610. for (uint8_t b : data) { // Polynomial division
  611. uint8_t factor = b ^ result.at(0);
  612. result.erase(result.begin());
  613. result.push_back(0);
  614. for (size_t i = 0; i < result.size(); i++)
  615. result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor);
  616. }
  617. return result;
  618. }
  619. uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) {
  620. // Russian peasant multiplication
  621. int z = 0;
  622. for (int i = 7; i >= 0; i--) {
  623. z = (z << 1) ^ ((z >> 7) * 0x11D);
  624. z ^= ((y >> i) & 1) * x;
  625. }
  626. assert(z >> 8 == 0);
  627. return static_cast<uint8_t>(z);
  628. }
  629. int QrCode::finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const {
  630. int n = runHistory.at(1);
  631. assert(n <= size * 3);
  632. bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n;
  633. return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0)
  634. + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0);
  635. }
  636. int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const {
  637. if (currentRunColor) { // Terminate dark run
  638. finderPenaltyAddHistory(currentRunLength, runHistory);
  639. currentRunLength = 0;
  640. }
  641. currentRunLength += size; // Add light border to final run
  642. finderPenaltyAddHistory(currentRunLength, runHistory);
  643. return finderPenaltyCountPatterns(runHistory);
  644. }
  645. void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const {
  646. if (runHistory.at(0) == 0)
  647. currentRunLength += size; // Add light border to initial run
  648. std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end());
  649. runHistory.at(0) = currentRunLength;
  650. }
  651. bool QrCode::getBit(long x, int i) {
  652. return ((x >> i) & 1) != 0;
  653. }
  654. /*---- Tables of constants ----*/
  655. const int QrCode::PENALTY_N1 = 3;
  656. const int QrCode::PENALTY_N2 = 3;
  657. const int QrCode::PENALTY_N3 = 40;
  658. const int QrCode::PENALTY_N4 = 10;
  659. const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = {
  660. // Version: (note that index 0 is for padding, and is set to an illegal value)
  661. //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
  662. {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low
  663. {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium
  664. {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile
  665. {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High
  666. };
  667. const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
  668. // Version: (note that index 0 is for padding, and is set to an illegal value)
  669. //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
  670. {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low
  671. {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium
  672. {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile
  673. {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High
  674. };
  675. data_too_long::data_too_long(const std::string &msg) :
  676. std::length_error(msg) {}
  677. /*---- Class BitBuffer ----*/
  678. BitBuffer::BitBuffer()
  679. : std::vector<bool>() {}
  680. void BitBuffer::appendBits(std::uint32_t val, int len) {
  681. if (len < 0 || len > 31 || val >> len != 0)
  682. throw std::domain_error("Value out of range");
  683. for (int i = len - 1; i >= 0; i--) // Append bit by bit
  684. this->push_back(((val >> i) & 1) != 0);
  685. }
  686. }