tapirscan 1.0.0 → 1.2.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 (33) hide show
  1. package/README.md +184 -105
  2. package/dist/completion-host.d.mts +40 -0
  3. package/dist/completion-host.mjs +188 -0
  4. package/dist/detail-runtime/direct-recovery.d.mts +28 -0
  5. package/dist/detail-runtime/direct-recovery.mjs +142 -0
  6. package/dist/detail-runtime/host.d.mts +40 -0
  7. package/dist/detail-runtime/host.mjs +282 -0
  8. package/dist/detail-runtime/scanner.d.mts +12 -0
  9. package/dist/detail-runtime/scanner.mjs +70 -0
  10. package/dist/detail.d.ts +3 -4
  11. package/dist/detail.js +3 -6
  12. package/dist/index.d.ts +91 -33
  13. package/dist/index.js +174 -86
  14. package/dist/multiformat/coverage.d.ts +7 -0
  15. package/dist/multiformat/coverage.js +26 -0
  16. package/dist/multiformat/formats.d.ts +4 -2
  17. package/dist/multiformat/formats.js +13 -1
  18. package/dist/multiformat/geometry.d.ts +5 -0
  19. package/dist/multiformat/geometry.js +13 -3
  20. package/dist/multiformat/linear-duplicates.d.ts +16 -0
  21. package/dist/multiformat/linear-duplicates.js +163 -0
  22. package/dist/multiformat/scanner.d.ts +11 -2
  23. package/dist/multiformat/scanner.js +127 -24
  24. package/examples/camera.html +63 -0
  25. package/examples/scan-worker.mjs +20 -0
  26. package/examples/worker-client.mjs +63 -0
  27. package/package.json +7 -6
  28. package/wasm/{high-release-20260915.wasm → high-complete-release-20260916.wasm} +0 -0
  29. package/wasm/{low-release-20260915.wasm → low-complete-release-20260916.wasm} +0 -0
  30. package/wasm/{medium-release-20260915.wasm → medium-complete-release-20260916.wasm} +0 -0
  31. package/wasm/multiformat.json +2 -1
  32. package/wasm/multiformat.wasm +0 -0
  33. package/wasm/{very-high-release-20260915.wasm → very-high-complete-release-20260916.wasm} +0 -0
