tapirscan 1.2.1 → 1.3.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.
Files changed (84) hide show
  1. package/LICENSE +220 -0
  2. package/README.md +384 -226
  3. package/dist/browser-worker.d.ts +33 -0
  4. package/dist/browser-worker.js +83 -0
  5. package/dist/browser.d.ts +44 -0
  6. package/dist/browser.js +211 -0
  7. package/dist/freeze.d.ts +6 -0
  8. package/dist/freeze.js +7 -0
  9. package/dist/index.d.ts +53 -46
  10. package/dist/index.js +168 -209
  11. package/dist/layout.d.ts +19 -0
  12. package/dist/layout.js +27 -0
  13. package/dist/multiformat/format-registry.d.ts +26 -0
  14. package/dist/multiformat/format-registry.js +63 -0
  15. package/dist/multiformat/formats.d.ts +4 -24
  16. package/dist/multiformat/formats.js +15 -46
  17. package/dist/rust-session.d.ts +19 -0
  18. package/dist/rust-session.js +102 -0
  19. package/examples/camera.html +28 -29
  20. package/examples/vite/README.md +31 -0
  21. package/examples/vite/index.html +14 -0
  22. package/examples/vite/main.js +33 -0
  23. package/examples/vite/package.json +16 -0
  24. package/examples/vite/vite.config.js +6 -0
  25. package/package.json +28 -11
  26. package/wasm/build.json +295 -0
  27. package/wasm/experimental-turbo16.wasm +0 -0
  28. package/wasm/experimental-turbo2.wasm +0 -0
  29. package/wasm/experimental-turbo4.wasm +0 -0
  30. package/wasm/experimental-turbo8.wasm +0 -0
  31. package/wasm/high.wasm +0 -0
  32. package/wasm/low.wasm +0 -0
  33. package/wasm/medium.wasm +0 -0
  34. package/wasm/very-high.wasm +0 -0
  35. package/dist/completion-host.d.mts +0 -40
  36. package/dist/completion-host.mjs +0 -188
  37. package/dist/detail-20260914/continuity.d.mts +0 -2
  38. package/dist/detail-20260914/continuity.mjs +0 -62
  39. package/dist/detail-20260914/detail-proposals-rich.d.mts +0 -13
  40. package/dist/detail-20260914/detail-proposals-rich.mjs +0 -53
  41. package/dist/detail-20260914/direct-recovery.d.mts +0 -28
  42. package/dist/detail-20260914/direct-recovery.mjs +0 -139
  43. package/dist/detail-20260914/host.d.mts +0 -40
  44. package/dist/detail-20260914/host.mjs +0 -280
  45. package/dist/detail-20260914/scanner.d.mts +0 -12
  46. package/dist/detail-20260914/scanner.mjs +0 -64
  47. package/dist/detail-20260914/source-evidence.d.mts +0 -10
  48. package/dist/detail-20260914/source-evidence.mjs +0 -94
  49. package/dist/detail-canvas.d.ts +0 -35
  50. package/dist/detail-canvas.js +0 -73
  51. package/dist/detail-runtime/direct-recovery.d.mts +0 -28
  52. package/dist/detail-runtime/direct-recovery.mjs +0 -142
  53. package/dist/detail-runtime/host.d.mts +0 -40
  54. package/dist/detail-runtime/host.mjs +0 -284
  55. package/dist/detail-runtime/scanner.d.mts +0 -12
  56. package/dist/detail-runtime/scanner.mjs +0 -70
  57. package/dist/detail.d.ts +0 -20
  58. package/dist/detail.js +0 -84
  59. package/dist/host.d.ts +0 -112
  60. package/dist/host.js +0 -184
  61. package/dist/host64.d.ts +0 -112
  62. package/dist/host64.js +0 -184
  63. package/dist/multiformat/coverage.d.ts +0 -7
  64. package/dist/multiformat/coverage.js +0 -26
  65. package/dist/multiformat/geometry.d.ts +0 -37
  66. package/dist/multiformat/geometry.js +0 -132
  67. package/dist/multiformat/linear-duplicates.d.ts +0 -16
  68. package/dist/multiformat/linear-duplicates.js +0 -163
  69. package/dist/multiformat/pixels.d.ts +0 -3
  70. package/dist/multiformat/pixels.js +0 -36
  71. package/dist/multiformat/scanner.d.ts +0 -60
  72. package/dist/multiformat/scanner.js +0 -382
  73. package/dist/multiformat-host.d.ts +0 -121
  74. package/dist/multiformat-host.js +0 -207
  75. package/dist/policy.d.ts +0 -12
  76. package/dist/policy.js +0 -12
  77. package/examples/scan-worker.mjs +0 -20
  78. package/examples/worker-client.mjs +0 -63
  79. package/wasm/high-shared-retail-portable-20260919.wasm +0 -0
  80. package/wasm/low-shared-retail-portable-20260919.wasm +0 -0
  81. package/wasm/medium-shared-retail-portable-20260919.wasm +0 -0
  82. package/wasm/multiformat.json +0 -7
  83. package/wasm/multiformat.wasm +0 -0
  84. package/wasm/very-high-shared-retail-portable-20260919.wasm +0 -0
