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 #pragma once 25 26 #include <stdbool.h> 27 #include <stddef.h> 28 #include <stdint.h> 29 30 31 #ifdef __cplusplus 32 extern "C" { 33 #endif 34 35 char *strchr(const char *s, int c); 36 37 /* 38 * This library creates QR Code symbols, which is a type of two-dimension barcode. 39 * Invented by Denso Wave and described in the ISO/IEC 18004 standard. 40 * A QR Code structure is an immutable square grid of dark and light cells. 41 * The library provides functions to create a QR Code from text or binary data. 42 * The library covers the QR Code Model 2 specification, supporting all versions (sizes) 43 * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. 44 * 45 * Ways to create a QR Code object: 46 * - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary(). 47 * - Low level: Custom-make the list of segments and call 48 * qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced(). 49 * (Note that all ways require supplying the desired error correction level and various byte buffers.) 50 */ 51 52 53 /*---- Enum and struct types----*/ 54 55 /* 56 * The error correction level in a QR Code symbol. 57 */ 58 enum qrcodegen_Ecc { 59 // Must be declared in ascending order of error protection 60 // so that an internal qrcodegen function works properly 61 qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords 62 qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords 63 qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords 64 qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords 65 }; 66 67 68 /* 69 * The mask pattern used in a QR Code symbol. 70 */ 71 enum qrcodegen_Mask { 72 // A special value to tell the QR Code encoder to 73 // automatically select an appropriate mask pattern 74 qrcodegen_Mask_AUTO = -1, 75 // The eight actual mask patterns 76 qrcodegen_Mask_0 = 0, 77 qrcodegen_Mask_1, 78 qrcodegen_Mask_2, 79 qrcodegen_Mask_3, 80 qrcodegen_Mask_4, 81 qrcodegen_Mask_5, 82 qrcodegen_Mask_6, 83 qrcodegen_Mask_7, 84 }; 85 86 87 /* 88 * Describes how a segment's data bits are interpreted. 89 */ 90 enum qrcodegen_Mode { 91 qrcodegen_Mode_NUMERIC = 0x1, 92 qrcodegen_Mode_ALPHANUMERIC = 0x2, 93 qrcodegen_Mode_BYTE = 0x4, 94 qrcodegen_Mode_KANJI = 0x8, 95 qrcodegen_Mode_ECI = 0x7, 96 }; 97 98 99 /* 100 * A segment of character/binary/control data in a QR Code symbol. 101 * The mid-level way to create a segment is to take the payload data 102 * and call a factory function such as qrcodegen_makeNumeric(). 103 * The low-level way to create a segment is to custom-make the bit buffer 104 * and initialize a qrcodegen_Segment struct with appropriate values. 105 * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. 106 * Any segment longer than this is meaningless for the purpose of generating QR Codes. 107 * Moreover, the maximum allowed bit length is 32767 because 108 * the largest QR Code (version 40) has 31329 modules. 109 */ 110 struct qrcodegen_Segment { 111 // The mode indicator of this segment. 112 enum qrcodegen_Mode mode; 113 114 // The length of this segment's unencoded data. Measured in characters for 115 // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. 116 // Always zero or positive. Not the same as the data's bit length. 117 int numChars; 118 119 // The data bits of this segment, packed in bitwise big endian. 120 // Can be null if the bit length is zero. 121 uint8_t *data; 122 123 // The number of valid data bits used in the buffer. Requires 124 // 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8. 125 // The character count (numChars) must agree with the mode and the bit buffer length. 126 int bitLength; 127 }; 128 129 130 131 /*---- Macro constants and functions ----*/ 132 133 #define qrcodegen_VERSION_MIN 1 // The minimum version number supported in the QR Code Model 2 standard 134 #define qrcodegen_VERSION_MAX 40 // The maximum version number supported in the QR Code Model 2 standard 135 136 // Calculates the number of bytes needed to store any QR Code up to and including the given version number, 137 // as a compile-time constant. For example, 'uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];' 138 // can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16). 139 // Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX. 140 #define qrcodegen_BUFFER_LEN_FOR_VERSION(n) ((((n) * 4 + 17) * ((n) * 4 + 17) + 7) / 8 + 1) 141 142 // The worst-case number of bytes needed to store one QR Code, up to and including 143 // version 40. This value equals 3918, which is just under 4 kilobytes. 144 // Use this more convenient value to avoid calculating tighter memory bounds for buffers. 145 #define qrcodegen_BUFFER_LEN_MAX qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX) 146 147 148 149 /*---- Functions (high level) to generate QR Codes ----*/ 150 151 /* 152 * Encodes the given text string to a QR Code, returning true if successful. 153 * If the data is too long to fit in any version in the given range 154 * at the given ECC level, then false is returned. 155 * 156 * The input text must be encoded in UTF-8 and contain no NULs. 157 * Requires 1 <= minVersion <= maxVersion <= 40. 158 * 159 * The smallest possible QR Code version within the given range is automatically 160 * chosen for the output. Iff boostEcl is true, then the ECC level of the result 161 * may be higher than the ecl argument if it can be done without increasing the 162 * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or 163 * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). 164 * 165 * About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion): 166 * - Before calling the function: 167 * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow 168 * reading and writing; hence each array must have a length of at least len. 169 * - The two ranges must not overlap (aliasing). 170 * - The initial state of both ranges can be uninitialized 171 * because the function always writes before reading. 172 * - After the function returns: 173 * - Both ranges have no guarantee on which elements are initialized and what values are stored. 174 * - tempBuffer contains no useful data and should be treated as entirely uninitialized. 175 * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). 176 * 177 * If successful, the resulting QR Code may use numeric, 178 * alphanumeric, or byte mode to encode the text. 179 * 180 * In the most optimistic case, a QR Code at version 40 with low ECC 181 * can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string 182 * up to 4296 characters, or any digit string up to 7089 characters. 183 * These numbers represent the hard upper limit of the QR Code standard. 184 * 185 * Please consult the QR Code specification for information on 186 * data capacities per version, ECC level, and text encoding mode. 187 */ 188 bool qrcodegen_encodeText(const char *text, uint8_t tempBuffer[], uint8_t qrcode[], 189 enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl); 190 191 192 /* 193 * Encodes the given binary data to a QR Code, returning true if successful. 194 * If the data is too long to fit in any version in the given range 195 * at the given ECC level, then false is returned. 196 * 197 * Requires 1 <= minVersion <= maxVersion <= 40. 198 * 199 * The smallest possible QR Code version within the given range is automatically 200 * chosen for the output. Iff boostEcl is true, then the ECC level of the result 201 * may be higher than the ecl argument if it can be done without increasing the 202 * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or 203 * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). 204 * 205 * About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion): 206 * - Before calling the function: 207 * - The array ranges dataAndTemp[0 : len] and qrcode[0 : len] must allow 208 * reading and writing; hence each array must have a length of at least len. 209 * - The two ranges must not overlap (aliasing). 210 * - The input array range dataAndTemp[0 : dataLen] should normally be 211 * valid UTF-8 text, but is not required by the QR Code standard. 212 * - The initial state of dataAndTemp[dataLen : len] and qrcode[0 : len] 213 * can be uninitialized because the function always writes before reading. 214 * - After the function returns: 215 * - Both ranges have no guarantee on which elements are initialized and what values are stored. 216 * - dataAndTemp contains no useful data and should be treated as entirely uninitialized. 217 * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). 218 * 219 * If successful, the resulting QR Code will use byte mode to encode the data. 220 * 221 * In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte 222 * sequence up to length 2953. This is the hard upper limit of the QR Code standard. 223 * 224 * Please consult the QR Code specification for information on 225 * data capacities per version, ECC level, and text encoding mode. 226 */ 227 bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[], 228 enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl); 229 230 231 /*---- Functions (low level) to generate QR Codes ----*/ 232 233 /* 234 * Encodes the given segments to a QR Code, returning true if successful. 235 * If the data is too long to fit in any version at the given ECC level, 236 * then false is returned. 237 * 238 * The smallest possible QR Code version is automatically chosen for 239 * the output. The ECC level of the result may be higher than the 240 * ecl argument if it can be done without increasing the version. 241 * 242 * About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX): 243 * - Before calling the function: 244 * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow 245 * reading and writing; hence each array must have a length of at least len. 246 * - The two ranges must not overlap (aliasing). 247 * - The initial state of both ranges can be uninitialized 248 * because the function always writes before reading. 249 * - The input array segs can contain segments whose data buffers overlap with tempBuffer. 250 * - After the function returns: 251 * - Both ranges have no guarantee on which elements are initialized and what values are stored. 252 * - tempBuffer contains no useful data and should be treated as entirely uninitialized. 253 * - Any segment whose data buffer overlaps with tempBuffer[0 : len] 254 * must be treated as having invalid values in that array. 255 * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). 256 * 257 * Please consult the QR Code specification for information on 258 * data capacities per version, ECC level, and text encoding mode. 259 * 260 * This function allows the user to create a custom sequence of segments that switches 261 * between modes (such as alphanumeric and byte) to encode text in less space. 262 * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). 263 */ 264 bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len, 265 enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]); 266 267 268 /* 269 * Encodes the given segments to a QR Code, returning true if successful. 270 * If the data is too long to fit in any version in the given range 271 * at the given ECC level, then false is returned. 272 * 273 * Requires 1 <= minVersion <= maxVersion <= 40. 274 * 275 * The smallest possible QR Code version within the given range is automatically 276 * chosen for the output. Iff boostEcl is true, then the ECC level of the result 277 * may be higher than the ecl argument if it can be done without increasing the 278 * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or 279 * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). 280 * 281 * About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX): 282 * - Before calling the function: 283 * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow 284 * reading and writing; hence each array must have a length of at least len. 285 * - The two ranges must not overlap (aliasing). 286 * - The initial state of both ranges can be uninitialized 287 * because the function always writes before reading. 288 * - The input array segs can contain segments whose data buffers overlap with tempBuffer. 289 * - After the function returns: 290 * - Both ranges have no guarantee on which elements are initialized and what values are stored. 291 * - tempBuffer contains no useful data and should be treated as entirely uninitialized. 292 * - Any segment whose data buffer overlaps with tempBuffer[0 : len] 293 * must be treated as having invalid values in that array. 294 * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). 295 * 296 * Please consult the QR Code specification for information on 297 * data capacities per version, ECC level, and text encoding mode. 298 * 299 * This function allows the user to create a custom sequence of segments that switches 300 * between modes (such as alphanumeric and byte) to encode text in less space. 301 * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). 302 */ 303 bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl, 304 int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[]); 305 306 307 /* 308 * Tests whether the given string can be encoded as a segment in numeric mode. 309 * A string is encodable iff each character is in the range 0 to 9. 310 */ 311 bool qrcodegen_isNumeric(const char *text); 312 313 314 /* 315 * Tests whether the given string can be encoded as a segment in alphanumeric mode. 316 * A string is encodable iff each character is in the following set: 0 to 9, A to Z 317 * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. 318 */ 319 bool qrcodegen_isAlphanumeric(const char *text); 320 321 322 /* 323 * Returns the number of bytes (uint8_t) needed for the data buffer of a segment 324 * containing the given number of characters using the given mode. Notes: 325 * - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or the internal 326 * calculation of the number of needed bits exceeds INT16_MAX (i.e. 32767). 327 * - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096. 328 * - It is okay for the user to allocate more bytes for the buffer than needed. 329 * - For byte mode, numChars measures the number of bytes, not Unicode code points. 330 * - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned. 331 * An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. 332 */ 333 size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars); 334 335 336 /* 337 * Returns a segment representing the given binary data encoded in 338 * byte mode. All input byte arrays are acceptable. Any text string 339 * can be converted to UTF-8 bytes and encoded as a byte mode segment. 340 */ 341 struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]); 342 343 344 /* 345 * Returns a segment representing the given string of decimal digits encoded in numeric mode. 346 */ 347 struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]); 348 349 350 /* 351 * Returns a segment representing the given text string encoded in alphanumeric mode. 352 * The characters allowed are: 0 to 9, A to Z (uppercase only), space, 353 * dollar, percent, asterisk, plus, hyphen, period, slash, colon. 354 */ 355 struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]); 356 357 358 /* 359 * Returns a segment representing an Extended Channel Interpretation 360 * (ECI) designator with the given assignment value. 361 */ 362 struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]); 363 364 365 /*---- Functions to extract raw data from QR Codes ----*/ 366 367 /* 368 * Returns the side length of the given QR Code, assuming that encoding succeeded. 369 * The result is in the range [21, 177]. Note that the length of the array buffer 370 * is related to the side length - every 'uint8_t qrcode[]' must have length at least 371 * qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1). 372 */ 373 int qrcodegen_getSize(const uint8_t qrcode[]); 374 375 376 /* 377 * Returns the color of the module (pixel) at the given coordinates, which is false 378 * for light or true for dark. The top left corner has the coordinates (x=0, y=0). 379 * If the given coordinates are out of bounds, then false (light) is returned. 380 */ 381 bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y); 382 383 384 #ifdef __cplusplus 385 } 386 #endif 387