Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

qrcodegen.ts

996 lines40.2 KB

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