@sythos/js_barcode_universal 1.2.5 → 1.4.1

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 (124) hide show
  1. package/AI_USAGE.md +33 -0
  2. package/LICENSE +11 -2
  3. package/NOTICE.md +10 -4
  4. package/README.md +601 -465
  5. package/bundle/sythos-barcode.esm.js +4669 -74
  6. package/bundle/sythos-barcode.js +4575 -72
  7. package/examples/create.html +1010 -730
  8. package/examples/read.html +1 -0
  9. package/licenses/README.md +40 -58
  10. package/licenses/aztec-code.license +15 -13
  11. package/licenses/aztec-rune.license +76 -0
  12. package/licenses/codabar.license +18 -15
  13. package/licenses/code-11.license +11 -9
  14. package/licenses/code-128.license +10 -8
  15. package/licenses/code-39.license +10 -8
  16. package/licenses/code-93.license +16 -14
  17. package/licenses/compact-pdf417.license +76 -0
  18. package/licenses/data-matrix.license +15 -13
  19. package/licenses/ean-13.license +10 -8
  20. package/licenses/ean-2.license +74 -0
  21. package/licenses/ean-5.license +74 -0
  22. package/licenses/ean-8.license +10 -8
  23. package/licenses/frameqr.license +84 -0
  24. package/licenses/gs1-128.license +10 -8
  25. package/licenses/gs1-databar.license +81 -0
  26. package/licenses/isbn.license +10 -8
  27. package/licenses/itf-14.license +10 -8
  28. package/licenses/itf.license +9 -7
  29. package/licenses/micro-qr.license +79 -0
  30. package/licenses/micropdf417.license +52 -67
  31. package/licenses/msi-plessey.license +13 -11
  32. package/licenses/pdf417.license +78 -37
  33. package/licenses/pharmacode.license +14 -12
  34. package/licenses/qr-code.license +9 -7
  35. package/licenses/rmqr.license +79 -0
  36. package/licenses/upc-a.license +12 -10
  37. package/licenses/upc-e.license +10 -8
  38. package/package.json +109 -88
  39. package/src/aztec/decoder.js +1 -0
  40. package/src/aztec/detector.js +1 -0
  41. package/src/aztec/encoder.js +1 -0
  42. package/src/aztec/high-level.js +1 -0
  43. package/src/aztec/index.js +1 -0
  44. package/src/aztec/tables.js +1 -0
  45. package/src/aztecrune/decoder.js +156 -0
  46. package/src/aztecrune/detector.js +167 -0
  47. package/src/aztecrune/encoder.js +122 -0
  48. package/src/aztecrune/index.js +50 -0
  49. package/src/aztecrune/tables.js +138 -0
  50. package/src/compactpdf417/decoder.js +129 -0
  51. package/src/compactpdf417/detector.js +140 -0
  52. package/src/compactpdf417/encoder.js +141 -0
  53. package/src/compactpdf417/index.js +22 -0
  54. package/src/compactpdf417/tables.js +174 -0
  55. package/src/core/bit-buffer.js +1 -0
  56. package/src/core/bit-matrix.js +1 -0
  57. package/src/core/errors.js +1 -0
  58. package/src/core/galois-field.js +1 -0
  59. package/src/core/index.js +1 -0
  60. package/src/core/reed-solomon.js +1 -0
  61. package/src/databar/codec.js +182 -0
  62. package/src/databar/decoder.js +115 -0
  63. package/src/databar/encoder.js +97 -0
  64. package/src/databar/gs1.js +178 -0
  65. package/src/databar/index.js +69 -0
  66. package/src/databar/patterns.js +144 -0
  67. package/src/databar/tables.js +125 -0
  68. package/src/datamatrix/decoder.js +263 -262
  69. package/src/datamatrix/detector.js +226 -225
  70. package/src/datamatrix/encoder.js +192 -191
  71. package/src/datamatrix/index.js +43 -42
  72. package/src/datamatrix/tables.js +124 -123
  73. package/src/frameqr/decoder.js +240 -0
  74. package/src/frameqr/detector.js +193 -0
  75. package/src/frameqr/encoder.js +157 -0
  76. package/src/frameqr/index.js +43 -0
  77. package/src/frameqr/tables.js +271 -0
  78. package/src/image/binarizer.js +1 -0
  79. package/src/image/grid-sampler.js +1 -0
  80. package/src/image/index.js +1 -0
  81. package/src/image/luminance.js +1 -0
  82. package/src/image/perspective.js +1 -0
  83. package/src/index.js +155 -2
  84. package/src/micropdf417/compaction.js +1 -0
  85. package/src/micropdf417/decoder.js +1 -0
  86. package/src/micropdf417/detector.js +1 -0
  87. package/src/micropdf417/encoder.js +1 -0
  88. package/src/micropdf417/error-correction.js +1 -0
  89. package/src/micropdf417/index.js +1 -0
  90. package/src/micropdf417/tables.js +1 -0
  91. package/src/microqr/decoder.js +246 -0
  92. package/src/microqr/detector.js +356 -0
  93. package/src/microqr/encoder.js +270 -0
  94. package/src/microqr/index.js +37 -0
  95. package/src/microqr/tables.js +317 -0
  96. package/src/oned/addons.js +421 -0
  97. package/src/oned/index.js +77 -59
  98. package/src/oned/patterns.js +1 -0
  99. package/src/oned/reader.js +1 -0
  100. package/src/oned/writers.js +1 -0
  101. package/src/pdf417/compaction.js +1 -0
  102. package/src/pdf417/decoder.js +1 -0
  103. package/src/pdf417/detector.js +1 -0
  104. package/src/pdf417/encoder.js +1 -0
  105. package/src/pdf417/error-correction.js +1 -0
  106. package/src/pdf417/index.js +5 -0
  107. package/src/pdf417/tables.js +1 -0
  108. package/src/qr/decoder.js +1 -0
  109. package/src/qr/detector.js +1 -0
  110. package/src/qr/encoder.js +1 -0
  111. package/src/qr/index.js +1 -0
  112. package/src/qr/tables.js +1 -0
  113. package/src/render/image-data.js +1 -0
  114. package/src/render/index.js +1 -0
  115. package/src/render/options.js +1 -0
  116. package/src/render/png.js +1 -0
  117. package/src/render/svg.js +1 -0
  118. package/src/render/webgl.js +1 -0
  119. package/src/render/webgpu.js +1 -0
  120. package/src/rmqr/decoder.js +102 -0
  121. package/src/rmqr/detector.js +91 -0
  122. package/src/rmqr/encoder.js +173 -0
  123. package/src/rmqr/index.js +38 -0
  124. package/src/rmqr/tables.js +155 -0
