qrcode.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. /**
  2. * The MIT License (MIT)
  3. *
  4. * This library is written and maintained by Richard Moore.
  5. * Major parts were derived from Project Nayuki's library.
  6. *
  7. * Copyright (c) 2017 Richard Moore (https://github.com/ricmoo/QRCode)
  8. * Copyright (c) 2017 Project Nayuki (https://www.nayuki.io/page/qr-code-generator-library)
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * of this software and associated documentation files (the "Software"), to deal
  12. * in the Software without restriction, including without limitation the rights
  13. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. * copies of the Software, and to permit persons to whom the Software is
  15. * furnished to do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. * THE SOFTWARE.
  27. */
  28. /**
  29. * Special thanks to Nayuki (https://www.nayuki.io/) from which this library was
  30. * heavily inspired and compared against.
  31. *
  32. * See: https://github.com/nayuki/QR-Code-generator/tree/master/cpp
  33. */
  34. #include "qrcode.h"
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #if LOCK_VERSION == 0
  38. static const uint16_t NUM_ERROR_CORRECTION_CODEWORDS[4][40] = {
  39. // 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
  40. {10, 16, 26, 36, 48, 64, 72, 88, 110, 130, 150, 176, 198, 216,
  41. 240, 280, 308, 338, 364, 416, 442, 476, 504, 560, 588, 644, 700, 728,
  42. 784, 812, 868, 924, 980, 1036, 1064, 1120, 1204, 1260, 1316, 1372}, // Medium
  43. {7, 10, 15, 20, 26, 36, 40, 48, 60, 72, 80, 96, 104, 120,
  44. 132, 144, 168, 180, 196, 224, 224, 252, 270, 300, 312, 336, 360, 390,
  45. 420, 450, 480, 510, 540, 570, 570, 600, 630, 660, 720, 750}, // Low
  46. {17, 28, 44, 64, 88, 112, 130, 156, 192, 224, 264, 308, 352, 384,
  47. 432, 480, 532, 588, 650, 700, 750, 816, 900, 960, 1050, 1110, 1200, 1260,
  48. 1350, 1440, 1530, 1620, 1710, 1800, 1890, 1980, 2100, 2220, 2310, 2430}, // High
  49. {13, 22, 36, 52, 72, 96, 108, 132, 160, 192, 224, 260, 288, 320,
  50. 360, 408, 448, 504, 546, 600, 644, 690, 750, 810, 870, 952, 1020, 1050,
  51. 1140, 1200, 1290, 1350, 1440, 1530, 1590, 1680, 1770, 1860, 1950, 2040}, // Quartile
  52. };
  53. static const uint8_t NUM_ERROR_CORRECTION_BLOCKS[4][40] = {
  54. // Version: (note that index 0 is for padding, and is set to an illegal value)
  55. // 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
  56. {1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16,
  57. 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium
  58. {1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8,
  59. 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low
  60. {1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25,
  61. 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High
  62. {1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20,
  63. 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile
  64. };
  65. static const uint16_t NUM_RAW_DATA_MODULES[40] = {
  66. // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  67. 208,
  68. 359,
  69. 567,
  70. 807,
  71. 1079,
  72. 1383,
  73. 1568,
  74. 1936,
  75. 2336,
  76. 2768,
  77. 3232,
  78. 3728,
  79. 4256,
  80. 4651,
  81. 5243,
  82. 5867,
  83. 6523,
  84. // 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  85. 7211,
  86. 7931,
  87. 8683,
  88. 9252,
  89. 10068,
  90. 10916,
  91. 11796,
  92. 12708,
  93. 13652,
  94. 14628,
  95. 15371,
  96. 16411,
  97. 17483,
  98. 18587,
  99. // 32, 33, 34, 35, 36, 37, 38, 39, 40
  100. 19723,
  101. 20891,
  102. 22091,
  103. 23008,
  104. 24272,
  105. 25568,
  106. 26896,
  107. 28256,
  108. 29648};
  109. // @TODO: Put other LOCK_VERSIONS here
  110. #elif LOCK_VERSION == 3
  111. static const int16_t NUM_ERROR_CORRECTION_CODEWORDS[4] = {26, 15, 44, 36};
  112. static const int8_t NUM_ERROR_CORRECTION_BLOCKS[4] = {1, 1, 2, 2};
  113. static const uint16_t NUM_RAW_DATA_MODULES = 567;
  114. #else
  115. #error Unsupported LOCK_VERSION (add it...)
  116. #endif
  117. static int max(int a, int b) {
  118. if(a > b) {
  119. return a;
  120. }
  121. return b;
  122. }
  123. /*
  124. static int abs(int value) {
  125. if (value < 0) { return -value; }
  126. return value;
  127. }
  128. */
  129. static int8_t getAlphanumeric(char c) {
  130. if(c >= '0' && c <= '9') {
  131. return (c - '0');
  132. }
  133. if(c >= 'A' && c <= 'Z') {
  134. return (c - 'A' + 10);
  135. }
  136. switch(c) {
  137. case ' ':
  138. return 36;
  139. case '$':
  140. return 37;
  141. case '%':
  142. return 38;
  143. case '*':
  144. return 39;
  145. case '+':
  146. return 40;
  147. case '-':
  148. return 41;
  149. case '.':
  150. return 42;
  151. case '/':
  152. return 43;
  153. case ':':
  154. return 44;
  155. }
  156. return -1;
  157. }
  158. /* static bool isAlphanumeric(const char *text, uint16_t length) { */
  159. /* while (length != 0) { */
  160. /* if (getAlphanumeric(text[--length]) == -1) { return false; } */
  161. /* } */
  162. /* return true; */
  163. /* } */
  164. /* static bool isNumeric(const char *text, uint16_t length) { */
  165. /* while (length != 0) { */
  166. /* char c = text[--length]; */
  167. /* if (c < '0' || c > '9') { return false; } */
  168. /* } */
  169. /* return true; */
  170. /* } */
  171. // We store the following tightly packed (less 8) in modeInfo
  172. // <=9 <=26 <= 40
  173. // NUMERIC ( 10, 12, 14);
  174. // ALPHANUMERIC ( 9, 11, 13);
  175. // BYTE ( 8, 16, 16);
  176. static char getModeBits(uint8_t version, uint8_t mode) {
  177. // Note: We use 15 instead of 16; since 15 doesn't exist and we cannot store 16 (8 + 8) in 3 bits
  178. // hex(int("".join(reversed([('00' + bin(x - 8)[2:])[-3:] for x in [10, 9, 8, 12, 11, 15, 14, 13, 15]])), 2))
  179. unsigned int modeInfo = 0x7bbb80a;
  180. #if LOCK_VERSION == 0 || LOCK_VERSION > 9
  181. if(version > 9) {
  182. modeInfo >>= 9;
  183. }
  184. #endif
  185. #if LOCK_VERSION == 0 || LOCK_VERSION > 26
  186. if(version > 26) {
  187. modeInfo >>= 9;
  188. }
  189. #endif
  190. char result = 8 + ((modeInfo >> (3 * mode)) & 0x07);
  191. if(result == 15) {
  192. result = 16;
  193. }
  194. return result;
  195. }
  196. typedef struct BitBucket {
  197. uint32_t bitOffsetOrWidth;
  198. uint16_t capacityBytes;
  199. uint8_t* data;
  200. } BitBucket;
  201. /*
  202. void bb_dump(BitBucket *bitBuffer) {
  203. printf("Buffer: ");
  204. for (uint32_t i = 0; i < bitBuffer->capacityBytes; i++) {
  205. printf("%02x", bitBuffer->data[i]);
  206. if ((i % 4) == 3) { printf(" "); }
  207. }
  208. printf("\n");
  209. }
  210. */
  211. static uint16_t bb_getGridSizeBytes(uint8_t size) {
  212. return (((size * size) + 7) / 8);
  213. }
  214. static uint16_t bb_getBufferSizeBytes(uint32_t bits) {
  215. return ((bits + 7) / 8);
  216. }
  217. static void bb_initBuffer(BitBucket* bitBuffer, uint8_t* data, int32_t capacityBytes) {
  218. bitBuffer->bitOffsetOrWidth = 0;
  219. bitBuffer->capacityBytes = capacityBytes;
  220. bitBuffer->data = data;
  221. memset(data, 0, bitBuffer->capacityBytes);
  222. }
  223. static void bb_initGrid(BitBucket* bitGrid, uint8_t* data, uint8_t size) {
  224. bitGrid->bitOffsetOrWidth = size;
  225. bitGrid->capacityBytes = bb_getGridSizeBytes(size);
  226. bitGrid->data = data;
  227. memset(data, 0, bitGrid->capacityBytes);
  228. }
  229. static void bb_appendBits(BitBucket* bitBuffer, uint32_t val, uint8_t length) {
  230. uint32_t offset = bitBuffer->bitOffsetOrWidth;
  231. for(int8_t i = length - 1; i >= 0; i--, offset++) {
  232. bitBuffer->data[offset >> 3] |= ((val >> i) & 1) << (7 - (offset & 7));
  233. }
  234. bitBuffer->bitOffsetOrWidth = offset;
  235. }
  236. /*
  237. void bb_setBits(BitBucket *bitBuffer, uint32_t val, int offset, uint8_t length) {
  238. for (int8_t i = length - 1; i >= 0; i--, offset++) {
  239. bitBuffer->data[offset >> 3] |= ((val >> i) & 1) << (7 - (offset & 7));
  240. }
  241. }
  242. */
  243. static void bb_setBit(BitBucket* bitGrid, uint8_t x, uint8_t y, bool on) {
  244. uint32_t offset = y * bitGrid->bitOffsetOrWidth + x;
  245. uint8_t mask = 1 << (7 - (offset & 0x07));
  246. if(on) {
  247. bitGrid->data[offset >> 3] |= mask;
  248. } else {
  249. bitGrid->data[offset >> 3] &= ~mask;
  250. }
  251. }
  252. static void bb_invertBit(BitBucket* bitGrid, uint8_t x, uint8_t y, bool invert) {
  253. uint32_t offset = y * bitGrid->bitOffsetOrWidth + x;
  254. uint8_t mask = 1 << (7 - (offset & 0x07));
  255. bool on = ((bitGrid->data[offset >> 3] & (1 << (7 - (offset & 0x07)))) != 0);
  256. if(on ^ invert) {
  257. bitGrid->data[offset >> 3] |= mask;
  258. } else {
  259. bitGrid->data[offset >> 3] &= ~mask;
  260. }
  261. }
  262. static bool bb_getBit(BitBucket* bitGrid, uint8_t x, uint8_t y) {
  263. uint32_t offset = y * bitGrid->bitOffsetOrWidth + x;
  264. return (bitGrid->data[offset >> 3] & (1 << (7 - (offset & 0x07)))) != 0;
  265. }
  266. // XORs the data modules in this QR Code with the given mask pattern. Due to XOR's mathematical
  267. // properties, calling applyMask(m) twice with the same value is equivalent to no change at all.
  268. // This means it is possible to apply a mask, undo it, and try another mask. Note that a final
  269. // well-formed QR Code symbol needs exactly one mask applied (not zero, not two, etc.).
  270. static void applyMask(BitBucket* modules, BitBucket* isFunction, uint8_t mask) {
  271. uint8_t size = modules->bitOffsetOrWidth;
  272. for(uint8_t y = 0; y < size; y++) {
  273. for(uint8_t x = 0; x < size; x++) {
  274. if(bb_getBit(isFunction, x, y)) {
  275. continue;
  276. }
  277. bool invert = 0;
  278. switch(mask) {
  279. case 0:
  280. invert = (x + y) % 2 == 0;
  281. break;
  282. case 1:
  283. invert = y % 2 == 0;
  284. break;
  285. case 2:
  286. invert = x % 3 == 0;
  287. break;
  288. case 3:
  289. invert = (x + y) % 3 == 0;
  290. break;
  291. case 4:
  292. invert = (x / 3 + y / 2) % 2 == 0;
  293. break;
  294. case 5:
  295. invert = x * y % 2 + x * y % 3 == 0;
  296. break;
  297. case 6:
  298. invert = (x * y % 2 + x * y % 3) % 2 == 0;
  299. break;
  300. case 7:
  301. invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
  302. break;
  303. }
  304. bb_invertBit(modules, x, y, invert);
  305. }
  306. }
  307. }
  308. static void
  309. setFunctionModule(BitBucket* modules, BitBucket* isFunction, uint8_t x, uint8_t y, bool on) {
  310. bb_setBit(modules, x, y, on);
  311. bb_setBit(isFunction, x, y, true);
  312. }
  313. // Draws a 9*9 finder pattern including the border separator, with the center module at (x, y).
  314. static void drawFinderPattern(BitBucket* modules, BitBucket* isFunction, uint8_t x, uint8_t y) {
  315. uint8_t size = modules->bitOffsetOrWidth;
  316. for(int8_t i = -4; i <= 4; i++) {
  317. for(int8_t j = -4; j <= 4; j++) {
  318. uint8_t dist = max(abs(i), abs(j)); // Chebyshev/infinity norm
  319. int16_t xx = x + j, yy = y + i;
  320. if(0 <= xx && xx < size && 0 <= yy && yy < size) {
  321. setFunctionModule(modules, isFunction, xx, yy, dist != 2 && dist != 4);
  322. }
  323. }
  324. }
  325. }
  326. // Draws a 5*5 alignment pattern, with the center module at (x, y).
  327. static void drawAlignmentPattern(BitBucket* modules, BitBucket* isFunction, uint8_t x, uint8_t y) {
  328. for(int8_t i = -2; i <= 2; i++) {
  329. for(int8_t j = -2; j <= 2; j++) {
  330. setFunctionModule(modules, isFunction, x + j, y + i, max(abs(i), abs(j)) != 1);
  331. }
  332. }
  333. }
  334. // Draws two copies of the format bits (with its own error correction code)
  335. // based on the given mask and this object's error correction level field.
  336. static void drawFormatBits(BitBucket* modules, BitBucket* isFunction, uint8_t ecc, uint8_t mask) {
  337. uint8_t size = modules->bitOffsetOrWidth;
  338. // Calculate error correction code and pack bits
  339. uint32_t data = ecc << 3 | mask; // errCorrLvl is uint2, mask is uint3
  340. uint32_t rem = data;
  341. for(int i = 0; i < 10; i++) {
  342. rem = (rem << 1) ^ ((rem >> 9) * 0x537);
  343. }
  344. data = data << 10 | rem;
  345. data ^= 0x5412; // uint15
  346. // Draw first copy
  347. for(uint8_t i = 0; i <= 5; i++) {
  348. setFunctionModule(modules, isFunction, 8, i, ((data >> i) & 1) != 0);
  349. }
  350. setFunctionModule(modules, isFunction, 8, 7, ((data >> 6) & 1) != 0);
  351. setFunctionModule(modules, isFunction, 8, 8, ((data >> 7) & 1) != 0);
  352. setFunctionModule(modules, isFunction, 7, 8, ((data >> 8) & 1) != 0);
  353. for(int8_t i = 9; i < 15; i++) {
  354. setFunctionModule(modules, isFunction, 14 - i, 8, ((data >> i) & 1) != 0);
  355. }
  356. // Draw second copy
  357. for(int8_t i = 0; i <= 7; i++) {
  358. setFunctionModule(modules, isFunction, size - 1 - i, 8, ((data >> i) & 1) != 0);
  359. }
  360. for(int8_t i = 8; i < 15; i++) {
  361. setFunctionModule(modules, isFunction, 8, size - 15 + i, ((data >> i) & 1) != 0);
  362. }
  363. setFunctionModule(modules, isFunction, 8, size - 8, true);
  364. }
  365. // Draws two copies of the version bits (with its own error correction code),
  366. // based on this object's version field (which only has an effect for 7 <= version <= 40).
  367. static void drawVersion(BitBucket* modules, BitBucket* isFunction, uint8_t version) {
  368. int8_t size = modules->bitOffsetOrWidth;
  369. #if LOCK_VERSION != 0 && LOCK_VERSION < 7
  370. return;
  371. #else
  372. if(version < 7) {
  373. return;
  374. }
  375. // Calculate error correction code and pack bits
  376. uint32_t rem = version; // version is uint6, in the range [7, 40]
  377. for(uint8_t i = 0; i < 12; i++) {
  378. rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
  379. }
  380. uint32_t data = version << 12 | rem; // uint18
  381. // Draw two copies
  382. for(uint8_t i = 0; i < 18; i++) {
  383. bool bit = ((data >> i) & 1) != 0;
  384. uint8_t a = size - 11 + i % 3, b = i / 3;
  385. setFunctionModule(modules, isFunction, a, b, bit);
  386. setFunctionModule(modules, isFunction, b, a, bit);
  387. }
  388. #endif
  389. }
  390. static void
  391. drawFunctionPatterns(BitBucket* modules, BitBucket* isFunction, uint8_t version, uint8_t ecc) {
  392. uint8_t size = modules->bitOffsetOrWidth;
  393. // Draw the horizontal and vertical timing patterns
  394. for(uint8_t i = 0; i < size; i++) {
  395. setFunctionModule(modules, isFunction, 6, i, i % 2 == 0);
  396. setFunctionModule(modules, isFunction, i, 6, i % 2 == 0);
  397. }
  398. // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
  399. drawFinderPattern(modules, isFunction, 3, 3);
  400. drawFinderPattern(modules, isFunction, size - 4, 3);
  401. drawFinderPattern(modules, isFunction, 3, size - 4);
  402. #if LOCK_VERSION == 0 || LOCK_VERSION > 1
  403. if(version > 1) {
  404. // Draw the numerous alignment patterns
  405. uint8_t alignCount = version / 7 + 2;
  406. uint8_t step;
  407. if(version != 32) {
  408. step = (version * 4 + alignCount * 2 + 1) / (2 * alignCount - 2) *
  409. 2; // ceil((size - 13) / (2*numAlign - 2)) * 2
  410. } else { // C-C-C-Combo breaker!
  411. step = 26;
  412. }
  413. uint8_t alignPositionIndex = alignCount - 1;
  414. uint8_t alignPosition[alignCount];
  415. alignPosition[0] = 6;
  416. uint8_t size = version * 4 + 17;
  417. for(uint8_t i = 0, pos = size - 7; i < alignCount - 1; i++, pos -= step) {
  418. alignPosition[alignPositionIndex--] = pos;
  419. }
  420. for(uint8_t i = 0; i < alignCount; i++) {
  421. for(uint8_t j = 0; j < alignCount; j++) {
  422. if((i == 0 && j == 0) || (i == 0 && j == alignCount - 1) ||
  423. (i == alignCount - 1 && j == 0)) {
  424. continue; // Skip the three finder corners
  425. } else {
  426. drawAlignmentPattern(modules, isFunction, alignPosition[i], alignPosition[j]);
  427. }
  428. }
  429. }
  430. }
  431. #endif
  432. // Draw configuration data
  433. drawFormatBits(
  434. modules, isFunction, ecc, 0); // Dummy mask value; overwritten later in the constructor
  435. drawVersion(modules, isFunction, version);
  436. }
  437. // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
  438. // data area of this QR Code symbol. Function modules need to be marked off before this is called.
  439. static void drawCodewords(BitBucket* modules, BitBucket* isFunction, BitBucket* codewords) {
  440. uint32_t bitLength = codewords->bitOffsetOrWidth;
  441. uint8_t* data = codewords->data;
  442. uint8_t size = modules->bitOffsetOrWidth;
  443. // Bit index into the data
  444. uint32_t i = 0;
  445. // Do the funny zigzag scan
  446. for(int16_t right = size - 1; right >= 1;
  447. right -= 2) { // Index of right column in each column pair
  448. if(right == 6) {
  449. right = 5;
  450. }
  451. for(uint8_t vert = 0; vert < size; vert++) { // Vertical counter
  452. for(int j = 0; j < 2; j++) {
  453. uint8_t x = right - j; // Actual x coordinate
  454. bool upwards = ((right & 2) == 0) ^ (x < 6);
  455. uint8_t y = upwards ? size - 1 - vert : vert; // Actual y coordinate
  456. if(!bb_getBit(isFunction, x, y) && i < bitLength) {
  457. bb_setBit(modules, x, y, ((data[i >> 3] >> (7 - (i & 7))) & 1) != 0);
  458. i++;
  459. }
  460. // If there are any remainder bits (0 to 7), they are already
  461. // set to 0/false/white when the grid of modules was initialized
  462. }
  463. }
  464. }
  465. }
  466. #define PENALTY_N1 3
  467. #define PENALTY_N2 3
  468. #define PENALTY_N3 40
  469. #define PENALTY_N4 10
  470. // Calculates and returns the penalty score based on state of this QR Code's current modules.
  471. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
  472. // @TODO: This can be optimized by working with the bytes instead of bits.
  473. static uint32_t getPenaltyScore(BitBucket* modules) {
  474. uint32_t result = 0;
  475. uint8_t size = modules->bitOffsetOrWidth;
  476. // Adjacent modules in row having same color
  477. for(uint8_t y = 0; y < size; y++) {
  478. bool colorX = bb_getBit(modules, 0, y);
  479. for(uint8_t x = 1, runX = 1; x < size; x++) {
  480. bool cx = bb_getBit(modules, x, y);
  481. if(cx != colorX) {
  482. colorX = cx;
  483. runX = 1;
  484. } else {
  485. runX++;
  486. if(runX == 5) {
  487. result += PENALTY_N1;
  488. } else if(runX > 5) {
  489. result++;
  490. }
  491. }
  492. }
  493. }
  494. // Adjacent modules in column having same color
  495. for(uint8_t x = 0; x < size; x++) {
  496. bool colorY = bb_getBit(modules, x, 0);
  497. for(uint8_t y = 1, runY = 1; y < size; y++) {
  498. bool cy = bb_getBit(modules, x, y);
  499. if(cy != colorY) {
  500. colorY = cy;
  501. runY = 1;
  502. } else {
  503. runY++;
  504. if(runY == 5) {
  505. result += PENALTY_N1;
  506. } else if(runY > 5) {
  507. result++;
  508. }
  509. }
  510. }
  511. }
  512. uint16_t black = 0;
  513. for(uint8_t y = 0; y < size; y++) {
  514. uint16_t bitsRow = 0, bitsCol = 0;
  515. for(uint8_t x = 0; x < size; x++) {
  516. bool color = bb_getBit(modules, x, y);
  517. // 2*2 blocks of modules having same color
  518. if(x > 0 && y > 0) {
  519. bool colorUL = bb_getBit(modules, x - 1, y - 1);
  520. bool colorUR = bb_getBit(modules, x, y - 1);
  521. bool colorL = bb_getBit(modules, x - 1, y);
  522. if(color == colorUL && color == colorUR && color == colorL) {
  523. result += PENALTY_N2;
  524. }
  525. }
  526. // Finder-like pattern in rows and columns
  527. bitsRow = ((bitsRow << 1) & 0x7FF) | color;
  528. bitsCol = ((bitsCol << 1) & 0x7FF) | bb_getBit(modules, y, x);
  529. // Needs 11 bits accumulated
  530. if(x >= 10) {
  531. if(bitsRow == 0x05D || bitsRow == 0x5D0) {
  532. result += PENALTY_N3;
  533. }
  534. if(bitsCol == 0x05D || bitsCol == 0x5D0) {
  535. result += PENALTY_N3;
  536. }
  537. }
  538. // Balance of black and white modules
  539. if(color) {
  540. black++;
  541. }
  542. }
  543. }
  544. // Find smallest k such that (45-5k)% <= dark/total <= (55+5k)%
  545. uint16_t total = size * size;
  546. for(uint16_t k = 0; black * 20 < (9 - k) * total || black * 20 > (11 + k) * total; k++) {
  547. result += PENALTY_N4;
  548. }
  549. return result;
  550. }
  551. static uint8_t rs_multiply(uint8_t x, uint8_t y) {
  552. // Russian peasant multiplication
  553. // See: https://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication
  554. uint16_t z = 0;
  555. for(int8_t i = 7; i >= 0; i--) {
  556. z = (z << 1) ^ ((z >> 7) * 0x11D);
  557. z ^= ((y >> i) & 1) * x;
  558. }
  559. return z;
  560. }
  561. static void rs_init(uint8_t degree, uint8_t* coeff) {
  562. memset(coeff, 0, degree);
  563. coeff[degree - 1] = 1;
  564. // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
  565. // drop the highest term, and store the rest of the coefficients in order of descending powers.
  566. // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
  567. uint16_t root = 1;
  568. for(uint8_t i = 0; i < degree; i++) {
  569. // Multiply the current product by (x - r^i)
  570. for(uint8_t j = 0; j < degree; j++) {
  571. coeff[j] = rs_multiply(coeff[j], root);
  572. if(j + 1 < degree) {
  573. coeff[j] ^= coeff[j + 1];
  574. }
  575. }
  576. root = (root << 1) ^ ((root >> 7) * 0x11D); // Multiply by 0x02 mod GF(2^8/0x11D)
  577. }
  578. }
  579. static void rs_getRemainder(
  580. uint8_t degree,
  581. uint8_t* coeff,
  582. uint8_t* data,
  583. uint8_t length,
  584. uint8_t* result,
  585. uint8_t stride) {
  586. // Compute the remainder by performing polynomial division
  587. //for (uint8_t i = 0; i < degree; i++) { result[] = 0; }
  588. //memset(result, 0, degree);
  589. for(uint8_t i = 0; i < length; i++) {
  590. uint8_t factor = data[i] ^ result[0];
  591. for(uint8_t j = 1; j < degree; j++) {
  592. result[(j - 1) * stride] = result[j * stride];
  593. }
  594. result[(degree - 1) * stride] = 0;
  595. for(uint8_t j = 0; j < degree; j++) {
  596. result[j * stride] ^= rs_multiply(coeff[j], factor);
  597. }
  598. }
  599. }
  600. static int8_t encodeDataCodewords(
  601. BitBucket* dataCodewords,
  602. const uint8_t* text,
  603. uint16_t length,
  604. int8_t mode,
  605. uint8_t version) {
  606. if(mode == MODE_NUMERIC) {
  607. bb_appendBits(dataCodewords, 1 << MODE_NUMERIC, 4);
  608. bb_appendBits(dataCodewords, length, getModeBits(version, MODE_NUMERIC));
  609. uint16_t accumData = 0;
  610. uint8_t accumCount = 0;
  611. for(uint16_t i = 0; i < length; i++) {
  612. accumData = accumData * 10 + ((char)(text[i]) - '0');
  613. accumCount++;
  614. if(accumCount == 3) {
  615. bb_appendBits(dataCodewords, accumData, 10);
  616. accumData = 0;
  617. accumCount = 0;
  618. }
  619. }
  620. // 1 or 2 digits remaining
  621. if(accumCount > 0) {
  622. bb_appendBits(dataCodewords, accumData, accumCount * 3 + 1);
  623. }
  624. } else if(mode == MODE_ALPHANUMERIC) {
  625. bb_appendBits(dataCodewords, 1 << MODE_ALPHANUMERIC, 4);
  626. bb_appendBits(dataCodewords, length, getModeBits(version, MODE_ALPHANUMERIC));
  627. uint16_t accumData = 0;
  628. uint8_t accumCount = 0;
  629. for(uint16_t i = 0; i < length; i++) {
  630. accumData = accumData * 45 + getAlphanumeric((char)(text[i]));
  631. accumCount++;
  632. if(accumCount == 2) {
  633. bb_appendBits(dataCodewords, accumData, 11);
  634. accumData = 0;
  635. accumCount = 0;
  636. }
  637. }
  638. // 1 character remaining
  639. if(accumCount > 0) {
  640. bb_appendBits(dataCodewords, accumData, 6);
  641. }
  642. } else {
  643. bb_appendBits(dataCodewords, 1 << MODE_BYTE, 4);
  644. bb_appendBits(dataCodewords, length, getModeBits(version, MODE_BYTE));
  645. for(uint16_t i = 0; i < length; i++) {
  646. bb_appendBits(dataCodewords, (char)(text[i]), 8);
  647. }
  648. }
  649. //bb_setBits(dataCodewords, length, 4, getModeBits(version, mode));
  650. return mode;
  651. }
  652. static void performErrorCorrection(uint8_t version, uint8_t ecc, BitBucket* data) {
  653. // See: http://www.thonky.com/qr-code-tutorial/structure-final-message
  654. #if LOCK_VERSION == 0
  655. uint8_t numBlocks = NUM_ERROR_CORRECTION_BLOCKS[ecc][version - 1];
  656. uint16_t totalEcc = NUM_ERROR_CORRECTION_CODEWORDS[ecc][version - 1];
  657. uint16_t moduleCount = NUM_RAW_DATA_MODULES[version - 1];
  658. #else
  659. uint8_t numBlocks = NUM_ERROR_CORRECTION_BLOCKS[ecc];
  660. uint16_t totalEcc = NUM_ERROR_CORRECTION_CODEWORDS[ecc];
  661. uint16_t moduleCount = NUM_RAW_DATA_MODULES;
  662. #endif
  663. uint8_t blockEccLen = totalEcc / numBlocks;
  664. uint8_t numShortBlocks = numBlocks - moduleCount / 8 % numBlocks;
  665. uint8_t shortBlockLen = moduleCount / 8 / numBlocks;
  666. uint8_t shortDataBlockLen = shortBlockLen - blockEccLen;
  667. uint8_t result[data->capacityBytes];
  668. memset(result, 0, sizeof(result));
  669. uint8_t coeff[blockEccLen];
  670. rs_init(blockEccLen, coeff);
  671. uint16_t offset = 0;
  672. uint8_t* dataBytes = data->data;
  673. // Interleave all short blocks
  674. for(uint8_t i = 0; i < shortDataBlockLen; i++) {
  675. uint16_t index = i;
  676. uint8_t stride = shortDataBlockLen;
  677. for(uint8_t blockNum = 0; blockNum < numBlocks; blockNum++) {
  678. result[offset++] = dataBytes[index];
  679. #if LOCK_VERSION == 0 || LOCK_VERSION >= 5
  680. if(blockNum == numShortBlocks) {
  681. stride++;
  682. }
  683. #endif
  684. index += stride;
  685. }
  686. }
  687. // Version less than 5 only have short blocks
  688. #if LOCK_VERSION == 0 || LOCK_VERSION >= 5
  689. {
  690. // Interleave long blocks
  691. uint16_t index = shortDataBlockLen * (numShortBlocks + 1);
  692. uint8_t stride = shortDataBlockLen;
  693. for(uint8_t blockNum = 0; blockNum < numBlocks - numShortBlocks; blockNum++) {
  694. result[offset++] = dataBytes[index];
  695. if(blockNum == 0) {
  696. stride++;
  697. }
  698. index += stride;
  699. }
  700. }
  701. #endif
  702. // Add all ecc blocks, interleaved
  703. uint8_t blockSize = shortDataBlockLen;
  704. for(uint8_t blockNum = 0; blockNum < numBlocks; blockNum++) {
  705. #if LOCK_VERSION == 0 || LOCK_VERSION >= 5
  706. if(blockNum == numShortBlocks) {
  707. blockSize++;
  708. }
  709. #endif
  710. rs_getRemainder(
  711. blockEccLen, coeff, dataBytes, blockSize, &result[offset + blockNum], numBlocks);
  712. dataBytes += blockSize;
  713. }
  714. memcpy(data->data, result, data->capacityBytes);
  715. data->bitOffsetOrWidth = moduleCount;
  716. }
  717. // We store the Format bits tightly packed into a single byte (each of the 4 modes is 2 bits)
  718. // The format bits can be determined by ECC_FORMAT_BITS >> (2 * ecc)
  719. static const uint8_t ECC_FORMAT_BITS = (0x02 << 6) | (0x03 << 4) | (0x00 << 2) | (0x01 << 0);
  720. uint16_t qrcode_getBufferSize(uint8_t version) {
  721. return bb_getGridSizeBytes(4 * version + 17);
  722. }
  723. // @TODO: Return error if data is too big.
  724. int8_t qrcode_initBytes(
  725. QRCode* qrcode,
  726. uint8_t* modules,
  727. int8_t mode,
  728. uint8_t version,
  729. uint8_t ecc,
  730. uint8_t* data,
  731. uint16_t length) {
  732. uint8_t size = version * 4 + 17;
  733. qrcode->version = version;
  734. qrcode->size = size;
  735. qrcode->ecc = ecc;
  736. qrcode->modules = modules;
  737. uint8_t eccFormatBits = (ECC_FORMAT_BITS >> (2 * ecc)) & 0x03;
  738. #if LOCK_VERSION == 0
  739. uint16_t moduleCount = NUM_RAW_DATA_MODULES[version - 1];
  740. uint16_t dataCapacity =
  741. moduleCount / 8 - NUM_ERROR_CORRECTION_CODEWORDS[eccFormatBits][version - 1];
  742. #else
  743. version = LOCK_VERSION;
  744. uint16_t moduleCount = NUM_RAW_DATA_MODULES;
  745. uint16_t dataCapacity = moduleCount / 8 - NUM_ERROR_CORRECTION_CODEWORDS[eccFormatBits];
  746. #endif
  747. struct BitBucket codewords;
  748. uint8_t codewordBytes[bb_getBufferSizeBytes(moduleCount)];
  749. bb_initBuffer(&codewords, codewordBytes, (int32_t)sizeof(codewordBytes));
  750. // Place the data code words into the buffer
  751. mode = encodeDataCodewords(&codewords, data, length, mode, version);
  752. if(mode < 0) {
  753. return -1;
  754. }
  755. qrcode->mode = mode;
  756. // Add terminator and pad up to a byte if applicable
  757. uint32_t padding = (dataCapacity * 8) - codewords.bitOffsetOrWidth;
  758. if(padding > 4) {
  759. padding = 4;
  760. }
  761. bb_appendBits(&codewords, 0, padding);
  762. bb_appendBits(&codewords, 0, (8 - codewords.bitOffsetOrWidth % 8) % 8);
  763. // Pad with alternate bytes until data capacity is reached
  764. for(uint8_t padByte = 0xEC; codewords.bitOffsetOrWidth < (dataCapacity * 8);
  765. padByte ^= 0xEC ^ 0x11) {
  766. bb_appendBits(&codewords, padByte, 8);
  767. }
  768. BitBucket modulesGrid;
  769. bb_initGrid(&modulesGrid, modules, size);
  770. BitBucket isFunctionGrid;
  771. uint8_t isFunctionGridBytes[bb_getGridSizeBytes(size)];
  772. bb_initGrid(&isFunctionGrid, isFunctionGridBytes, size);
  773. // Draw function patterns, draw all codewords, do masking
  774. drawFunctionPatterns(&modulesGrid, &isFunctionGrid, version, eccFormatBits);
  775. performErrorCorrection(version, eccFormatBits, &codewords);
  776. drawCodewords(&modulesGrid, &isFunctionGrid, &codewords);
  777. // Find the best (lowest penalty) mask
  778. uint8_t mask = 0;
  779. int32_t minPenalty = INT32_MAX;
  780. for(uint8_t i = 0; i < 8; i++) {
  781. drawFormatBits(&modulesGrid, &isFunctionGrid, eccFormatBits, i);
  782. applyMask(&modulesGrid, &isFunctionGrid, i);
  783. int penalty = getPenaltyScore(&modulesGrid);
  784. if(penalty < minPenalty) {
  785. mask = i;
  786. minPenalty = penalty;
  787. }
  788. applyMask(&modulesGrid, &isFunctionGrid, i); // Undoes the mask due to XOR
  789. }
  790. qrcode->mask = mask;
  791. // Overwrite old format bits
  792. drawFormatBits(&modulesGrid, &isFunctionGrid, eccFormatBits, mask);
  793. // Apply the final choice of mask
  794. applyMask(&modulesGrid, &isFunctionGrid, mask);
  795. return 0;
  796. }
  797. /* int8_t qrcode_initText(QRCode *qrcode, uint8_t *modules, uint8_t version, uint8_t ecc, const char *data) { */
  798. /* return qrcode_initBytes(qrcode, modules, version, ecc, (uint8_t*)data, strlen(data)); */
  799. /* } */
  800. bool qrcode_getModule(QRCode* qrcode, uint8_t x, uint8_t y) {
  801. if(x >= qrcode->size || y >= qrcode->size) {
  802. return false;
  803. }
  804. uint32_t offset = y * qrcode->size + x;
  805. return (qrcode->modules[offset >> 3] & (1 << (7 - (offset & 0x07)))) != 0;
  806. }
  807. /*
  808. uint8_t qrcode_getHexLength(QRCode *qrcode) {
  809. return ((qrcode->size * qrcode->size) + 7) / 4;
  810. }
  811. void qrcode_getHex(QRCode *qrcode, char *result) {
  812. }
  813. */