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: 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: 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 "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 "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 if (bb.length != dataUsedBits) 125 throw "Assertion error"; 126 127 // Add terminator and pad up to a byte if applicable 128 const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; 129 if (bb.length > dataCapacityBits) 130 throw "Assertion error"; 131 appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); 132 appendBits(0, (8 - bb.length % 8) % 8, bb); 133 if (bb.length % 8 != 0) 134 throw "Assertion error"; 135 136 // Pad with alternating bytes until data capacity is reached 137 for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11) 138 appendBits(padByte, 8, bb); 139 140 // Pack bits into bytes in big endian 141 let dataCodewords: Array<byte> = []; 142 while (dataCodewords.length * 8 < bb.length) 143 dataCodewords.push(0); 144 bb.forEach((b: bit, i: int) => 145 dataCodewords[i >>> 3] |= b << (7 - (i & 7))); 146 147 // Create the QR Code object 148 return new QrCode(version, ecl, dataCodewords, mask); 149 } 150 151 152 /*-- Fields --*/ 153 154 // The width and height of this QR Code, measured in modules, between 155 // 21 and 177 (inclusive). This is equal to version * 4 + 17. 156 public readonly size: int; 157 158 // The modules of this QR Code (false = light, true = dark). 159 // Immutable after constructor finishes. Accessed through getModule(). 160 private readonly modules : Array<Array<boolean>> = []; 161 162 // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. 163 private readonly isFunction: Array<Array<boolean>> = []; 164 165 166 /*-- Constructor (low level) and fields --*/ 167 168 // Creates a new QR Code with the given version number, 169 // error correction level, data codeword bytes, and mask number. 170 // This is a low-level API that most users should not use directly. 171 // A mid-level API is the encodeSegments() function. 172 public constructor( 173 // The version number of this QR Code, which is between 1 and 40 (inclusive). 174 // This determines the size of this barcode. 175 public readonly version: int, 176 177 // The error correction level used in this QR Code. 178 public readonly errorCorrectionLevel: QrCode.Ecc, 179 180 dataCodewords: Array<byte>, 181 182 // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). 183 // Even if a QR Code is created with automatic masking requested (mask = -1), 184 // the resulting object still has a mask value between 0 and 7. 185 public readonly mask: int) { 186 187 // Check scalar arguments 188 if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) 189 throw "Version value out of range"; 190 if (mask < -1 || mask > 7) 191 throw "Mask value out of range"; 192 this.size = version * 4 + 17; 193 194 // Initialize both grids to be size*size arrays of Boolean false 195 let row: Array<boolean> = []; 196 for (let i = 0; i < this.size; i++) 197 row.push(false); 198 for (let i = 0; i < this.size; i++) { 199 this.modules .push(row.slice()); // Initially all light 200 this.isFunction.push(row.slice()); 201 } 202 203 // Compute ECC, draw modules 204 this.drawFunctionPatterns(); 205 const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords); 206 this.drawCodewords(allCodewords); 207 208 // Do masking 209 if (mask == -1) { // Automatically choose best mask 210 let minPenalty: int = 1000000000; 211 for (let i = 0; i < 8; i++) { 212 this.applyMask(i); 213 this.drawFormatBits(i); 214 const penalty: int = this.getPenaltyScore(); 215 if (penalty < minPenalty) { 216 mask = i; 217 minPenalty = penalty; 218 } 219 this.applyMask(i); // Undoes the mask due to XOR 220 } 221 } 222 if (mask < 0 || mask > 7) 223 throw "Assertion error"; 224 this.mask = mask; 225 this.applyMask(mask); // Apply the final choice of mask 226 this.drawFormatBits(mask); // Overwrite old format bits 227 228 this.isFunction = []; 229 } 230 231 232 /*-- Accessor methods --*/ 233 234 // Returns the color of the module (pixel) at the given coordinates, which is false 235 // for light or true for dark. The top left corner has the coordinates (x=0, y=0). 236 // If the given coordinates are out of bounds, then false (light) is returned. 237 public getModule(x: int, y: int): boolean { 238 return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; 239 } 240 241 242 /*-- Private helper methods for constructor: Drawing function modules --*/ 243 244 // Reads this object's version field, and draws and marks all function modules. 245 private drawFunctionPatterns(): void { 246 // Draw horizontal and vertical timing patterns 247 for (let i = 0; i < this.size; i++) { 248 this.setFunctionModule(6, i, i % 2 == 0); 249 this.setFunctionModule(i, 6, i % 2 == 0); 250 } 251 252 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) 253 this.drawFinderPattern(3, 3); 254 this.drawFinderPattern(this.size - 4, 3); 255 this.drawFinderPattern(3, this.size - 4); 256 257 // Draw numerous alignment patterns 258 const alignPatPos: Array<int> = this.getAlignmentPatternPositions(); 259 const numAlign: int = alignPatPos.length; 260 for (let i = 0; i < numAlign; i++) { 261 for (let j = 0; j < numAlign; j++) { 262 // Don't draw on the three finder corners 263 if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0)) 264 this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); 265 } 266 } 267 268 // Draw configuration data 269 this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor 270 this.drawVersion(); 271 } 272 273 274 // Draws two copies of the format bits (with its own error correction code) 275 // based on the given mask and this object's error correction level field. 276 private drawFormatBits(mask: int): void { 277 // Calculate error correction code and pack bits 278 const data: int = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3 279 let rem: int = data; 280 for (let i = 0; i < 10; i++) 281 rem = (rem << 1) ^ ((rem >>> 9) * 0x537); 282 const bits = (data << 10 | rem) ^ 0x5412; // uint15 283 if (bits >>> 15 != 0) 284 throw "Assertion error"; 285 286 // Draw first copy 287 for (let i = 0; i <= 5; i++) 288 this.setFunctionModule(8, i, getBit(bits, i)); 289 this.setFunctionModule(8, 7, getBit(bits, 6)); 290 this.setFunctionModule(8, 8, getBit(bits, 7)); 291 this.setFunctionModule(7, 8, getBit(bits, 8)); 292 for (let i = 9; i < 15; i++) 293 this.setFunctionModule(14 - i, 8, getBit(bits, i)); 294 295 // Draw second copy 296 for (let i = 0; i < 8; i++) 297 this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); 298 for (let i = 8; i < 15; i++) 299 this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); 300 this.setFunctionModule(8, this.size - 8, true); // Always dark 301 } 302 303 304 // Draws two copies of the version bits (with its own error correction code), 305 // based on this object's version field, iff 7 <= version <= 40. 306 private drawVersion(): void { 307 if (this.version < 7) 308 return; 309 310 // Calculate error correction code and pack bits 311 let rem: int = this.version; // version is uint6, in the range [7, 40] 312 for (let i = 0; i < 12; i++) 313 rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25); 314 const bits: int = this.version << 12 | rem; // uint18 315 if (bits >>> 18 != 0) 316 throw "Assertion error"; 317 318 // Draw two copies 319 for (let i = 0; i < 18; i++) { 320 const color: boolean = getBit(bits, i); 321 const a: int = this.size - 11 + i % 3; 322 const b: int = Math.floor(i / 3); 323 this.setFunctionModule(a, b, color); 324 this.setFunctionModule(b, a, color); 325 } 326 } 327 328 329 // Draws a 9*9 finder pattern including the border separator, 330 // with the center module at (x, y). Modules can be out of bounds. 331 private drawFinderPattern(x: int, y: int): void { 332 for (let dy = -4; dy <= 4; dy++) { 333 for (let dx = -4; dx <= 4; dx++) { 334 const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm 335 const xx: int = x + dx; 336 const yy: int = y + dy; 337 if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) 338 this.setFunctionModule(xx, yy, dist != 2 && dist != 4); 339 } 340 } 341 } 342 343 344 // Draws a 5*5 alignment pattern, with the center module 345 // at (x, y). All modules must be in bounds. 346 private drawAlignmentPattern(x: int, y: int): void { 347 for (let dy = -2; dy <= 2; dy++) { 348 for (let dx = -2; dx <= 2; dx++) 349 this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); 350 } 351 } 352 353 354 // Sets the color of a module and marks it as a function module. 355 // Only used by the constructor. Coordinates must be in bounds. 356 private setFunctionModule(x: int, y: int, isDark: boolean): void { 357 this.modules[y][x] = isDark; 358 this.isFunction[y][x] = true; 359 } 360 361 362 /*-- Private helper methods for constructor: Codewords and masking --*/ 363 364 // Returns a new byte string representing the given data with the appropriate error correction 365 // codewords appended to it, based on this object's version and error correction level. 366 private addEccAndInterleave(data: Array<byte>): Array<byte> { 367 const ver: int = this.version; 368 const ecl: QrCode.Ecc = this.errorCorrectionLevel; 369 if (data.length != QrCode.getNumDataCodewords(ver, ecl)) 370 throw "Invalid argument"; 371 372 // Calculate parameter numbers 373 const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; 374 const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver]; 375 const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8); 376 const numShortBlocks: int = numBlocks - rawCodewords % numBlocks; 377 const shortBlockLen: int = Math.floor(rawCodewords / numBlocks); 378 379 // Split data into blocks and append ECC to each block 380 let blocks: Array<Array<byte>> = []; 381 const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen); 382 for (let i = 0, k = 0; i < numBlocks; i++) { 383 let dat: Array<byte> = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); 384 k += dat.length; 385 const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv); 386 if (i < numShortBlocks) 387 dat.push(0); 388 blocks.push(dat.concat(ecc)); 389 } 390 391 // Interleave (not concatenate) the bytes from every block into a single sequence 392 let result: Array<byte> = []; 393 for (let i = 0; i < blocks[0].length; i++) { 394 blocks.forEach((block, j) => { 395 // Skip the padding byte in short blocks 396 if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) 397 result.push(block[i]); 398 }); 399 } 400 if (result.length != rawCodewords) 401 throw "Assertion error"; 402 return result; 403 } 404 405 406 // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire 407 // data area of this QR Code. Function modules need to be marked off before this is called. 408 private drawCodewords(data: Array<byte>): void { 409 if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) 410 throw "Invalid argument"; 411 let i: int = 0; // Bit index into the data 412 // Do the funny zigzag scan 413 for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair 414 if (right == 6) 415 right = 5; 416 for (let vert = 0; vert < this.size; vert++) { // Vertical counter 417 for (let j = 0; j < 2; j++) { 418 const x: int = right - j; // Actual x coordinate 419 const upward: boolean = ((right + 1) & 2) == 0; 420 const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate 421 if (!this.isFunction[y][x] && i < data.length * 8) { 422 this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); 423 i++; 424 } 425 // If this QR Code has any remainder bits (0 to 7), they were assigned as 426 // 0/false/light by the constructor and are left unchanged by this method 427 } 428 } 429 } 430 if (i != data.length * 8) 431 throw "Assertion error"; 432 } 433 434 435 // XORs the codeword modules in this QR Code with the given mask pattern. 436 // The function modules must be marked and the codeword bits must be drawn 437 // before masking. Due to the arithmetic of XOR, calling applyMask() with 438 // the same mask value a second time will undo the mask. A final well-formed 439 // QR Code needs exactly one (not zero, two, etc.) mask applied. 440 private applyMask(mask: int): void { 441 if (mask < 0 || mask > 7) 442 throw "Mask value out of range"; 443 for (let y = 0; y < this.size; y++) { 444 for (let x = 0; x < this.size; x++) { 445 let invert: boolean; 446 switch (mask) { 447 case 0: invert = (x + y) % 2 == 0; break; 448 case 1: invert = y % 2 == 0; break; 449 case 2: invert = x % 3 == 0; break; 450 case 3: invert = (x + y) % 3 == 0; break; 451 case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0; break; 452 case 5: invert = x * y % 2 + x * y % 3 == 0; break; 453 case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; 454 case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; 455 default: throw "Assertion error"; 456 } 457 if (!this.isFunction[y][x] && invert) 458 this.modules[y][x] = !this.modules[y][x]; 459 } 460 } 461 } 462 463 464 // Calculates and returns the penalty score based on state of this QR Code's current modules. 465 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. 466 private getPenaltyScore(): int { 467 let result: int = 0; 468 469 // Adjacent modules in row having same color, and finder-like patterns 470 for (let y = 0; y < this.size; y++) { 471 let runColor = false; 472 let runX = 0; 473 let runHistory = [0,0,0,0,0,0,0]; 474 for (let x = 0; x < this.size; x++) { 475 if (this.modules[y][x] == runColor) { 476 runX++; 477 if (runX == 5) 478 result += QrCode.PENALTY_N1; 479 else if (runX > 5) 480 result++; 481 } else { 482 this.finderPenaltyAddHistory(runX, runHistory); 483 if (!runColor) 484 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; 485 runColor = this.modules[y][x]; 486 runX = 1; 487 } 488 } 489 result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3; 490 } 491 // Adjacent modules in column having same color, and finder-like patterns 492 for (let x = 0; x < this.size; x++) { 493 let runColor = false; 494 let runY = 0; 495 let runHistory = [0,0,0,0,0,0,0]; 496 for (let y = 0; y < this.size; y++) { 497 if (this.modules[y][x] == runColor) { 498 runY++; 499 if (runY == 5) 500 result += QrCode.PENALTY_N1; 501 else if (runY > 5) 502 result++; 503 } else { 504 this.finderPenaltyAddHistory(runY, runHistory); 505 if (!runColor) 506 result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; 507 runColor = this.modules[y][x]; 508 runY = 1; 509 } 510 } 511 result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3; 512 } 513 514 // 2*2 blocks of modules having same color 515 for (let y = 0; y < this.size - 1; y++) { 516 for (let x = 0; x < this.size - 1; x++) { 517 const color: boolean = this.modules[y][x]; 518 if ( color == this.modules[y][x + 1] && 519 color == this.modules[y + 1][x] && 520 color == this.modules[y + 1][x + 1]) 521 result += QrCode.PENALTY_N2; 522 } 523 } 524 525 // Balance of dark and light modules 526 let dark: int = 0; 527 for (const row of this.modules) 528 dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark); 529 const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2 530 // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% 531 const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; 532 result += k * QrCode.PENALTY_N4; 533 return result; 534 } 535 536 537 /*-- Private helper functions --*/ 538 539 // Returns an ascending list of positions of alignment patterns for this version number. 540 // Each position is in the range [0,177), and are used on both the x and y axes. 541 // This could be implemented as lookup table of 40 variable-length lists of integers. 542 private getAlignmentPatternPositions(): Array<int> { 543 if (this.version == 1) 544 return []; 545 else { 546 const numAlign: int = Math.floor(this.version / 7) + 2; 547 const step: int = (this.version == 32) ? 26 : 548 Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2; 549 let result: Array<int> = [6]; 550 for (let pos = this.size - 7; result.length < numAlign; pos -= step) 551 result.splice(1, 0, pos); 552 return result; 553 } 554 } 555 556 557 // Returns the number of data bits that can be stored in a QR Code of the given version number, after 558 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. 559 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. 560 private static getNumRawDataModules(ver: int): int { 561 if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) 562 throw "Version number out of range"; 563 let result: int = (16 * ver + 128) * ver + 64; 564 if (ver >= 2) { 565 const numAlign: int = Math.floor(ver / 7) + 2; 566 result -= (25 * numAlign - 10) * numAlign - 55; 567 if (ver >= 7) 568 result -= 36; 569 } 570 if (!(208 <= result && result <= 29648)) 571 throw "Assertion error"; 572 return result; 573 } 574 575 576 // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any 577 // QR Code of the given version number and error correction level, with remainder bits discarded. 578 // This stateless pure function could be implemented as a (40*4)-cell lookup table. 579 private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int { 580 return Math.floor(QrCode.getNumRawDataModules(ver) / 8) - 581 QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] * 582 QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; 583 } 584 585 586 // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be 587 // implemented as a lookup table over all possible parameter values, instead of as an algorithm. 588 private static reedSolomonComputeDivisor(degree: int): Array<byte> { 589 if (degree < 1 || degree > 255) 590 throw "Degree out of range"; 591 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. 592 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93]. 593 let result: Array<byte> = []; 594 for (let i = 0; i < degree - 1; i++) 595 result.push(0); 596 result.push(1); // Start off with the monomial x^0 597 598 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), 599 // and drop the highest monomial term which is always 1x^degree. 600 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). 601 let root = 1; 602 for (let i = 0; i < degree; i++) { 603 // Multiply the current product by (x - r^i) 604 for (let j = 0; j < result.length; j++) { 605 result[j] = QrCode.reedSolomonMultiply(result[j], root); 606 if (j + 1 < result.length) 607 result[j] ^= result[j + 1]; 608 } 609 root = QrCode.reedSolomonMultiply(root, 0x02); 610 } 611 return result; 612 } 613 614 615 // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. 616 private static reedSolomonComputeRemainder(data: Array<byte>, divisor: Array<byte>): Array<byte> { 617 let result: Array<byte> = divisor.map(_ => 0); 618 for (const b of data) { // Polynomial division 619 const factor: byte = b ^ (result.shift() as byte); 620 result.push(0); 621 divisor.forEach((coef, i) => 622 result[i] ^= QrCode.reedSolomonMultiply(coef, factor)); 623 } 624 return result; 625 } 626 627 628 // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result 629 // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. 630 private static reedSolomonMultiply(x: byte, y: byte): byte { 631 if (x >>> 8 != 0 || y >>> 8 != 0) 632 throw "Byte out of range"; 633 // Russian peasant multiplication 634 let z: int = 0; 635 for (let i = 7; i >= 0; i--) { 636 z = (z << 1) ^ ((z >>> 7) * 0x11D); 637 z ^= ((y >>> i) & 1) * x; 638 } 639 if (z >>> 8 != 0) 640 throw "Assertion error"; 641 return z as byte; 642 } 643 644 645 // Can only be called immediately after a light run is added, and 646 // returns either 0, 1, or 2. A helper function for getPenaltyScore(). 647 private finderPenaltyCountPatterns(runHistory: Array<int>): int { 648 const n: int = runHistory[1]; 649 if (n > this.size * 3) 650 throw "Assertion error"; 651 const core: boolean = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; 652 return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) 653 + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); 654 } 655 656 657 // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). 658 private finderPenaltyTerminateAndCount(currentRunColor: boolean, currentRunLength: int, runHistory: Array<int>): int { 659 if (currentRunColor) { // Terminate dark run 660 this.finderPenaltyAddHistory(currentRunLength, runHistory); 661 currentRunLength = 0; 662 } 663 currentRunLength += this.size; // Add light border to final run 664 this.finderPenaltyAddHistory(currentRunLength, runHistory); 665 return this.finderPenaltyCountPatterns(runHistory); 666 } 667 668 669 // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). 670 private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void { 671 if (runHistory[0] == 0) 672 currentRunLength += this.size; // Add light border to initial run 673 runHistory.pop(); 674 runHistory.unshift(currentRunLength); 675 } 676 677 678 /*-- Constants and tables --*/ 679 680 // The minimum version number supported in the QR Code Model 2 standard. 681 public static readonly MIN_VERSION: int = 1; 682 // The maximum version number supported in the QR Code Model 2 standard. 683 public static readonly MAX_VERSION: int = 40; 684 685 // For use in getPenaltyScore(), when evaluating which mask is best. 686 private static readonly PENALTY_N1: int = 3; 687 private static readonly PENALTY_N2: int = 3; 688 private static readonly PENALTY_N3: int = 40; 689 private static readonly PENALTY_N4: int = 10; 690 691 private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [ 692 // Version: (note that index 0 is for padding, and is set to an illegal value) 693 //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 694 [-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 695 [-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 696 [-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 697 [-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 698 ]; 699 700 private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [ 701 // Version: (note that index 0 is for padding, and is set to an illegal value) 702 //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 703 [-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 704 [-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 705 [-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 706 [-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 707 ]; 708 709 } 710 711 712 // Appends the given number of low-order bits of the given value 713 // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len. 714 function appendBits(val: int, len: int, bb: Array<bit>): void { 715 if (len < 0 || len > 31 || val >>> len != 0) 716 throw "Value out of range"; 717 for (let i = len - 1; i >= 0; i--) // Append bit by bit 718 bb.push((val >>> i) & 1); 719 } 720 721 722 // Returns true iff the i'th bit of x is set to 1. 723 function getBit(x: int, i: int): boolean { 724 return ((x >>> i) & 1) != 0; 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: 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 "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 "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 "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(2, 2, bb); 815 appendBits(assignVal, 14, bb); 816 } else if (assignVal < 1000000) { 817 appendBits(6, 3, bb); 818 appendBits(assignVal, 21, bb); 819 } else 820 throw "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 "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: 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