qrcode.c 31 KB

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