qrcode.c 30 KB

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