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