package/dist/host.js DELETED
@@ -1,184 +0,0 @@
1
- /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
2
- export function isQuadShape(value) {
3
- if (!Array.isArray(value) || value.length !== 4)
4
- return false;
5
- for (let i = 0; i < 4; i++) {
6
- if (!Object.hasOwn(value, i))
7
- return false;
8
- const point = value[i];
9
- if (!Array.isArray(point) || point.length !== 2)
10
- return false;
11
- for (let j = 0; j < 2; j++)
12
- if (!Object.hasOwn(point, j) || typeof point[j] !== 'number')
13
- return false;
14
- }
15
- return true;
16
- }
17
- export class ScannerError extends Error {
18
- code;
19
- constructor(code, message) { super(message); this.name = 'ScannerError'; this.code = code; }
20
- }
21
- function integer(value, min, max, name) {
22
- if (!Number.isSafeInteger(value) || value < min || value > max)
23
- throw new ScannerError('invalid_input', `Invalid ${name}`);
24
- return value;
25
- }
26
- function status(code) {
27
- if (code !== 0)
28
- throw new ScannerError(`core_${code}`, `Independent scanner rejected operation (${code})`);
29
- }
30
- function parseFrame(text, count) {
31
- const v = JSON.parse(text);
32
- if (!v || typeof v !== 'object')
33
- throw new ScannerError('invalid_output', 'Expected frame object');
34
- const f = v;
35
- if (!Array.isArray(f.candidates) || f.candidates.length !== count || !Array.isArray(f.barcodes) || typeof f.unfinished !== 'boolean' || !f.reconciliation)
36
- throw new ScannerError('invalid_output', 'Invalid frame shape');
37
- for (let i = 0; i < f.candidates.length; i++) {
38
- const c = f.candidates[i];
39
- if (c.candidate_index !== i || !Array.isArray(c.coverage) || c.coverage.length !== 4 || !Array.isArray(c.observations) || !Array.isArray(c.detections) || typeof c.error !== 'boolean')
40
- throw new ScannerError('invalid_output', 'Invalid candidate shape');
41
- }
42
- for (const b of f.barcodes)
43
- if (!/^\d{13}$/.test(b.text) || !Array.isArray(b.polygon) || b.polygon.length !== 4 || !Array.isArray(b.candidate_indices) || b.candidate_indices.some(i => !Number.isInteger(i) || i < 0 || i >= count))
44
- throw new ScannerError('invalid_output', 'Invalid barcode shape');
45
- return f;
46
- }
47
- /** Validate before asynchronous work; returned bytes are owned by the caller. */
48
- export function snapshotImage(image) {
49
- if (!image || typeof image !== 'object')
50
- throw new ScannerError('invalid_input', 'Invalid image');
51
- const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
52
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
53
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
54
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
55
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
56
- if (image.data.byteLength < required)
57
- throw new ScannerError('invalid_input', 'Image buffer is too short');
58
- return { data: new Uint8Array(image.data.subarray(0, required)), width, height, channels: image.channels, stride };
59
- }
60
- export function snapshotPolicy(policy) {
61
- if (!policy || typeof policy !== 'object')
62
- throw new ScannerError('invalid_input', 'Invalid policy');
63
- const copy = { ...policy };
64
- for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
65
- if (copy[key] !== undefined && typeof copy[key] !== 'boolean')
66
- throw new ScannerError('invalid_input', `Invalid ${key}`);
67
- integer(copy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
68
- integer(copy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
69
- integer(copy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
70
- integer(copy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
71
- integer(copy.maxResults ?? 1024, 1, 4096, 'result budget');
72
- return copy;
73
- }
74
- /** Uncalibrated support ordering; ties preserve spatial output order. */
75
- export function rankBarcodes(barcodes) {
76
- return [...barcodes].sort((a, b) => b.support - a.support);
77
- }
78
- export class IndependentScanner {
79
- #exports;
80
- #handle;
81
- constructor(exports) {
82
- this.#exports = exports;
83
- if (exports.regions_version() !== 1)
84
- throw new ScannerError('abi_version', 'Unsupported scanner ABI');
85
- this.#handle = exports.regions_new();
86
- if (!this.#handle)
87
- throw new ScannerError('capacity', 'Scanner handle capacity exhausted');
88
- }
89
- static async create(bytes) {
90
- const module = await WebAssembly.compile(bytes);
91
- const instance = await WebAssembly.instantiate(module, {});
92
- const exports = instance.exports;
93
- for (const name of ['regions_localize', 'regions_version', 'regions_new', 'regions_destroy', 'regions_prepare', 'regions_input_ptr', 'regions_input_len', 'regions_quads_ptr', 'regions_output_ptr', 'regions_output_len', 'regions_scan']) {
94
- if (typeof instance.exports[name] !== 'function')
95
- throw new ScannerError('abi_shape', `Missing ${name}`);
96
- }
97
- if (!(exports.memory instanceof WebAssembly.Memory))
98
- throw new ScannerError('abi_shape', 'Missing memory');
99
- return new IndependentScanner(exports);
100
- }
101
- /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
102
- scan(image, quads, policy = {}) {
103
- return this.#scan(image, quads, policy, false);
104
- }
105
- /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
106
- scanLocalized(image, policy = {}, fitLimit = 8, fullFrame = false) {
107
- const start = performance.now();
108
- if (!this.#handle)
109
- throw new ScannerError('disposed', 'Scanner is disposed');
110
- if (!image || typeof image !== 'object')
111
- throw new ScannerError('invalid_input', 'Invalid image');
112
- const width = integer(image.width, 3, 0xffffffff, 'width'), height = integer(image.height, 3, 0xffffffff, 'height');
113
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
114
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
115
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
116
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
117
- if (image.data.byteLength < required)
118
- throw new ScannerError('invalid_input', 'Image buffer is too short');
119
- integer(fitLimit, 0, 8, 'shear limit');
120
- const e = this.#exports, id = this.#handle;
121
- status(e.regions_prepare(id, width, height, image.channels, stride));
122
- if (e.regions_input_len(id) !== required)
123
- throw new ScannerError('abi_shape', 'Input allocation mismatch');
124
- new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
125
- status(e.regions_localize(id, fitLimit));
126
- const localization = JSON.parse(new TextDecoder().decode(new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id))));
127
- if (!Array.isArray(localization.proposals) || localization.proposals.length > 32 || localization.proposals.some((p) => !isQuadShape(p.polygon)))
128
- throw new ScannerError('abi_shape', 'Invalid localization');
129
- const searchWindows = fullFrame ? [{ kind: 'full_frame_search', polygon: [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]], candidateIndex: localization.proposals.length }] : [];
130
- const localizationMs = performance.now() - start, decodeStart = performance.now();
131
- const scan = this.#scan(image, [...localization.proposals.map((p) => p.polygon), ...searchWindows.map(p => p.polygon)], policy, true);
132
- return { localization, searchWindows, scan, localizationMs, decodingMs: performance.now() - decodeStart, scanMs: performance.now() - start };
133
- }
134
- #scan(image, quads, policy, prepared) {
135
- const start = performance.now();
136
- if (!this.#handle)
137
- throw new ScannerError('disposed', 'Scanner is disposed');
138
- if (!image || typeof image !== 'object' || !Array.isArray(quads) || !policy || typeof policy !== 'object')
139
- throw new ScannerError('invalid_input', 'Invalid scan arguments');
140
- for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
141
- if (policy[key] !== undefined && typeof policy[key] !== 'boolean')
142
- throw new ScannerError('invalid_input', `Invalid ${key}`);
143
- const e = this.#exports, id = this.#handle;
144
- const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
145
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
146
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
147
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
148
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
149
- if (image.data.byteLength < required)
150
- throw new ScannerError('invalid_input', 'Image buffer is too short');
151
- integer(quads.length, 0, 64, 'candidate count');
152
- for (const q of quads)
153
- if (!isQuadShape(q))
154
- throw new ScannerError('invalid_input', 'Invalid quad shape');
155
- const perCandidate = integer(policy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
156
- const perFrame = integer(policy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
157
- const checks = integer(policy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
158
- const pixels = integer(policy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
159
- const results = integer(policy.maxResults ?? 1024, 1, 4096, 'result budget');
160
- const flags = (policy.transitionCleanup ? 1 : 0) | (policy.sourceIdentity ? 2 : 0) | (policy.interiorNormalization ? 4 : 0) | (policy.guardBias ? 8 : 0) | (policy.allowSingleRow ? 16 : 0);
161
- if (!prepared) {
162
- status(e.regions_prepare(id, width, height, image.channels, stride));
163
- if (e.regions_input_len(id) !== required)
164
- throw new ScannerError('abi_shape', 'Input allocation mismatch');
165
- new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
166
- }
167
- const coordinates = new Float64Array(e.memory.buffer, e.regions_quads_ptr(id), 512);
168
- quads.forEach((q, i) => q.forEach((p, j) => { coordinates[i * 8 + j * 2] = p[0]; coordinates[i * 8 + j * 2 + 1] = p[1]; }));
169
- status(e.regions_scan(id, quads.length, flags, perCandidate, perFrame, checks, pixels, results));
170
- // Scan can grow memory. Never reuse the earlier input/coordinate views.
171
- const output = new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id)).slice();
172
- const frame = parseFrame(new TextDecoder().decode(output), quads.length);
173
- return { ...frame, candidateTimingsAvailable: false, elapsedMs: performance.now() - start };
174
- }
175
- /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
176
- best(result) {
177
- return rankBarcodes(result.barcodes)[0];
178
- }
179
- dispose() { if (this.#handle) {
180
- const id = this.#handle;
181
- this.#handle = 0;
182
- status(this.#exports.regions_destroy(id));
183
- } }
184
- }
package/dist/host64.d.ts DELETED
@@ -1,112 +0,0 @@
1
- /** Independent EAN-13 supplied-region scanner. Experimental; no localizer or
2
- * reference decoder is imported. All result confidence remains uncalibrated. */
3
- export type Point = readonly [number, number];
4
- export type Quad = readonly [Point, Point, Point, Point];
5
- export interface Image {
6
- data: Uint8Array;
7
- width: number;
8
- height: number;
9
- channels: 1 | 3 | 4;
10
- stride: number;
11
- }
12
- export interface Policy {
13
- transitionCleanup?: boolean;
14
- sourceIdentity?: boolean;
15
- interiorNormalization?: boolean;
16
- guardBias?: boolean;
17
- /** Experimental: accept one full-quiet scanline; increases false-read risk. Default false. */
18
- allowSingleRow?: boolean;
19
- maxRetryPathsPerCandidate?: number;
20
- maxRetryPathsPerFrame?: number;
21
- maxAssociationChecks?: number;
22
- maxAssociationPixels?: number;
23
- maxResults?: number;
24
- }
25
- export interface Detection {
26
- text: string;
27
- polygon: Quad;
28
- support: number;
29
- axis: number;
30
- }
31
- export interface Barcode extends Detection {
32
- candidate_indices: number[];
33
- }
34
- export interface Observation {
35
- text: string;
36
- axis: number;
37
- fraction: number;
38
- left: number;
39
- right: number;
40
- cost: number;
41
- gap: number;
42
- }
43
- export interface Candidate {
44
- candidate_index: number;
45
- coverage: readonly (readonly [number | null, number | null])[];
46
- error: boolean;
47
- error_detail: 'invalid_geometry' | 'sampling_error' | null;
48
- unfinished: boolean;
49
- ms: number;
50
- work: Record<string, number>;
51
- detections: Detection[];
52
- observations: Observation[];
53
- }
54
- export interface ScanFrame {
55
- unfinished: boolean;
56
- candidates: Candidate[];
57
- barcodes: Barcode[];
58
- reconciliation: {
59
- comparisons: number;
60
- merged: number;
61
- ambiguous: number;
62
- conflicting: number;
63
- pending_observations: number;
64
- truncated: boolean;
65
- source_pairs: number;
66
- source_matches: number;
67
- source_pixels: number;
68
- source_capped: number;
69
- pending_coverage_checks: number;
70
- pending_quarantined: number;
71
- };
72
- }
73
- export interface ScanResult extends ScanFrame {
74
- /** This WASM build has no internal clock. Candidate ms values are unavailable zeros. */
75
- candidateTimingsAvailable: false;
76
- /** Actual host wall time, including validation, preparation/copies, decode and JSON parsing. */
77
- elapsedMs: number;
78
- }
79
- /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
80
- export declare function isQuadShape(value: unknown): value is Quad;
81
- export declare class ScannerError extends Error {
82
- readonly code: string;
83
- constructor(code: string, message: string);
84
- }
85
- /** Validate before asynchronous work; returned bytes are owned by the caller. */
86
- export declare function snapshotImage(image: Image): Image;
87
- export declare function snapshotPolicy(policy: Policy): Policy;
88
- /** Uncalibrated support ordering; ties preserve spatial output order. */
89
- export declare function rankBarcodes(barcodes: readonly Barcode[]): Barcode[];
90
- export declare class IndependentScanner {
91
- #private;
92
- private constructor();
93
- static create(bytes: BufferSource): Promise<IndependentScanner>;
94
- /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
95
- scan(image: Image, quads: readonly Quad[], policy?: Policy): ScanResult;
96
- /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
97
- scanLocalized(image: Image, policy?: Policy, fitLimit?: number, fullFrame?: boolean): {
98
- localization: any;
99
- searchWindows: {
100
- kind: string;
101
- polygon: number[][];
102
- candidateIndex: any;
103
- }[];
104
- scan: ScanResult;
105
- localizationMs: number;
106
- decodingMs: number;
107
- scanMs: number;
108
- };
109
- /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
110
- best(result: ScanFrame): Barcode | undefined;
111
- dispose(): void;
112
- }
package/dist/host64.js DELETED
@@ -1,184 +0,0 @@
1
- /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
2
- export function isQuadShape(value) {
3
- if (!Array.isArray(value) || value.length !== 4)
4
- return false;
5
- for (let i = 0; i < 4; i++) {
6
- if (!Object.hasOwn(value, i))
7
- return false;
8
- const point = value[i];
9
- if (!Array.isArray(point) || point.length !== 2)
10
- return false;
11
- for (let j = 0; j < 2; j++)
12
- if (!Object.hasOwn(point, j) || typeof point[j] !== 'number')
13
- return false;
14
- }
15
- return true;
16
- }
17
- export class ScannerError extends Error {
18
- code;
19
- constructor(code, message) { super(message); this.name = 'ScannerError'; this.code = code; }
20
- }
21
- function integer(value, min, max, name) {
22
- if (!Number.isSafeInteger(value) || value < min || value > max)
23
- throw new ScannerError('invalid_input', `Invalid ${name}`);
24
- return value;
25
- }
26
- function status(code) {
27
- if (code !== 0)
28
- throw new ScannerError(`core_${code}`, `Independent scanner rejected operation (${code})`);
29
- }
30
- function parseFrame(text, count) {
31
- const v = JSON.parse(text);
32
- if (!v || typeof v !== 'object')
33
- throw new ScannerError('invalid_output', 'Expected frame object');
34
- const f = v;
35
- if (!Array.isArray(f.candidates) || f.candidates.length !== count || !Array.isArray(f.barcodes) || typeof f.unfinished !== 'boolean' || !f.reconciliation)
36
- throw new ScannerError('invalid_output', 'Invalid frame shape');
37
- for (let i = 0; i < f.candidates.length; i++) {
38
- const c = f.candidates[i];
39
- if (c.candidate_index !== i || !Array.isArray(c.coverage) || c.coverage.length !== 4 || !Array.isArray(c.observations) || !Array.isArray(c.detections) || typeof c.error !== 'boolean')
40
- throw new ScannerError('invalid_output', 'Invalid candidate shape');
41
- }
42
- for (const b of f.barcodes)
43
- if (!/^\d{13}$/.test(b.text) || !Array.isArray(b.polygon) || b.polygon.length !== 4 || !Array.isArray(b.candidate_indices) || b.candidate_indices.some(i => !Number.isInteger(i) || i < 0 || i >= count))
44
- throw new ScannerError('invalid_output', 'Invalid barcode shape');
45
- return f;
46
- }
47
- /** Validate before asynchronous work; returned bytes are owned by the caller. */
48
- export function snapshotImage(image) {
49
- if (!image || typeof image !== 'object')
50
- throw new ScannerError('invalid_input', 'Invalid image');
51
- const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
52
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
53
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
54
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
55
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
56
- if (image.data.byteLength < required)
57
- throw new ScannerError('invalid_input', 'Image buffer is too short');
58
- return { data: new Uint8Array(image.data.subarray(0, required)), width, height, channels: image.channels, stride };
59
- }
60
- export function snapshotPolicy(policy) {
61
- if (!policy || typeof policy !== 'object')
62
- throw new ScannerError('invalid_input', 'Invalid policy');
63
- const copy = { ...policy };
64
- for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
65
- if (copy[key] !== undefined && typeof copy[key] !== 'boolean')
66
- throw new ScannerError('invalid_input', `Invalid ${key}`);
67
- integer(copy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
68
- integer(copy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
69
- integer(copy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
70
- integer(copy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
71
- integer(copy.maxResults ?? 1024, 1, 4096, 'result budget');
72
- return copy;
73
- }
74
- /** Uncalibrated support ordering; ties preserve spatial output order. */
75
- export function rankBarcodes(barcodes) {
76
- return [...barcodes].sort((a, b) => b.support - a.support);
77
- }
78
- export class IndependentScanner {
79
- #exports;
80
- #handle;
81
- constructor(exports) {
82
- this.#exports = exports;
83
- if (exports.regions_version() !== 1)
84
- throw new ScannerError('abi_version', 'Unsupported scanner ABI');
85
- this.#handle = exports.regions_new();
86
- if (!this.#handle)
87
- throw new ScannerError('capacity', 'Scanner handle capacity exhausted');
88
- }
89
- static async create(bytes) {
90
- const module = await WebAssembly.compile(bytes);
91
- const instance = await WebAssembly.instantiate(module, {});
92
- const exports = instance.exports;
93
- for (const name of ['regions_localize', 'regions_version', 'regions_new', 'regions_destroy', 'regions_prepare', 'regions_input_ptr', 'regions_input_len', 'regions_quads_ptr', 'regions_output_ptr', 'regions_output_len', 'regions_scan']) {
94
- if (typeof instance.exports[name] !== 'function')
95
- throw new ScannerError('abi_shape', `Missing ${name}`);
96
- }
97
- if (!(exports.memory instanceof WebAssembly.Memory))
98
- throw new ScannerError('abi_shape', 'Missing memory');
99
- return new IndependentScanner(exports);
100
- }
101
- /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
102
- scan(image, quads, policy = {}) {
103
- return this.#scan(image, quads, policy, false);
104
- }
105
- /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
106
- scanLocalized(image, policy = {}, fitLimit = 8, fullFrame = false) {
107
- const start = performance.now();
108
- if (!this.#handle)
109
- throw new ScannerError('disposed', 'Scanner is disposed');
110
- if (!image || typeof image !== 'object')
111
- throw new ScannerError('invalid_input', 'Invalid image');
112
- const width = integer(image.width, 3, 0xffffffff, 'width'), height = integer(image.height, 3, 0xffffffff, 'height');
113
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
114
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
115
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
116
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
117
- if (image.data.byteLength < required)
118
- throw new ScannerError('invalid_input', 'Image buffer is too short');
119
- integer(fitLimit, 0, 8, 'shear limit');
120
- const e = this.#exports, id = this.#handle;
121
- status(e.regions_prepare(id, width, height, image.channels, stride));
122
- if (e.regions_input_len(id) !== required)
123
- throw new ScannerError('abi_shape', 'Input allocation mismatch');
124
- new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
125
- status(e.regions_localize(id, fitLimit));
126
- const localization = JSON.parse(new TextDecoder().decode(new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id))));
127
- if (!Array.isArray(localization.proposals) || localization.proposals.length > (fullFrame ? 63 : 64) || localization.proposals.some((p) => !isQuadShape(p.polygon)))
128
- throw new ScannerError('abi_shape', 'Invalid localization');
129
- const searchWindows = fullFrame ? [{ kind: 'full_frame_search', polygon: [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]], candidateIndex: localization.proposals.length }] : [];
130
- const localizationMs = performance.now() - start, decodeStart = performance.now();
131
- const scan = this.#scan(image, [...localization.proposals.map((p) => p.polygon), ...searchWindows.map(p => p.polygon)], policy, true);
132
- return { localization, searchWindows, scan, localizationMs, decodingMs: performance.now() - decodeStart, scanMs: performance.now() - start };
133
- }
134
- #scan(image, quads, policy, prepared) {
135
- const start = performance.now();
136
- if (!this.#handle)
137
- throw new ScannerError('disposed', 'Scanner is disposed');
138
- if (!image || typeof image !== 'object' || !Array.isArray(quads) || !policy || typeof policy !== 'object')
139
- throw new ScannerError('invalid_input', 'Invalid scan arguments');
140
- for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
141
- if (policy[key] !== undefined && typeof policy[key] !== 'boolean')
142
- throw new ScannerError('invalid_input', `Invalid ${key}`);
143
- const e = this.#exports, id = this.#handle;
144
- const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
145
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
146
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
147
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
148
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
149
- if (image.data.byteLength < required)
150
- throw new ScannerError('invalid_input', 'Image buffer is too short');
151
- integer(quads.length, 0, 64, 'candidate count');
152
- for (const q of quads)
153
- if (!isQuadShape(q))
154
- throw new ScannerError('invalid_input', 'Invalid quad shape');
155
- const perCandidate = integer(policy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
156
- const perFrame = integer(policy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
157
- const checks = integer(policy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
158
- const pixels = integer(policy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
159
- const results = integer(policy.maxResults ?? 1024, 1, 4096, 'result budget');
160
- const flags = (policy.transitionCleanup ? 1 : 0) | (policy.sourceIdentity ? 2 : 0) | (policy.interiorNormalization ? 4 : 0) | (policy.guardBias ? 8 : 0) | (policy.allowSingleRow ? 16 : 0);
161
- if (!prepared) {
162
- status(e.regions_prepare(id, width, height, image.channels, stride));
163
- if (e.regions_input_len(id) !== required)
164
- throw new ScannerError('abi_shape', 'Input allocation mismatch');
165
- new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
166
- }
167
- const coordinates = new Float64Array(e.memory.buffer, e.regions_quads_ptr(id), 512);
168
- quads.forEach((q, i) => q.forEach((p, j) => { coordinates[i * 8 + j * 2] = p[0]; coordinates[i * 8 + j * 2 + 1] = p[1]; }));
169
- status(e.regions_scan(id, quads.length, flags, perCandidate, perFrame, checks, pixels, results));
170
- // Scan can grow memory. Never reuse the earlier input/coordinate views.
171
- const output = new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id)).slice();
172
- const frame = parseFrame(new TextDecoder().decode(output), quads.length);
173
- return { ...frame, candidateTimingsAvailable: false, elapsedMs: performance.now() - start };
174
- }
175
- /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
176
- best(result) {
177
- return rankBarcodes(result.barcodes)[0];
178
- }
179
- dispose() { if (this.#handle) {
180
- const id = this.#handle;
181
- this.#handle = 0;
182
- status(this.#exports.regions_destroy(id));
183
- } }
184
- }
@@ -1,7 +0,0 @@
1
- import type { Quad } from "../host.js";
2
- /** Convex containment, including the boundary; reject degenerate coverage. */
3
- export declare function containsPoint(point: readonly number[], quad: Quad): boolean;
4
- /** Only deep retries are deferred. Normal proposals and the full-frame bit remain. */
5
- export declare function uncoveredRetryMask(proposals: readonly {
6
- polygon: Quad;
7
- }[], coverage: readonly Quad[], initial?: readonly number[]): [number, number];
@@ -1,26 +0,0 @@
1
- /** Convex containment, including the boundary; reject degenerate coverage. */
2
- export function containsPoint(point, quad) {
3
- if (!point.every(Number.isFinite) || quad.some((p) => !p.every(Number.isFinite)))
4
- return false;
5
- let positive = false;
6
- let negative = false;
7
- let area = 0;
8
- for (let i = 0; i < 4; i++) {
9
- const a = quad[i], b = quad[(i + 1) % 4];
10
- const cross = (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0]);
11
- positive ||= cross > 1e-6;
12
- negative ||= cross < -1e-6;
13
- area += a[0] * b[1] - b[0] * a[1];
14
- }
15
- return Math.abs(area) > 1e-6 && !(positive && negative);
16
- }
17
- /** Only deep retries are deferred. Normal proposals and the full-frame bit remain. */
18
- export function uncoveredRetryMask(proposals, coverage, initial = [0xffffffff, 0xffffffff]) {
19
- const mask = [initial[0] >>> 0, initial[1] >>> 0];
20
- proposals.forEach((proposal, index) => {
21
- if (coverage.some((quad) => proposal.polygon.every((point) => containsPoint(point, quad)))) {
22
- mask[index >>> 5] = (mask[index >>> 5] & ~(1 << (index & 31))) >>> 0;
23
- }
24
- });
25
- return mask;
26
- }
@@ -1,37 +0,0 @@
1
- import type { Quad } from "../host.js";
2
- export type Transform = readonly number[];
3
- export declare function project(t: Transform, x: number, y: number): [number, number];
4
- export declare function transformFor(quad: Quad, width: number, height: number): Transform;
5
- export declare function rectificationPlan(quad: Quad): {
6
- width: number;
7
- height: number;
8
- transform: number[];
9
- };
10
- export declare function rectify(gray: Uint8Array, width: number, height: number, quad: Quad): {
11
- data: Uint8Array<ArrayBuffer>;
12
- width: number;
13
- height: number;
14
- transform: number[];
15
- };
16
- /** Convex intersection, including opposite winding and projective quadrilaterals. */
17
- export declare function polygonOverlap(a: Quad, b: Quad): {
18
- iou: number;
19
- smaller: number;
20
- a: number;
21
- b: number;
22
- };
23
- /** Suppress overlapping reads of the same physical symbol, never by text alone. */
24
- export declare function distinctReads<T extends {
25
- text: string;
26
- format: string;
27
- polygon: Quad;
28
- support: number;
29
- eanAddOn?: string;
30
- readerInitialization?: boolean;
31
- structuredAppend?: {
32
- index: number;
33
- count: number;
34
- id?: string;
35
- parity?: number;
36
- };
37
- }>(reads: readonly T[]): T[];