qr-decoder-js 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.jsQR +201 -0
- package/LICENSE.qcore +21 -0
- package/README.md +19 -127
- package/README_ZH.md +19 -122
- package/dist/cjs/core/decoder.js +246 -0
- package/dist/cjs/core/encoding.js +217 -0
- package/dist/cjs/core/preprocess.js +687 -0
- package/dist/cjs/index.js +12 -0
- package/dist/cjs/native/binarize.js +76 -0
- package/dist/cjs/native/bitstream.js +138 -0
- package/dist/cjs/native/format.js +33 -0
- package/dist/cjs/native/gf256.js +50 -0
- package/dist/cjs/native/locator.js +159 -0
- package/dist/cjs/native/matrix-decoder.js +166 -0
- package/dist/cjs/native/matrix.js +31 -0
- package/dist/cjs/native/reed-solomon.js +106 -0
- package/dist/cjs/native/sampling.js +71 -0
- package/dist/cjs/native/scanner.js +60 -0
- package/dist/cjs/native/versions.js +45 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/core/decoder.d.ts +59 -0
- package/dist/esm/core/decoder.js +242 -0
- package/dist/esm/core/encoding.d.ts +33 -0
- package/dist/esm/core/encoding.js +211 -0
- package/dist/esm/core/preprocess.d.ts +191 -0
- package/dist/esm/core/preprocess.js +670 -0
- package/dist/esm/index.d.ts +7 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/native/binarize.d.ts +6 -0
- package/dist/esm/native/binarize.js +73 -0
- package/dist/esm/native/bitstream.d.ts +14 -0
- package/dist/esm/native/bitstream.js +135 -0
- package/dist/esm/native/format.d.ts +9 -0
- package/dist/esm/native/format.js +30 -0
- package/dist/esm/native/gf256.d.ts +5 -0
- package/dist/esm/native/gf256.js +44 -0
- package/dist/esm/native/locator.d.ts +14 -0
- package/dist/esm/native/locator.js +156 -0
- package/dist/esm/native/matrix-decoder.d.ts +5 -0
- package/dist/esm/native/matrix-decoder.js +162 -0
- package/dist/esm/native/matrix.d.ts +12 -0
- package/dist/esm/native/matrix.js +27 -0
- package/dist/esm/native/reed-solomon.d.ts +2 -0
- package/dist/esm/native/reed-solomon.js +103 -0
- package/dist/esm/native/sampling.d.ts +7 -0
- package/dist/esm/native/sampling.js +68 -0
- package/dist/esm/native/scanner.d.ts +2 -0
- package/dist/esm/native/scanner.js +57 -0
- package/dist/esm/native/versions.d.ts +9 -0
- package/dist/esm/native/versions.js +42 -0
- package/dist/{index.d.ts → esm/types.d.ts} +15 -0
- package/package.json +17 -19
- package/dist/qr-decoder.js +0 -2670
- package/dist/qr-decoder.umd.cjs +0 -1
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { BitMatrix } from './matrix.js';
|
|
2
|
+
/** Convert RGBA pixels to a locally thresholded QR matrix and, optionally, its inverse. */
|
|
3
|
+
export function binarize(data, width, height, returnInverted) {
|
|
4
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0 || data.length !== width * height * 4) {
|
|
5
|
+
throw new Error('Malformed image data');
|
|
6
|
+
}
|
|
7
|
+
const gray = new Uint8Array(width * height);
|
|
8
|
+
const histogram = new Uint32Array(256);
|
|
9
|
+
const tile = 16, columns = Math.ceil(width / tile), rows = Math.ceil(height / tile);
|
|
10
|
+
const minimum = new Uint8Array(columns * rows).fill(255), maximum = new Uint8Array(columns * rows);
|
|
11
|
+
for (let y = 0; y < height; y++) {
|
|
12
|
+
const tileRow = Math.floor(y / tile) * columns;
|
|
13
|
+
for (let x = 0, i = y * width; x < width; x++, i++) {
|
|
14
|
+
const offset = i * 4;
|
|
15
|
+
const luma = data[offset] * 0.299 + data[offset + 1] * 0.587 + data[offset + 2] * 0.114;
|
|
16
|
+
const alpha = data[offset + 3] / 255;
|
|
17
|
+
const value = Math.round(alpha === 1 ? luma : luma * alpha + 255 * (1 - alpha));
|
|
18
|
+
gray[i] = value;
|
|
19
|
+
histogram[value]++;
|
|
20
|
+
const index = tileRow + Math.floor(x / tile);
|
|
21
|
+
if (value < minimum[index])
|
|
22
|
+
minimum[index] = value;
|
|
23
|
+
if (value > maximum[index])
|
|
24
|
+
maximum[index] = value;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
let total = 0;
|
|
28
|
+
for (let i = 0; i < 256; i++)
|
|
29
|
+
total += i * histogram[i];
|
|
30
|
+
let leftCount = 0, leftSum = 0, best = -1, globalThreshold = 127;
|
|
31
|
+
for (let i = 0; i < 255; i++) {
|
|
32
|
+
leftCount += histogram[i];
|
|
33
|
+
leftSum += i * histogram[i];
|
|
34
|
+
const rightCount = gray.length - leftCount;
|
|
35
|
+
if (!leftCount || !rightCount)
|
|
36
|
+
continue;
|
|
37
|
+
const difference = leftSum / leftCount - (total - leftSum) / rightCount;
|
|
38
|
+
const variance = leftCount * rightCount * difference * difference;
|
|
39
|
+
if (variance > best) {
|
|
40
|
+
best = variance;
|
|
41
|
+
globalThreshold = i;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const thresholds = new Uint8Array(columns * rows);
|
|
45
|
+
for (let ty = 0; ty < rows; ty++)
|
|
46
|
+
for (let tx = 0; tx < columns; tx++) {
|
|
47
|
+
let low = 255, high = 0;
|
|
48
|
+
for (let y = Math.max(0, ty - 1); y <= Math.min(rows - 1, ty + 1); y++)
|
|
49
|
+
for (let x = Math.max(0, tx - 1); x <= Math.min(columns - 1, tx + 1); x++) {
|
|
50
|
+
const index = y * columns + x;
|
|
51
|
+
low = Math.min(low, minimum[index]);
|
|
52
|
+
high = Math.max(high, maximum[index]);
|
|
53
|
+
}
|
|
54
|
+
thresholds[ty * columns + tx] = high - low >= 24 ? Math.floor((low + high) / 2) : globalThreshold;
|
|
55
|
+
}
|
|
56
|
+
const binarized = BitMatrix.createEmpty(width, height);
|
|
57
|
+
const inverted = returnInverted ? BitMatrix.createEmpty(width, height) : null;
|
|
58
|
+
for (let y = 0; y < height; y++) {
|
|
59
|
+
const row = binarized.row(y), inverse = inverted?.row(y);
|
|
60
|
+
const tileRow = Math.floor(y / tile) * columns;
|
|
61
|
+
for (let tx = 0; tx < columns; tx++) {
|
|
62
|
+
const threshold = thresholds[tileRow + tx];
|
|
63
|
+
const end = Math.min((tx + 1) * tile, width);
|
|
64
|
+
for (let x = tx * tile; x < end; x++) {
|
|
65
|
+
const bit = gray[y * width + x] <= threshold ? 1 : 0;
|
|
66
|
+
row[x] = bit;
|
|
67
|
+
if (inverse)
|
|
68
|
+
inverse[x] = 1 - bit;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { binarized, inverted };
|
|
73
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface Segment {
|
|
2
|
+
type: 'numeric' | 'alphanumeric' | 'byte' | 'kanji' | 'eci';
|
|
3
|
+
text?: string;
|
|
4
|
+
bytes?: number[];
|
|
5
|
+
assignmentNumber?: number;
|
|
6
|
+
}
|
|
7
|
+
export interface Payload {
|
|
8
|
+
text: string;
|
|
9
|
+
bytes: number[];
|
|
10
|
+
chunks: Segment[];
|
|
11
|
+
version: number;
|
|
12
|
+
}
|
|
13
|
+
/** Parse data codewords after QR error correction into ordered payload segments. */
|
|
14
|
+
export declare function decodePayload(data: Uint8Array | Uint8ClampedArray, version: number): Payload;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
class Bits {
|
|
2
|
+
constructor(data) {
|
|
3
|
+
this.data = data;
|
|
4
|
+
this.position = 0;
|
|
5
|
+
}
|
|
6
|
+
get remaining() { return this.data.length * 8 - this.position; }
|
|
7
|
+
get offset() { return this.position & 7; }
|
|
8
|
+
read(count) {
|
|
9
|
+
if (count > this.remaining)
|
|
10
|
+
throw new Error('Truncated QR payload');
|
|
11
|
+
let value = 0;
|
|
12
|
+
for (let i = 0; i < count; i++, this.position++) {
|
|
13
|
+
value = (value << 1) | ((this.data[this.position >> 3] >> (7 - (this.position & 7))) & 1);
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';
|
|
19
|
+
/** Parse data codewords after QR error correction into ordered payload segments. */
|
|
20
|
+
export function decodePayload(data, version) {
|
|
21
|
+
if (version < 1 || version > 40)
|
|
22
|
+
throw new RangeError('Invalid QR version');
|
|
23
|
+
const bits = new Bits(data);
|
|
24
|
+
const tier = version <= 9 ? 0 : version <= 26 ? 1 : 2;
|
|
25
|
+
const result = { text: '', bytes: [], chunks: [], version };
|
|
26
|
+
let fnc1 = false;
|
|
27
|
+
while (bits.remaining >= 4) {
|
|
28
|
+
const mode = bits.read(4);
|
|
29
|
+
if (mode === 0) {
|
|
30
|
+
// An all-zero matrix can satisfy Reed-Solomon yet is not a QR payload.
|
|
31
|
+
// Validate standard pad codewords when no data segment has been found.
|
|
32
|
+
if (!result.chunks.some(chunk => chunk.type !== 'eci')) {
|
|
33
|
+
if (bits.offset && bits.read(8 - bits.offset) !== 0)
|
|
34
|
+
throw new Error('Invalid QR padding');
|
|
35
|
+
let pad = 0xec;
|
|
36
|
+
while (bits.remaining >= 8) {
|
|
37
|
+
if (bits.read(8) !== pad)
|
|
38
|
+
throw new Error('Invalid QR padding');
|
|
39
|
+
pad ^= 0xfd;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
if (mode === 7) {
|
|
45
|
+
const first = bits.read(8);
|
|
46
|
+
let assignment;
|
|
47
|
+
if ((first & 0x80) === 0)
|
|
48
|
+
assignment = first;
|
|
49
|
+
else if ((first & 0xc0) === 0x80)
|
|
50
|
+
assignment = ((first & 0x3f) << 8) | bits.read(8);
|
|
51
|
+
else if ((first & 0xe0) === 0xc0)
|
|
52
|
+
assignment = ((first & 0x1f) << 16) | bits.read(16);
|
|
53
|
+
else
|
|
54
|
+
throw new Error('Invalid ECI assignment');
|
|
55
|
+
result.chunks.push({ type: 'eci', assignmentNumber: assignment });
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (mode === 3) {
|
|
59
|
+
bits.read(16);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (mode === 5 || mode === 9) {
|
|
63
|
+
if (mode === 9)
|
|
64
|
+
bits.read(8);
|
|
65
|
+
fnc1 = true;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const widths = { 1: [10, 12, 14], 2: [9, 11, 13], 4: [8, 16, 16], 8: [8, 10, 12] };
|
|
69
|
+
if (!widths[mode])
|
|
70
|
+
throw new Error(`Unsupported QR mode ${mode}`);
|
|
71
|
+
let count = bits.read(widths[mode][tier]);
|
|
72
|
+
let text = '';
|
|
73
|
+
const bytes = [];
|
|
74
|
+
if (mode === 1) {
|
|
75
|
+
while (count >= 3) {
|
|
76
|
+
const n = bits.read(10);
|
|
77
|
+
if (n >= 1000)
|
|
78
|
+
throw new Error('Invalid numeric group');
|
|
79
|
+
text += String(n).padStart(3, '0');
|
|
80
|
+
count -= 3;
|
|
81
|
+
}
|
|
82
|
+
if (count) {
|
|
83
|
+
const n = bits.read(count === 2 ? 7 : 4);
|
|
84
|
+
if (n >= 10 ** count)
|
|
85
|
+
throw new Error('Invalid numeric group');
|
|
86
|
+
text += String(n).padStart(count, '0');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
else if (mode === 2) {
|
|
90
|
+
while (count >= 2) {
|
|
91
|
+
const n = bits.read(11);
|
|
92
|
+
if (n >= 2025)
|
|
93
|
+
throw new Error('Invalid alphanumeric group');
|
|
94
|
+
text += ALPHABET[Math.floor(n / 45)] + ALPHABET[n % 45];
|
|
95
|
+
count -= 2;
|
|
96
|
+
}
|
|
97
|
+
if (count) {
|
|
98
|
+
const n = bits.read(6);
|
|
99
|
+
if (n >= 45)
|
|
100
|
+
throw new Error('Invalid alphanumeric group');
|
|
101
|
+
text += ALPHABET[n];
|
|
102
|
+
}
|
|
103
|
+
if (fnc1)
|
|
104
|
+
text = text.replace(/%%|%/g, match => match === '%%' ? '%' : '\x1d');
|
|
105
|
+
}
|
|
106
|
+
else if (mode === 4) {
|
|
107
|
+
while (count--)
|
|
108
|
+
bytes.push(bits.read(8));
|
|
109
|
+
result.chunks.push({ type: 'byte', bytes });
|
|
110
|
+
result.bytes.push(...bytes);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
while (count--) {
|
|
115
|
+
const n = bits.read(13);
|
|
116
|
+
let code = (Math.floor(n / 0xc0) << 8) | (n % 0xc0);
|
|
117
|
+
code += code < 0x1f00 ? 0x8140 : 0xc140;
|
|
118
|
+
bytes.push(code >> 8, code & 255);
|
|
119
|
+
}
|
|
120
|
+
text = new TextDecoder('shift_jis', { fatal: true }).decode(new Uint8Array(bytes));
|
|
121
|
+
result.chunks.push({ type: 'kanji', bytes, text });
|
|
122
|
+
result.bytes.push(...bytes);
|
|
123
|
+
result.text += text;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
for (const char of text)
|
|
127
|
+
bytes.push(char.charCodeAt(0));
|
|
128
|
+
result.chunks.push({ type: mode === 1 ? 'numeric' : 'alphanumeric', text });
|
|
129
|
+
result.bytes.push(...bytes);
|
|
130
|
+
result.text += text;
|
|
131
|
+
}
|
|
132
|
+
if (bits.remaining && bits.read(bits.remaining) !== 0)
|
|
133
|
+
throw new Error('Invalid QR padding');
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** QR error-correction levels in the two-bit order used by the format field. */
|
|
2
|
+
export type ErrorCorrectionLevel = 'M' | 'L' | 'H' | 'Q';
|
|
3
|
+
export interface FormatInformation {
|
|
4
|
+
errorCorrection: ErrorCorrectionLevel;
|
|
5
|
+
mask: number;
|
|
6
|
+
distance: number;
|
|
7
|
+
}
|
|
8
|
+
/** Decode either of the two BCH-protected format copies, correcting up to three bits. */
|
|
9
|
+
export declare function decodeFormat(first: number, second: number): FormatInformation | null;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const LEVELS = ['M', 'L', 'H', 'Q'];
|
|
2
|
+
function formatCode(data) {
|
|
3
|
+
let remainder = data << 10;
|
|
4
|
+
for (let bit = 14; bit >= 10; bit--) {
|
|
5
|
+
if ((remainder & (1 << bit)) !== 0)
|
|
6
|
+
remainder ^= 0x537 << (bit - 10);
|
|
7
|
+
}
|
|
8
|
+
return ((data << 10) | remainder) ^ 0x5412;
|
|
9
|
+
}
|
|
10
|
+
function distance(a, b) {
|
|
11
|
+
let bits = a ^ b;
|
|
12
|
+
let count = 0;
|
|
13
|
+
while (bits !== 0) {
|
|
14
|
+
bits &= bits - 1;
|
|
15
|
+
count++;
|
|
16
|
+
}
|
|
17
|
+
return count;
|
|
18
|
+
}
|
|
19
|
+
/** Decode either of the two BCH-protected format copies, correcting up to three bits. */
|
|
20
|
+
export function decodeFormat(first, second) {
|
|
21
|
+
let best = null;
|
|
22
|
+
for (let value = 0; value < 32; value++) {
|
|
23
|
+
const encoded = formatCode(value);
|
|
24
|
+
const errors = Math.min(distance(first & 0x7fff, encoded), distance(second & 0x7fff, encoded));
|
|
25
|
+
if (errors <= 3 && (best === null || errors < best.distance)) {
|
|
26
|
+
best = { errorCorrection: LEVELS[value >> 3], mask: value & 7, distance: errors };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return best;
|
|
30
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare function multiply(a: number, b: number): number;
|
|
2
|
+
export declare function divide(a: number, b: number): number;
|
|
3
|
+
export declare function power(a: number, n: number): number;
|
|
4
|
+
/** Evaluate a received codeword polynomial at consecutive QR field roots. */
|
|
5
|
+
export declare function syndromes(codewords: Uint8Array, count: number): Uint8Array;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Arithmetic in the QR Code field GF(256), with primitive polynomial 0x11d. */
|
|
2
|
+
const exponent = new Uint8Array(512);
|
|
3
|
+
const logarithm = new Uint8Array(256);
|
|
4
|
+
let value = 1;
|
|
5
|
+
for (let i = 0; i < 255; i++) {
|
|
6
|
+
exponent[i] = value;
|
|
7
|
+
exponent[i + 255] = value;
|
|
8
|
+
logarithm[value] = i;
|
|
9
|
+
value <<= 1;
|
|
10
|
+
if ((value & 0x100) !== 0)
|
|
11
|
+
value ^= 0x11d;
|
|
12
|
+
}
|
|
13
|
+
exponent[510] = exponent[0];
|
|
14
|
+
exponent[511] = exponent[1];
|
|
15
|
+
export function multiply(a, b) {
|
|
16
|
+
return a === 0 || b === 0 ? 0 : exponent[logarithm[a] + logarithm[b]];
|
|
17
|
+
}
|
|
18
|
+
export function divide(a, b) {
|
|
19
|
+
if (b === 0)
|
|
20
|
+
throw new RangeError('Cannot divide by zero in GF(256)');
|
|
21
|
+
return a === 0 ? 0 : exponent[logarithm[a] - logarithm[b] + 255];
|
|
22
|
+
}
|
|
23
|
+
export function power(a, n) {
|
|
24
|
+
if (n === 0)
|
|
25
|
+
return 1;
|
|
26
|
+
if (a === 0) {
|
|
27
|
+
if (n < 0)
|
|
28
|
+
throw new RangeError('Cannot raise zero to a negative power');
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
31
|
+
const reduced = ((n % 255) + 255) % 255;
|
|
32
|
+
return exponent[(logarithm[a] * reduced) % 255];
|
|
33
|
+
}
|
|
34
|
+
/** Evaluate a received codeword polynomial at consecutive QR field roots. */
|
|
35
|
+
export function syndromes(codewords, count) {
|
|
36
|
+
const result = new Uint8Array(count);
|
|
37
|
+
for (let root = 0; root < count; root++) {
|
|
38
|
+
let sum = 0;
|
|
39
|
+
for (const codeword of codewords)
|
|
40
|
+
sum = multiply(sum, exponent[root]) ^ codeword;
|
|
41
|
+
result[root] = sum;
|
|
42
|
+
}
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BitMatrix } from './matrix.js';
|
|
2
|
+
export interface Point {
|
|
3
|
+
x: number;
|
|
4
|
+
y: number;
|
|
5
|
+
}
|
|
6
|
+
export interface QRLocation {
|
|
7
|
+
topLeft: Point;
|
|
8
|
+
topRight: Point;
|
|
9
|
+
bottomLeft: Point;
|
|
10
|
+
alignmentPattern: Point;
|
|
11
|
+
dimension: number;
|
|
12
|
+
}
|
|
13
|
+
/** Find candidate QR finder triples and estimate their module dimensions. */
|
|
14
|
+
export declare function locate(image: BitMatrix): IterableIterator<QRLocation>;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
function matchesFinder(first, second, middle, fourth, last, unit) {
|
|
2
|
+
const tolerance = unit * 0.8;
|
|
3
|
+
return unit >= 0.7 &&
|
|
4
|
+
Math.abs(middle - unit * 3) <= unit * 1.65 &&
|
|
5
|
+
Math.abs(first - unit) <= tolerance && Math.abs(second - unit) <= tolerance &&
|
|
6
|
+
Math.abs(fourth - unit) <= tolerance && Math.abs(last - unit) <= tolerance;
|
|
7
|
+
}
|
|
8
|
+
// Cross-check a possible finder center against the 1:1:3:1:1 pattern on another axis.
|
|
9
|
+
function crossCheck(image, x, y, vertical, limit) {
|
|
10
|
+
const fixed = Math.floor(vertical ? x : y);
|
|
11
|
+
const center = Math.floor(vertical ? y : x);
|
|
12
|
+
const length = vertical ? image.height : image.width;
|
|
13
|
+
const pixel = (n) => n >= 0 && n < length && image.get(vertical ? fixed : n, vertical ? n : fixed);
|
|
14
|
+
if (!pixel(center))
|
|
15
|
+
return null;
|
|
16
|
+
let a = center, b = center;
|
|
17
|
+
while (a >= 0 && pixel(a) && center - a <= limit * 4)
|
|
18
|
+
a--;
|
|
19
|
+
while (b < length && pixel(b) && b - center <= limit * 4)
|
|
20
|
+
b++;
|
|
21
|
+
const middle = b - a - 1;
|
|
22
|
+
let left = a;
|
|
23
|
+
while (left >= 0 && !pixel(left) && a - left <= limit * 2)
|
|
24
|
+
left--;
|
|
25
|
+
let farLeft = left;
|
|
26
|
+
while (farLeft >= 0 && pixel(farLeft) && left - farLeft <= limit * 2)
|
|
27
|
+
farLeft--;
|
|
28
|
+
let right = b;
|
|
29
|
+
while (right < length && !pixel(right) && right - b <= limit * 2)
|
|
30
|
+
right++;
|
|
31
|
+
let farRight = right;
|
|
32
|
+
while (farRight < length && pixel(farRight) && farRight - right <= limit * 2)
|
|
33
|
+
farRight++;
|
|
34
|
+
const size = (farRight - farLeft - 1) / 7;
|
|
35
|
+
if (!matchesFinder(left - farLeft, a - left, middle, right - b, farRight - right, size))
|
|
36
|
+
return null;
|
|
37
|
+
return { center: (a + b) / 2, size };
|
|
38
|
+
}
|
|
39
|
+
function findPatterns(image) {
|
|
40
|
+
const candidates = [];
|
|
41
|
+
for (let y = 0; y < image.height; y++) {
|
|
42
|
+
const row = image.row(y);
|
|
43
|
+
let first = 0, second = 0, middle = 0, fourth = 0, last = 0;
|
|
44
|
+
let start = 0;
|
|
45
|
+
let color = row[0];
|
|
46
|
+
for (let x = 1; x <= image.width; x++) {
|
|
47
|
+
const current = x < image.width ? row[x] : 1 - color;
|
|
48
|
+
if (current === color)
|
|
49
|
+
continue;
|
|
50
|
+
first = second;
|
|
51
|
+
second = middle;
|
|
52
|
+
middle = fourth;
|
|
53
|
+
fourth = last;
|
|
54
|
+
last = x - start;
|
|
55
|
+
const unit = (first + second + middle + fourth + last) / 7;
|
|
56
|
+
if (color === 1 && first > 0 && matchesFinder(first, second, middle, fourth, last, unit)) {
|
|
57
|
+
const cx = x - last - fourth - middle / 2;
|
|
58
|
+
const vertical = crossCheck(image, cx, y, true, unit);
|
|
59
|
+
const horizontal = vertical && crossCheck(image, cx, vertical.center, false, unit);
|
|
60
|
+
if (vertical && horizontal && Math.max(vertical.size, horizontal.size) < Math.min(vertical.size, horizontal.size) * 2.5) {
|
|
61
|
+
const size = (vertical.size + horizontal.size) / 2;
|
|
62
|
+
const existing = candidates.find(p => Math.hypot(p.x - horizontal.center, p.y - vertical.center) < Math.max(p.size, size) * 2 && Math.abs(p.size - size) < size);
|
|
63
|
+
if (existing) {
|
|
64
|
+
const n = ++existing.hits;
|
|
65
|
+
existing.x += (horizontal.center - existing.x) / n;
|
|
66
|
+
existing.y += (vertical.center - existing.y) / n;
|
|
67
|
+
existing.size += (size - existing.size) / n;
|
|
68
|
+
}
|
|
69
|
+
else
|
|
70
|
+
candidates.push({ x: horizontal.center, y: vertical.center, size, hits: 1 });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
start = x;
|
|
74
|
+
color = current;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return candidates.filter(p => p.hits >= Math.max(1, Math.floor(p.size / 2))).sort((a, b) => b.hits - a.hits).slice(0, 24);
|
|
78
|
+
}
|
|
79
|
+
function findAlignment(image, expected, size, radius) {
|
|
80
|
+
let best = expected;
|
|
81
|
+
let bestScore = Infinity;
|
|
82
|
+
const minX = Math.max(1, Math.floor(expected.x - radius)), maxX = Math.min(image.width - 2, Math.ceil(expected.x + radius));
|
|
83
|
+
const minY = Math.max(1, Math.floor(expected.y - radius)), maxY = Math.min(image.height - 2, Math.ceil(expected.y + radius));
|
|
84
|
+
for (let y = minY; y <= maxY; y++)
|
|
85
|
+
for (let x = minX; x <= maxX; x++) {
|
|
86
|
+
if (!image.get(x, y))
|
|
87
|
+
continue;
|
|
88
|
+
const line = (vertical) => {
|
|
89
|
+
const origin = vertical ? y : x, limit = vertical ? image.height : image.width;
|
|
90
|
+
const pixel = (n) => n >= 0 && n < limit && image.get(vertical ? x : n, vertical ? n : y);
|
|
91
|
+
let left = origin, right = origin;
|
|
92
|
+
while (left >= 0 && pixel(left) && origin - left < size * 2)
|
|
93
|
+
left--;
|
|
94
|
+
while (right < limit && pixel(right) && right - origin < size * 2)
|
|
95
|
+
right++;
|
|
96
|
+
let leftWhite = left, rightWhite = right;
|
|
97
|
+
while (leftWhite >= 0 && !pixel(leftWhite) && left - leftWhite < size * 2)
|
|
98
|
+
leftWhite--;
|
|
99
|
+
while (rightWhite < limit && !pixel(rightWhite) && rightWhite - right < size * 2)
|
|
100
|
+
rightWhite++;
|
|
101
|
+
const runs = [left - leftWhite, right - left - 1, rightWhite - right];
|
|
102
|
+
return { center: (left + right) / 2, error: runs.reduce((sum, run) => sum + Math.abs(run - size) / size, 0) };
|
|
103
|
+
};
|
|
104
|
+
const horizontal = line(false);
|
|
105
|
+
if (horizontal.error >= bestScore)
|
|
106
|
+
continue;
|
|
107
|
+
const vertical = line(true);
|
|
108
|
+
const score = horizontal.error + vertical.error + Math.hypot(x - expected.x, y - expected.y) / Math.max(size, 1) * 0.08;
|
|
109
|
+
if (score < bestScore) {
|
|
110
|
+
bestScore = score;
|
|
111
|
+
best = { x: horizontal.center, y: vertical.center };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return bestScore <= 2.5 ? best : expected;
|
|
115
|
+
}
|
|
116
|
+
/** Find candidate QR finder triples and estimate their module dimensions. */
|
|
117
|
+
export function* locate(image) {
|
|
118
|
+
const patterns = findPatterns(image);
|
|
119
|
+
const choices = [];
|
|
120
|
+
for (let i = 0; i < patterns.length; i++)
|
|
121
|
+
for (let j = i + 1; j < patterns.length; j++)
|
|
122
|
+
for (let k = j + 1; k < patterns.length; k++) {
|
|
123
|
+
const triple = [patterns[i], patterns[j], patterns[k]];
|
|
124
|
+
for (let pivot = 0; pivot < 3; pivot++) {
|
|
125
|
+
const tl = triple[pivot], a = triple[(pivot + 1) % 3], b = triple[(pivot + 2) % 3];
|
|
126
|
+
const ax = a.x - tl.x, ay = a.y - tl.y, bx = b.x - tl.x, by = b.y - tl.y;
|
|
127
|
+
const da = Math.hypot(ax, ay), db = Math.hypot(bx, by);
|
|
128
|
+
const dot = Math.abs(ax * bx + ay * by) / (da * db);
|
|
129
|
+
if (!Number.isFinite(dot) || dot > 0.55 || Math.min(da, db) < 8 * Math.min(tl.size, a.size, b.size) || Math.max(da, db) / Math.min(da, db) > 2.5)
|
|
130
|
+
continue;
|
|
131
|
+
const topRight = ax * by - ay * bx > 0 ? a : b;
|
|
132
|
+
const bottomLeft = topRight === a ? b : a;
|
|
133
|
+
const size = (tl.size * 2 + a.size + b.size) / 4;
|
|
134
|
+
const estimated = (da + db) / (2 * size) + 7;
|
|
135
|
+
const dimension = 21 + 4 * Math.round((estimated - 21) / 4);
|
|
136
|
+
if (dimension < 21 || dimension > 177)
|
|
137
|
+
continue;
|
|
138
|
+
const geometry = dot * 4 + Math.abs(Math.log(da / db)) * 2 + Math.abs(estimated - dimension) / 8;
|
|
139
|
+
const support = Math.log(1 + Math.min(tl.hits, a.hits, b.hits));
|
|
140
|
+
for (const candidateDimension of [dimension, dimension - 4, dimension + 4]) {
|
|
141
|
+
if (candidateDimension < 21 || candidateDimension > 177)
|
|
142
|
+
continue;
|
|
143
|
+
const factor = (candidateDimension - 10) / (candidateDimension - 7);
|
|
144
|
+
const expected = { x: tl.x + (topRight.x + bottomLeft.x - 2 * tl.x) * factor, y: tl.y + (topRight.y + bottomLeft.y - 2 * tl.y) * factor };
|
|
145
|
+
choices.push({ location: { topLeft: tl, topRight, bottomLeft, alignmentPattern: expected, dimension: candidateDimension }, score: geometry - support + Math.abs(candidateDimension - dimension) / 16, size, radius: Math.min(4 * size, Math.min(da, db) * 0.2) });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
choices.sort((a, b) => a.score - b.score);
|
|
150
|
+
for (const { location, size, radius } of choices.slice(0, 24)) {
|
|
151
|
+
if (location.dimension !== 21) {
|
|
152
|
+
location.alignmentPattern = findAlignment(image, location.alignmentPattern, size, radius);
|
|
153
|
+
}
|
|
154
|
+
yield location;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { BitMatrix } from './matrix.js';
|
|
2
|
+
import { Payload } from './bitstream.js';
|
|
3
|
+
export declare function isVersionValid(n: number, get: (x: number, y: number) => boolean): boolean;
|
|
4
|
+
/** Decode both normal and mirrored orientations of a sampled QR module grid. */
|
|
5
|
+
export declare function decode(matrix: BitMatrix, confidence?: Uint8Array): Payload | null;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { BitMatrix } from './matrix.js';
|
|
2
|
+
import { decodeFormat } from './format.js';
|
|
3
|
+
import { decodePayload } from './bitstream.js';
|
|
4
|
+
import { correctCodewords } from './reed-solomon.js';
|
|
5
|
+
import { VERSIONS } from './versions.js';
|
|
6
|
+
function hamming(value) {
|
|
7
|
+
let count = 0;
|
|
8
|
+
while (value) {
|
|
9
|
+
value &= value - 1;
|
|
10
|
+
count++;
|
|
11
|
+
}
|
|
12
|
+
return count;
|
|
13
|
+
}
|
|
14
|
+
function versionBits(version) {
|
|
15
|
+
let remainder = version << 12;
|
|
16
|
+
for (let bit = 17; bit >= 12; bit--)
|
|
17
|
+
if (remainder & (1 << bit))
|
|
18
|
+
remainder ^= 0x1f25 << (bit - 12);
|
|
19
|
+
return (version << 12) | remainder;
|
|
20
|
+
}
|
|
21
|
+
export function isVersionValid(n, get) {
|
|
22
|
+
const version = (n - 17) / 4;
|
|
23
|
+
if (version < 7)
|
|
24
|
+
return true;
|
|
25
|
+
let first = 0, second = 0;
|
|
26
|
+
for (let i = 0; i < 18; i++) {
|
|
27
|
+
const x = n - 11 + i % 3, y = Math.floor(i / 3);
|
|
28
|
+
if (get(x, y))
|
|
29
|
+
first |= 1 << i;
|
|
30
|
+
if (get(y, x))
|
|
31
|
+
second |= 1 << i;
|
|
32
|
+
}
|
|
33
|
+
const expected = versionBits(version);
|
|
34
|
+
return Math.min(hamming(first ^ expected), hamming(second ^ expected)) <= 3;
|
|
35
|
+
}
|
|
36
|
+
function functionMask(dimension, spec, version) {
|
|
37
|
+
const reserved = BitMatrix.createEmpty(dimension, dimension);
|
|
38
|
+
reserved.setRegion(0, 0, 9, 9, true);
|
|
39
|
+
reserved.setRegion(dimension - 8, 0, 8, 9, true);
|
|
40
|
+
reserved.setRegion(0, dimension - 8, 9, 8, true);
|
|
41
|
+
for (const y of spec.alignment)
|
|
42
|
+
for (const x of spec.alignment) {
|
|
43
|
+
if ((x === 6 && (y === 6 || y === dimension - 7)) || (y === 6 && x === dimension - 7))
|
|
44
|
+
continue;
|
|
45
|
+
reserved.setRegion(x - 2, y - 2, 5, 5, true);
|
|
46
|
+
}
|
|
47
|
+
reserved.setRegion(6, 9, 1, dimension - 17, true);
|
|
48
|
+
reserved.setRegion(9, 6, dimension - 17, 1, true);
|
|
49
|
+
if (version >= 7) {
|
|
50
|
+
reserved.setRegion(dimension - 11, 0, 3, 6, true);
|
|
51
|
+
reserved.setRegion(0, dimension - 11, 6, 3, true);
|
|
52
|
+
}
|
|
53
|
+
return reserved;
|
|
54
|
+
}
|
|
55
|
+
function maskBit(mask, x, y) {
|
|
56
|
+
switch (mask) {
|
|
57
|
+
case 0: return (x + y) % 2 === 0;
|
|
58
|
+
case 1: return y % 2 === 0;
|
|
59
|
+
case 2: return x % 3 === 0;
|
|
60
|
+
case 3: return (x + y) % 3 === 0;
|
|
61
|
+
case 4: return (Math.floor(y / 2) + Math.floor(x / 3)) % 2 === 0;
|
|
62
|
+
case 5: return (x * y) % 2 + (x * y) % 3 === 0;
|
|
63
|
+
case 6: return ((x * y) % 2 + (x * y) % 3) % 2 === 0;
|
|
64
|
+
default: return ((x + y) % 2 + (x * y) % 3) % 2 === 0;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function decodeOrientation(matrix, mirrored, confidence) {
|
|
68
|
+
const dimension = matrix.width;
|
|
69
|
+
if (dimension !== matrix.height || dimension < 21 || dimension > 177 || dimension % 4 !== 1)
|
|
70
|
+
return null;
|
|
71
|
+
const version = (dimension - 17) / 4, spec = VERSIONS[version - 1];
|
|
72
|
+
const get = (x, y) => mirrored ? matrix.get(y, x) : matrix.get(x, y);
|
|
73
|
+
if (!isVersionValid(dimension, get))
|
|
74
|
+
return null;
|
|
75
|
+
let first = 0, second = 0;
|
|
76
|
+
const add = (value, x, y) => (value << 1) | Number(get(x, y));
|
|
77
|
+
for (let x = 0; x <= 8; x++)
|
|
78
|
+
if (x !== 6)
|
|
79
|
+
first = add(first, x, 8);
|
|
80
|
+
for (let y = 7; y >= 0; y--)
|
|
81
|
+
if (y !== 6)
|
|
82
|
+
first = add(first, 8, y);
|
|
83
|
+
for (let y = dimension - 1; y >= dimension - 7; y--)
|
|
84
|
+
second = add(second, 8, y);
|
|
85
|
+
for (let x = dimension - 8; x < dimension; x++)
|
|
86
|
+
second = add(second, x, 8);
|
|
87
|
+
const format = decodeFormat(first, second);
|
|
88
|
+
if (!format)
|
|
89
|
+
return null;
|
|
90
|
+
const reserved = functionMask(dimension, spec, version);
|
|
91
|
+
const words = [], wordConfidence = [];
|
|
92
|
+
let byte = 0, count = 0, minimumConfidence = 255, upwards = true;
|
|
93
|
+
for (let right = dimension - 1; right > 0; right -= 2) {
|
|
94
|
+
if (right === 6)
|
|
95
|
+
right--;
|
|
96
|
+
for (let step = 0; step < dimension; step++) {
|
|
97
|
+
const y = upwards ? dimension - 1 - step : step;
|
|
98
|
+
for (let offset = 0; offset < 2; offset++) {
|
|
99
|
+
const x = right - offset;
|
|
100
|
+
if (reserved.get(x, y))
|
|
101
|
+
continue;
|
|
102
|
+
byte = (byte << 1) | Number(get(x, y) !== maskBit(format.mask, x, y));
|
|
103
|
+
if (confidence)
|
|
104
|
+
minimumConfidence = Math.min(minimumConfidence, confidence[mirrored ? x * dimension + y : y * dimension + x]);
|
|
105
|
+
if (++count === 8) {
|
|
106
|
+
words.push(byte);
|
|
107
|
+
wordConfidence.push(minimumConfidence);
|
|
108
|
+
byte = 0;
|
|
109
|
+
count = 0;
|
|
110
|
+
minimumConfidence = 255;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
upwards = !upwards;
|
|
115
|
+
}
|
|
116
|
+
const ec = spec.blocks[format.errorCorrection];
|
|
117
|
+
const blocks = [];
|
|
118
|
+
for (const [number, length] of ec.groups)
|
|
119
|
+
for (let i = 0; i < number; i++)
|
|
120
|
+
blocks.push({ length, bytes: [], confidence: [] });
|
|
121
|
+
const required = blocks.reduce((sum, block) => sum + block.length + ec.parity, 0);
|
|
122
|
+
if (words.length < required)
|
|
123
|
+
return null;
|
|
124
|
+
let pos = 0;
|
|
125
|
+
const maxData = Math.max(...blocks.map(block => block.length));
|
|
126
|
+
const append = (block) => { block.bytes.push(words[pos]); block.confidence.push(wordConfidence[pos++]); };
|
|
127
|
+
for (let i = 0; i < maxData; i++)
|
|
128
|
+
for (const block of blocks)
|
|
129
|
+
if (i < block.length)
|
|
130
|
+
append(block);
|
|
131
|
+
for (let i = 0; i < ec.parity; i++)
|
|
132
|
+
for (const block of blocks)
|
|
133
|
+
append(block);
|
|
134
|
+
const payload = [];
|
|
135
|
+
for (const block of blocks) {
|
|
136
|
+
const input = Uint8Array.from(block.bytes);
|
|
137
|
+
let corrected = correctCodewords(input, ec.parity);
|
|
138
|
+
if (!corrected && confidence && Math.min(...block.confidence) < Math.max(...block.confidence)) {
|
|
139
|
+
const indices = block.confidence.map((_, i) => i).sort((a, b) => block.confidence[a] - block.confidence[b] || a - b);
|
|
140
|
+
// Retain six parity symbols for verification after each erasure attempt.
|
|
141
|
+
for (let count = 2; !corrected && count <= ec.parity - 6; count += 2) {
|
|
142
|
+
corrected = correctCodewords(input, ec.parity, indices.slice(0, count));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (!corrected)
|
|
146
|
+
return null;
|
|
147
|
+
for (let i = 0; i < block.length; i++)
|
|
148
|
+
payload.push(corrected[i]);
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
return decodePayload(Uint8Array.from(payload), version);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** Decode both normal and mirrored orientations of a sampled QR module grid. */
|
|
158
|
+
export function decode(matrix, confidence) {
|
|
159
|
+
if (confidence && confidence.length !== matrix.width * matrix.height)
|
|
160
|
+
throw new RangeError('Invalid module confidence');
|
|
161
|
+
return decodeOrientation(matrix, false, confidence) || decodeOrientation(matrix, true, confidence);
|
|
162
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Boolean image or QR module grid in row-major order. */
|
|
2
|
+
export declare class BitMatrix {
|
|
3
|
+
readonly width: number;
|
|
4
|
+
readonly height: number;
|
|
5
|
+
private readonly cells;
|
|
6
|
+
private constructor();
|
|
7
|
+
static createEmpty(width: number, height: number): BitMatrix;
|
|
8
|
+
row(y: number): Uint8Array;
|
|
9
|
+
get(x: number, y: number): boolean;
|
|
10
|
+
set(x: number, y: number, value: boolean): void;
|
|
11
|
+
setRegion(left: number, top: number, width: number, height: number, value: boolean): void;
|
|
12
|
+
}
|