@sythos/js_barcode_universal 0.1.0 → 1.1.0

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.
@@ -0,0 +1,262 @@
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 decoder for an already sampled symbol.
33
+ *
34
+ * The detector owns locating, perspective correction and orientation. This
35
+ * module starts with the complete, upright symbol including its finder borders.
36
+ * The table entry is deliberately read through a small normalizer so table data
37
+ * remains declarative: it needs total rows/columns, one data-region's rows and
38
+ * columns, data/ECC codeword counts, and either a block count or data block
39
+ * lengths. The standard 144x144 uneven data blocks are supported.
40
+ *
41
+ * @module datamatrix/decoder
42
+ */
43
+
44
+ import { ChecksumError, FormatError } from '../core/errors.js';
45
+ import { GF256_DM } from '../core/galois-field.js';
46
+ import { rsDecode } from '../core/reed-solomon.js';
47
+ import { SYMBOLS } from './tables.js';
48
+
49
+ const CW_PAD = 129;
50
+ const CW_BASE256 = 231;
51
+
52
+ /** @param {object} entry @param {...string} names @returns {number | undefined} */
53
+ function numberField(entry, ...names) {
54
+ for (const name of names) if (Number.isInteger(entry[name])) return entry[name];
55
+ return undefined;
56
+ }
57
+
58
+ /** Normalize the public table entry into the decoder's geometry contract. */
59
+ function layoutFor(width, height) {
60
+ const entry = SYMBOLS.find((s) =>
61
+ numberField(s, 'columns', 'cols', 'matrixColumns', 'width') === width &&
62
+ numberField(s, 'rows', 'matrixRows', 'height') === height);
63
+ if (!entry) throw new FormatError(`Data Matrix: ${width}x${height} is not an ECC 200 symbol size`);
64
+
65
+ const regionRows = numberField(entry, 'dataRegionRows', 'regionRows') ??
66
+ (numberField(entry, 'regionHeight') ? numberField(entry, 'regionHeight') - 2 : undefined);
67
+ const regionCols = numberField(entry, 'dataRegionColumns', 'dataRegionCols', 'regionColumns') ??
68
+ (numberField(entry, 'regionWidth') ? numberField(entry, 'regionWidth') - 2 : undefined);
69
+ const dataCount = numberField(entry, 'dataCodewords', 'dataCapacity');
70
+ const eccCount = numberField(entry, 'errorCodewords', 'eccCodewords');
71
+ const blockCount = numberField(entry, 'interleavedBlocks', 'interleavedBlockCount', 'blockCount', 'rsBlocks') || 1;
72
+ if (!regionRows || !regionCols || dataCount === undefined || eccCount === undefined ||
73
+ height % (regionRows + 2) || width % (regionCols + 2) || eccCount % blockCount) {
74
+ throw new FormatError(`Data Matrix: invalid table layout for ${width}x${height}`);
75
+ }
76
+
77
+ const rows = height / (regionRows + 2);
78
+ const cols = width / (regionCols + 2);
79
+ const blockData = Array.isArray(entry.blockDataCodewords) ? entry.blockDataCodewords.slice() :
80
+ Array.isArray(entry.dataCodewordsPerBlock) ? entry.dataCodewordsPerBlock.slice() : null;
81
+ let dataLengths;
82
+ if (blockData) {
83
+ dataLengths = blockData;
84
+ } else {
85
+ // The sole uneven ECC 200 distribution is 144x144: its first eight of ten
86
+ // blocks contain one extra data codeword. This derives it instead of hiding
87
+ // a magic size check in the deinterleaver.
88
+ const short = Math.floor(dataCount / blockCount);
89
+ dataLengths = new Array(blockCount).fill(short);
90
+ for (let i = 0; i < dataCount % blockCount; i++) dataLengths[i]++;
91
+ }
92
+ if (dataLengths.length !== blockCount || dataLengths.reduce((a, b) => a + b, 0) !== dataCount) {
93
+ throw new FormatError(`Data Matrix: inconsistent block layout for ${width}x${height}`);
94
+ }
95
+ return { entry, regionRows, regionCols, regionRowCount: rows, regionColCount: cols,
96
+ dataRows: rows * regionRows, dataCols: cols * regionCols, dataCount, eccCount,
97
+ blockCount, eccPerBlock: eccCount / blockCount, dataLengths };
98
+ }
99
+
100
+ /** Remove the L/finders from every data region, retaining only placement modules. */
101
+ function extractDataModules(matrix, layout) {
102
+ const data = new Uint8Array(layout.dataRows * layout.dataCols);
103
+ for (let regionY = 0; regionY < layout.regionRowCount; regionY++) {
104
+ for (let regionX = 0; regionX < layout.regionColCount; regionX++) {
105
+ const sourceX = regionX * (layout.regionCols + 2) + 1;
106
+ const sourceY = regionY * (layout.regionRows + 2) + 1;
107
+ for (let y = 0; y < layout.regionRows; y++) {
108
+ const targetY = regionY * layout.regionRows + y;
109
+ for (let x = 0; x < layout.regionCols; x++) {
110
+ data[targetY * layout.dataCols + regionX * layout.regionCols + x] =
111
+ matrix.get(sourceX + x, sourceY + y) ? 1 : 0;
112
+ }
113
+ }
114
+ }
115
+ }
116
+ return data;
117
+ }
118
+
119
+ /** Read placement codewords using the ECC 200 Utah sweep (the inverse writer path). */
120
+ function readPlacement(modules, rows, cols, count) {
121
+ const seen = new Uint8Array(rows * cols);
122
+ const out = new Uint8Array(count);
123
+ const get = (row, col) => modules[row * cols + col] !== 0;
124
+ const module = (row, col) => {
125
+ if (row < 0) { row += rows; col += 4 - ((rows + 4) % 8); }
126
+ if (col < 0) { col += cols; row += 4 - ((cols + 4) % 8); }
127
+ if (row < 0 || row >= rows || col < 0 || col >= cols) {
128
+ throw new FormatError('Data Matrix: placement coordinate escaped data region');
129
+ }
130
+ seen[row * cols + col] = 1;
131
+ return get(row, col) ? 1 : 0;
132
+ };
133
+ const bits = (coords) => coords.reduce((value, p) => (value << 1) | module(p[0], p[1]), 0);
134
+ const utah = (row, col) => bits([[row - 2, col - 2], [row - 2, col - 1], [row - 1, col - 2], [row - 1, col - 1],
135
+ [row - 1, col], [row, col - 2], [row, col - 1], [row, col]]);
136
+ const corner1 = () => bits([[rows - 1, 0], [rows - 1, 1], [rows - 1, 2], [0, cols - 2], [0, cols - 1], [1, cols - 1], [2, cols - 1], [3, cols - 1]]);
137
+ const corner2 = () => bits([[rows - 3, 0], [rows - 2, 0], [rows - 1, 0], [0, cols - 4], [0, cols - 3], [0, cols - 2], [0, cols - 1], [1, cols - 1]]);
138
+ const corner3 = () => bits([[rows - 3, 0], [rows - 2, 0], [rows - 1, 0], [0, cols - 2], [0, cols - 1], [1, cols - 1], [2, cols - 1], [3, cols - 1]]);
139
+ const corner4 = () => bits([[rows - 1, 0], [rows - 1, cols - 1], [0, cols - 3], [0, cols - 2], [0, cols - 1], [1, cols - 3], [1, cols - 2], [1, cols - 1]]);
140
+
141
+ let row = 4, col = 0, n = 0;
142
+ const put = (value) => { if (n < count) out[n++] = value; };
143
+ do {
144
+ if (row === rows && col === 0) put(corner1());
145
+ if (row === rows - 2 && col === 0 && cols % 4 !== 0) put(corner2());
146
+ if (row === rows - 2 && col === 0 && cols % 8 === 4) put(corner3());
147
+ if (row === rows + 4 && col === 2 && cols % 8 === 0) put(corner4());
148
+ do { if (row < rows && col >= 0 && !seen[row * cols + col]) put(utah(row, col)); row -= 2; col += 2; } while (row >= 0 && col < cols);
149
+ row += 1; col += 3;
150
+ do { if (row >= 0 && col < cols && !seen[row * cols + col]) put(utah(row, col)); row += 2; col -= 2; } while (row < rows && col >= 0);
151
+ row += 3; col += 1;
152
+ } while (row < rows || col < cols);
153
+ if (n !== count) throw new FormatError(`Data Matrix: placement yielded ${n}, expected ${count} codewords`);
154
+ return out;
155
+ }
156
+
157
+ /** Restore RS blocks, correct them, then concatenate their data portions. */
158
+ function deinterleaveAndCorrect(codewords, layout) {
159
+ if (codewords.length !== layout.dataCount + layout.eccCount) throw new FormatError('Data Matrix: codeword count mismatch');
160
+ const blocks = layout.dataLengths.map((len) => new Uint8Array(len + layout.eccPerBlock));
161
+ // Data codewords arrive in their original stream order. ECC 200 deals that
162
+ // stream round-robin across the RS blocks, so the inverse is determined by
163
+ // the wire index rather than by splitting it into consecutive block-sized
164
+ // chunks. For 144x144, indices 1550..1557 naturally land in the eight long
165
+ // blocks while the two short blocks remain at 155 data codewords.
166
+ for (let i = 0; i < layout.dataCount; i++) {
167
+ blocks[i % layout.blockCount][Math.floor(i / layout.blockCount)] = codewords[i];
168
+ }
169
+
170
+ // Parity normally begins with block zero. The uneven 144x144 layout rotates
171
+ // the parity wire order to begin with its first short block; derive the same
172
+ // mapping from the declarative lengths instead of keying it to dimensions.
173
+ const longest = Math.max(...layout.dataLengths);
174
+ const firstShort = layout.dataLengths.findIndex((length) => length < longest);
175
+ const rotation = firstShort < 0 ? 0 : firstShort;
176
+ let at = layout.dataCount;
177
+ for (let i = 0; i < layout.eccPerBlock; i++) {
178
+ for (let slot = 0; slot < layout.blockCount; slot++) {
179
+ const block = (slot + rotation) % layout.blockCount;
180
+ blocks[block][layout.dataLengths[block] + i] = codewords[at++];
181
+ }
182
+ }
183
+
184
+ let corrections = 0;
185
+ const data = new Uint8Array(layout.dataCount);
186
+ for (let b = 0; b < blocks.length; b++) {
187
+ corrections += rsDecode(blocks[b], layout.eccPerBlock, GF256_DM, 1);
188
+ }
189
+ // Rebuild the original high-level codeword stream after correction. Keeping
190
+ // this in wire-index order is essential: concatenating block data passes
191
+ // single-block round trips but scrambles every multi-block payload.
192
+ for (let i = 0; i < layout.dataCount; i++) {
193
+ data[i] = blocks[i % layout.blockCount][Math.floor(i / layout.blockCount)];
194
+ }
195
+ return { data, corrections };
196
+ }
197
+
198
+ function unrandomize(value, position) {
199
+ const pseudo = ((149 * position) % 255) + 1;
200
+ return value - pseudo >= 0 ? value - pseudo : value - pseudo + 256;
201
+ }
202
+
203
+ /** Decode ASCII plus Base 256, preserving semantic bytes alongside text. */
204
+ function parseData(data) {
205
+ let text = '';
206
+ const bytes = [];
207
+ let upperShift = false;
208
+ let gs1 = false;
209
+ for (let i = 0; i < data.length;) {
210
+ const cw = data[i++];
211
+ if (cw === CW_PAD) break;
212
+ if (cw <= 128) {
213
+ const value = cw - 1 + (upperShift ? 128 : 0);
214
+ upperShift = false;
215
+ text += String.fromCharCode(value); bytes.push(value); continue;
216
+ }
217
+ if (cw <= 229) {
218
+ const pair = cw - 130;
219
+ const digits = String(pair).padStart(2, '0'); text += digits; bytes.push(digits.charCodeAt(0), digits.charCodeAt(1)); continue;
220
+ }
221
+ if (cw === 232) {
222
+ if (i === 1) gs1 = true;
223
+ else { text += '\x1d'; bytes.push(29); }
224
+ continue;
225
+ }
226
+ if (cw === 235) { upperShift = true; continue; }
227
+ if (cw === CW_BASE256) {
228
+ if (i >= data.length) throw new FormatError('Data Matrix: Base 256 length is missing');
229
+ let length = unrandomize(data[i], i + 1); i++;
230
+ if (length === 0) length = data.length - i;
231
+ else if (length >= 250) {
232
+ if (i >= data.length) throw new FormatError('Data Matrix: Base 256 extended length is missing');
233
+ length = 250 * (length - 249) + unrandomize(data[i], i + 1); i++;
234
+ }
235
+ if (i + length > data.length) throw new FormatError('Data Matrix: Base 256 segment exceeds data capacity');
236
+ const segment = new Uint8Array(length);
237
+ for (let n = 0; n < length; n++, i++) segment[n] = unrandomize(data[i], i + 1);
238
+ bytes.push(...segment);
239
+ for (let n = 0; n < segment.length; n++) text += String.fromCharCode(segment[n]);
240
+ continue;
241
+ }
242
+ throw new FormatError(`Data Matrix: unsupported encoding codeword ${cw}`);
243
+ }
244
+ return { text, bytes: Uint8Array.from(bytes), gs1 };
245
+ }
246
+
247
+ /**
248
+ * Decode an upright, sampled Data Matrix ECC 200 symbol.
249
+ *
250
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix Full symbol, no quiet zone.
251
+ * @returns {{text: string, bytes: Uint8Array, correctedErrors: number, symbol: object}}
252
+ */
253
+ export function decodeDataMatrix(matrix) {
254
+ if (!matrix || !Number.isInteger(matrix.width) || !Number.isInteger(matrix.height)) throw new FormatError('Data Matrix: no matrix supplied');
255
+ const layout = layoutFor(matrix.width, matrix.height);
256
+ const placement = readPlacement(extractDataModules(matrix, layout), layout.dataRows, layout.dataCols, layout.dataCount + layout.eccCount);
257
+ const { data, corrections } = deinterleaveAndCorrect(placement, layout);
258
+ const result = parseData(data);
259
+ return { ...result, corrections, correctedErrors: corrections, symbol: layout.entry };
260
+ }
261
+
262
+ export { ChecksumError };
@@ -0,0 +1,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-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
+ }
@@ -0,0 +1,191 @@
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
+ /** Data Matrix ECC 200 encoder: ASCII/Base256, RS interleaving and Annex F placement. */
32
+ import { BitMatrix } from '../core/bit-matrix.js';
33
+ import { EncodeError } from '../core/errors.js';
34
+ import { GF256_DM } from '../core/galois-field.js';
35
+ import { rsEncode } from '../core/reed-solomon.js';
36
+ import { symbolForDataCodewords } from './tables.js';
37
+
38
+ function asciiCodewords(text) {
39
+ const out = [];
40
+ for (let i = 0; i < text.length;) {
41
+ const a = text.charCodeAt(i);
42
+ if (a > 255) throw new EncodeError('Data Matrix ASCII: characters must fit ISO-8859-1; use Base256 for UTF-8');
43
+ if (i + 1 < text.length) {
44
+ const b = text.charCodeAt(i + 1);
45
+ if (a >= 48 && a <= 57 && b >= 48 && b <= 57) { out.push(130 + (a - 48) * 10 + b - 48); i += 2; continue; }
46
+ }
47
+ if (a <= 127) out.push(a + 1);
48
+ else out.push(235, a - 127);
49
+ i++;
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function bytesFor(value) {
55
+ if (value instanceof Uint8Array) return value;
56
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
57
+ if (typeof value !== 'string') throw new EncodeError('Data Matrix: value must be a string or byte array');
58
+ return new TextEncoder().encode(value);
59
+ }
60
+
61
+ function randomize255(value, position) {
62
+ const pseudo = (149 * position) % 255 + 1;
63
+ return value + pseudo <= 255 ? value + pseudo : value + pseudo - 256;
64
+ }
65
+
66
+ function base256Codewords(value, prefixLength = 0) {
67
+ const bytes = bytesFor(value);
68
+ if (bytes.length > 1555) throw new EncodeError('Data Matrix Base256: payload exceeds ECC 200 capacity');
69
+ const out = [231];
70
+ if (bytes.length <= 249) out.push(bytes.length);
71
+ else out.push(Math.floor(bytes.length / 250) + 249, bytes.length % 250);
72
+ // Base256 randomization uses the absolute 1-based codeword position in the
73
+ // symbol. A leading GS1 FNC1 therefore shifts every randomized codeword.
74
+ for (let i = 1; i < out.length; i++) out[i] = randomize255(out[i], prefixLength + i + 1);
75
+ for (const b of bytes) out.push(randomize255(b, prefixLength + out.length + 1));
76
+ return out;
77
+ }
78
+
79
+ function pad(data, capacity) {
80
+ const out = data.slice();
81
+ if (out.length < capacity) out.push(129);
82
+ while (out.length < capacity) {
83
+ const position = out.length + 1;
84
+ const pseudo = (149 * position) % 253 + 1;
85
+ const v = 129 + pseudo;
86
+ out.push(v <= 254 ? v : v - 254);
87
+ }
88
+ return out;
89
+ }
90
+
91
+ function interleave(data, symbol) {
92
+ const blocks = symbol.dataBlockLengths.map((length) => ({ data: new Array(length), ecc: null }));
93
+ let at = 0;
94
+ const longest = Math.max(...symbol.dataBlockLengths);
95
+ // Data codewords are dealt across the RS blocks by column. Splitting the
96
+ // stream into consecutive chunks and then interleaving those chunks looks
97
+ // self-consistent to a decoder doing the same inverse operation, but it is
98
+ // not ECC 200's wire order once a symbol has multiple blocks.
99
+ for (let i = 0; i < longest; i++) {
100
+ for (const block of blocks) if (i < block.data.length) block.data[i] = data[at++];
101
+ }
102
+ for (const block of blocks) {
103
+ // ECC 200 starts its generator roots at alpha^1 (generator base 1).
104
+ block.ecc = rsEncode(block.data, symbol.eccPerBlock, GF256_DM, 1);
105
+ }
106
+
107
+ const out = [];
108
+ for (let i = 0; i < longest; i++) for (const b of blocks) if (i < b.data.length) out.push(b.data[i]);
109
+ // The 144x144 symbol has eight long and two short data blocks. Its parity
110
+ // interleave begins with the first short block; deriving the rotation from
111
+ // the declarative lengths keeps that exception out of a size-specific test.
112
+ const eccOffset = blocks.findIndex((block) => block.data.length < longest);
113
+ const rotation = eccOffset < 0 ? 0 : eccOffset;
114
+ for (let i = 0; i < symbol.eccPerBlock; i++) {
115
+ for (let b = 0; b < blocks.length; b++) out.push(blocks[(b + rotation) % blocks.length].ecc[i]);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ function place(codewords, rows, cols) {
121
+ const cells = new Int8Array(rows * cols).fill(-1);
122
+ const bit = (row, col, pos, n) => {
123
+ if (row < 0) { row += rows; col += 4 - ((rows + 4) % 8); }
124
+ if (col < 0) { col += cols; row += 4 - ((cols + 4) % 8); }
125
+ cells[row * cols + col] = (codewords[pos] >>> (8 - n)) & 1;
126
+ };
127
+ const utah = (r, c, p) => { bit(r - 2, c - 2, p, 1); bit(r - 2, c - 1, p, 2); bit(r - 1, c - 2, p, 3); bit(r - 1, c - 1, p, 4); bit(r - 1, c, p, 5); bit(r, c - 2, p, 6); bit(r, c - 1, p, 7); bit(r, c, p, 8); };
128
+ const corner1 = (p) => { bit(rows - 1, 0, p, 1); bit(rows - 1, 1, p, 2); bit(rows - 1, 2, p, 3); bit(0, cols - 2, p, 4); bit(0, cols - 1, p, 5); bit(1, cols - 1, p, 6); bit(2, cols - 1, p, 7); bit(3, cols - 1, p, 8); };
129
+ const corner2 = (p) => { bit(rows - 3, 0, p, 1); bit(rows - 2, 0, p, 2); bit(rows - 1, 0, p, 3); bit(0, cols - 4, p, 4); bit(0, cols - 3, p, 5); bit(0, cols - 2, p, 6); bit(0, cols - 1, p, 7); bit(1, cols - 1, p, 8); };
130
+ const corner3 = (p) => { bit(rows - 3, 0, p, 1); bit(rows - 2, 0, p, 2); bit(rows - 1, 0, p, 3); bit(0, cols - 2, p, 4); bit(0, cols - 1, p, 5); bit(1, cols - 1, p, 6); bit(2, cols - 1, p, 7); bit(3, cols - 1, p, 8); };
131
+ const corner4 = (p) => { bit(rows - 1, 0, p, 1); bit(rows - 1, cols - 1, p, 2); bit(0, cols - 3, p, 3); bit(0, cols - 2, p, 4); bit(0, cols - 1, p, 5); bit(1, cols - 3, p, 6); bit(1, cols - 2, p, 7); bit(1, cols - 1, p, 8); };
132
+ let row = 4, col = 0, pos = 0;
133
+ do {
134
+ if (row === rows && col === 0) corner1(pos++);
135
+ if (row === rows - 2 && col === 0 && cols % 4 !== 0) corner2(pos++);
136
+ if (row === rows - 2 && col === 0 && cols % 8 === 4) corner3(pos++);
137
+ if (row === rows + 4 && col === 2 && cols % 8 === 0) corner4(pos++);
138
+ do { if (row < rows && col >= 0 && cells[row * cols + col] < 0) utah(row, col, pos++); row -= 2; col += 2; } while (row >= 0 && col < cols);
139
+ row += 1; col += 3;
140
+ do { if (row >= 0 && col < cols && cells[row * cols + col] < 0) utah(row, col, pos++); row += 2; col -= 2; } while (row < rows && col >= 0);
141
+ row += 3; col += 1;
142
+ } while (row < rows || col < cols);
143
+ if (cells[cells.length - 1] < 0) { cells[cells.length - 1] = 1; cells[cells.length - cols - 2] = 1; }
144
+ if (pos !== codewords.length) throw new EncodeError(`Data Matrix: placement consumed ${pos} of ${codewords.length} codewords`);
145
+ return cells;
146
+ }
147
+
148
+ function buildMatrix(codewords, symbol) {
149
+ const regionCols = symbol.width / symbol.regionWidth;
150
+ const regionRows = symbol.height / symbol.regionHeight;
151
+ const dataWidth = symbol.dataRegionColumns;
152
+ const dataHeight = symbol.dataRegionRows;
153
+ const data = place(codewords, regionRows * dataHeight, regionCols * dataWidth);
154
+ const matrix = new BitMatrix(symbol.width, symbol.height);
155
+ for (let ry = 0; ry < regionRows; ry++) for (let rx = 0; rx < regionCols; rx++) {
156
+ const x0 = rx * symbol.regionWidth, y0 = ry * symbol.regionHeight;
157
+ for (let x = 0; x < symbol.regionWidth; x++) { if ((x & 1) === 0) matrix.set(x0 + x, y0); matrix.set(x0 + x, y0 + dataHeight + 1); }
158
+ // The top and right timing borders are complementary: top-left is dark,
159
+ // top-right is light, and the solid bottom-right corner remains dark.
160
+ for (let y = 0; y < symbol.regionHeight; y++) { matrix.set(x0, y0 + y); if ((y & 1) === 1) matrix.set(x0 + dataWidth + 1, y0 + y); }
161
+ for (let y = 0; y < dataHeight; y++) for (let x = 0; x < dataWidth; x++) if (data[(ry * dataHeight + y) * (regionCols * dataWidth) + rx * dataWidth + x]) matrix.set(x0 + 1 + x, y0 + 1 + y);
162
+ }
163
+ return matrix;
164
+ }
165
+
166
+ /** Encode a string (ASCII mode) or byte payload (Base256) into Data Matrix ECC 200. */
167
+ export function encodeDataMatrix(value, options = {}) {
168
+ const encoding = options.encoding ?? (value instanceof Uint8Array ? 'base256' : 'ascii');
169
+ let raw;
170
+ if (encoding === 'ascii') {
171
+ if (typeof value !== 'string') throw new EncodeError('Data Matrix ASCII: value must be a string');
172
+ raw = asciiCodewords(value);
173
+ } else if (encoding === 'base256') raw = base256Codewords(value, options.gs1 === true ? 1 : 0);
174
+ else throw new EncodeError(`Data Matrix: unsupported encoding "${encoding}"`);
175
+ // GS1 DataMatrix is ECC 200 with FNC1 in the first codeword position.
176
+ if (options.gs1 === true) raw.unshift(232);
177
+ const shape = options.shape ?? 'any';
178
+ if (shape !== 'any' && shape !== 'square' && shape !== 'rectangular') throw new EncodeError(`Data Matrix: invalid shape "${shape}"`);
179
+ const symbol = symbolForDataCodewords(raw.length, shape);
180
+ if (!symbol) throw new EncodeError(`Data Matrix: ${raw.length} data codewords do not fit an ECC 200 ${shape} symbol`);
181
+ return buildMatrix(interleave(pad(raw, symbol.dataCodewords), symbol), symbol);
182
+ }
183
+
184
+ /** Encode already compacted ASCII/Base256 codewords, primarily for conformance tests. */
185
+ export function encodeDataMatrixCodewords(codewords, options = {}) {
186
+ if (!Array.isArray(codewords) && !(codewords instanceof Uint8Array)) throw new EncodeError('Data Matrix: codewords must be an array');
187
+ for (const c of codewords) if (!Number.isInteger(c) || c < 0 || c > 255) throw new EncodeError('Data Matrix: codewords must be bytes');
188
+ const symbol = symbolForDataCodewords(codewords.length, options.shape ?? 'any');
189
+ if (!symbol) throw new EncodeError('Data Matrix: codewords do not fit ECC 200');
190
+ return buildMatrix(interleave(pad(Array.from(codewords), symbol.dataCodewords), symbol), symbol);
191
+ }