1/* 2 * QR Code generator library (TypeScript) 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"use strict"; 25 26 27namespace qrcodegen { 28 29 type bit = number; 30 type byte = number; 31 type int = number; 32 33 34 /*---- QR Code symbol class ----*/ 35 36 /* 37 * A QR Code symbol, which is a type of two-dimension barcode. 38 * Invented by Denso Wave and described in the ISO/IEC 18004 standard. 39 * Instances of this class represent an immutable square grid of dark and light cells. 40 * The class provides static factory functions to create a QR Code from text or binary data. 41 * The class covers the QR Code Model 2 specification, supporting all versions (sizes) 42 * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. 43 * 44 * Ways to create a QR Code object: 45 * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary(). 46 * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments(). 47 * - Low level: Custom-make the array of data codeword bytes (including 48 * segment headers and final padding, excluding error correction codewords), 49 * supply the appropriate version number, and call the QrCode() constructor. 50 * (Note that all ways require supplying the desired error correction level.) 51 */ 52 export class QrCode { 53 54 /*-- Static factory functions (high level) --*/ 55 56 // Returns a QR Code representing the given Unicode text string at the given error correction level. 57 // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer 58 // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible 59 // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the 60 // ecl argument if it can be done without increasing the version. 61 public static encodeText(text: string, ecl: QrCode.Ecc): QrCode { 62 const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text); 63 return QrCode.encodeSegments(segs, ecl); 64 } 65 66 67 // Returns a QR Code representing the given binary data at the given error correction level. 68 // This function always encodes using the binary segment mode, not any text mode. The maximum number of 69 // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. 70 // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. 71 public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCode.Ecc): QrCode { 72 const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data); 73 return QrCode.encodeSegments([seg], ecl); 74 } 75 76 77 /*-- Static factory functions (mid level) --*/ 78 79 // Returns a QR Code representing the given segments with the given encoding parameters. 80 // The smallest possible QR Code version within the given range is automatically 81 // chosen for the output. Iff boostEcl is true, then the ECC level of the result 82 // may be higher than the ecl argument if it can be done without increasing the 83 // version. The mask number is either between 0 to 7 (inclusive) to force that 84 // mask, or -1 to automatically choose an appropriate mask (which may be slow). 85 // This function allows the user to create a custom sequence of segments that switches 86 // between modes (such as alphanumeric and byte) to encode text in less space. 87 // This is a mid-level API; the high-level API is encodeText() and encodeBinary(). 88 public static encodeSegments(segs: Readonly<Array<QrSegment>>, ecl: QrCode.Ecc, 89 minVersion: int = 1, maxVersion: int = 40, 90 mask: int = -1, boostEcl: boolean = true): QrCode { 91 92 if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) 93 || mask < -1 || mask > 7) 94 throw new RangeError("Invalid value"); 95 96 // Find the minimal version number to use 97 let version: int; 98 let dataUsedBits: int; 99 for (version = minVersion; ; version++) { 100 const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available 101 const usedBits: number = QrSegment.getTotalBits(segs, version); 102 if (usedBits <= dataCapacityBits) { 103 dataUsedBits = usedBits; 104 break; // This version number is found to be suitable 105 } 106 if (version >= maxVersion) // All versions in the range could not fit the given data 107 throw new RangeError("Data too long"); 108 } 109 110 // Increase the error correction level while the data still fits in the current version number 111 for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) { // From low to high 112 if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) 113 ecl = newEcl; 114 } 115 116 // Concatenate all segments to create the data bit string 117 let bb: Array<bit> = [] 118 for (const seg of segs) { 119 appendBits(seg.mode.modeBits, 4, bb); 120 appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb); 121 for (const b of seg.getData()) 122 bb.push(b); 123 } 124 assert(bb.length == dataUsedBits); 125 126 // Add terminator and pad up to a byte if applicable 127 const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; 128 assert(bb.length <= dataCapacityBits); 129 appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); 130 appendBits(0, (8 - bb.length % 8) % 8, bb); 131 assert(bb.length % 8 == 0); 132 133 // Pad with alternating bytes until data capacity is reached 134 for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11) 135 appendBits(padByte, 8, bb); 136 137 // Pack bits into bytes in big endian 138 let dataCodewords: Array<byte> = []; 139 while (dataCodewords.length * 8 < bb.length) 140 dataCodewords.push(0); 141 bb.forEach((b: bit, i: int) => 142 dataCodewords[i >>> 3] |= b << (7 - (i & 7))); 143 144 // Create the QR Code object 145 return new QrCode(version, ecl, dataCodewords, mask); 146 } 147 148 149 /*-- Fields --*/ 150 151 // The width and height of this QR Code, measured in modules, between 152 // 21 and 177 (inclusive). This is equal to version * 4 + 17. 153 public readonly size: int; 154 155 // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). 156 // Even if a QR Code is created with automatic masking requested (mask = -1), 157 // the resulting object still has a mask value between 0 and 7. 158 public readonly mask: int; 159 160 // The modules of this QR Code (false = light, true = dark). 161 // Immutable after constructor finishes. Accessed through getModule(). 162 private readonly modules : Array<Array<boolean>> = []; 163 164 // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. 165 private readonly isFunction: Array<Array<boolean>> = []; 166 167 168 /*-- Constructor (low level) and fields --*/ 169 170 // Creates a new QR Code with the given version number, 171 // error correction level, data codeword bytes, and mask number. 172 // This is a low-level API that most users should not use directly. 173 // A mid-level API is the encodeSegments() function. 174 public constructor( 175 // The version number of this QR Code, which is between 1 and 40 (inclusive). 176 // This determines the size of this barcode. 177 public readonly version: int, 178 179 // The error correction level used in this QR Code. 180 public readonly errorCorrectionLevel: QrCode.Ecc, 181 182 dataCodewords: Readonly<Array<byte>>, 183 184 msk: int) { 185 186 // Check scalar arguments 187 if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) 188 throw new RangeError("Version value out of range"); 189 if (msk < -1 || msk > 7) 190 throw new RangeError("Mask value out of range"); 191 this.size = version * 4 + 17; 192 193 // Initialize both grids to be size*size arrays of Boolean false 194 let row: Array<boolean> = []; 195 for (let i = 0; i < this.size; i++) 196 row.push(false); 197 for (let i = 0; i < this.size; i++) { 198 this.modules .push(row.slice()); // Initially all light 199 this.isFunction.push(row.slice()); 200 } 201 202 // Compute ECC, draw modules 203 this.drawFunctionPatterns(); 204 const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords); 205 this.drawCodewords(allCodewords); 206 207 // Do masking 208 if (msk == -1) { // Automatically choose best mask 209 let minPenalty: int = 1000000000; 210 for (let i = 0; i < 8; i++) { 211 this.applyMask(i); 212 this.drawFormatBits(i); 213 const penalty: int = this.getPenaltyScore(); 214 if (penalty < minPenalty) { 215 msk = i; 216 minPenalty = penalty; 217 } 218 this.applyMask(i); // Undoes the mask due to XOR 219 } 220 } 221 assert(0 <= msk && msk <= 7); 222 this.mask = msk; 223 this.applyMask(msk); // Apply the final choice of mask 224 this.drawFormatBits(msk); // Overwrite old format bits 225 226 this.isFunction = []; 227 } 228 229 230 /*-- Accessor methods --*/ 231 232 // Returns the color of the module (pixel) at the given coordinates, which is false 233 // for light or true for dark. The top left corner has the coordinates (x=0, y=0). 234 // If the given coordinates are out of bounds, then false (light) is returned. 235 public getModule(x: int, y: int): boolean { 236 return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; 237 } 238 239 240 /*-- Private helper methods for constructor: Drawing function modules --*/ 241 242 // Reads this object's version field, and draws and marks all function modules. 243 private drawFunctionPatterns(): void { 244 // Draw horizontal and vertical timing patterns 245 for (let i = 0; i < this.size; i++) { 246 this.setFunctionModule(6, i, i % 2 == 0); 247 this.setFunctionModule(i, 6, i % 2 == 0); 248 } 249 250 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) 251 this.drawFinderPattern(3, 3); 252 this.drawFinderPattern(this.size - 4, 3); 253 this.drawFinderPattern(3, this.size - 4); 254 255 // Draw numerous alignment patterns 256 const alignPatPos: Array<int> = this.getAlignmentPatternPositions(); 257 const numAlign: int = alignPatPos.length; 258 for (let i = 0; i < numAlign; i++) { 259 for (let j = 0; j < numAlign; j++) { 260 // Don't draw on the three finder corners 261 if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0)) 262 this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); 263 } 264 } 265 266 // Draw configuration data 267 this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor 268 this.drawVersion(); 269 } 270 271 272 // Draws two copies of the format bits (with its own error correction code) 273 // based on the given mask and this object's error correction level field. 274 private drawFormatBits(mask: int): void { 275 // Calculate error correction code and pack bits 276 const data: int = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3 277 let rem: int = data; 278 for (let i = 0; i < 10; i++) 279 rem = (rem << 1) ^ ((rem >>> 9) * 0x537); 280 const bits = (data << 10 | rem) ^ 0x5412; // uint15 281 assert(bits >>> 15 == 0); 282 283 // Draw first copy 284 for (let i = 0; i <= 5; i++) 285 this.setFunctionModule(8, i, getBit(bits, i)); 286 this.setFunctionModule(8, 7, getBit(bits, 6)); 287 this.setFunctionModule(8, 8, getBit(bits, 7)); 288 this.setFunctionModule(7, 8, getBit(bits, 8)); 289 for (let i = 9; i < 15; i++) 290 this.setFunctionModule(14 - i, 8, getBit(bits, i)); 291 292 // Draw second copy 293 for (let i = 0; i < 8; i++) 294 this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); 295 for (let i = 8; i < 15; i++) 296 this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); 297 this.setFunctionModule(8, this.size - 8, true); // Always dark 298 } 299 300 301 // Draws two copies of the version bits (with its own error correction code), 302 // based on this object's version field, iff 7 <= version <= 40. 303 private drawVersion(): void { 304 if (this.version < 7) 305 return; 306 307 // Calculate error correction code and pack bits 308 let rem: int = this.version; // version is uint6, in the range [7, 40] 309 for (let i = 0; i < 12; i++) 310 rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25); 311 const bits: int = this.version << 12 | rem; // uint18 312 assert(bits >>> 18 == 0); 313 314 // Draw two copies 315 for (let i = 0; i < 18; i++) { 316 const color: boolean = getBit(bits, i); 317 const a: int = this.size - 11 + i % 3; 318 const b: int = Math.floor(i / 3); 319 this.setFunctionModule(a, b, color); 320 this.setFunctionModule(b, a, color); 321 } 322 } 323 324 325 // Draws a 9*9 finder pattern including the border separator, 326 // with the center module at (x, y). Modules can be out of bounds. 327 private drawFinderPattern(x: int, y: int): void { 328 for (let dy = -4; dy <= 4; dy++) { 329 for (let dx = -4; dx <= 4; dx++) { 330 const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm 331 const xx: int = x + dx; 332 const yy: int = y + dy; 333 if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) 334 this.setFunctionModule(xx, yy, dist != 2 && dist != 4); 335 } 336 } 337 } 338 339 340 // Draws a 5*5 alignment pattern, with the center module 341 // at (x, y). All modules must be in bounds. 342 private drawAlignmentPattern(x: int, y: int): void { 343 for (let dy = -2; dy <= 2; dy++) { 344 for (let dx = -2; dx <= 2; dx++) 345 this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); 346 } 347 } 348 349 350 // Sets the color of a module and marks it as a function module. 351 // Only used by the constructor. Coordinates must be in bounds. 352 private setFunctionModule(x: int, y: int, isDark: boolean): void { 353 this.modules[y][x] = isDark; 354 this.isFunction[y][x] = true; 355 } 356 357 358 /*-- Private helper methods for constructor: Codewords and masking --*/ 359 360 // Returns a new byte string representing the given data with the appropriate error correction 361 // codewords appended to it, based on this object's version and error correction level. 362 private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> { 363 const ver: int = this.version; 364 const ecl: QrCode.Ecc = this.errorCorrectionLevel; 365 if (data.length != QrCode.getNumDataCodewords(ver, ecl)) 366 throw new RangeError("Invalid argument"); 367 368 // Calculate parameter numbers 369 const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; 370 const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver]; 371 const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8); 372 const numShortBlocks: int = numBlocks - rawCodewords % numBlocks; 373 const shortBlockLen: int = Math.floor(rawCodewords / numBlocks); 374 375 // Split data into blocks and append ECC to each block 376 let blocks: Array<Array<byte>> = []; 377 const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen); 378 for (let i = 0, k = 0; i < numBlocks; i++) { 379 let dat: Array<byte> = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); 380 k += dat.length; 381 const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv); 382 if (i < numShortBlocks) 383 dat.push(0); 384 blocks.push(dat.concat(ecc)); 385 } 386 387 // Interleave (not concatenate) the bytes from every block into a single sequence 388 let result: Array<byte> = []; 389 for (let i = 0; i < blocks[0].length; i++) { 390 blocks.forEach((block, j) => { 391 // Skip the padding byte in short blocks 392 if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) 393 result.push(block[i]); 394 }); 395 } 396 assert(result.length == rawCodewords); 397 return result; 398 } 399 400 401 // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire 402 // data area of this QR Code. Function modules need to be marked off before this is called. 403 private drawCodewords(data: Readonly<Array<byte>>): void { 404 if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) 405 throw new RangeError("Invalid argument"); 406 let i: int = 0; // Bit index into the data 407 // Do the funny zigzag scan 408 for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair 409 if (right == 6) 410 right = 5; 411 for (let vert = 0; vert < this.size; vert++) { // Vertical counter 412 for (let j = 0; j < 2; j++) { 413 const x: int = right - j; // Actual x coordinate 414 const upward: boolean = ((right + 1) & 2) == 0; 415 const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate 416 if (!this.isFunction[y][x] && i < data.length * 8) { 417 this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); 418 i++; 419 } 420 // If this QR Code has any remainder bits (0 to 7), they were assigned as 421 // 0/false/light by the constructor and are left unchanged by this method 422 } 423 } 424 } 425 assert(i == data.length * 8); 426 } 427 428 429 // XORs the codeword modules in this QR Code with the given mask pattern. 430 // The function modules must be marked and the codeword bits must be drawn 431 // before masking. Due to the arithmetic of XOR, calling applyMask() with 432 // the same mask value a second time will undo the mask. A final well-formed 433 // QR Code needs exactly one (not zero, two, etc.) mask applied. 434 private applyMask(mask: int): void { 435 if (mask < 0 || mask > 7) 436 throw new RangeError("Mask value out of range"); 437 for (let y = 0; y < this.size; y++) { 438 for (let x = 0; x < this.size; x++) { 439 let invert: boolean; 440 switch (mask) { 441 case 0: invert = (x + y) % 2 == 0; break; 442 case 1: invert = y % 2 == 0; break; 443 case 2: invert = x % 3 == 0; break; 444 case 3: invert = (x + y) % 3 == 0; break; 445 case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0; break; 446 case 5: invert = x * y % 2 + x * y % 3 == 0; break; 447 case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; 448 case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; 449 default: throw new Error("Unreachable"); 450 } 451 if (!this.isFunction[y][x] && invert) 452 this.modules[y][x] = !this.modules[y][x]; 453 } 454 } 455 } 456 457 458 // Calculates and returns the penalty score based on state of this QR Code's current modules. 459 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. 460 private getPenaltyScore(): int { 461 let result: int = 0; 462 463 // Adjacent modules in row having same color, and finder-like patterns 464 for (let y = 0; y < this.size; y++) { 465 let runColor = false; 466 let runX = 0; 467 let runHistory = [0,0,0,0,0,0,0]; 468 for (let x = 0; x < this.size; x++) { 469 if (this.modules[y][x] == runColor) { 470 runX++; 471 if (runX == 5) 472 result += QrCode.PENALTY_N1; 473 else if (runX > 5) 474 result++; 475 } else { 476 this.finderPenaltyAddHistory(runX, runHistory); 477 if (!runColor) 478 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; 479 runColor = this.modules[y][x]; 480 runX = 1; 481 } 482 } 483 result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3; 484 } 485 // Adjacent modules in column having same color, and finder-like patterns 486 for (let x = 0; x < this.size; x++) { 487 let runColor = false; 488 let runY = 0; 489 let runHistory = [0,0,0,0,0,0,0]; 490 for (let y = 0; y < this.size; y++) { 491 if (this.modules[y][x] == runColor) { 492 runY++; 493 if (runY == 5) 494 result += QrCode.PENALTY_N1; 495 else if (runY > 5) 496 result++; 497 } else { 498 this.finderPenaltyAddHistory(runY, runHistory); 499 if (!runColor) 500 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; 501 runColor = this.modules[y][x]; 502 runY = 1; 503 } 504 } 505 result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3; 506 } 507 508 // 2*2 blocks of modules having same color 509 for (let y = 0; y < this.size - 1; y++) { 510 for (let x = 0; x < this.size - 1; x++) { 511 const color: boolean = this.modules[y][x]; 512 if ( color == this.modules[y][x + 1] && 513 color == this.modules[y + 1][x] && 514 color == this.modules[y + 1][x + 1]) 515 result += QrCode.PENALTY_N2; 516 } 517 } 518 519 // Balance of dark and light modules 520 let dark: int = 0; 521 for (const row of this.modules) 522 dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark); 523 const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2 524 // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% 525 const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; 526 assert(0 <= k && k <= 9); 527 result += k * QrCode.PENALTY_N4; 528 assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 529 return result; 530 } 531 532 533 /*-- Private helper functions --*/ 534 535 // Returns an ascending list of positions of alignment patterns for this version number. 536 // Each position is in the range [0,177), and are used on both the x and y axes. 537 // This could be implemented as lookup table of 40 variable-length lists of integers. 538 private getAlignmentPatternPositions(): Array<int> { 539 if (this.version == 1) 540 return []; 541 else { 542 const numAlign: int = Math.floor(this.version / 7) + 2; 543 const step: int = (this.version == 32) ? 26 : 544 Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2; 545 let result: Array<int> = [6]; 546 for (let pos = this.size - 7; result.length < numAlign; pos -= step) 547 result.splice(1, 0, pos); 548 return result; 549 } 550 } 551 552 553 // Returns the number of data bits that can be stored in a QR Code of the given version number, after 554 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. 555 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. 556 private static getNumRawDataModules(ver: int): int { 557 if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) 558 throw new RangeError("Version number out of range"); 559 let result: int = (16 * ver + 128) * ver + 64; 560 if (ver >= 2) { 561 const numAlign: int = Math.floor(ver / 7) + 2; 562 result -= (25 * numAlign - 10) * numAlign - 55; 563 if (ver >= 7) 564 result -= 36; 565 } 566 assert(208 <= result && result <= 29648); 567 return result; 568 } 569 570 571 // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any 572 // QR Code of the given version number and error correction level, with remainder bits discarded. 573 // This stateless pure function could be implemented as a (40*4)-cell lookup table. 574 private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int { 575 return Math.floor(QrCode.getNumRawDataModules(ver) / 8) - 576 QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] * 577 QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; 578 } 579 580 581 // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be 582 // implemented as a lookup table over all possible parameter values, instead of as an algorithm. 583 private static reedSolomonComputeDivisor(degree: int): Array<byte> { 584 if (degree < 1 || degree > 255) 585 throw new RangeError("Degree out of range"); 586 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. 587 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93]. 588 let result: Array<byte> = []; 589 for (let i = 0; i < degree - 1; i++) 590 result.push(0); 591 result.push(1); // Start off with the monomial x^0 592 593 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), 594 // and drop the highest monomial term which is always 1x^degree. 595 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). 596 let root = 1; 597 for (let i = 0; i < degree; i++) { 598 // Multiply the current product by (x - r^i) 599 for (let j = 0; j < result.length; j++) { 600 result[j] = QrCode.reedSolomonMultiply(result[j], root); 601 if (j + 1 < result.length) 602 result[j] ^= result[j + 1]; 603 } 604 root = QrCode.reedSolomonMultiply(root, 0x02); 605 } 606 return result; 607 } 608 609 610 // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. 611 private static reedSolomonComputeRemainder(data: Readonly<Array<byte>>, divisor: Readonly<Array<byte>>): Array<byte> { 612 let result: Array<byte> = divisor.map(_ => 0); 613 for (const b of data) { // Polynomial division 614 const factor: byte = b ^ (result.shift() as byte); 615 result.push(0); 616 divisor.forEach((coef, i) => 617 result[i] ^= QrCode.reedSolomonMultiply(coef, factor)); 618 } 619 return result; 620 } 621 622 623 // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result 624 // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. 625 private static reedSolomonMultiply(x: byte, y: byte): byte { 626 if (x >>> 8 != 0 || y >>> 8 != 0) 627 throw new RangeError("Byte out of range"); 628 // Russian peasant multiplication 629 let z: int = 0; 630 for (let i = 7; i >= 0; i--) { 631 z = (z << 1) ^ ((z >>> 7) * 0x11D); 632 z ^= ((y >>> i) & 1) * x; 633 } 634 assert(z >>> 8 == 0); 635 return z as byte; 636 } 637 638 639 // Can only be called immediately after a light run is added, and 640 // returns either 0, 1, or 2. A helper function for getPenaltyScore(). 641 private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int { 642 const n: int = runHistory[1]; 643 assert(n <= this.size * 3); 644 const core: boolean = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; 645 return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) 646 + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); 647 } 648 649 650 // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). 651 private finderPenaltyTerminateAndCount(currentRunColor: boolean, currentRunLength: int, runHistory: Array<int>): int { 652 if (currentRunColor) { // Terminate dark run 653 this.finderPenaltyAddHistory(currentRunLength, runHistory); 654 currentRunLength = 0; 655 } 656 currentRunLength += this.size; // Add light border to final run 657 this.finderPenaltyAddHistory(currentRunLength, runHistory); 658 return this.finderPenaltyCountPatterns(runHistory); 659 } 660 661 662 // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). 663 private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void { 664 if (runHistory[0] == 0) 665 currentRunLength += this.size; // Add light border to initial run 666 runHistory.pop(); 667 runHistory.unshift(currentRunLength); 668 } 669 670 671 /*-- Constants and tables --*/ 672 673 // The minimum version number supported in the QR Code Model 2 standard. 674 public static readonly MIN_VERSION: int = 1; 675 // The maximum version number supported in the QR Code Model 2 standard. 676 public static readonly MAX_VERSION: int = 40; 677 678 // For use in getPenaltyScore(), when evaluating which mask is best. 679 private static readonly PENALTY_N1: int = 3; 680 private static readonly PENALTY_N2: int = 3; 681 private static readonly PENALTY_N3: int = 40; 682 private static readonly PENALTY_N4: int = 10; 683 684 private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [ 685 // Version: (note that index 0 is for padding, and is set to an illegal value) 686 //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 687 [-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 688 [-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 689 [-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 690 [-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 691 ]; 692 693 private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [ 694 // Version: (note that index 0 is for padding, and is set to an illegal value) 695 //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 696 [-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 697 [-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 698 [-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 699 [-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 700 ]; 701 702 } 703 704 705 // Appends the given number of low-order bits of the given value 706 // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len. 707 function appendBits(val: int, len: int, bb: Array<bit>): void { 708 if (len < 0 || len > 31 || val >>> len != 0) 709 throw new RangeError("Value out of range"); 710 for (let i = len - 1; i >= 0; i--) // Append bit by bit 711 bb.push((val >>> i) & 1); 712 } 713 714 715 // Returns true iff the i'th bit of x is set to 1. 716 function getBit(x: int, i: int): boolean { 717 return ((x >>> i) & 1) != 0; 718 } 719 720 721 // Throws an exception if the given condition is false. 722 function assert(cond: boolean): void { 723 if (!cond) 724 throw new Error("Assertion error"); 725 } 726 727 728 729 /*---- Data segment class ----*/ 730 731 /* 732 * A segment of character/binary/control data in a QR Code symbol. 733 * Instances of this class are immutable. 734 * The mid-level way to create a segment is to take the payload data 735 * and call a static factory function such as QrSegment.makeNumeric(). 736 * The low-level way to create a segment is to custom-make the bit buffer 737 * and call the QrSegment() constructor with appropriate values. 738 * This segment class imposes no length restrictions, but QR Codes have restrictions. 739 * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. 740 * Any segment longer than this is meaningless for the purpose of generating QR Codes. 741 */ 742 export class QrSegment { 743 744 /*-- Static factory functions (mid level) --*/ 745 746 // Returns a segment representing the given binary data encoded in 747 // byte mode. All input byte arrays are acceptable. Any text string 748 // can be converted to UTF-8 bytes and encoded as a byte mode segment. 749 public static makeBytes(data: Readonly<Array<byte>>): QrSegment { 750 let bb: Array<bit> = [] 751 for (const b of data) 752 appendBits(b, 8, bb); 753 return new QrSegment(QrSegment.Mode.BYTE, data.length, bb); 754 } 755 756 757 // Returns a segment representing the given string of decimal digits encoded in numeric mode. 758 public static makeNumeric(digits: string): QrSegment { 759 if (!QrSegment.isNumeric(digits)) 760 throw new RangeError("String contains non-numeric characters"); 761 let bb: Array<bit> = [] 762 for (let i = 0; i < digits.length; ) { // Consume up to 3 digits per iteration 763 const n: int = Math.min(digits.length - i, 3); 764 appendBits(parseInt(digits.substr(i, n), 10), n * 3 + 1, bb); 765 i += n; 766 } 767 return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb); 768 } 769 770 771 // Returns a segment representing the given text string encoded in alphanumeric mode. 772 // The characters allowed are: 0 to 9, A to Z (uppercase only), space, 773 // dollar, percent, asterisk, plus, hyphen, period, slash, colon. 774 public static makeAlphanumeric(text: string): QrSegment { 775 if (!QrSegment.isAlphanumeric(text)) 776 throw new RangeError("String contains unencodable characters in alphanumeric mode"); 777 let bb: Array<bit> = [] 778 let i: int; 779 for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2 780 let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; 781 temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); 782 appendBits(temp, 11, bb); 783 } 784 if (i < text.length) // 1 character remaining 785 appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb); 786 return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb); 787 } 788 789 790 // Returns a new mutable list of zero or more segments to represent the given Unicode text string. 791 // The result may use various segment modes and switch modes to optimize the length of the bit stream. 792 public static makeSegments(text: string): Array<QrSegment> { 793 // Select the most efficient segment encoding automatically 794 if (text == "") 795 return []; 796 else if (QrSegment.isNumeric(text)) 797 return [QrSegment.makeNumeric(text)]; 798 else if (QrSegment.isAlphanumeric(text)) 799 return [QrSegment.makeAlphanumeric(text)]; 800 else 801 return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))]; 802 } 803 804 805 // Returns a segment representing an Extended Channel Interpretation 806 // (ECI) designator with the given assignment value. 807 public static makeEci(assignVal: int): QrSegment { 808 let bb: Array<bit> = [] 809 if (assignVal < 0) 810 throw new RangeError("ECI assignment value out of range"); 811 else if (assignVal < (1 << 7)) 812 appendBits(assignVal, 8, bb); 813 else if (assignVal < (1 << 14)) { 814 appendBits(0b10, 2, bb); 815 appendBits(assignVal, 14, bb); 816 } else if (assignVal < 1000000) { 817 appendBits(0b110, 3, bb); 818 appendBits(assignVal, 21, bb); 819 } else 820 throw new RangeError("ECI assignment value out of range"); 821 return new QrSegment(QrSegment.Mode.ECI, 0, bb); 822 } 823 824 825 // Tests whether the given string can be encoded as a segment in numeric mode. 826 // A string is encodable iff each character is in the range 0 to 9. 827 public static isNumeric(text: string): boolean { 828 return QrSegment.NUMERIC_REGEX.test(text); 829 } 830 831 832 // Tests whether the given string can be encoded as a segment in alphanumeric mode. 833 // A string is encodable iff each character is in the following set: 0 to 9, A to Z 834 // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. 835 public static isAlphanumeric(text: string): boolean { 836 return QrSegment.ALPHANUMERIC_REGEX.test(text); 837 } 838 839 840 /*-- Constructor (low level) and fields --*/ 841 842 // Creates a new QR Code segment with the given attributes and data. 843 // The character count (numChars) must agree with the mode and the bit buffer length, 844 // but the constraint isn't checked. The given bit buffer is cloned and stored. 845 public constructor( 846 // The mode indicator of this segment. 847 public readonly mode: QrSegment.Mode, 848 849 // The length of this segment's unencoded data. Measured in characters for 850 // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. 851 // Always zero or positive. Not the same as the data's bit length. 852 public readonly numChars: int, 853 854 // The data bits of this segment. Accessed through getData(). 855 private readonly bitData: Array<bit>) { 856 857 if (numChars < 0) 858 throw new RangeError("Invalid argument"); 859 this.bitData = bitData.slice(); // Make defensive copy 860 } 861 862 863 /*-- Methods --*/ 864 865 // Returns a new copy of the data bits of this segment. 866 public getData(): Array<bit> { 867 return this.bitData.slice(); // Make defensive copy 868 } 869 870 871 // (Package-private) Calculates and returns the number of bits needed to encode the given segments at 872 // the given version. The result is infinity if a segment has too many characters to fit its length field. 873 public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number { 874 let result: number = 0; 875 for (const seg of segs) { 876 const ccbits: int = seg.mode.numCharCountBits(version); 877 if (seg.numChars >= (1 << ccbits)) 878 return Infinity; // The segment's length doesn't fit the field's bit width 879 result += 4 + ccbits + seg.bitData.length; 880 } 881 return result; 882 } 883 884 885 // Returns a new array of bytes representing the given string encoded in UTF-8. 886 private static toUtf8ByteArray(str: string): Array<byte> { 887 str = encodeURI(str); 888 let result: Array<byte> = []; 889 for (let i = 0; i < str.length; i++) { 890 if (str.charAt(i) != "%") 891 result.push(str.charCodeAt(i)); 892 else { 893 result.push(parseInt(str.substr(i + 1, 2), 16)); 894 i += 2; 895 } 896 } 897 return result; 898 } 899 900 901 /*-- Constants --*/ 902 903 // Describes precisely all strings that are encodable in numeric mode. 904 private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/; 905 906 // Describes precisely all strings that are encodable in alphanumeric mode. 907 private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/; 908 909 // The set of all legal characters in alphanumeric mode, 910 // where each character value maps to the index in the string. 911 private static readonly ALPHANUMERIC_CHARSET: string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; 912 913 } 914 915} 916 917 918 919/*---- Public helper enumeration ----*/ 920 921namespace qrcodegen.QrCode { 922 923 type int = number; 924 925 926 /* 927 * The error correction level in a QR Code symbol. Immutable. 928 */ 929 export class Ecc { 930 931 /*-- Constants --*/ 932 933 public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords 934 public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords 935 public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords 936 public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords 937 938 939 /*-- Constructor and fields --*/ 940 941 private constructor( 942 // In the range 0 to 3 (unsigned 2-bit integer). 943 public readonly ordinal: int, 944 // (Package-private) In the range 0 to 3 (unsigned 2-bit integer). 945 public readonly formatBits: int) {} 946 947 } 948} 949 950 951 952/*---- Public helper enumeration ----*/ 953 954namespace qrcodegen.QrSegment { 955 956 type int = number; 957 958 959 /* 960 * Describes how a segment's data bits are interpreted. Immutable. 961 */ 962 export class Mode { 963 964 /*-- Constants --*/ 965 966 public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]); 967 public static readonly ALPHANUMERIC = new Mode(0x2, [ 9, 11, 13]); 968 public static readonly BYTE = new Mode(0x4, [ 8, 16, 16]); 969 public static readonly KANJI = new Mode(0x8, [ 8, 10, 12]); 970 public static readonly ECI = new Mode(0x7, [ 0, 0, 0]); 971 972 973 /*-- Constructor and fields --*/ 974 975 private constructor( 976 // The mode indicator bits, which is a uint4 value (range 0 to 15). 977 public readonly modeBits: int, 978 // Number of character count bits for three different version ranges. 979 private readonly numBitsCharCount: [int,int,int]) {} 980 981 982 /*-- Method --*/ 983 984 // (Package-private) Returns the bit width of the character count field for a segment in 985 // this mode in a QR Code at the given version number. The result is in the range [0, 16]. 986 public numCharCountBits(ver: int): int { 987 return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; 988 } 989 990 } 991} 992