@@ -0,0 +1,28 @@
1
+ /** Bounded source-guided hypotheses, without another localizer/shear search per crop. */
2
+ export function recoverDirectSeed(image: any, scanner: any, policy: any, baseline: any, budget?: number, factor?: number, sequential?: boolean, scharr?: boolean, minimumSpan?: number, maxDirections?: number, coverage?: any[]): {
3
+ barcodes: any[];
4
+ additions: any[];
5
+ attempts: {
6
+ x: number;
7
+ y: number;
8
+ w: number;
9
+ h: number;
10
+ factor: number;
11
+ frame: any;
12
+ reads: any;
13
+ deferredReads: any;
14
+ proposals: {
15
+ polygon: number[][];
16
+ score: number;
17
+ text: string;
18
+ }[];
19
+ unfinished: any;
20
+ }[];
21
+ proposals: {
22
+ polygon: number[][];
23
+ score: number;
24
+ text: string;
25
+ }[];
26
+ extraMs: number;
27
+ searchLimited: boolean;
28
+ };
@@ -0,0 +1,142 @@
1
+ import { makeCanvas } from "../detail-canvas.js";
2
+ import { detailProposals } from "../detail-20260914/detail-proposals-rich.mjs";
3
+ import { sourceEvidence } from "../detail-20260914/source-evidence.mjs";
4
+ import { coveredByContinuousBars } from "../detail-20260914/continuity.mjs";
5
+ function refinedAngle(image, seed) {
6
+ const gray = (x, y) => {
7
+ const i = (y * image.width + x) * 4;
8
+ return (77 * image.data[i] + 150 * image.data[i + 1] + 29 * image.data[i + 2]) / 256;
9
+ };
10
+ let xx = 0, yy = 0, xy = 0, sx = 0, sy = 0, n = 0;
11
+ for (let y = Math.max(1, Math.round(seed.y) - 12); y < Math.min(image.height - 1, seed.y + 12); y++)
12
+ for (let x = Math.max(1, Math.round(seed.x) - 12); x < Math.min(image.width - 1, seed.x + 12); x++) {
13
+ const a = gray(x - 1, y - 1), b = gray(x, y - 1), c = gray(x + 1, y - 1), d = gray(x - 1, y), e = gray(x + 1, y), f = gray(x - 1, y + 1), g = gray(x, y + 1), h = gray(x + 1, y + 1);
14
+ const gx = (3 * (c - a) + 10 * (e - d) + 3 * (h - f)) / 16, gy = (3 * (f - a) + 10 * (g - b) + 3 * (h - c)) / 16;
15
+ xx += gx * gx;
16
+ yy += gy * gy;
17
+ xy += gx * gy;
18
+ sx += gx;
19
+ sy += gy;
20
+ n++;
21
+ }
22
+ return 0.5 * Math.atan2(2 * (xy - (sx * sy) / n), xx - (sx * sx) / n - yy + (sy * sy) / n);
23
+ }
24
+ function contains(point, q) {
25
+ let hit = false;
26
+ for (let i = 0, j = q.length - 1; i < q.length; j = i++) {
27
+ if (q[i][1] > point[1] !== q[j][1] > point[1] &&
28
+ point[0] < ((q[j][0] - q[i][0]) * (point[1] - q[i][1])) / (q[j][1] - q[i][1]) + q[i][0])
29
+ hit = !hit;
30
+ }
31
+ return hit;
32
+ }
33
+ function covered(image, point, barcode) {
34
+ return contains(point, barcode.polygon) || coveredByContinuousBars(image, point, barcode);
35
+ }
36
+ function sourceSpan(p) {
37
+ const dx = p[1][0] - p[0][0], dy = p[1][1] - p[0][1];
38
+ return (Math.abs(dx * (p[3][1] - p[0][1]) - dy * (p[3][0] - p[0][0])) /
39
+ Math.max(1e-9, Math.hypot(dx, dy)));
40
+ }
41
+ /** Bounded source-guided hypotheses, without another localizer/shear search per crop. */
42
+ export function recoverDirectSeed(image, scanner, policy, baseline, budget = 64, factor = 3, sequential = false, scharr = false, minimumSpan = 0, maxDirections = Infinity, coverage = []) {
43
+ const start = performance.now();
44
+ const seeds = detailProposals(image, 2, 256, 4);
45
+ const additions = [], attempts = [], proposals = [];
46
+ const tile = makeCanvas(1, 1), up = makeCanvas(1, 1);
47
+ const tc = tile.getContext("2d"), uc = up.getContext("2d", { willReadFrequently: true });
48
+ for (const seed of seeds) {
49
+ if (seed.score < seeds[0].score * 0.6)
50
+ continue;
51
+ if (coverage.some((quad) => containsPoint([seed.x, seed.y], quad)))
52
+ continue;
53
+ if ([...baseline.scan.barcodes, ...additions].some((b) => covered(image, [seed.x, seed.y], b)))
54
+ continue;
55
+ const quads = [];
56
+ const initialAngle = scharr ? refinedAngle(image, seed) : seed.angle;
57
+ const directions = (scharr ? [0, -3, 3] : [0, -5, 5, -10, 10, -15, 15, -20, 20]).map((offset) => initialAngle + (offset * Math.PI) / 180);
58
+ for (const angle of directions) {
59
+ const c = Math.cos(angle), s = Math.sin(angle);
60
+ const polygon = [
61
+ [-96, -24],
62
+ [96, -24],
63
+ [96, 24],
64
+ [-96, 24],
65
+ ].map(([u, v]) => [seed.x + u * c - v * s, seed.y + u * s + v * c]);
66
+ const evidence = sourceEvidence(image, polygon, true, 32);
67
+ if (Math.max(evidence.transitions, evidence.localTransitions) >= 32)
68
+ quads.push(polygon);
69
+ if (quads.length >= maxDirections)
70
+ break;
71
+ }
72
+ if (!quads.length)
73
+ continue;
74
+ const size = 256, w = Math.min(size, image.width), h = Math.min(size, image.height);
75
+ const x = Math.max(0, Math.min(image.width - w, Math.round(seed.x - w / 2)));
76
+ const y = Math.max(0, Math.min(image.height - h, Math.round(seed.y - h / 2)));
77
+ const bytes = new Uint8ClampedArray(w * h * 4);
78
+ for (let row = 0; row < h; row++) {
79
+ const from = ((y + row) * image.width + x) * 4;
80
+ bytes.set(image.data.subarray(from, from + w * 4), row * w * 4);
81
+ }
82
+ tile.width = w;
83
+ tile.height = h;
84
+ tc.putImageData({ data: bytes, width: w, height: h }, 0, 0);
85
+ up.width = w * factor;
86
+ up.height = h * factor;
87
+ uc.imageSmoothingEnabled = true;
88
+ uc.drawImage(tile, 0, 0, up.width, up.height);
89
+ const pixels = uc.getImageData(0, 0, up.width, up.height);
90
+ const batches = sequential ? quads.map((q) => [q]) : [quads];
91
+ for (const batch of batches) {
92
+ const result = scanner.scan({
93
+ data: new Uint8Array(pixels.data.buffer),
94
+ width: up.width,
95
+ height: up.height,
96
+ channels: 4,
97
+ stride: up.width * 4,
98
+ }, batch.map((q) => q.map(([a, b]) => [(a - x) * factor, (b - y) * factor])), {
99
+ ...policy,
100
+ maxRetryPathsPerCandidate: budget,
101
+ maxRetryPathsPerFrame: budget * batch.length,
102
+ });
103
+ const allReads = result.barcodes.map((b) => ({
104
+ ...b,
105
+ polygon: b.polygon.map(([a, b]) => [x + a / factor, y + b / factor]),
106
+ }));
107
+ const reads = allReads.filter((b) => sourceSpan(b.polygon) >= minimumSpan);
108
+ const deferredReads = allReads.filter((b) => sourceSpan(b.polygon) < minimumSpan);
109
+ for (const read of reads) {
110
+ const center = read.polygon.reduce((a, p) => [a[0] + p[0] / 4, a[1] + p[1] / 4], [0, 0]);
111
+ if (![...baseline.scan.barcodes, ...additions].some((old) => old.text === read.text && covered(image, center, old)))
112
+ additions.push(read);
113
+ }
114
+ const localized = batch.map((polygon) => ({ polygon, score: seed.score, text: "" }));
115
+ proposals.push(...localized);
116
+ attempts.push({
117
+ x,
118
+ y,
119
+ w,
120
+ h,
121
+ factor,
122
+ // Raw evidence remains in crop coordinates with this explicit transform.
123
+ frame: result,
124
+ reads,
125
+ deferredReads,
126
+ proposals: localized,
127
+ unfinished: result.unfinished || deferredReads.length > 0,
128
+ });
129
+ if (sequential && reads.some((b) => covered(image, [seed.x, seed.y], b)))
130
+ break;
131
+ }
132
+ }
133
+ return {
134
+ barcodes: [...baseline.scan.barcodes, ...additions],
135
+ additions,
136
+ attempts,
137
+ proposals,
138
+ extraMs: performance.now() - start,
139
+ searchLimited: true,
140
+ };
141
+ }
142
+ import { containsPoint } from "../multiformat/coverage.js";
@@ -0,0 +1,40 @@
1
+ /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
2
+ export function isQuadShape(value: any): boolean;
3
+ /** Validate before asynchronous work; returned bytes are owned by the caller. */
4
+ export function snapshotImage(image: any): {
5
+ data: Uint8Array<any>;
6
+ width: any;
7
+ height: any;
8
+ channels: any;
9
+ stride: any;
10
+ };
11
+ export function snapshotPolicy(policy: any): any;
12
+ /** Uncalibrated support ordering; ties preserve spatial output order. */
13
+ export function rankBarcodes(barcodes: any): any[];
14
+ export class ScannerError extends Error {
15
+ constructor(code: any, message: any);
16
+ code: any;
17
+ }
18
+ export class IndependentScanner {
19
+ static create(bytes: any): Promise<IndependentScanner>;
20
+ constructor(exports: any);
21
+ /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
22
+ scan(image: any, quads: any, policy?: {}): any;
23
+ /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
24
+ scanLocalized(image: any, policy?: {}, fitLimit?: number, fullFrame?: boolean, transform?: undefined): {
25
+ localization: any;
26
+ searchWindows: {
27
+ kind: string;
28
+ polygon: number[][];
29
+ candidateIndex: any;
30
+ }[];
31
+ scan: any;
32
+ localizationMs: number;
33
+ decodingMs: number;
34
+ scanMs: number;
35
+ };
36
+ /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
37
+ best(result: any): any;
38
+ dispose(): void;
39
+ #private;
40
+ }
@@ -0,0 +1,282 @@
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) {
20
+ super(message);
21
+ this.name = "ScannerError";
22
+ this.code = code;
23
+ }
24
+ }
25
+ function integer(value, min, max, name) {
26
+ if (!Number.isSafeInteger(value) || value < min || value > max)
27
+ throw new ScannerError("invalid_input", `Invalid ${name}`);
28
+ return value;
29
+ }
30
+ function status(code) {
31
+ if (code !== 0)
32
+ throw new ScannerError(`core_${code}`, `Independent scanner rejected operation (${code})`);
33
+ }
34
+ function parseFrame(text, count) {
35
+ const v = JSON.parse(text);
36
+ if (!v || typeof v !== "object")
37
+ throw new ScannerError("invalid_output", "Expected frame object");
38
+ const f = v;
39
+ if (!Array.isArray(f.candidates) ||
40
+ f.candidates.length !== count ||
41
+ !Array.isArray(f.barcodes) ||
42
+ typeof f.unfinished !== "boolean" ||
43
+ !f.reconciliation)
44
+ throw new ScannerError("invalid_output", "Invalid frame shape");
45
+ for (let i = 0; i < f.candidates.length; i++) {
46
+ const c = f.candidates[i];
47
+ if (c.candidate_index !== i ||
48
+ !Array.isArray(c.coverage) ||
49
+ c.coverage.length !== 4 ||
50
+ !Array.isArray(c.observations) ||
51
+ !Array.isArray(c.detections) ||
52
+ typeof c.error !== "boolean")
53
+ throw new ScannerError("invalid_output", "Invalid candidate shape");
54
+ }
55
+ for (const b of f.barcodes)
56
+ if (!/^\d{13}$/.test(b.text) ||
57
+ !Array.isArray(b.polygon) ||
58
+ b.polygon.length !== 4 ||
59
+ !Array.isArray(b.candidate_indices) ||
60
+ b.candidate_indices.some((i) => !Number.isInteger(i) || i < 0 || i >= count))
61
+ throw new ScannerError("invalid_output", "Invalid barcode shape");
62
+ return f;
63
+ }
64
+ /** Validate before asynchronous work; returned bytes are owned by the caller. */
65
+ export function snapshotImage(image) {
66
+ if (!image || typeof image !== "object")
67
+ throw new ScannerError("invalid_input", "Invalid image");
68
+ const width = integer(image.width, 1, 0xffffffff, "width"), height = integer(image.height, 1, 0xffffffff, "height");
69
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
70
+ throw new ScannerError("invalid_input", "Invalid image buffer/channels");
71
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, "stride");
72
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, "image length");
73
+ if (image.data.byteLength < required)
74
+ throw new ScannerError("invalid_input", "Image buffer is too short");
75
+ return {
76
+ data: new Uint8Array(image.data.subarray(0, required)),
77
+ width,
78
+ height,
79
+ channels: image.channels,
80
+ stride,
81
+ };
82
+ }
83
+ export function snapshotPolicy(policy) {
84
+ if (!policy || typeof policy !== "object")
85
+ throw new ScannerError("invalid_input", "Invalid policy");
86
+ const copy = { ...policy };
87
+ for (const key of [
88
+ "transitionCleanup",
89
+ "sourceIdentity",
90
+ "interiorNormalization",
91
+ "guardBias",
92
+ "allowSingleRow",
93
+ ])
94
+ if (copy[key] !== undefined && typeof copy[key] !== "boolean")
95
+ throw new ScannerError("invalid_input", `Invalid ${key}`);
96
+ integer(copy.maxRetryPathsPerCandidate ?? 512, 0, 4096, "candidate budget");
97
+ integer(copy.maxRetryPathsPerFrame ?? 8192, 0, 65536, "frame budget");
98
+ integer(copy.maxAssociationChecks ?? 200000, 0, 2000000, "comparison budget");
99
+ integer(copy.maxAssociationPixels ?? 2000000, 0, 16000000, "pixel budget");
100
+ integer(copy.maxResults ?? 1024, 1, 4096, "result budget");
101
+ return copy;
102
+ }
103
+ /** Uncalibrated support ordering; ties preserve spatial output order. */
104
+ export function rankBarcodes(barcodes) {
105
+ return [...barcodes].sort((a, b) => b.support - a.support);
106
+ }
107
+ export class IndependentScanner {
108
+ #exports;
109
+ #handle;
110
+ constructor(exports) {
111
+ this.#exports = exports;
112
+ if (exports.regions_version() !== 1)
113
+ throw new ScannerError("abi_version", "Unsupported scanner ABI");
114
+ this.#handle = exports.regions_new();
115
+ if (!this.#handle)
116
+ throw new ScannerError("capacity", "Scanner handle capacity exhausted");
117
+ }
118
+ static async create(bytes) {
119
+ const module = await WebAssembly.compile(bytes);
120
+ const instance = await WebAssembly.instantiate(module, {});
121
+ const exports = instance.exports;
122
+ for (const name of [
123
+ "regions_localize",
124
+ "regions_version",
125
+ "regions_new",
126
+ "regions_destroy",
127
+ "regions_prepare",
128
+ "regions_input_ptr",
129
+ "regions_input_len",
130
+ "regions_quads_ptr",
131
+ "regions_output_ptr",
132
+ "regions_output_len",
133
+ "regions_scan",
134
+ ]) {
135
+ if (typeof instance.exports[name] !== "function")
136
+ throw new ScannerError("abi_shape", `Missing ${name}`);
137
+ }
138
+ if (!(exports.memory instanceof WebAssembly.Memory))
139
+ throw new ScannerError("abi_shape", "Missing memory");
140
+ return new IndependentScanner(exports);
141
+ }
142
+ /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
143
+ scan(image, quads, policy = {}) {
144
+ return this.#scan(image, quads, policy, false);
145
+ }
146
+ /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
147
+ scanLocalized(image, policy = {}, fitLimit = 8, fullFrame = false, transform = undefined) {
148
+ const start = performance.now();
149
+ if (!this.#handle)
150
+ throw new ScannerError("disposed", "Scanner is disposed");
151
+ if (!image || typeof image !== "object")
152
+ throw new ScannerError("invalid_input", "Invalid image");
153
+ const width = integer(image.width, 3, 0xffffffff, "width"), height = integer(image.height, 3, 0xffffffff, "height");
154
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
155
+ throw new ScannerError("invalid_input", "Invalid image buffer/channels");
156
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, "stride");
157
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, "image length");
158
+ if (image.data.byteLength < required)
159
+ throw new ScannerError("invalid_input", "Image buffer is too short");
160
+ integer(fitLimit, 0, 8, "shear limit");
161
+ const e = this.#exports, id = this.#handle;
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
+ status(e.regions_localize(id, fitLimit));
167
+ let localization = JSON.parse(new TextDecoder().decode(new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id))));
168
+ if (transform)
169
+ localization = transform(localization);
170
+ if (localization.retryMask)
171
+ policy = { ...policy, retryMask: localization.retryMask };
172
+ if (!Array.isArray(localization.proposals) ||
173
+ localization.proposals.length > (fullFrame ? 63 : 64) ||
174
+ localization.proposals.some((p) => !isQuadShape(p.polygon)))
175
+ throw new ScannerError("abi_shape", "Invalid localization");
176
+ const searchWindows = fullFrame
177
+ ? [
178
+ {
179
+ kind: "full_frame_search",
180
+ polygon: [
181
+ [0, 0],
182
+ [width - 1, 0],
183
+ [width - 1, height - 1],
184
+ [0, height - 1],
185
+ ],
186
+ candidateIndex: localization.proposals.length,
187
+ },
188
+ ]
189
+ : [];
190
+ const localizationMs = performance.now() - start, decodeStart = performance.now();
191
+ const scan = this.#scan(image, [...localization.proposals.map((p) => p.polygon), ...searchWindows.map((p) => p.polygon)], policy, true);
192
+ return {
193
+ localization,
194
+ searchWindows,
195
+ scan,
196
+ localizationMs,
197
+ decodingMs: performance.now() - decodeStart,
198
+ scanMs: performance.now() - start,
199
+ };
200
+ }
201
+ #scan(image, quads, policy, prepared) {
202
+ const start = performance.now();
203
+ if (!this.#handle)
204
+ throw new ScannerError("disposed", "Scanner is disposed");
205
+ if (!image ||
206
+ typeof image !== "object" ||
207
+ !Array.isArray(quads) ||
208
+ !policy ||
209
+ typeof policy !== "object")
210
+ throw new ScannerError("invalid_input", "Invalid scan arguments");
211
+ for (const key of [
212
+ "transitionCleanup",
213
+ "sourceIdentity",
214
+ "interiorNormalization",
215
+ "guardBias",
216
+ "allowSingleRow",
217
+ ])
218
+ if (policy[key] !== undefined && typeof policy[key] !== "boolean")
219
+ throw new ScannerError("invalid_input", `Invalid ${key}`);
220
+ const e = this.#exports, id = this.#handle;
221
+ const width = integer(image.width, 1, 0xffffffff, "width"), height = integer(image.height, 1, 0xffffffff, "height");
222
+ if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
223
+ throw new ScannerError("invalid_input", "Invalid image buffer/channels");
224
+ const stride = integer(image.stride, width * image.channels, 0xffffffff, "stride");
225
+ const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, "image length");
226
+ if (image.data.byteLength < required)
227
+ throw new ScannerError("invalid_input", "Image buffer is too short");
228
+ integer(quads.length, 0, 64, "candidate count");
229
+ for (const q of quads)
230
+ if (!isQuadShape(q))
231
+ throw new ScannerError("invalid_input", "Invalid quad shape");
232
+ const perCandidate = integer(policy.maxRetryPathsPerCandidate ?? 512, 0, 4096, "candidate budget");
233
+ const perFrame = integer(policy.maxRetryPathsPerFrame ?? 8192, 0, 65536, "frame budget");
234
+ const checks = integer(policy.maxAssociationChecks ?? 200000, 0, 2000000, "comparison budget");
235
+ const pixels = integer(policy.maxAssociationPixels ?? 2000000, 0, 16000000, "pixel budget");
236
+ const results = integer(policy.maxResults ?? 1024, 1, 4096, "result budget");
237
+ if (policy.finishCandidates && e.regions_completion_supported?.() !== 1)
238
+ throw new Error("This WASM build does not support finishCandidates");
239
+ const flags = (policy.transitionCleanup ? 1 : 0) |
240
+ (policy.sourceIdentity ? 2 : 0) |
241
+ (policy.interiorNormalization ? 4 : 0) |
242
+ (policy.guardBias ? 8 : 0) |
243
+ (policy.allowSingleRow ? 16 : 0) | (policy.finishCandidates ? 32 : 0);
244
+ if (!prepared) {
245
+ status(e.regions_prepare(id, width, height, image.channels, stride));
246
+ if (e.regions_input_len(id) !== required)
247
+ throw new ScannerError("abi_shape", "Input allocation mismatch");
248
+ new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
249
+ }
250
+ const coordinates = new Float64Array(e.memory.buffer, e.regions_quads_ptr(id), 512);
251
+ quads.forEach((q, i) => q.forEach((p, j) => {
252
+ coordinates[i * 8 + j * 2] = p[0];
253
+ coordinates[i * 8 + j * 2 + 1] = p[1];
254
+ }));
255
+ const mask = policy.retryMask ?? [4294967295, 4294967295];
256
+ if (!Array.isArray(mask) || mask.length !== 2)
257
+ throw new ScannerError("invalid_input", "Invalid retry mask");
258
+ for (const value of mask)
259
+ integer(value, 0, 4294967295, "retry mask");
260
+ if (e.regions_scan_mask)
261
+ status(e.regions_scan_mask(id, quads.length, flags, perCandidate, perFrame, checks, pixels, results, mask[0], mask[1]));
262
+ else if (policy.retryMask)
263
+ throw new ScannerError("abi_shape", "Missing retry scheduling ABI");
264
+ else
265
+ status(e.regions_scan(id, quads.length, flags, perCandidate, perFrame, checks, pixels, results));
266
+ // Scan can grow memory. Never reuse the earlier input/coordinate views.
267
+ const output = new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id)).slice();
268
+ const frame = parseFrame(new TextDecoder().decode(output), quads.length);
269
+ return { ...frame, candidateTimingsAvailable: false, elapsedMs: performance.now() - start };
270
+ }
271
+ /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
272
+ best(result) {
273
+ return rankBarcodes(result.barcodes)[0];
274
+ }
275
+ dispose() {
276
+ if (this.#handle) {
277
+ const id = this.#handle;
278
+ this.#handle = 0;
279
+ status(this.#exports.regions_destroy(id));
280
+ }
281
+ }
282
+ }
@@ -0,0 +1,12 @@
1
+ /** Preserve undecoded geometry without assigning crop indices to primary proposals. */
2
+ export function detailRegions(found: any, recovery: any): any;
3
+ /** Workbench composition. Each crop keeps its own candidate-index namespace. */
4
+ export class DetailScanner {
5
+ static create(primaryBytes: any, recoveryBytes: any, directions: any): Promise<DetailScanner>;
6
+ constructor(primary: any, recovery: any, directions: any);
7
+ primary: any;
8
+ recovery: any;
9
+ directions: any;
10
+ scanLocalized(image: any, policy: any, fitLimit: any, fullFrame: any, coverage?: any[]): any;
11
+ dispose(): void;
12
+ }
@@ -0,0 +1,70 @@
1
+ import { IndependentScanner } from "./host.mjs";
2
+ import { evidencePlan } from "../detail-20260914/source-evidence.mjs";
3
+ import { recoverDirectSeed } from "./direct-recovery.mjs";
4
+ import { uncoveredRetryMask } from "../multiformat/coverage.js";
5
+ /** Workbench composition. Each crop keeps its own candidate-index namespace. */
6
+ export class DetailScanner {
7
+ constructor(primary, recovery, directions) {
8
+ this.primary = primary;
9
+ this.recovery = recovery;
10
+ this.directions = directions;
11
+ }
12
+ static async create(primaryBytes, recoveryBytes, directions) {
13
+ if (![1, 2, 3].includes(directions))
14
+ throw new Error("Invalid recovery direction budget");
15
+ const primary = await IndependentScanner.create(primaryBytes);
16
+ try {
17
+ return new DetailScanner(primary, await IndependentScanner.create(recoveryBytes), directions);
18
+ }
19
+ catch (error) {
20
+ primary.dispose();
21
+ throw error;
22
+ }
23
+ }
24
+ scanLocalized(image, policy, fitLimit, fullFrame, coverage = []) {
25
+ // The source samplers use tightly packed RGBA, as supplied by the camera worker.
26
+ if (image.channels !== 4 || image.stride !== image.width * 4)
27
+ throw new Error("Detail discovery requires tightly packed RGBA");
28
+ const start = performance.now();
29
+ const found = this.primary.scanLocalized(image, policy, fitLimit, fullFrame, (localization) => {
30
+ const plan = evidencePlan(image, localization, 48);
31
+ return coverage.length
32
+ ? { ...plan, retryMask: uncoveredRetryMask(plan.proposals, coverage, plan.retryMask) }
33
+ : plan;
34
+ });
35
+ const recovery = recoverDirectSeed(image, this.recovery, policy, found, 64, 3, true, true, 1, this.directions, coverage);
36
+ return {
37
+ ...found,
38
+ // Do not concatenate crop-local candidate indices into the primary frame.
39
+ // Consumers use detailRegions; raw frames and coordinate transforms stay inspectable.
40
+ recovery,
41
+ detailRegions: detailRegions(found, recovery),
42
+ scanMs: performance.now() - start,
43
+ };
44
+ }
45
+ dispose() {
46
+ this.primary.dispose();
47
+ this.recovery.dispose();
48
+ }
49
+ }
50
+ /** Preserve undecoded geometry without assigning crop indices to primary proposals. */
51
+ export function detailRegions(found, recovery) {
52
+ const decoded = new Set(found.scan.barcodes.flatMap((barcode) => barcode.candidate_indices));
53
+ const regions = recovery.barcodes.map((barcode) => ({
54
+ text: barcode.text,
55
+ polygon: barcode.polygon,
56
+ support: barcode.support,
57
+ }));
58
+ found.localization.proposals.forEach((proposal, index) => {
59
+ if (!decoded.has(index))
60
+ regions.push({ text: "", polygon: proposal.polygon, score: proposal.score });
61
+ });
62
+ for (const attempt of recovery.attempts) {
63
+ const accepted = new Set(attempt.reads.flatMap((barcode) => barcode.candidate_indices));
64
+ attempt.proposals.forEach((proposal, index) => {
65
+ if (!accepted.has(index))
66
+ regions.push({ text: "", polygon: proposal.polygon, score: proposal.score });
67
+ });
68
+ }
69
+ return regions;
70
+ }
package/dist/detail.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { type DetailResult } from "./detail-20260914/scanner.mjs";
2
- import { IndependentScanner, type Image, type ScanFrame } from "./host.js";
1
+ import { type DetailResult } from "./detail-runtime/scanner.mjs";
2
+ import { IndependentScanner, type Image, type Quad } from "./host.js";
3
3
  import type { Mode } from "./index.js";
