qrcode.c 31 KB

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