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