4
4
  export declare const fitLimits: {
5
5
  readonly low: 0;
@@ -13,7 +13,6 @@ export declare class ReleaseDetailScanner {
13
13
  private disposed;
14
14
  private constructor();
15
15
  static create(primary: ArrayBuffer, low: ArrayBuffer, mode: Exclude<Mode, "low">): Promise<ReleaseDetailScanner>;
16
- scanLocalized(image: Image, policy: Parameters<IndependentScanner["scanLocalized"]>[1], fit: number, full: boolean): DetailResult;
17
- best(frame: ScanFrame): import("./host.js").Barcode | undefined;
16
+ scanLocalized(image: Image, policy: Parameters<IndependentScanner["scanLocalized"]>[1], fit: number, full: boolean, coverage?: readonly Quad[]): DetailResult;
18
17
  dispose(): void;
19
18
  }
package/dist/detail.js CHANGED
@@ -1,4 +1,4 @@
1
- import { DetailScanner } from "./detail-20260914/scanner.mjs";
1
+ import { DetailScanner } from "./detail-runtime/scanner.mjs";
2
2
  export const fitLimits = { low: 0, medium: 1, high: 4, "very-high": 1 };
3
3
  /** Preserve the public gray/RGB/RGBA and padded-stride image contract. */
4
4
  function packed(image) {
@@ -49,10 +49,10 @@ export class ReleaseDetailScanner {
49
49
  static async create(primary, low, mode) {
50
50
  return new ReleaseDetailScanner(await DetailScanner.create(primary, low, mode === "medium" ? 1 : 2));
51
51
  }
52
- scanLocalized(image, policy, fit, full) {
52
+ scanLocalized(image, policy, fit, full, coverage = []) {
53
53
  if (this.disposed)
54
54
  throw Error("Scanner is disposed");
55
- const result = this.scanner.scanLocalized(packed(image), policy ?? {}, fit, full);
55
+ const result = this.scanner.scanLocalized(packed(image), policy ?? {}, fit, full, coverage);
56
56
  const primaryCount = result.scan.barcodes.length;
57
57
  const barcodes = result.recovery.barcodes.map((b, i) => i < primaryCount ? b : { ...b, candidate_indices: [] });
58
58
  const localization = result.localization;
@@ -75,9 +75,6 @@ export class ReleaseDetailScanner {
75
75
  },
76
76
  };
77
77
  }
78
- best(frame) {
79
- return frame.barcodes.reduce((best, b) => (!best || b.support > best.support ? b : best), undefined);
80
- }
81
78
  dispose() {
82
79
  if (!this.disposed) {
83
80
  this.scanner.dispose();