1 /*
2  * QR Code generator library (C)
3  *
4  * Copyright (c) Project Nayuki. (MIT License)
5  * https://www.nayuki.io/page/qr-code-generator-library
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  * - The above copyright notice and this permission notice shall be included in
14  *   all copies or substantial portions of the Software.
15  * - The Software is provided "as is", without warranty of any kind, express or
16  *   implied, including but not limited to the warranties of merchantability,
17  *   fitness for a particular purpose and noninfringement. In no event shall the
18  *   authors or copyright holders be liable for any claim, damages or other
19  *   liability, whether in an action of contract, tort or otherwise, arising from,
20  *   out of or in connection with the Software or the use or other dealings in the
21  *   Software.
22  */
23 
24 #include "qrcodegen.h"
25 #include "../../misc/lv_assert.h"
26 
27 #if LV_USE_QRCODE
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <string.h>
31 
32 #ifndef QRCODEGEN_TEST
33     #define testable static  // Keep functions private
34 #else
35     #define testable  // Expose private functions
36 #endif
37 
38 
39 /*---- Forward declarations for private functions ----*/
40 
41 // Regarding all public and private functions defined in this source file:
42 // - They require all pointer/array arguments to be not null unless the array length is zero.
43 // - They only read input scalar/array arguments, write to output pointer/array
44 //   arguments, and return scalar values; they are "pure" functions.
45 // - They don't read mutable global variables or write to any global variables.
46 // - They don't perform I/O, read the clock, print to console, etc.
47 // - They allocate a small and constant amount of stack memory.
48 // - They don't allocate or free any memory on the heap.
49 // - They don't recurse or mutually recurse. All the code
50 //   could be inlined into the top-level public functions.
51 // - They run in at most quadratic time with respect to input arguments.
52 //   Most functions run in linear time, and some in constant time.
53 //   There are no unbounded loops or non-obvious termination conditions.
54 // - They are completely thread-safe if the caller does not give the
55 //   same writable buffer to concurrent calls to these functions.
56 
57 testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int * bitLen);
58 
59 testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]);
60 testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl);
61 testable int getNumRawDataModules(int ver);
62 
63 testable void calcReedSolomonGenerator(int degree, uint8_t result[]);
64 testable void calcReedSolomonRemainder(const uint8_t data[], int dataLen,
65                                        const uint8_t generator[], int degree, uint8_t result[]);
66 testable uint8_t finiteFieldMultiply(uint8_t x, uint8_t y);
67 
68 testable void initializeFunctionModules(int version, uint8_t qrcode[]);
69 static void drawWhiteFunctionModules(uint8_t qrcode[], int version);
70 static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]);
71 testable int getAlignmentPatternPositions(int version, uint8_t result[7]);
72 static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]);
73 
74 static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]);
75 static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask);
76 static long getPenaltyScore(const uint8_t qrcode[]);
77 static void addRunToHistory(unsigned char run, unsigned char history[7]);
78 static bool hasFinderLikePattern(const unsigned char runHistory[7]);
79 
80 testable bool getModule(const uint8_t qrcode[], int x, int y);
81 testable void setModule(uint8_t qrcode[], int x, int y, bool isBlack);
82 testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isBlack);
83 static bool getBit(int x, int i);
84 
85 testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars);
86 testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version);
87 static int numCharCountBits(enum qrcodegen_Mode mode, int version);
88 
89 
90 
91 /*---- Private tables of constants ----*/
92 
93 // The set of all legal characters in alphanumeric mode, where each character
94 // value maps to the index in the string. For checking text and encoding segments.
95 static const char * ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
96 
97 // For generating error correction codes.
98 testable const int8_t ECC_CODEWORDS_PER_BLOCK[4][41] = {
99     // Version: (note that index 0 is for padding, and is set to an illegal value)
100     //0,  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
101     {-1,  7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30},  // Low
102     {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28},  // Medium
103     {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30},  // Quartile
104     {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30},  // High
105 };
106 
107 #define qrcodegen_REED_SOLOMON_DEGREE_MAX 30  // Based on the table above
108 
109 // For generating error correction codes.
110 testable const int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
111     // Version: (note that index 0 is for padding, and is set to an illegal value)
112     //0, 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
113     {-1, 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
114     {-1, 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
115     {-1, 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
116     {-1, 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
117 };
118 
119 // For automatic mask pattern selection.
120 static const int PENALTY_N1 =  3;
121 static const int PENALTY_N2 =  3;
122 static const int PENALTY_N3 = 40;
123 static const int PENALTY_N4 = 10;
124 
125 
126 
127 /*---- High-level QR Code encoding functions ----*/
128 
129 // Public function - see documentation comment in header file.
qrcodegen_encodeText(const char * text,uint8_t tempBuffer[],uint8_t qrcode[],enum qrcodegen_Ecc ecl,int minVersion,int maxVersion,enum qrcodegen_Mask mask,bool boostEcl)130 bool qrcodegen_encodeText(const char * text, uint8_t tempBuffer[], uint8_t qrcode[],
131                           enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl)
132 {
133 
134     size_t textLen = strlen(text);
135     if(textLen == 0)
136         return qrcodegen_encodeSegmentsAdvanced(NULL, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode);
137     size_t bufLen = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion);
138 
139     struct qrcodegen_Segment seg;
140     if(qrcodegen_isNumeric(text)) {
141         if(qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen)
142             goto fail;
143         seg = qrcodegen_makeNumeric(text, tempBuffer);
144     }
145     else if(qrcodegen_isAlphanumeric(text)) {
146         if(qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen)
147             goto fail;
148         seg = qrcodegen_makeAlphanumeric(text, tempBuffer);
149     }
150     else {
151         if(textLen > bufLen)
152             goto fail;
153         for(size_t i = 0; i < textLen; i++)
154             tempBuffer[i] = (uint8_t)text[i];
155         seg.mode = qrcodegen_Mode_BYTE;
156         seg.bitLength = calcSegmentBitLength(seg.mode, textLen);
157         if(seg.bitLength == -1)
158             goto fail;
159         seg.numChars = (int)textLen;
160         seg.data = tempBuffer;
161     }
162     return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode);
163 
164 fail:
165     qrcode[0] = 0;  // Set size to invalid value for safety
166     return false;
167 }
168 
169 
170 // Public function - see documentation comment in header file.
qrcodegen_encodeBinary(uint8_t dataAndTemp[],size_t dataLen,uint8_t qrcode[],enum qrcodegen_Ecc ecl,int minVersion,int maxVersion,enum qrcodegen_Mask mask,bool boostEcl)171 bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[],
172                             enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl)
173 {
174 
175     struct qrcodegen_Segment seg;
176     seg.mode = qrcodegen_Mode_BYTE;
177     seg.bitLength = calcSegmentBitLength(seg.mode, dataLen);
178     if(seg.bitLength == -1) {
179         qrcode[0] = 0;  // Set size to invalid value for safety
180         return false;
181     }
182     seg.numChars = (int)dataLen;
183     seg.data = dataAndTemp;
184     return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode);
185 }
186 
187 
188 // Appends the given number of low-order bits of the given value to the given byte-based
189 // bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits.
appendBitsToBuffer(unsigned int val,int numBits,uint8_t buffer[],int * bitLen)190 testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int * bitLen)
191 {
192     LV_ASSERT(0 <= numBits && numBits <= 16 && (unsigned long)val >> numBits == 0);
193     for(int i = numBits - 1; i >= 0; i--, (*bitLen)++)
194         buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7));
195 }
196 
197 
198 
199 /*---- Low-level QR Code encoding functions ----*/
200 
201 // Public function - see documentation comment in header file.
qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[],size_t len,enum qrcodegen_Ecc ecl,uint8_t tempBuffer[],uint8_t qrcode[])202 bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len,
203                               enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[])
204 {
205     return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl,
206                                             qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, -1, true, tempBuffer, qrcode);
207 }
208 
209 
210 // Public function - see documentation comment in header file.
qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[],size_t len,enum qrcodegen_Ecc ecl,int minVersion,int maxVersion,int mask,bool boostEcl,uint8_t tempBuffer[],uint8_t qrcode[])211 bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl,
212                                       int minVersion, int maxVersion, int mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[])
213 {
214     LV_ASSERT(segs != NULL || len == 0);
215     LV_ASSERT(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX);
216     LV_ASSERT(0 <= (int)ecl && (int)ecl <= 3 && -1 <= (int)mask && (int)mask <= 7);
217 
218     // Find the minimal version number to use
219     int version, dataUsedBits;
220     for(version = minVersion; ; version++) {
221         int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;  // Number of data bits available
222         dataUsedBits = getTotalBits(segs, len, version);
223         if(dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
224             break;  // This version number is found to be suitable
225         if(version >= maxVersion) {   // All versions in the range could not fit the given data
226             qrcode[0] = 0;  // Set size to invalid value for safety
227             return false;
228         }
229     }
230     LV_ASSERT(dataUsedBits != -1);
231 
232     // Increase the error correction level while the data still fits in the current version number
233     for(int i = (int)qrcodegen_Ecc_MEDIUM; i <= (int)qrcodegen_Ecc_HIGH; i++) {   // From low to high
234         if(boostEcl && dataUsedBits <= getNumDataCodewords(version, (enum qrcodegen_Ecc)i) * 8)
235             ecl = (enum qrcodegen_Ecc)i;
236     }
237 
238     // Concatenate all segments to create the data bit string
239     memset(qrcode, 0, qrcodegen_BUFFER_LEN_FOR_VERSION(version) * sizeof(qrcode[0]));
240     int bitLen = 0;
241     for(size_t i = 0; i < len; i++) {
242         const struct qrcodegen_Segment * seg = &segs[i];
243         appendBitsToBuffer((int)seg->mode, 4, qrcode, &bitLen);
244         appendBitsToBuffer(seg->numChars, numCharCountBits(seg->mode, version), qrcode, &bitLen);
245         for(int j = 0; j < seg->bitLength; j++)
246             appendBitsToBuffer((seg->data[j >> 3] >> (7 - (j & 7))) & 1, 1, qrcode, &bitLen);
247     }
248     LV_ASSERT(bitLen == dataUsedBits);
249 
250     // Add terminator and pad up to a byte if applicable
251     int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;
252     LV_ASSERT(bitLen <= dataCapacityBits);
253     int terminatorBits = dataCapacityBits - bitLen;
254     if(terminatorBits > 4)
255         terminatorBits = 4;
256     appendBitsToBuffer(0, terminatorBits, qrcode, &bitLen);
257     appendBitsToBuffer(0, (8 - bitLen % 8) % 8, qrcode, &bitLen);
258     LV_ASSERT(bitLen % 8 == 0);
259 
260     // Pad with alternating bytes until data capacity is reached
261     for(uint8_t padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
262         appendBitsToBuffer(padByte, 8, qrcode, &bitLen);
263 
264     // Draw function and data codeword modules
265     addEccAndInterleave(qrcode, version, ecl, tempBuffer);
266     initializeFunctionModules(version, qrcode);
267     drawCodewords(tempBuffer, getNumRawDataModules(version) / 8, qrcode);
268     drawWhiteFunctionModules(qrcode, version);
269     initializeFunctionModules(version, tempBuffer);
270 
271     // Handle masking
272     if(mask == qrcodegen_Mask_AUTO) {   // Automatically choose best mask
273         long minPenalty = LONG_MAX;
274         for(int i = 0; i < 8; i++) {
275             enum qrcodegen_Mask msk = (enum qrcodegen_Mask)i;
276             applyMask(tempBuffer, qrcode, msk);
277             drawFormatBits(ecl, msk, qrcode);
278             long penalty = getPenaltyScore(qrcode);
279             if(penalty < minPenalty) {
280                 mask = msk;
281                 minPenalty = penalty;
282             }
283             applyMask(tempBuffer, qrcode, msk);  // Undoes the mask due to XOR
284         }
285     }
286     LV_ASSERT(0 <= (int)mask && (int)mask <= 7);
287     applyMask(tempBuffer, qrcode, mask);
288     drawFormatBits(ecl, mask, qrcode);
289     return true;
290 }
291 
292 
293 
294 /*---- Error correction code generation functions ----*/
295 
296 // Appends error correction bytes to each block of the given data array, then interleaves
297 // bytes from the blocks and stores them in the result array. data[0 : dataLen] contains
298 // the input data. data[dataLen : rawCodewords] is used as a temporary work area and will
299 // be clobbered by this function. The final answer is stored in result[0 : rawCodewords].
addEccAndInterleave(uint8_t data[],int version,enum qrcodegen_Ecc ecl,uint8_t result[])300 testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[])
301 {
302     // Calculate parameter numbers
303     LV_ASSERT(0 <= (int)ecl && (int)ecl < 4 && qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX);
304     int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[(int)ecl][version];
305     int blockEccLen = ECC_CODEWORDS_PER_BLOCK  [(int)ecl][version];
306     int rawCodewords = getNumRawDataModules(version) / 8;
307     int dataLen = getNumDataCodewords(version, ecl);
308     int numShortBlocks = numBlocks - rawCodewords % numBlocks;
309     int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen;
310 
311     // Split data into blocks, calculate ECC, and interleave
312     // (not concatenate) the bytes into a single sequence
313     uint8_t generator[qrcodegen_REED_SOLOMON_DEGREE_MAX];
314     calcReedSolomonGenerator(blockEccLen, generator);
315     const uint8_t * dat = data;
316     for(int i = 0; i < numBlocks; i++) {
317         int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1);
318         uint8_t * ecc = &data[dataLen]; // Temporary storage
319         calcReedSolomonRemainder(dat, datLen, generator, blockEccLen, ecc);
320         for(int j = 0, k = i; j < datLen; j++, k += numBlocks) {   // Copy data
321             if(j == shortBlockDataLen)
322                 k -= numShortBlocks;
323             result[k] = dat[j];
324         }
325         for(int j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks)   // Copy ECC
326             result[k] = ecc[j];
327         dat += datLen;
328     }
329 }
330 
331 
332 // Returns the number of 8-bit codewords that can be used for storing data (not ECC),
333 // for the given version number and error correction level. The result is in the range [9, 2956].
getNumDataCodewords(int version,enum qrcodegen_Ecc ecl)334 testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl)
335 {
336     int v = version, e = (int)ecl;
337     LV_ASSERT(0 <= e && e < 4);
338     return getNumRawDataModules(v) / 8
339            - ECC_CODEWORDS_PER_BLOCK    [e][v]
340            * NUM_ERROR_CORRECTION_BLOCKS[e][v];
341 }
342 
343 
344 // Returns the number of data bits that can be stored in a QR Code of the given version number, after
345 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
346 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
getNumRawDataModules(int ver)347 testable int getNumRawDataModules(int ver)
348 {
349     LV_ASSERT(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX);
350     int result = (16 * ver + 128) * ver + 64;
351     if(ver >= 2) {
352         int numAlign = ver / 7 + 2;
353         result -= (25 * numAlign - 10) * numAlign - 55;
354         if(ver >= 7)
355             result -= 36;
356     }
357     return result;
358 }
359 
360 
361 
362 /*---- Reed-Solomon ECC generator functions ----*/
363 
364 // Calculates the Reed-Solomon generator polynomial of the given degree, storing in result[0 : degree].
calcReedSolomonGenerator(int degree,uint8_t result[])365 testable void calcReedSolomonGenerator(int degree, uint8_t result[])
366 {
367     // Start with the monomial x^0
368     LV_ASSERT(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX);
369     memset(result, 0, degree * sizeof(result[0]));
370     result[degree - 1] = 1;
371 
372     // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
373     // drop the highest term, and store the rest of the coefficients in order of descending powers.
374     // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
375     uint8_t root = 1;
376     for(int i = 0; i < degree; i++) {
377         // Multiply the current product by (x - r^i)
378         for(int j = 0; j < degree; j++) {
379             result[j] = finiteFieldMultiply(result[j], root);
380             if(j + 1 < degree)
381                 result[j] ^= result[j + 1];
382         }
383         root = finiteFieldMultiply(root, 0x02);
384     }
385 }
386 
387 
388 // Calculates the remainder of the polynomial data[0 : dataLen] when divided by the generator[0 : degree], where all
389 // polynomials are in big endian and the generator has an implicit leading 1 term, storing the result in result[0 : degree].
calcReedSolomonRemainder(const uint8_t data[],int dataLen,const uint8_t generator[],int degree,uint8_t result[])390 testable void calcReedSolomonRemainder(const uint8_t data[], int dataLen,
391                                        const uint8_t generator[], int degree, uint8_t result[])
392 {
393 
394     // Perform polynomial division
395     LV_ASSERT(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX);
396     memset(result, 0, degree * sizeof(result[0]));
397     for(int i = 0; i < dataLen; i++) {
398         uint8_t factor = data[i] ^ result[0];
399         memmove(&result[0], &result[1], (degree - 1) * sizeof(result[0]));
400         result[degree - 1] = 0;
401         for(int j = 0; j < degree; j++)
402             result[j] ^= finiteFieldMultiply(generator[j], factor);
403     }
404 }
405 
406 #undef qrcodegen_REED_SOLOMON_DEGREE_MAX
407 
408 
409 // Returns the product of the two given field elements modulo GF(2^8/0x11D).
410 // All inputs are valid. This could be implemented as a 256*256 lookup table.
finiteFieldMultiply(uint8_t x,uint8_t y)411 testable uint8_t finiteFieldMultiply(uint8_t x, uint8_t y)
412 {
413     // Russian peasant multiplication
414     uint8_t z = 0;
415     for(int i = 7; i >= 0; i--) {
416         z = (z << 1) ^ ((z >> 7) * 0x11D);
417         z ^= ((y >> i) & 1) * x;
418     }
419     return z;
420 }
421 
422 
423 
424 /*---- Drawing function modules ----*/
425 
426 // Clears the given QR Code grid with white modules for the given
427 // version's size, then marks every function module as black.
initializeFunctionModules(int version,uint8_t qrcode[])428 testable void initializeFunctionModules(int version, uint8_t qrcode[])
429 {
430     // Initialize QR Code
431     int qrsize = version * 4 + 17;
432     memset(qrcode, 0, ((qrsize * qrsize + 7) / 8 + 1) * sizeof(qrcode[0]));
433     qrcode[0] = (uint8_t)qrsize;
434 
435     // Fill horizontal and vertical timing patterns
436     fillRectangle(6, 0, 1, qrsize, qrcode);
437     fillRectangle(0, 6, qrsize, 1, qrcode);
438 
439     // Fill 3 finder patterns (all corners except bottom right) and format bits
440     fillRectangle(0, 0, 9, 9, qrcode);
441     fillRectangle(qrsize - 8, 0, 8, 9, qrcode);
442     fillRectangle(0, qrsize - 8, 9, 8, qrcode);
443 
444     // Fill numerous alignment patterns
445     uint8_t alignPatPos[7];
446     int numAlign = getAlignmentPatternPositions(version, alignPatPos);
447     for(int i = 0; i < numAlign; i++) {
448         for(int j = 0; j < numAlign; j++) {
449             // Don't draw on the three finder corners
450             if(!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
451                 fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode);
452         }
453     }
454 
455     // Fill version blocks
456     if(version >= 7) {
457         fillRectangle(qrsize - 11, 0, 3, 6, qrcode);
458         fillRectangle(0, qrsize - 11, 6, 3, qrcode);
459     }
460 }
461 
462 
463 // Draws white function modules and possibly some black modules onto the given QR Code, without changing
464 // non-function modules. This does not draw the format bits. This requires all function modules to be previously
465 // marked black (namely by initializeFunctionModules()), because this may skip redrawing black function modules.
drawWhiteFunctionModules(uint8_t qrcode[],int version)466 static void drawWhiteFunctionModules(uint8_t qrcode[], int version)
467 {
468     // Draw horizontal and vertical timing patterns
469     int qrsize = qrcodegen_getSize(qrcode);
470     for(int i = 7; i < qrsize - 7; i += 2) {
471         setModule(qrcode, 6, i, false);
472         setModule(qrcode, i, 6, false);
473     }
474 
475     // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
476     for(int dy = -4; dy <= 4; dy++) {
477         for(int dx = -4; dx <= 4; dx++) {
478             int dist = abs(dx);
479             if(abs(dy) > dist)
480                 dist = abs(dy);
481             if(dist == 2 || dist == 4) {
482                 setModuleBounded(qrcode, 3 + dx, 3 + dy, false);
483                 setModuleBounded(qrcode, qrsize - 4 + dx, 3 + dy, false);
484                 setModuleBounded(qrcode, 3 + dx, qrsize - 4 + dy, false);
485             }
486         }
487     }
488 
489     // Draw numerous alignment patterns
490     uint8_t alignPatPos[7];
491     int numAlign = getAlignmentPatternPositions(version, alignPatPos);
492     for(int i = 0; i < numAlign; i++) {
493         for(int j = 0; j < numAlign; j++) {
494             if((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))
495                 continue;  // Don't draw on the three finder corners
496             for(int dy = -1; dy <= 1; dy++) {
497                 for(int dx = -1; dx <= 1; dx++)
498                     setModule(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0);
499             }
500         }
501     }
502 
503     // Draw version blocks
504     if(version >= 7) {
505         // Calculate error correction code and pack bits
506         int rem = version;  // version is uint6, in the range [7, 40]
507         for(int i = 0; i < 12; i++)
508             rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
509         long bits = (long)version << 12 | rem;  // uint18
510         LV_ASSERT(bits >> 18 == 0);
511 
512         // Draw two copies
513         for(int i = 0; i < 6; i++) {
514             for(int j = 0; j < 3; j++) {
515                 int k = qrsize - 11 + j;
516                 setModule(qrcode, k, i, (bits & 1) != 0);
517                 setModule(qrcode, i, k, (bits & 1) != 0);
518                 bits >>= 1;
519             }
520         }
521     }
522 }
523 
524 
525 // Draws two copies of the format bits (with its own error correction code) based
526 // on the given mask and error correction level. This always draws all modules of
527 // the format bits, unlike drawWhiteFunctionModules() which might skip black modules.
drawFormatBits(enum qrcodegen_Ecc ecl,enum qrcodegen_Mask mask,uint8_t qrcode[])528 static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[])
529 {
530     // Calculate error correction code and pack bits
531     LV_ASSERT(0 <= (int)mask && (int)mask <= 7);
532     static const int table[] = {1, 0, 3, 2};
533     int data = table[(int)ecl] << 3 | (int)mask;  // errCorrLvl is uint2, mask is uint3
534     int rem = data;
535     for(int i = 0; i < 10; i++)
536         rem = (rem << 1) ^ ((rem >> 9) * 0x537);
537     int bits = (data << 10 | rem) ^ 0x5412;  // uint15
538     LV_ASSERT(bits >> 15 == 0);
539 
540     // Draw first copy
541     for(int i = 0; i <= 5; i++)
542         setModule(qrcode, 8, i, getBit(bits, i));
543     setModule(qrcode, 8, 7, getBit(bits, 6));
544     setModule(qrcode, 8, 8, getBit(bits, 7));
545     setModule(qrcode, 7, 8, getBit(bits, 8));
546     for(int i = 9; i < 15; i++)
547         setModule(qrcode, 14 - i, 8, getBit(bits, i));
548 
549     // Draw second copy
550     int qrsize = qrcodegen_getSize(qrcode);
551     for(int i = 0; i < 8; i++)
552         setModule(qrcode, qrsize - 1 - i, 8, getBit(bits, i));
553     for(int i = 8; i < 15; i++)
554         setModule(qrcode, 8, qrsize - 15 + i, getBit(bits, i));
555     setModule(qrcode, 8, qrsize - 8, true);  // Always black
556 }
557 
558 
559 // Calculates and stores an ascending list of positions of alignment patterns
560 // for this version number, returning the length of the list (in the range [0,7]).
561 // Each position is in the range [0,177), and are used on both the x and y axes.
562 // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
getAlignmentPatternPositions(int version,uint8_t result[7])563 testable int getAlignmentPatternPositions(int version, uint8_t result[7])
564 {
565     if(version == 1)
566         return 0;
567     int numAlign = version / 7 + 2;
568     int step = (version == 32) ? 26 :
569                (version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2;
570     for(int i = numAlign - 1, pos = version * 4 + 10; i >= 1; i--, pos -= step)
571         result[i] = pos;
572     result[0] = 6;
573     return numAlign;
574 }
575 
576 
577 // Sets every pixel in the range [left : left + width] * [top : top + height] to black.
fillRectangle(int left,int top,int width,int height,uint8_t qrcode[])578 static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[])
579 {
580     for(int dy = 0; dy < height; dy++) {
581         for(int dx = 0; dx < width; dx++)
582             setModule(qrcode, left + dx, top + dy, true);
583     }
584 }
585 
586 
587 
588 /*---- Drawing data modules and masking ----*/
589 
590 // Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of
591 // the QR Code to be black at function modules and white at codeword modules (including unused remainder bits).
drawCodewords(const uint8_t data[],int dataLen,uint8_t qrcode[])592 static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[])
593 {
594     int qrsize = qrcodegen_getSize(qrcode);
595     int i = 0;  // Bit index into the data
596     // Do the funny zigzag scan
597     for(int right = qrsize - 1; right >= 1; right -= 2) {   // Index of right column in each column pair
598         if(right == 6)
599             right = 5;
600         for(int vert = 0; vert < qrsize; vert++) {   // Vertical counter
601             for(int j = 0; j < 2; j++) {
602                 int x = right - j;  // Actual x coordinate
603                 bool upward = ((right + 1) & 2) == 0;
604                 int y = upward ? qrsize - 1 - vert : vert;  // Actual y coordinate
605                 if(!getModule(qrcode, x, y) && i < dataLen * 8) {
606                     bool black = getBit(data[i >> 3], 7 - (i & 7));
607                     setModule(qrcode, x, y, black);
608                     i++;
609                 }
610                 // If this QR Code has any remainder bits (0 to 7), they were assigned as
611                 // 0/false/white by the constructor and are left unchanged by this method
612             }
613         }
614     }
615     LV_ASSERT(i == dataLen * 8);
616 }
617 
618 
619 // XORs the codeword modules in this QR Code with the given mask pattern.
620 // The function modules must be marked and the codeword bits must be drawn
621 // before masking. Due to the arithmetic of XOR, calling applyMask() with
622 // the same mask value a second time will undo the mask. A final well-formed
623 // QR Code needs exactly one (not zero, two, etc.) mask applied.
applyMask(const uint8_t functionModules[],uint8_t qrcode[],enum qrcodegen_Mask mask)624 static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask)
625 {
626     LV_ASSERT(0 <= (int)mask && (int)mask <= 7);  // Disallows qrcodegen_Mask_AUTO
627     int qrsize = qrcodegen_getSize(qrcode);
628     for(int y = 0; y < qrsize; y++) {
629         for(int x = 0; x < qrsize; x++) {
630             if(getModule(functionModules, x, y))
631                 continue;
632             bool invert;
633             switch((int)mask) {
634                 case 0:
635                     invert = (x + y) % 2 == 0;
636                     break;
637                 case 1:
638                     invert = y % 2 == 0;
639                     break;
640                 case 2:
641                     invert = x % 3 == 0;
642                     break;
643                 case 3:
644                     invert = (x + y) % 3 == 0;
645                     break;
646                 case 4:
647                     invert = (x / 3 + y / 2) % 2 == 0;
648                     break;
649                 case 5:
650                     invert = x * y % 2 + x * y % 3 == 0;
651                     break;
652                 case 6:
653                     invert = (x * y % 2 + x * y % 3) % 2 == 0;
654                     break;
655                 case 7:
656                     invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
657                     break;
658                 default:
659                     LV_ASSERT(false);
660                     return;
661             }
662             bool val = getModule(qrcode, x, y);
663             setModule(qrcode, x, y, val ^ invert);
664         }
665     }
666 }
667 
668 
669 // Calculates and returns the penalty score based on state of the given QR Code's current modules.
670 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
getPenaltyScore(const uint8_t qrcode[])671 static long getPenaltyScore(const uint8_t qrcode[])
672 {
673     int qrsize = qrcodegen_getSize(qrcode);
674     long result = 0;
675 
676     // Adjacent modules in row having same color, and finder-like patterns
677     for(int y = 0; y < qrsize; y++) {
678         unsigned char runHistory[7] = {0};
679         bool color = false;
680         unsigned char runX = 0;
681         for(int x = 0; x < qrsize; x++) {
682             if(getModule(qrcode, x, y) == color) {
683                 runX++;
684                 if(runX == 5)
685                     result += PENALTY_N1;
686                 else if(runX > 5)
687                     result++;
688             }
689             else {
690                 addRunToHistory(runX, runHistory);
691                 if(!color && hasFinderLikePattern(runHistory))
692                     result += PENALTY_N3;
693                 color = getModule(qrcode, x, y);
694                 runX = 1;
695             }
696         }
697         addRunToHistory(runX, runHistory);
698         if(color)
699             addRunToHistory(0, runHistory);  // Dummy run of white
700         if(hasFinderLikePattern(runHistory))
701             result += PENALTY_N3;
702     }
703     // Adjacent modules in column having same color, and finder-like patterns
704     for(int x = 0; x < qrsize; x++) {
705         unsigned char runHistory[7] = {0};
706         bool color = false;
707         unsigned char runY = 0;
708         for(int y = 0; y < qrsize; y++) {
709             if(getModule(qrcode, x, y) == color) {
710                 runY++;
711                 if(runY == 5)
712                     result += PENALTY_N1;
713                 else if(runY > 5)
714                     result++;
715             }
716             else {
717                 addRunToHistory(runY, runHistory);
718                 if(!color && hasFinderLikePattern(runHistory))
719                     result += PENALTY_N3;
720                 color = getModule(qrcode, x, y);
721                 runY = 1;
722             }
723         }
724         addRunToHistory(runY, runHistory);
725         if(color)
726             addRunToHistory(0, runHistory);  // Dummy run of white
727         if(hasFinderLikePattern(runHistory))
728             result += PENALTY_N3;
729     }
730 
731     // 2*2 blocks of modules having same color
732     for(int y = 0; y < qrsize - 1; y++) {
733         for(int x = 0; x < qrsize - 1; x++) {
734             bool  color = getModule(qrcode, x, y);
735             if(color == getModule(qrcode, x + 1, y) &&
736                color == getModule(qrcode, x, y + 1) &&
737                color == getModule(qrcode, x + 1, y + 1))
738                 result += PENALTY_N2;
739         }
740     }
741 
742     // Balance of black and white modules
743     int black = 0;
744     for(int y = 0; y < qrsize; y++) {
745         for(int x = 0; x < qrsize; x++) {
746             if(getModule(qrcode, x, y))
747                 black++;
748         }
749     }
750     int total = qrsize * qrsize;  // Note that size is odd, so black/total != 1/2
751     // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
752     int k = (int)((labs(black * 20L - total * 10L) + total - 1) / total) - 1;
753     result += k * PENALTY_N4;
754     return result;
755 }
756 
757 
758 // Inserts the given value to the front of the given array, which shifts over the
759 // existing values and deletes the last value. A helper function for getPenaltyScore().
addRunToHistory(unsigned char run,unsigned char history[7])760 static void addRunToHistory(unsigned char run, unsigned char history[7])
761 {
762     memmove(&history[1], &history[0], 6 * sizeof(history[0]));
763     history[0] = run;
764 }
765 
766 
767 // Tests whether the given run history has the pattern of ratio 1:1:3:1:1 in the middle, and
768 // surrounded by at least 4 on either or both ends. A helper function for getPenaltyScore().
769 // Must only be called immediately after a run of white modules has ended.
hasFinderLikePattern(const unsigned char runHistory[7])770 static bool hasFinderLikePattern(const unsigned char runHistory[7])
771 {
772     unsigned char n = runHistory[1];
773     // The maximum QR Code size is 177, hence the run length n <= 177.
774     // Arithmetic is promoted to int, so n*4 will not overflow.
775     return n > 0 && runHistory[2] == n && runHistory[4] == n && runHistory[5] == n
776            && runHistory[3] == n * 3 && (runHistory[0] >= n * 4 || runHistory[6] >= n * 4);
777 }
778 
779 
780 
781 /*---- Basic QR Code information ----*/
782 
783 // Public function - see documentation comment in header file.
qrcodegen_getSize(const uint8_t qrcode[])784 int qrcodegen_getSize(const uint8_t qrcode[])
785 {
786     LV_ASSERT(qrcode != NULL);
787     int result = qrcode[0];
788     LV_ASSERT((qrcodegen_VERSION_MIN * 4 + 17) <= result
789            && result <= (qrcodegen_VERSION_MAX * 4 + 17));
790     return result;
791 }
792 
793 
794 // Public function - see documentation comment in header file.
qrcodegen_getModule(const uint8_t qrcode[],int x,int y)795 bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y)
796 {
797     LV_ASSERT(qrcode != NULL);
798     int qrsize = qrcode[0];
799     return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModule(qrcode, x, y);
800 }
801 
802 
803 // Gets the module at the given coordinates, which must be in bounds.
getModule(const uint8_t qrcode[],int x,int y)804 testable bool getModule(const uint8_t qrcode[], int x, int y)
805 {
806     int qrsize = qrcode[0];
807     LV_ASSERT(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize);
808     int index = y * qrsize + x;
809     return getBit(qrcode[(index >> 3) + 1], index & 7);
810 }
811 
812 
813 // Sets the module at the given coordinates, which must be in bounds.
setModule(uint8_t qrcode[],int x,int y,bool isBlack)814 testable void setModule(uint8_t qrcode[], int x, int y, bool isBlack)
815 {
816     int qrsize = qrcode[0];
817     LV_ASSERT(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize);
818     int index = y * qrsize + x;
819     int bitIndex = index & 7;
820     int byteIndex = (index >> 3) + 1;
821     if(isBlack)
822         qrcode[byteIndex] |= 1 << bitIndex;
823     else
824         qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF;
825 }
826 
827 
828 // Sets the module at the given coordinates, doing nothing if out of bounds.
setModuleBounded(uint8_t qrcode[],int x,int y,bool isBlack)829 testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isBlack)
830 {
831     int qrsize = qrcode[0];
832     if(0 <= x && x < qrsize && 0 <= y && y < qrsize)
833         setModule(qrcode, x, y, isBlack);
834 }
835 
836 
837 // Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14.
getBit(int x,int i)838 static bool getBit(int x, int i)
839 {
840     return ((x >> i) & 1) != 0;
841 }
842 
843 
844 
845 /*---- Segment handling ----*/
846 
847 // Public function - see documentation comment in header file.
qrcodegen_isAlphanumeric(const char * text)848 bool qrcodegen_isAlphanumeric(const char * text)
849 {
850     LV_ASSERT(text != NULL);
851     for(; *text != '\0'; text++) {
852         if(strchr(ALPHANUMERIC_CHARSET, *text) == NULL)
853             return false;
854     }
855     return true;
856 }
857 
858 
859 // Public function - see documentation comment in header file.
qrcodegen_isNumeric(const char * text)860 bool qrcodegen_isNumeric(const char * text)
861 {
862     LV_ASSERT(text != NULL);
863     for(; *text != '\0'; text++) {
864         if(*text < '0' || *text > '9')
865             return false;
866     }
867     return true;
868 }
869 
870 
871 // Public function - see documentation comment in header file.
qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode,size_t numChars)872 size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars)
873 {
874     int temp = calcSegmentBitLength(mode, numChars);
875     if(temp == -1)
876         return SIZE_MAX;
877     LV_ASSERT(0 <= temp && temp <= INT16_MAX);
878     return ((size_t)temp + 7) / 8;
879 }
880 
881 
882 // Returns the number of data bits needed to represent a segment
883 // containing the given number of characters using the given mode. Notes:
884 // - Returns -1 on failure, i.e. numChars > INT16_MAX or
885 //   the number of needed bits exceeds INT16_MAX (i.e. 32767).
886 // - Otherwise, all valid results are in the range [0, INT16_MAX].
887 // - For byte mode, numChars measures the number of bytes, not Unicode code points.
888 // - For ECI mode, numChars must be 0, and the worst-case number of bits is returned.
889 //   An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
calcSegmentBitLength(enum qrcodegen_Mode mode,size_t numChars)890 testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars)
891 {
892     // All calculations are designed to avoid overflow on all platforms
893     if(numChars > (unsigned int)INT16_MAX)
894         return -1;
895     long result = (long)numChars;
896     if(mode == qrcodegen_Mode_NUMERIC)
897         result = (result * 10 + 2) / 3;  // ceil(10/3 * n)
898     else if(mode == qrcodegen_Mode_ALPHANUMERIC)
899         result = (result * 11 + 1) / 2;  // ceil(11/2 * n)
900     else if(mode == qrcodegen_Mode_BYTE)
901         result *= 8;
902     else if(mode == qrcodegen_Mode_KANJI)
903         result *= 13;
904     else if(mode == qrcodegen_Mode_ECI && numChars == 0)
905         result = 3 * 8;
906     else {  // Invalid argument
907         LV_ASSERT(false);
908         return -1;
909     }
910     LV_ASSERT(result >= 0);
911     if((unsigned int)result > (unsigned int)INT16_MAX)
912         return -1;
913     return (int)result;
914 }
915 
916 
917 // Public function - see documentation comment in header file.
qrcodegen_makeBytes(const uint8_t data[],size_t len,uint8_t buf[])918 struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[])
919 {
920     LV_ASSERT(data != NULL || len == 0);
921     struct qrcodegen_Segment result;
922     result.mode = qrcodegen_Mode_BYTE;
923     result.bitLength = calcSegmentBitLength(result.mode, len);
924     LV_ASSERT(result.bitLength != -1);
925     result.numChars = (int)len;
926     if(len > 0)
927         memcpy(buf, data, len * sizeof(buf[0]));
928     result.data = buf;
929     return result;
930 }
931 
932 
933 // Public function - see documentation comment in header file.
qrcodegen_makeNumeric(const char * digits,uint8_t buf[])934 struct qrcodegen_Segment qrcodegen_makeNumeric(const char * digits, uint8_t buf[])
935 {
936     LV_ASSERT(digits != NULL);
937     struct qrcodegen_Segment result;
938     size_t len = strlen(digits);
939     result.mode = qrcodegen_Mode_NUMERIC;
940     int bitLen = calcSegmentBitLength(result.mode, len);
941     LV_ASSERT(bitLen != -1);
942     result.numChars = (int)len;
943     if(bitLen > 0)
944         memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
945     result.bitLength = 0;
946 
947     unsigned int accumData = 0;
948     int accumCount = 0;
949     for(; *digits != '\0'; digits++) {
950         char c = *digits;
951         LV_ASSERT('0' <= c && c <= '9');
952         accumData = accumData * 10 + (unsigned int)(c - '0');
953         accumCount++;
954         if(accumCount == 3) {
955             appendBitsToBuffer(accumData, 10, buf, &result.bitLength);
956             accumData = 0;
957             accumCount = 0;
958         }
959     }
960     if(accumCount > 0)   // 1 or 2 digits remaining
961         appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength);
962     LV_ASSERT(result.bitLength == bitLen);
963     result.data = buf;
964     return result;
965 }
966 
967 
968 // Public function - see documentation comment in header file.
qrcodegen_makeAlphanumeric(const char * text,uint8_t buf[])969 struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char * text, uint8_t buf[])
970 {
971     LV_ASSERT(text != NULL);
972     struct qrcodegen_Segment result;
973     size_t len = strlen(text);
974     result.mode = qrcodegen_Mode_ALPHANUMERIC;
975     int bitLen = calcSegmentBitLength(result.mode, len);
976     LV_ASSERT(bitLen != -1);
977     result.numChars = (int)len;
978     if(bitLen > 0)
979         memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
980     result.bitLength = 0;
981 
982     unsigned int accumData = 0;
983     int accumCount = 0;
984     for(; *text != '\0'; text++) {
985         const char * temp = strchr(ALPHANUMERIC_CHARSET, *text);
986         LV_ASSERT(temp != NULL);
987         accumData = accumData * 45 + (unsigned int)(temp - ALPHANUMERIC_CHARSET);
988         accumCount++;
989         if(accumCount == 2) {
990             appendBitsToBuffer(accumData, 11, buf, &result.bitLength);
991             accumData = 0;
992             accumCount = 0;
993         }
994     }
995     if(accumCount > 0)   // 1 character remaining
996         appendBitsToBuffer(accumData, 6, buf, &result.bitLength);
997     LV_ASSERT(result.bitLength == bitLen);
998     result.data = buf;
999     return result;
1000 }
1001 
1002 
1003 // Public function - see documentation comment in header file.
qrcodegen_makeEci(long assignVal,uint8_t buf[])1004 struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[])
1005 {
1006     struct qrcodegen_Segment result;
1007     result.mode = qrcodegen_Mode_ECI;
1008     result.numChars = 0;
1009     result.bitLength = 0;
1010     if(assignVal < 0) {
1011         LV_ASSERT(false);
1012     }
1013     else if(assignVal < (1 << 7)) {
1014         memset(buf, 0, 1 * sizeof(buf[0]));
1015         appendBitsToBuffer(assignVal, 8, buf, &result.bitLength);
1016     }
1017     else if(assignVal < (1 << 14)) {
1018         memset(buf, 0, 2 * sizeof(buf[0]));
1019         appendBitsToBuffer(2, 2, buf, &result.bitLength);
1020         appendBitsToBuffer(assignVal, 14, buf, &result.bitLength);
1021     }
1022     else if(assignVal < 1000000L) {
1023         memset(buf, 0, 3 * sizeof(buf[0]));
1024         appendBitsToBuffer(6, 3, buf, &result.bitLength);
1025         appendBitsToBuffer(assignVal >> 10, 11, buf, &result.bitLength);
1026         appendBitsToBuffer(assignVal & 0x3FF, 10, buf, &result.bitLength);
1027     }
1028     else {
1029         LV_ASSERT(false);
1030     }
1031     result.data = buf;
1032     return result;
1033 }
1034 
1035 
1036 // Calculates the number of bits needed to encode the given segments at the given version.
1037 // Returns a non-negative number if successful. Otherwise returns -1 if a segment has too
1038 // many characters to fit its length field, or the total bits exceeds INT16_MAX.
getTotalBits(const struct qrcodegen_Segment segs[],size_t len,int version)1039 testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version)
1040 {
1041     LV_ASSERT(segs != NULL || len == 0);
1042     long result = 0;
1043     for(size_t i = 0; i < len; i++) {
1044         int numChars  = segs[i].numChars;
1045         int bitLength = segs[i].bitLength;
1046         LV_ASSERT(0 <= numChars  && numChars  <= INT16_MAX);
1047         LV_ASSERT(0 <= bitLength && bitLength <= INT16_MAX);
1048         int ccbits = numCharCountBits(segs[i].mode, version);
1049         LV_ASSERT(0 <= ccbits && ccbits <= 16);
1050         if(numChars >= (1L << ccbits))
1051             return -1;  // The segment's length doesn't fit the field's bit width
1052         result += 4L + ccbits + bitLength;
1053         if(result > INT16_MAX)
1054             return -1;  // The sum might overflow an int type
1055     }
1056     LV_ASSERT(0 <= result && result <= INT16_MAX);
1057     return (int)result;
1058 }
1059 
1060 
1061 // Returns the bit width of the character count field for a segment in the given mode
1062 // in a QR Code at the given version number. The result is in the range [0, 16].
numCharCountBits(enum qrcodegen_Mode mode,int version)1063 static int numCharCountBits(enum qrcodegen_Mode mode, int version)
1064 {
1065     LV_ASSERT(qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX);
1066     int i = (version + 7) / 17;
1067     switch(mode) {
1068         case qrcodegen_Mode_NUMERIC     : {
1069                 static const int temp[] = {10, 12, 14};
1070                 return temp[i];
1071             }
1072         case qrcodegen_Mode_ALPHANUMERIC: {
1073                 static const int temp[] = { 9, 11, 13};
1074                 return temp[i];
1075             }
1076         case qrcodegen_Mode_BYTE        : {
1077                 static const int temp[] = { 8, 16, 16};
1078                 return temp[i];
1079             }
1080         case qrcodegen_Mode_KANJI       : {
1081                 static const int temp[] = { 8, 10, 12};
1082                 return temp[i];
1083             }
1084         case qrcodegen_Mode_ECI         :
1085             return 0;
1086         default:
1087             LV_ASSERT(false);
1088             return -1;  // Dummy value
1089     }
1090 }
1091 
qrcodegen_getMinFitVersion(enum qrcodegen_Ecc ecl,size_t dataLen)1092 int qrcodegen_getMinFitVersion(enum qrcodegen_Ecc ecl, size_t dataLen)
1093 {
1094     struct qrcodegen_Segment seg;
1095     seg.mode = qrcodegen_Mode_BYTE;
1096     seg.bitLength = calcSegmentBitLength(seg.mode, dataLen);
1097     seg.numChars = (int)dataLen;
1098 
1099     for(int version = qrcodegen_VERSION_MIN; version <= qrcodegen_VERSION_MAX; version++) {
1100         int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;  // Number of data bits available
1101         int dataUsedBits = getTotalBits(&seg, 1, version);
1102         if(dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
1103             return version;
1104     }
1105     return -1;
1106 }
1107 
qrcodegen_version2size(int version)1108 int qrcodegen_version2size(int version)
1109 {
1110     if(version < qrcodegen_VERSION_MIN || version > qrcodegen_VERSION_MAX) {
1111         return -1;
1112     }
1113 
1114     return ((version - 1) * 4 + 21);
1115 }
1116 #endif
1117