@@ -1,225 +1,226 @@
1
- /*!
2
- * Sythos Barcode Suite
3
- *
4
- * MIT License
5
- *
6
- * Copyright (c) 2026 Sythos
7
- *
8
- * Permission is hereby granted, free of charge, to any person obtaining a copy
9
- * of this software and associated documentation files (the "Software"), to deal
10
- * in the Software without restriction, including without limitation the rights
11
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
- * copies of the Software, and to permit persons to whom the Software is
13
- * furnished to do so, subject to the following conditions:
14
- *
15
- * The above copyright notice and this permission notice shall be included in all
16
- * copies or substantial portions of the Software.
17
- *
18
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
- * SOFTWARE.
25
- *
26
- * SPDX-License-Identifier: MIT
27
- *
28
- * Original work. No code from any other barcode implementation.
29
- */
30
-
31
- /**
32
- * Data Matrix ECC 200 detection in a binarized image.
33
- *
34
- * An ECC 200 symbol is distinguished by two neighbouring solid finder borders
35
- * (the L) and two alternating clock borders. The detector first finds dark
36
- * connected components, then scores every legal ECC 200 size and every
37
- * quarter-turn of the component's bounding quadrilateral against those four
38
- * borders. This deliberately verifies the complete border rather than merely
39
- * looking for an L: ordinary text and table rules produce L shapes often.
40
- *
41
- * The resulting quadrilateral is sampled back into the canonical orientation:
42
- * solid borders at left and bottom. It is intentionally independent of the
43
- * payload decoder, so geometry can be used by callers that need the matrix.
44
- *
45
- * @module datamatrix/detector
46
- */
47
-
48
- import { NotFoundError } from '../core/errors.js';
49
- import { sampleGrid, sampleQuad } from '../image/grid-sampler.js';
50
- import { PerspectiveTransform } from '../image/perspective.js';
51
- import { decodeDataMatrix } from './decoder.js';
52
-
53
- // ECC 200 dimensions. DMRE is deliberately not included: it uses a separate
54
- // size table and is not part of the original ECC 200 family implemented here.
55
- const SIZES = [
56
- [10, 10], [12, 12], [14, 14], [16, 16], [18, 18], [20, 20], [22, 22], [24, 24], [26, 26],
57
- [32, 32], [36, 36], [40, 40], [44, 44], [48, 48], [52, 52], [64, 64], [72, 72], [80, 80],
58
- [88, 88], [96, 96], [104, 104], [120, 120], [132, 132], [144, 144],
59
- [18, 8], [32, 8], [26, 12], [36, 12], [36, 16], [48, 16],
60
- ];
61
-
62
- /** @typedef {{x:number, y:number}} Point */
63
- /** @typedef {{corners: Point[], dimension: number, width: number, height: number, moduleSize: number, matrix: import('../core/bit-matrix.js').BitMatrix}} Detection */
64
-
65
- function dark(image, x, y) {
66
- return image.get(Math.max(0, Math.min(image.width - 1, Math.round(x))),
67
- Math.max(0, Math.min(image.height - 1, Math.round(y))));
68
- }
69
-
70
- /** Return components which are large enough to plausibly contain a symbol. */
71
- function components(image) {
72
- const seen = new Uint8Array(image.width * image.height);
73
- const out = [];
74
- const push = (x, y, xs, ys) => { xs.push(x); ys.push(y); };
75
- for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
76
- const start = y * image.width + x;
77
- if (seen[start] || !image.get(x, y)) continue;
78
- const xs = [x], ys = [y]; seen[start] = 1;
79
- let head = 0, minX = x, maxX = x, minY = y, maxY = y;
80
- while (head < xs.length) {
81
- const px = xs[head], py = ys[head++];
82
- if (px < minX) minX = px; if (px > maxX) maxX = px;
83
- if (py < minY) minY = py; if (py > maxY) maxY = py;
84
- for (const [nx, ny] of [[px - 1, py], [px + 1, py], [px, py - 1], [px, py + 1]]) {
85
- if (nx < 0 || ny < 0 || nx >= image.width || ny >= image.height) continue;
86
- const at = ny * image.width + nx;
87
- if (!seen[at] && image.get(nx, ny)) { seen[at] = 1; push(nx, ny, xs, ys); }
88
- }
89
- }
90
- if (maxX - minX >= 7 && maxY - minY >= 7) out.push({ minX, minY, maxX, maxY, pixels: xs.length });
91
- }
92
- return out.sort((a, b) => b.pixels - a.pixels).slice(0, 40);
93
- }
94
-
95
- /** Sample a physical edge at module centres. */
96
- function edge(image, a, b, count) {
97
- const values = [];
98
- for (let i = 0; i < count; i++) {
99
- const t = (i + 0.5) / count;
100
- values.push(dark(image, a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t));
101
- }
102
- return values;
103
- }
104
-
105
- function solidScore(values) {
106
- let n = 0; for (const value of values) if (value) n++;
107
- return n / values.length;
108
- }
109
-
110
- function clockScore(values, startsDark) {
111
- let n = 0;
112
- for (let i = 0; i < values.length; i++) if (values[i] === ((i & 1) === 0 ? startsDark : !startsDark)) n++;
113
- return n / values.length;
114
- }
115
-
116
- /** Count light/dark changes along a physical edge at approximately one-pixel intervals. */
117
- function edgeTransitions(image, a, b) {
118
- const steps = Math.max(1, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y)));
119
- let previous = dark(image, a.x, a.y);
120
- let changes = 0;
121
- for (let i = 1; i <= steps; i++) {
122
- const t = i / steps;
123
- const value = dark(image, a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
124
- if (value !== previous) changes++;
125
- previous = value;
126
- }
127
- return changes;
128
- }
129
-
130
- /** Reject a smaller harmonic whose module-centre samples happen to alternate. */
131
- function transitionCountFits(observed, modules) {
132
- const expected = modules - 1;
133
- const tolerance = Math.max(2, Math.floor(expected * 0.08));
134
- return Math.abs(observed - expected) <= tolerance;
135
- }
136
-
137
- function sample(image, width, height, corners, voting) {
138
- if (width === height) return sampleQuad(image, width, corners, voting);
139
- const [tl, tr, br, bl] = corners;
140
- const transform = PerspectiveTransform.quadToQuad(0, 0, width, 0, width, height, 0, height,
141
- tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y);
142
- return sampleGrid(image, width, height, transform);
143
- }
144
-
145
- /**
146
- * Find Data Matrix symbols in a binarized image.
147
- *
148
- * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage Set bit = dark.
149
- * @returns {Detection | null} The strongest candidate, or null when absent.
150
- */
151
- export function detectDataMatrix(binaryImage) {
152
- if (!binaryImage || !binaryImage.width || !binaryImage.height) {
153
- throw new NotFoundError('detectDataMatrix: no image supplied');
154
- }
155
- const detections = [];
156
- const used = new Set();
157
- for (const box of components(binaryImage)) {
158
- const base = [
159
- { x: box.minX, y: box.minY }, { x: box.maxX + 1, y: box.minY },
160
- { x: box.maxX + 1, y: box.maxY + 1 }, { x: box.minX, y: box.maxY + 1 },
161
- ];
162
- // Profile the actual ink, rather than the outer sampling quadrilateral:
163
- // its far x/y boundary lies one pixel beyond the last dark pixel.
164
- const ink = [
165
- { x: box.minX, y: box.minY }, { x: box.maxX, y: box.minY },
166
- { x: box.maxX, y: box.maxY }, { x: box.minX, y: box.maxY },
167
- ];
168
- for (const [w, h] of SIZES) for (let turn = 0; turn < 4; turn++) {
169
- // A 90 degree turn swaps physical width and height.
170
- const physicalW = (turn & 1) ? h : w, physicalH = (turn & 1) ? w : h;
171
- const pitchX = (box.maxX - box.minX + 1) / physicalW;
172
- const pitchY = (box.maxY - box.minY + 1) / physicalH;
173
- if (Math.min(pitchX, pitchY) < 1 || Math.abs(pitchX - pitchY) > Math.max(pitchX, pitchY) * 0.22) continue;
174
- const corners = base.slice(turn).concat(base.slice(0, turn));
175
- const profile = ink.slice(turn).concat(ink.slice(0, turn));
176
- // Canonical edge order: top clock, right clock, bottom solid, left solid.
177
- const top = edge(binaryImage, profile[0], profile[1], w);
178
- const right = edge(binaryImage, profile[1], profile[2], h);
179
- const bottom = edge(binaryImage, profile[2], profile[3], w);
180
- const left = edge(binaryImage, profile[3], profile[0], h);
181
- // Sampling only the proposed module centres aliases exact harmonics: an
182
- // 80-module clock border, for example, can look like a perfect 16-module
183
- // border. Count transitions at image-pixel resolution as an independent
184
- // dimension measurement before accepting the candidate.
185
- if (!transitionCountFits(edgeTransitions(binaryImage, profile[0], profile[1]), w) ||
186
- !transitionCountFits(edgeTransitions(binaryImage, profile[1], profile[2]), h)) continue;
187
- // The top clock starts dark at the solid left border. The right clock is
188
- // anchored dark at the solid bottom border instead, so its top phase
189
- // depends on the symbol height (all ECC 200 heights are even and
190
- // therefore start light).
191
- const score = (clockScore(top, true) + clockScore(right, (h & 1) === 1) +
192
- solidScore(bottom) + solidScore(left)) / 4;
193
- if (score < 0.88) continue;
194
- const key = `${box.minX},${box.minY},${box.maxX},${box.maxY}`;
195
- if (used.has(key)) continue;
196
- let matrix;
197
- try { matrix = sample(binaryImage, w, h, corners, false); } catch (e) { continue; }
198
- used.add(key);
199
- detections.push({ corners, dimension: w === h ? w : 0, width: w, height: h,
200
- moduleSize: (pitchX + pitchY) / 2, matrix, score });
201
- }
202
- }
203
- detections.sort((a, b) => b.score - a.score || b.moduleSize - a.moduleSize);
204
- return detections[0] ?? null;
205
- }
206
-
207
- /**
208
- * Detect and decode Data Matrix symbols. Detection failure is normal for an
209
- * image without a symbol, so candidates that cannot decode are skipped.
210
- *
211
- * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage
212
- * @returns {(import('./decoder.js').DecodeResult & {corners: Point[]}) | null}
213
- */
214
- export function detectAndDecodeDataMatrix(binaryImage) {
215
- let detection;
216
- try { detection = detectDataMatrix(binaryImage); } catch (e) { return null; }
217
- if (!detection) return null;
218
- for (const voting of [false, true]) {
219
- let matrix = detection.matrix;
220
- try { if (voting) matrix = sample(binaryImage, detection.width, detection.height, detection.corners, true); } catch (e) { continue; }
221
- try { return Object.assign({ corners: detection.corners }, decodeDataMatrix(matrix)); }
222
- catch (e) { /* A geometric candidate is not necessarily a symbol. */ }
223
- }
224
- return null;
225
- }
1
+ /*!
2
+ * Sythos Barcode Suite
3
+ *
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2026 Sythos
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ * SPDX-FileCopyrightText: 2026 Sythos (https://www.sythos.net)
27
+ * SPDX-License-Identifier: MIT
28
+ *
29
+ * Original work. No code from any other barcode implementation.
30
+ */
31
+
32
+ /**
33
+ * Data Matrix ECC 200 detection in a binarized image.
34
+ *
35
+ * An ECC 200 symbol is distinguished by two neighbouring solid finder borders
36
+ * (the L) and two alternating clock borders. The detector first finds dark
37
+ * connected components, then scores every legal ECC 200 size and every
38
+ * quarter-turn of the component's bounding quadrilateral against those four
39
+ * borders. This deliberately verifies the complete border rather than merely
40
+ * looking for an L: ordinary text and table rules produce L shapes often.
41
+ *
42
+ * The resulting quadrilateral is sampled back into the canonical orientation:
43
+ * solid borders at left and bottom. It is intentionally independent of the
44
+ * payload decoder, so geometry can be used by callers that need the matrix.
45
+ *
46
+ * @module datamatrix/detector
47
+ */
48
+
49
+ import { NotFoundError } from '../core/errors.js';
50
+ import { sampleGrid, sampleQuad } from '../image/grid-sampler.js';
51
+ import { PerspectiveTransform } from '../image/perspective.js';
52
+ import { decodeDataMatrix } from './decoder.js';
53
+
54
+ // ECC 200 dimensions. DMRE is deliberately not included: it uses a separate
55
+ // size table and is not part of the original ECC 200 family implemented here.
56
+ const SIZES = [
57
+ [10, 10], [12, 12], [14, 14], [16, 16], [18, 18], [20, 20], [22, 22], [24, 24], [26, 26],
58
+ [32, 32], [36, 36], [40, 40], [44, 44], [48, 48], [52, 52], [64, 64], [72, 72], [80, 80],
59
+ [88, 88], [96, 96], [104, 104], [120, 120], [132, 132], [144, 144],
60
+ [18, 8], [32, 8], [26, 12], [36, 12], [36, 16], [48, 16],
61
+ ];
62
+
63
+ /** @typedef {{x:number, y:number}} Point */
64
+ /** @typedef {{corners: Point[], dimension: number, width: number, height: number, moduleSize: number, matrix: import('../core/bit-matrix.js').BitMatrix}} Detection */
65
+
66
+ function dark(image, x, y) {
67
+ return image.get(Math.max(0, Math.min(image.width - 1, Math.round(x))),
68
+ Math.max(0, Math.min(image.height - 1, Math.round(y))));
69
+ }
70
+
71
+ /** Return components which are large enough to plausibly contain a symbol. */
72
+ function components(image) {
73
+ const seen = new Uint8Array(image.width * image.height);
74
+ const out = [];
75
+ const push = (x, y, xs, ys) => { xs.push(x); ys.push(y); };
76
+ for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
77
+ const start = y * image.width + x;
78
+ if (seen[start] || !image.get(x, y)) continue;
79
+ const xs = [x], ys = [y]; seen[start] = 1;
80
+ let head = 0, minX = x, maxX = x, minY = y, maxY = y;
81
+ while (head < xs.length) {
82
+ const px = xs[head], py = ys[head++];
83
+ if (px < minX) minX = px; if (px > maxX) maxX = px;
84
+ if (py < minY) minY = py; if (py > maxY) maxY = py;
85
+ for (const [nx, ny] of [[px - 1, py], [px + 1, py], [px, py - 1], [px, py + 1]]) {
86
+ if (nx < 0 || ny < 0 || nx >= image.width || ny >= image.height) continue;
87
+ const at = ny * image.width + nx;
88
+ if (!seen[at] && image.get(nx, ny)) { seen[at] = 1; push(nx, ny, xs, ys); }
89
+ }
90
+ }
91
+ if (maxX - minX >= 7 && maxY - minY >= 7) out.push({ minX, minY, maxX, maxY, pixels: xs.length });
92
+ }
93
+ return out.sort((a, b) => b.pixels - a.pixels).slice(0, 40);
94
+ }
95
+
96
+ /** Sample a physical edge at module centres. */
97
+ function edge(image, a, b, count) {
98
+ const values = [];
99
+ for (let i = 0; i < count; i++) {
100
+ const t = (i + 0.5) / count;
101
+ values.push(dark(image, a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t));
102
+ }
103
+ return values;
104
+ }
105
+
106
+ function solidScore(values) {
107
+ let n = 0; for (const value of values) if (value) n++;
108
+ return n / values.length;
109
+ }
110
+
111
+ function clockScore(values, startsDark) {
112
+ let n = 0;
113
+ for (let i = 0; i < values.length; i++) if (values[i] === ((i & 1) === 0 ? startsDark : !startsDark)) n++;
114
+ return n / values.length;
115
+ }
116
+
117
+ /** Count light/dark changes along a physical edge at approximately one-pixel intervals. */
118
+ function edgeTransitions(image, a, b) {
119
+ const steps = Math.max(1, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y)));
120
+ let previous = dark(image, a.x, a.y);
121
+ let changes = 0;
122
+ for (let i = 1; i <= steps; i++) {
123
+ const t = i / steps;
124
+ const value = dark(image, a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
125
+ if (value !== previous) changes++;
126
+ previous = value;
127
+ }
128
+ return changes;
129
+ }
130
+
131
+ /** Reject a smaller harmonic whose module-centre samples happen to alternate. */
132
+ function transitionCountFits(observed, modules) {
133
+ const expected = modules - 1;
134
+ const tolerance = Math.max(2, Math.floor(expected * 0.08));
135
+ return Math.abs(observed - expected) <= tolerance;
136
+ }
137
+
138
+ function sample(image, width, height, corners, voting) {
139
+ if (width === height) return sampleQuad(image, width, corners, voting);
140
+ const [tl, tr, br, bl] = corners;
141
+ const transform = PerspectiveTransform.quadToQuad(0, 0, width, 0, width, height, 0, height,
142
+ tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y);
143
+ return sampleGrid(image, width, height, transform);
144
+ }
145
+
146
+ /**
147
+ * Find Data Matrix symbols in a binarized image.
148
+ *
149
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage Set bit = dark.
150
+ * @returns {Detection | null} The strongest candidate, or null when absent.
151
+ */
152
+ export function detectDataMatrix(binaryImage) {
153
+ if (!binaryImage || !binaryImage.width || !binaryImage.height) {
154
+ throw new NotFoundError('detectDataMatrix: no image supplied');
155
+ }
156
+ const detections = [];
157
+ const used = new Set();
158
+ for (const box of components(binaryImage)) {
159
+ const base = [
160
+ { x: box.minX, y: box.minY }, { x: box.maxX + 1, y: box.minY },
161
+ { x: box.maxX + 1, y: box.maxY + 1 }, { x: box.minX, y: box.maxY + 1 },
162
+ ];
163
+ // Profile the actual ink, rather than the outer sampling quadrilateral:
164
+ // its far x/y boundary lies one pixel beyond the last dark pixel.
165
+ const ink = [
166
+ { x: box.minX, y: box.minY }, { x: box.maxX, y: box.minY },
167
+ { x: box.maxX, y: box.maxY }, { x: box.minX, y: box.maxY },
168
+ ];
169
+ for (const [w, h] of SIZES) for (let turn = 0; turn < 4; turn++) {
170
+ // A 90 degree turn swaps physical width and height.
171
+ const physicalW = (turn & 1) ? h : w, physicalH = (turn & 1) ? w : h;
172
+ const pitchX = (box.maxX - box.minX + 1) / physicalW;
173
+ const pitchY = (box.maxY - box.minY + 1) / physicalH;
174
+ if (Math.min(pitchX, pitchY) < 1 || Math.abs(pitchX - pitchY) > Math.max(pitchX, pitchY) * 0.22) continue;
175
+ const corners = base.slice(turn).concat(base.slice(0, turn));
176
+ const profile = ink.slice(turn).concat(ink.slice(0, turn));
177
+ // Canonical edge order: top clock, right clock, bottom solid, left solid.
178
+ const top = edge(binaryImage, profile[0], profile[1], w);
179
+ const right = edge(binaryImage, profile[1], profile[2], h);
180
+ const bottom = edge(binaryImage, profile[2], profile[3], w);
181
+ const left = edge(binaryImage, profile[3], profile[0], h);
182
+ // Sampling only the proposed module centres aliases exact harmonics: an
183
+ // 80-module clock border, for example, can look like a perfect 16-module
184
+ // border. Count transitions at image-pixel resolution as an independent
185
+ // dimension measurement before accepting the candidate.
186
+ if (!transitionCountFits(edgeTransitions(binaryImage, profile[0], profile[1]), w) ||
187
+ !transitionCountFits(edgeTransitions(binaryImage, profile[1], profile[2]), h)) continue;
188
+ // The top clock starts dark at the solid left border. The right clock is
189
+ // anchored dark at the solid bottom border instead, so its top phase
190
+ // depends on the symbol height (all ECC 200 heights are even and
191
+ // therefore start light).
192
+ const score = (clockScore(top, true) + clockScore(right, (h & 1) === 1) +
193
+ solidScore(bottom) + solidScore(left)) / 4;
194
+ if (score < 0.88) continue;
195
+ const key = `${box.minX},${box.minY},${box.maxX},${box.maxY}`;
196
+ if (used.has(key)) continue;
197
+ let matrix;
198
+ try { matrix = sample(binaryImage, w, h, corners, false); } catch (e) { continue; }
199
+ used.add(key);
200
+ detections.push({ corners, dimension: w === h ? w : 0, width: w, height: h,
201
+ moduleSize: (pitchX + pitchY) / 2, matrix, score });
202
+ }
203
+ }
204
+ detections.sort((a, b) => b.score - a.score || b.moduleSize - a.moduleSize);
205
+ return detections[0] ?? null;
206
+ }
207
+
208
+ /**
209
+ * Detect and decode Data Matrix symbols. Detection failure is normal for an
210
+ * image without a symbol, so candidates that cannot decode are skipped.
211
+ *
212
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage
213
+ * @returns {(import('./decoder.js').DecodeResult & {corners: Point[]}) | null}
214
+ */
215
+ export function detectAndDecodeDataMatrix(binaryImage) {
216
+ let detection;
217
+ try { detection = detectDataMatrix(binaryImage); } catch (e) { return null; }
218
+ if (!detection) return null;
219
+ for (const voting of [false, true]) {
220
+ let matrix = detection.matrix;
221
+ try { if (voting) matrix = sample(binaryImage, detection.width, detection.height, detection.corners, true); } catch (e) { continue; }
222
+ try { return Object.assign({ corners: detection.corners }, decodeDataMatrix(matrix)); }
223
+ catch (e) { /* A geometric candidate is not necessarily a symbol. */ }
224
+ }
225
+ return null;
226
+ }