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