pixbeam 0.0.0-stage → 0.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.
@@ -0,0 +1,1801 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // src/core/constants.ts
6
+ var HEADER_SIZE = 18;
7
+ var TARGET_PACKET = 240;
8
+ var BIT_MODES = [3, 2, 1];
9
+ var PRESETS = [
10
+ { id: "128x72", w: 128, h: 72, u: 2 },
11
+ { id: "160x90", w: 160, h: 90, u: 2 },
12
+ { id: "192x108", w: 192, h: 108, u: 2 },
13
+ { id: "240x135", w: 240, h: 135, u: 3 },
14
+ { id: "288x162", w: 288, h: 162, u: 3 },
15
+ { id: "320x180", w: 320, h: 180, u: 4 }
16
+ ];
17
+ var PALETTES = {
18
+ 3: [[0, 0, 0], [0, 0, 255], [0, 255, 0], [0, 255, 255], [255, 0, 0], [255, 0, 255], [255, 255, 0], [255, 255, 255]],
19
+ 2: [[255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255]],
20
+ 1: [[0, 0, 0], [255, 255, 255]]
21
+ };
22
+
23
+ // src/core/crc32.ts
24
+ var TABLE = (() => {
25
+ const t = new Uint32Array(256);
26
+ for (let n = 0; n < 256; n++) {
27
+ let c = n;
28
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
29
+ t[n] = c >>> 0;
30
+ }
31
+ return t;
32
+ })();
33
+ function crc32(buf, init = 4294967295) {
34
+ let c = init;
35
+ for (let i = 0; i < buf.length; i++) c = TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
36
+ return (c ^ 4294967295) >>> 0;
37
+ }
38
+ function crc32Parts(a, b) {
39
+ let c = 4294967295;
40
+ for (let i = 0; i < a.length; i++) c = TABLE[(c ^ a[i]) & 255] ^ c >>> 8;
41
+ for (let i = 0; i < b.length; i++) c = TABLE[(c ^ b[i]) & 255] ^ c >>> 8;
42
+ return (c ^ 4294967295) >>> 0;
43
+ }
44
+
45
+ // src/core/prng.ts
46
+ function mulberry32(seed) {
47
+ let a = seed | 0;
48
+ return () => {
49
+ a = a + 1831565813 | 0;
50
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
51
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
52
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
53
+ };
54
+ }
55
+
56
+ // src/core/layout.ts
57
+ var cache = /* @__PURE__ */ new Map();
58
+ function buildMesh(w, h, u) {
59
+ const unit = Math.max(1, Math.round(u / 2));
60
+ const size = 5 * unit;
61
+ const m = 3.5 * u;
62
+ const cols = w >= 240 ? 4 : 3;
63
+ const rows = 3;
64
+ const snap = (v) => Math.round(v - size / 2) + size / 2;
65
+ const xs = Array.from({ length: cols }, (_, j) => j === 0 ? m : j === cols - 1 ? w - m : snap(m + j * (w - 2 * m) / (cols - 1)));
66
+ const ys = Array.from({ length: rows }, (_, i) => i === 0 ? m : i === rows - 1 ? h - m : snap(m + i * (h - 2 * m) / (rows - 1)));
67
+ const alignments = [];
68
+ for (let i = 0; i < rows; i++) {
69
+ for (let j = 0; j < cols; j++) {
70
+ const corner = (i === 0 || i === rows - 1) && (j === 0 || j === cols - 1);
71
+ if (corner) continue;
72
+ const x = snap(xs[j]);
73
+ const y = snap(ys[i]);
74
+ alignments.push({ row: i, col: j, x, y, left: x - size / 2, top: y - size / 2 });
75
+ }
76
+ }
77
+ return { xs, ys, alignments, unit, size };
78
+ }
79
+ function getLayout(preset, bits, order = "rows") {
80
+ const key = `${preset.id}:${bits}:${order}`;
81
+ const hit = cache.get(key);
82
+ if (hit) return hit;
83
+ const { w, h, u } = preset;
84
+ const zone = 8 * u;
85
+ const mesh = buildMesh(w, h, u);
86
+ const pad = mesh.unit;
87
+ const inZone = (c, r) => (r < zone || r >= h - zone) && (c < zone || c >= w - zone);
88
+ const inAlignment = (c, r) => mesh.alignments.some((a) => c >= a.left - pad && c < a.left + mesh.size + pad && r >= a.top - pad && r < a.top + mesh.size + pad);
89
+ const usable = (c, r) => !inZone(c, r) && !inAlignment(c, r);
90
+ const cells = [];
91
+ if (order === "rows") {
92
+ for (let r = 1; r < h - 1; r++) for (let c = 0; c < w; c++) if (usable(c, r)) cells.push(r * w + c);
93
+ } else {
94
+ for (let c = 0; c < w; c++) for (let r = 1; r < h - 1; r++) if (usable(c, r)) cells.push(r * w + c);
95
+ }
96
+ const top = [];
97
+ const bottom = [];
98
+ for (let c = zone; c < w - zone; c++) {
99
+ top.push(c);
100
+ bottom.push((h - 1) * w + c);
101
+ }
102
+ const cellCount = cells.length;
103
+ const capacity = Math.floor(cellCount * bits / 8);
104
+ const count = Math.max(1, Math.round(capacity / (TARGET_PACKET + HEADER_SIZE)));
105
+ const packetSize = Math.max(16, Math.floor(capacity / count) - HEADER_SIZE);
106
+ const packetsPerFrame = Math.floor(capacity / (packetSize + HEADER_SIZE));
107
+ const whitening = new Uint8Array(capacity);
108
+ const rnd = mulberry32(19288 + w * 31 + h * 7 + bits);
109
+ for (let i = 0; i < capacity; i++) whitening[i] = rnd() * 256 | 0;
110
+ const m = 3.5 * u;
111
+ const layout = {
112
+ preset,
113
+ bits,
114
+ order,
115
+ w,
116
+ h,
117
+ u,
118
+ zone,
119
+ quiet: 2 * u,
120
+ totalW: w + 4 * u,
121
+ totalH: h + 4 * u,
122
+ palette: PALETTES[bits],
123
+ dataCells: Int32Array.from(cells),
124
+ topPalette: Int32Array.from(top),
125
+ bottomPalette: Int32Array.from(bottom),
126
+ cellCount,
127
+ capacity,
128
+ packetSize,
129
+ packetsPerFrame,
130
+ whitening,
131
+ markerCenters: [[m, m], [w - m, m], [w - m, h - m], [m, h - m]],
132
+ mesh
133
+ };
134
+ cache.set(key, layout);
135
+ return layout;
136
+ }
137
+
138
+ // src/core/source.ts
139
+ function packSource(name, payload, compressed, original) {
140
+ let nameBytes = new TextEncoder().encode(name || "file");
141
+ if (nameBytes.length > 255) nameBytes = nameBytes.slice(0, 255);
142
+ const out = new Uint8Array(14 + nameBytes.length + payload.length);
143
+ const dv = new DataView(out.buffer);
144
+ out.set([80, 66, 1, compressed ? 1 : 0]);
145
+ dv.setUint32(4, original.length);
146
+ dv.setUint32(8, crc32(original));
147
+ dv.setUint16(12, nameBytes.length);
148
+ out.set(nameBytes, 14);
149
+ out.set(payload, 14 + nameBytes.length);
150
+ return out;
151
+ }
152
+ function unpackSource(src) {
153
+ if (src[0] !== 80 || src[1] !== 66) throw new Error("Format tidak dikenal");
154
+ const dv = new DataView(src.buffer, src.byteOffset, src.byteLength);
155
+ const nameLen = dv.getUint16(12);
156
+ return {
157
+ name: new TextDecoder().decode(src.subarray(14, 14 + nameLen)),
158
+ compressed: src[3] === 1,
159
+ originalSize: dv.getUint32(4),
160
+ originalCrc: dv.getUint32(8),
161
+ payload: src.subarray(14 + nameLen)
162
+ };
163
+ }
164
+
165
+ // src/core/fountain.ts
166
+ var LT_SEED_START = 268435456;
167
+ var cdfCache = /* @__PURE__ */ new Map();
168
+ function solitonCdf(k) {
169
+ const hit = cdfCache.get(k);
170
+ if (hit) return hit;
171
+ const c = 0.03;
172
+ const delta = 0.5;
173
+ let r = c * Math.log(k / delta) * Math.sqrt(k);
174
+ if (!(r > 1)) r = 1;
175
+ const pivot = Math.floor(k / r);
176
+ const weights = new Float64Array(k + 1);
177
+ let sum = 0;
178
+ for (let i = 1; i <= k; i++) {
179
+ const rho = i === 1 ? 1 / k : 1 / (i * (i - 1));
180
+ let tau = 0;
181
+ if (pivot >= 1 && pivot <= k) {
182
+ if (i < pivot) tau = r / (i * k);
183
+ else if (i === pivot) tau = r * Math.log(r / delta) / k;
184
+ }
185
+ weights[i] = rho + Math.max(0, tau);
186
+ sum += weights[i];
187
+ }
188
+ const cdf = new Float64Array(k + 1);
189
+ let acc = 0;
190
+ for (let i = 1; i <= k; i++) {
191
+ acc += weights[i] / sum;
192
+ cdf[i] = acc;
193
+ }
194
+ cdf[k] = 1;
195
+ cdfCache.set(k, cdf);
196
+ return cdf;
197
+ }
198
+ function neighbors(seed, k) {
199
+ const rnd = mulberry32((seed ^ 1540483477) >>> 0);
200
+ const cdf = solitonCdf(k);
201
+ const x = rnd();
202
+ let lo = 1;
203
+ let hi = k;
204
+ while (lo < hi) {
205
+ const mid = lo + hi >> 1;
206
+ if (cdf[mid] < x) lo = mid + 1;
207
+ else hi = mid;
208
+ }
209
+ const set = /* @__PURE__ */ new Set();
210
+ while (set.size < lo) set.add(Math.floor(rnd() * k));
211
+ return [...set];
212
+ }
213
+ function xorInto(a, b) {
214
+ for (let i = 0; i < a.length; i++) a[i] ^= b[i];
215
+ }
216
+ var FountainEncoder = class {
217
+ constructor(source, blockSize) {
218
+ __publicField(this, "source", source);
219
+ __publicField(this, "blockSize", blockSize);
220
+ __publicField(this, "blockCount");
221
+ __publicField(this, "fileId", Math.random() * 4294967295 >>> 0);
222
+ __publicField(this, "data");
223
+ __publicField(this, "seed", LT_SEED_START);
224
+ this.blockCount = Math.max(1, Math.ceil(source.length / blockSize));
225
+ this.data = new Uint8Array(this.blockCount * blockSize);
226
+ this.data.set(source);
227
+ }
228
+ get totalSize() {
229
+ return this.source.length;
230
+ }
231
+ next(out) {
232
+ const seed = this.seed++;
233
+ out.fill(0);
234
+ for (const b of neighbors(seed, this.blockCount)) {
235
+ const start = b * this.blockSize;
236
+ for (let i = 0; i < this.blockSize; i++) out[i] ^= this.data[start + i];
237
+ }
238
+ return seed;
239
+ }
240
+ };
241
+ var FountainDecoder = class {
242
+ constructor(fileId, totalSize, blockSize) {
243
+ __publicField(this, "fileId", fileId);
244
+ __publicField(this, "totalSize", totalSize);
245
+ __publicField(this, "blockSize", blockSize);
246
+ __publicField(this, "blockCount");
247
+ __publicField(this, "known", 0);
248
+ __publicField(this, "received", 0);
249
+ __publicField(this, "blocks");
250
+ __publicField(this, "seen", /* @__PURE__ */ new Set());
251
+ __publicField(this, "pending", []);
252
+ __publicField(this, "index");
253
+ this.blockCount = Math.max(1, Math.ceil(totalSize / blockSize));
254
+ this.blocks = new Array(this.blockCount);
255
+ this.index = new Array(this.blockCount);
256
+ }
257
+ get done() {
258
+ return this.known >= this.blockCount;
259
+ }
260
+ add(seed, payload) {
261
+ var _a;
262
+ if (this.done || this.seen.has(seed)) return;
263
+ this.seen.add(seed);
264
+ this.received++;
265
+ const data = new Uint8Array(payload);
266
+ const remaining = /* @__PURE__ */ new Set();
267
+ for (const b of neighbors(seed, this.blockCount)) {
268
+ const block = this.blocks[b];
269
+ if (block) xorInto(data, block);
270
+ else remaining.add(b);
271
+ }
272
+ if (remaining.size === 0) return;
273
+ if (remaining.size === 1) return this.resolve(remaining.values().next().value, data);
274
+ const id = this.pending.length;
275
+ this.pending.push({ remaining, data, alive: true });
276
+ for (const b of remaining) ((_a = this.index)[b] ?? (_a[b] = [])).push(id);
277
+ }
278
+ result() {
279
+ const out = new Uint8Array(this.blockCount * this.blockSize);
280
+ this.blocks.forEach((b, i) => out.set(b, i * this.blockSize));
281
+ return out.subarray(0, this.totalSize);
282
+ }
283
+ resolve(first, firstData) {
284
+ const queue = [[first, firstData]];
285
+ while (queue.length) {
286
+ const [idx, data] = queue.pop();
287
+ if (this.blocks[idx]) continue;
288
+ this.blocks[idx] = data;
289
+ this.known++;
290
+ const list = this.index[idx];
291
+ this.index[idx] = void 0;
292
+ if (!list) continue;
293
+ for (const id of list) {
294
+ const p = this.pending[id];
295
+ if (!p.alive) continue;
296
+ xorInto(p.data, data);
297
+ p.remaining.delete(idx);
298
+ if (p.remaining.size <= 1) {
299
+ p.alive = false;
300
+ if (p.remaining.size === 1) queue.push([p.remaining.values().next().value, p.data]);
301
+ }
302
+ }
303
+ }
304
+ }
305
+ };
306
+ function estimatePackets(blockCount) {
307
+ const overhead = blockCount > 2e3 ? 1.08 : blockCount > 300 ? 1.25 : blockCount > 50 ? 1.4 : 1.8;
308
+ return Math.ceil(blockCount * overhead);
309
+ }
310
+
311
+ // src/core/packets.ts
312
+ function encodeFrame(layout, enc) {
313
+ const frame = new Uint8Array(layout.capacity);
314
+ const stride = HEADER_SIZE + layout.packetSize;
315
+ const payload = new Uint8Array(layout.packetSize);
316
+ const dv = new DataView(frame.buffer);
317
+ for (let p = 0; p < layout.packetsPerFrame; p++) {
318
+ const off = p * stride;
319
+ const seed = enc.next(payload);
320
+ dv.setUint32(off, enc.fileId);
321
+ dv.setUint32(off + 4, enc.totalSize);
322
+ dv.setUint16(off + 8, layout.packetSize);
323
+ dv.setUint32(off + 10, seed);
324
+ frame.set(payload, off + HEADER_SIZE);
325
+ dv.setUint32(off + 14, crc32Parts(frame.subarray(off, off + 14), payload));
326
+ }
327
+ for (let i = 0; i < frame.length; i++) frame[i] ^= layout.whitening[i];
328
+ return frame;
329
+ }
330
+ function parsePackets(layout, bytes, count) {
331
+ for (let i = 0; i < bytes.length; i++) bytes[i] ^= layout.whitening[i];
332
+ const stride = HEADER_SIZE + layout.packetSize;
333
+ const dv = new DataView(bytes.buffer, bytes.byteOffset);
334
+ const out = [];
335
+ for (let p = 0; p < count; p++) {
336
+ const off = p * stride;
337
+ if (dv.getUint16(off + 8) !== layout.packetSize) continue;
338
+ const data = bytes.subarray(off + HEADER_SIZE, off + stride);
339
+ if (crc32Parts(bytes.subarray(off, off + 14), data) !== dv.getUint32(off + 14)) continue;
340
+ out.push({
341
+ index: p,
342
+ fileId: dv.getUint32(off),
343
+ totalSize: dv.getUint32(off + 4),
344
+ blockSize: layout.packetSize,
345
+ seed: dv.getUint32(off + 10),
346
+ data: data.slice()
347
+ });
348
+ }
349
+ return out;
350
+ }
351
+
352
+ // src/core/symbols.ts
353
+ function bytesToSymbols(bytes, bits, count) {
354
+ const out = new Uint8Array(count);
355
+ const mask = (1 << bits) - 1;
356
+ let acc = 0;
357
+ let accBits = 0;
358
+ let i = 0;
359
+ for (let s = 0; s < count; s++) {
360
+ while (accBits < bits) {
361
+ acc = acc << 8 | (i < bytes.length ? bytes[i] : 0);
362
+ i++;
363
+ accBits += 8;
364
+ }
365
+ out[s] = acc >>> accBits - bits & mask;
366
+ accBits -= bits;
367
+ acc &= (1 << accBits) - 1;
368
+ }
369
+ return out;
370
+ }
371
+ function symbolsToBytes(symbols, bits, size) {
372
+ const out = new Uint8Array(size);
373
+ let acc = 0;
374
+ let accBits = 0;
375
+ let o = 0;
376
+ for (let s = 0; s < symbols.length && o < size; s++) {
377
+ acc = acc << bits | symbols[s];
378
+ accBits += bits;
379
+ if (accBits >= 8) {
380
+ out[o++] = acc >>> accBits - 8 & 255;
381
+ accBits -= 8;
382
+ acc &= (1 << accBits) - 1;
383
+ }
384
+ }
385
+ return out;
386
+ }
387
+
388
+ // src/core/render.ts
389
+ function renderFrame(layout, frame, out) {
390
+ const { w, h, u, quiet, totalW, totalH, palette, zone } = layout;
391
+ const rgba = out ?? new Uint8ClampedArray(totalW * totalH * 4);
392
+ rgba.fill(255);
393
+ const put = (c, r, col) => {
394
+ const i = ((r + quiet) * totalW + c + quiet) * 4;
395
+ rgba[i] = col[0];
396
+ rgba[i + 1] = col[1];
397
+ rgba[i + 2] = col[2];
398
+ };
399
+ const size = 7 * u;
400
+ const black = [0, 0, 0];
401
+ for (const [ox, oy] of [[0, 0], [w - size, 0], [0, h - size], [w - size, h - size]]) {
402
+ for (let y = 0; y < size; y++) {
403
+ for (let x = 0; x < size; x++) {
404
+ const ring = Math.min(x, y, size - 1 - x, size - 1 - y);
405
+ if (ring < u || ring >= 2 * u) put(ox + x, oy + y, black);
406
+ }
407
+ }
408
+ }
409
+ const { unit, size: asize, alignments } = layout.mesh;
410
+ for (const a of alignments) {
411
+ for (let y = 0; y < asize; y++) {
412
+ for (let x = 0; x < asize; x++) {
413
+ const ring = Math.floor(Math.min(x, y, asize - 1 - x, asize - 1 - y) / unit);
414
+ if (ring !== 1) put(a.left + x, a.top + y, black);
415
+ }
416
+ }
417
+ }
418
+ for (let c = zone; c < w - zone; c++) {
419
+ const col = palette[(c - zone) % palette.length];
420
+ put(c, 0, col);
421
+ put(c, h - 1, col);
422
+ }
423
+ const symbols = bytesToSymbols(frame, layout.bits, layout.cellCount);
424
+ for (let s = 0; s < layout.cellCount; s++) {
425
+ const idx = layout.dataCells[s];
426
+ put(idx % w, idx / w | 0, palette[symbols[s]]);
427
+ }
428
+ return rgba;
429
+ }
430
+
431
+ // src/core/homography.ts
432
+ function homography(src, dst) {
433
+ const a = [];
434
+ const b = [];
435
+ for (let i = 0; i < 4; i++) {
436
+ const [u, v] = src[i];
437
+ const [x, y] = dst[i];
438
+ a.push([u, v, 1, 0, 0, 0, -u * x, -v * x]);
439
+ b.push(x);
440
+ a.push([0, 0, 0, u, v, 1, -u * y, -v * y]);
441
+ b.push(y);
442
+ }
443
+ for (let c = 0; c < 8; c++) {
444
+ let p = c;
445
+ for (let r = c + 1; r < 8; r++) if (Math.abs(a[r][c]) > Math.abs(a[p][c])) p = r;
446
+ [a[c], a[p]] = [a[p], a[c]];
447
+ [b[c], b[p]] = [b[p], b[c]];
448
+ if (Math.abs(a[c][c]) < 1e-12) return null;
449
+ for (let r = 0; r < 8; r++) {
450
+ if (r === c) continue;
451
+ const f = a[r][c] / a[c][c];
452
+ for (let k = c; k < 8; k++) a[r][k] -= f * a[c][k];
453
+ b[r] -= f * b[c];
454
+ }
455
+ }
456
+ const h = new Float64Array(9);
457
+ for (let i = 0; i < 8; i++) h[i] = b[i] / a[i][i];
458
+ h[8] = 1;
459
+ return h;
460
+ }
461
+ function project(h, u, v) {
462
+ const d = h[6] * u + h[7] * v + h[8];
463
+ return [(h[0] * u + h[1] * v + h[2]) / d, (h[3] * u + h[4] * v + h[5]) / d];
464
+ }
465
+
466
+ // src/core/detect.ts
467
+ function luminance(rgba, n) {
468
+ const lum = new Uint8Array(n);
469
+ for (let i = 0, p = 0; i < n; i++, p += 4) lum[i] = rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 >> 8;
470
+ return lum;
471
+ }
472
+ function binarize(rgba, w, h) {
473
+ const lum = luminance(rgba, w * h);
474
+ const bs = Math.max(8, Math.floor(Math.min(w, h) / 24));
475
+ const bw = Math.ceil(w / bs);
476
+ const bh = Math.ceil(h / bs);
477
+ const thr = new Float32Array(bw * bh);
478
+ for (let by = 0; by < bh; by++) {
479
+ for (let bx = 0; bx < bw; bx++) {
480
+ let mn = 255;
481
+ let mx = 0;
482
+ for (let y = by * bs; y < Math.min(h, (by + 1) * bs); y++) {
483
+ for (let x = bx * bs; x < Math.min(w, (bx + 1) * bs); x++) {
484
+ const v = lum[y * w + x];
485
+ if (v < mn) mn = v;
486
+ if (v > mx) mx = v;
487
+ }
488
+ }
489
+ thr[by * bw + bx] = mx - mn > 32 ? (mn + mx) / 2 : -1;
490
+ }
491
+ }
492
+ const avg = new Float32Array(bw * bh);
493
+ for (let by = 0; by < bh; by++) {
494
+ for (let bx = 0; bx < bw; bx++) {
495
+ let s = 0;
496
+ let c = 0;
497
+ for (let dy = -2; dy <= 2; dy++) {
498
+ for (let dx = -2; dx <= 2; dx++) {
499
+ const yy = by + dy;
500
+ const xx = bx + dx;
501
+ if (yy < 0 || xx < 0 || yy >= bh || xx >= bw) continue;
502
+ const t = thr[yy * bw + xx];
503
+ if (t >= 0) {
504
+ s += t;
505
+ c++;
506
+ }
507
+ }
508
+ }
509
+ avg[by * bw + bx] = c ? s / c : 0;
510
+ }
511
+ }
512
+ const bin = new Uint8Array(w * h);
513
+ for (let y = 0; y < h; y++) {
514
+ const row = Math.floor(y / bs) * bw;
515
+ for (let x = 0; x < w; x++) bin[y * w + x] = lum[y * w + x] < avg[row + Math.floor(x / bs)] ? 1 : 0;
516
+ }
517
+ return bin;
518
+ }
519
+ function ratioOk(c, mid = 3) {
520
+ const total = c[0] + c[1] + c[2] + c[3] + c[4];
521
+ const units = 4 + mid;
522
+ if (total < units) return false;
523
+ const m = total / units;
524
+ const tol = m * 0.6;
525
+ return Math.abs(c[0] - m) < tol && Math.abs(c[1] - m) < tol && Math.abs(c[2] - mid * m) < mid * tol && Math.abs(c[3] - m) < tol && Math.abs(c[4] - m) < tol;
526
+ }
527
+ function cross(bin, w, h, x0, y0, dx, dy, maxRun, mid = 3) {
528
+ const at = (t2) => {
529
+ const x = Math.round(x0 + dx * t2);
530
+ const y = Math.round(y0 + dy * t2);
531
+ if (x < 0 || y < 0 || x >= w || y >= h) return -1;
532
+ return bin[y * w + x];
533
+ };
534
+ if (at(0) !== 1) return null;
535
+ const c = [0, 0, 0, 0, 0];
536
+ let t = 0;
537
+ while (at(t) === 1) if (++c[2] > maxRun * 3) return null;
538
+ else t--;
539
+ const start = t + 1;
540
+ while (at(t) === 0) if (++c[1] > maxRun) return null;
541
+ else t--;
542
+ while (at(t) === 1) if (++c[0] > maxRun) return null;
543
+ else t--;
544
+ t = 1;
545
+ while (at(t) === 1) if (++c[2] > maxRun * 3) return null;
546
+ else t++;
547
+ const end = t - 1;
548
+ while (at(t) === 0) if (++c[3] > maxRun) return null;
549
+ else t++;
550
+ while (at(t) === 1) if (++c[4] > maxRun) return null;
551
+ else t++;
552
+ if (!c[0] || !c[1] || !c[3] || !c[4] || !ratioOk(c, mid)) return null;
553
+ return { center: (start + end) / 2, total: c[0] + c[1] + c[2] + c[3] + c[4] };
554
+ }
555
+ function findMarkers(bin, w, h) {
556
+ const found = [];
557
+ for (let y = 0; y < h; y += 1) {
558
+ const runs = [];
559
+ let cur = bin[y * w];
560
+ let len = 0;
561
+ let start = 0;
562
+ for (let x = 0; x <= w; x++) {
563
+ const v = x < w ? bin[y * w + x] : -1;
564
+ if (v === cur) len++;
565
+ else {
566
+ runs.push(cur, len, start);
567
+ cur = v;
568
+ len = 1;
569
+ start = x;
570
+ }
571
+ }
572
+ for (let i = 0; i + 14 < runs.length; i += 3) {
573
+ if (runs[i] !== 1) continue;
574
+ const c = [runs[i + 1], runs[i + 4], runs[i + 7], runs[i + 10], runs[i + 13]];
575
+ if (!ratioOk(c)) continue;
576
+ const total = c[0] + c[1] + c[2] + c[3] + c[4];
577
+ let cx = runs[i + 8] + c[2] / 2;
578
+ const v = cross(bin, w, h, cx, y, 0, 1, total);
579
+ if (!v) continue;
580
+ const cy = y + v.center;
581
+ const hz = cross(bin, w, h, cx, cy, 1, 0, total);
582
+ if (!hz) continue;
583
+ cx += hz.center;
584
+ const size = (v.total + hz.total) / 2;
585
+ const m = found.find((f) => Math.abs(f.x - cx) < f.size / 4 && Math.abs(f.y - cy) < f.size / 4 && Math.abs(f.size - size) < f.size / 2);
586
+ if (m) {
587
+ m.x = (m.x * m.hits + cx) / (m.hits + 1);
588
+ m.y = (m.y * m.hits + cy) / (m.hits + 1);
589
+ m.size = (m.size * m.hits + size) / (m.hits + 1);
590
+ m.hits++;
591
+ } else found.push({ x: cx, y: cy, size, hits: 1 });
592
+ }
593
+ }
594
+ return found;
595
+ }
596
+ function pickCorners(markers) {
597
+ let good = markers.filter((m) => m.hits >= 2);
598
+ if (good.length < 4) return null;
599
+ const sizes = [...good].sort((a, b) => b.hits - a.hits).slice(0, 8).map((m) => m.size).sort((a, b) => a - b);
600
+ const median = sizes[sizes.length >> 1];
601
+ good = good.filter((m) => m.size > median * 0.5 && m.size < median * 2);
602
+ if (good.length < 4) return null;
603
+ const best = (score) => good.reduce((a, b) => score(b) > score(a) ? b : a);
604
+ const ring = [
605
+ best((m) => -(m.x + m.y)),
606
+ best((m) => m.x - m.y),
607
+ best((m) => m.x + m.y),
608
+ best((m) => m.y - m.x)
609
+ ];
610
+ return new Set(ring).size === 4 ? ring : null;
611
+ }
612
+ function localBinary(rgba, n) {
613
+ const lum = luminance(rgba, n);
614
+ let mn = 255;
615
+ let mx = 0;
616
+ for (const v of lum) {
617
+ if (v < mn) mn = v;
618
+ if (v > mx) mx = v;
619
+ }
620
+ if (mx - mn < 40) return null;
621
+ const thr = (mn + mx) / 2;
622
+ const bin = new Uint8Array(n);
623
+ for (let i = 0; i < n; i++) bin[i] = lum[i] < thr ? 1 : 0;
624
+ return bin;
625
+ }
626
+ function crossAt(bin, w, h, x, y, maxRun, mid) {
627
+ let cx = x;
628
+ let cy = y;
629
+ let total = 0;
630
+ for (let pass = 0; pass < 2; pass++) {
631
+ const hz = cross(bin, w, h, cx, cy, 1, 0, maxRun, mid);
632
+ if (!hz) return null;
633
+ cx += hz.center;
634
+ const v = cross(bin, w, h, cx, cy, 0, 1, maxRun, mid);
635
+ if (!v) return null;
636
+ cy += v.center;
637
+ total = (hz.total + v.total) / 2;
638
+ }
639
+ return { x: cx, y: cy, total };
640
+ }
641
+ function refineMarker(rgba, w, h, guess, size, mid = 3, reachFactor = 1 / 7) {
642
+ const bin = localBinary(rgba, w * h);
643
+ if (!bin) return null;
644
+ const units = 4 + mid;
645
+ const maxRun = size / units * mid * 1.6;
646
+ const reach = Math.max(2, Math.round(size * reachFactor));
647
+ const step = Math.max(1, Math.round(size / units / 2));
648
+ const [gx, gy] = guess;
649
+ for (let r = 0; r <= reach; r += step) {
650
+ for (let dy = -r; dy <= r; dy += step) {
651
+ for (let dx = -r; dx <= r; dx += step) {
652
+ if (r && Math.max(Math.abs(dx), Math.abs(dy)) < r) continue;
653
+ const x = Math.round(gx + dx);
654
+ const y = Math.round(gy + dy);
655
+ if (x < 0 || y < 0 || x >= w || y >= h || bin[y * w + x] !== 1) continue;
656
+ const hit = crossAt(bin, w, h, x, y, maxRun, mid);
657
+ if (hit && hit.total > size * 0.6 && hit.total < size * 1.6 && Math.hypot(hit.x - gx, hit.y - gy) <= reach + size / units) {
658
+ return { x: hit.x, y: hit.y, size: hit.total, hits: 1 };
659
+ }
660
+ }
661
+ }
662
+ }
663
+ return null;
664
+ }
665
+
666
+ // src/core/decode.ts
667
+ function paletteMeans(layout, cells, row) {
668
+ const m = layout.palette.length;
669
+ const w = layout.w;
670
+ const reps = row.length / m;
671
+ const segments = Math.max(1, Math.floor(reps / 3));
672
+ const segW = Math.floor(row.length / segments);
673
+ const seg = new Float32Array(segments * m * 3);
674
+ const cnt = new Float32Array(segments * m);
675
+ for (let i = 0; i < row.length; i++) {
676
+ const s = Math.min(segments - 1, Math.floor(i / segW));
677
+ const k = i % m;
678
+ const p = row[i] * 4;
679
+ seg[(s * m + k) * 3] += cells[p];
680
+ seg[(s * m + k) * 3 + 1] += cells[p + 1];
681
+ seg[(s * m + k) * 3 + 2] += cells[p + 2];
682
+ cnt[s * m + k]++;
683
+ }
684
+ for (let i = 0; i < segments * m; i++) for (let ch = 0; ch < 3; ch++) seg[i * 3 + ch] /= cnt[i] || 1;
685
+ const perCol = new Float32Array(w * m * 3);
686
+ const first = layout.zone;
687
+ for (let c = 0; c < w; c++) {
688
+ const pos = (c - first) / segW - 0.5;
689
+ const s0 = Math.max(0, Math.min(segments - 1, Math.floor(pos)));
690
+ const s1 = Math.min(segments - 1, s0 + 1);
691
+ const t = Math.max(0, Math.min(1, pos - s0));
692
+ for (let k = 0; k < m; k++) {
693
+ for (let ch = 0; ch < 3; ch++) {
694
+ const a = seg[(s0 * m + k) * 3 + ch];
695
+ const b = seg[(s1 * m + k) * 3 + ch];
696
+ perCol[(c * m + k) * 3 + ch] = a + (b - a) * t;
697
+ }
698
+ }
699
+ }
700
+ return perCol;
701
+ }
702
+ function decodeCells(layout, cells, maxPackets = layout.packetsPerFrame) {
703
+ const { w, h, palette, bits } = layout;
704
+ const m = palette.length;
705
+ const top = paletteMeans(layout, cells, layout.topPalette);
706
+ const bottom = paletteMeans(layout, cells, layout.bottomPalette);
707
+ const count = Math.min(layout.packetsPerFrame, maxPackets);
708
+ const size = count * (HEADER_SIZE + layout.packetSize);
709
+ const symbolCount = Math.min(layout.cellCount, Math.ceil(size * 8 / bits));
710
+ const symbols = new Uint8Array(symbolCount);
711
+ for (let s = 0; s < symbolCount; s++) {
712
+ const idx = layout.dataCells[s];
713
+ const c = idx % w;
714
+ const t = (idx / w | 0) / (h - 1);
715
+ const p = idx * 4;
716
+ const r = cells[p];
717
+ const g = cells[p + 1];
718
+ const b = cells[p + 2];
719
+ let best = 0;
720
+ let bestD = Infinity;
721
+ const base = c * m * 3;
722
+ for (let k = 0; k < m; k++) {
723
+ const o = base + k * 3;
724
+ const dr = r - (top[o] + (bottom[o] - top[o]) * t);
725
+ const dg = g - (top[o + 1] + (bottom[o + 1] - top[o + 1]) * t);
726
+ const db = b - (top[o + 2] + (bottom[o + 2] - top[o + 2]) * t);
727
+ const d = dr * dr + dg * dg + db * db;
728
+ if (d < bestD) {
729
+ bestD = d;
730
+ best = k;
731
+ }
732
+ }
733
+ symbols[s] = best;
734
+ }
735
+ return { packets: parsePackets(layout, symbolsToBytes(symbols, bits, size), count), expected: count, symbols };
736
+ }
737
+
738
+ // src/core/diagnostics.ts
739
+ var TEST_FILE_ID = 3736100864;
740
+ var TestPattern = class {
741
+ constructor(seed = 1) {
742
+ __publicField(this, "seed", seed);
743
+ __publicField(this, "fileId", TEST_FILE_ID);
744
+ __publicField(this, "totalSize", 0);
745
+ }
746
+ next(out) {
747
+ const seed = this.seed++;
748
+ const rnd = mulberry32(seed * 2654435761);
749
+ for (let i = 0; i < out.length; i++) out[i] = rnd() * 256 | 0;
750
+ return seed;
751
+ }
752
+ };
753
+ var ErrorMap = class {
754
+ constructor(layout) {
755
+ __publicField(this, "layout", layout);
756
+ __publicField(this, "errors");
757
+ __publicField(this, "samples");
758
+ __publicField(this, "confusion");
759
+ __publicField(this, "shiftErrors", 0);
760
+ __publicField(this, "totalErrors", 0);
761
+ __publicField(this, "directions", new Uint32Array(9 * 4));
762
+ __publicField(this, "expectedGrid");
763
+ __publicField(this, "frames", 0);
764
+ __publicField(this, "measuredFrames", 0);
765
+ __publicField(this, "mode", "packet");
766
+ this.errors = new Uint32Array(layout.w * layout.h);
767
+ this.samples = new Uint32Array(layout.w * layout.h);
768
+ const m = layout.palette.length;
769
+ this.confusion = new Uint32Array(m * m);
770
+ this.expectedGrid = new Int16Array(layout.w * layout.h);
771
+ }
772
+ add(result) {
773
+ this.frames++;
774
+ const test = result.packets.find((p) => p.fileId === TEST_FILE_ID);
775
+ if (test) this.addExact(result, test.seed - test.index);
776
+ else this.addPacketLevel(result);
777
+ }
778
+ rate(idx) {
779
+ return this.samples[idx] ? this.errors[idx] / this.samples[idx] : 0;
780
+ }
781
+ summary(names) {
782
+ const { w, h, dataCells } = this.layout;
783
+ let err = 0;
784
+ let tot = 0;
785
+ const region = { center: [0, 0], edge: [0, 0] };
786
+ const areas = {};
787
+ for (const idx of dataCells) {
788
+ const c = idx % w;
789
+ const r = idx / w | 0;
790
+ err += this.errors[idx];
791
+ tot += this.samples[idx];
792
+ const nx = c / (w - 1);
793
+ const ny = r / (h - 1);
794
+ const inner = nx > 0.25 && nx < 0.75 && ny > 0.25 && ny < 0.75;
795
+ const bucket = inner ? region.center : region.edge;
796
+ bucket[0] += this.errors[idx];
797
+ bucket[1] += this.samples[idx];
798
+ const key = `${ny < 1 / 3 ? "atas" : ny < 2 / 3 ? "tengah" : "bawah"} ${nx < 1 / 3 ? "kiri" : nx < 2 / 3 ? "tengah" : "kanan"}`;
799
+ const a = areas[key] ?? (areas[key] = [0, 0]);
800
+ a[0] += this.errors[idx];
801
+ a[1] += this.samples[idx];
802
+ }
803
+ const pct2 = (a) => a[1] ? a[0] / a[1] : 0;
804
+ const worst = Object.entries(areas).sort((a, b) => pct2(b[1]) - pct2(a[1]))[0];
805
+ const concentration = worst && tot && err ? pct2(worst[1]) / (err / tot) : 0;
806
+ const m = this.layout.palette.length;
807
+ const confusions = [];
808
+ for (let from = 0; from < m; from++) {
809
+ let row = 0;
810
+ for (let to = 0; to < m; to++) row += this.confusion[from * m + to];
811
+ for (let to = 0; to < m; to++) {
812
+ if (to === from || !row) continue;
813
+ const rate = this.confusion[from * m + to] / row;
814
+ if (rate > 0) confusions.push({ from, to, rate });
815
+ }
816
+ }
817
+ confusions.sort((a, b) => b.rate - a.rate);
818
+ const cellErrorRate = tot ? err / tot : 0;
819
+ const shiftShare = this.totalErrors ? this.shiftErrors / this.totalErrors : 0;
820
+ let dominant = 0;
821
+ let matched = 0;
822
+ for (let a = 0; a < 9; a++) {
823
+ const d = this.directions.subarray(a * 4, a * 4 + 4);
824
+ dominant += Math.max(...d);
825
+ matched += d[0] + d[1] + d[2] + d[3];
826
+ }
827
+ const directionBias = matched > 20 ? dominant / matched : 0;
828
+ const centerRate = pct2(region.center);
829
+ const edgeRate = pct2(region.edge);
830
+ return {
831
+ mode: this.mode,
832
+ frames: this.frames,
833
+ measuredFrames: this.measuredFrames,
834
+ cellErrorRate,
835
+ shiftShare,
836
+ directionBias,
837
+ concentration,
838
+ centerRate,
839
+ edgeRate,
840
+ worstRegion: worst ? worst[0] : "-",
841
+ confusions: confusions.slice(0, 3),
842
+ hint: hintFor(this.mode, cellErrorRate, directionBias, concentration, centerRate, edgeRate, worst ? worst[0] : "", confusions, names)
843
+ };
844
+ }
845
+ addExact(result, firstSeed) {
846
+ this.mode = "exact";
847
+ this.measuredFrames++;
848
+ const { layout } = this;
849
+ const expected = bytesToSymbols(encodeFrame(layout, new TestPattern(firstSeed)), layout.bits, layout.cellCount);
850
+ const m = layout.palette.length;
851
+ const n = result.symbols.length;
852
+ const { w } = layout;
853
+ const grid = this.expectedGrid;
854
+ grid.fill(-1);
855
+ for (let s = 0; s < n; s++) grid[layout.dataCells[s]] = expected[s];
856
+ for (let s = 0; s < n; s++) {
857
+ const idx = layout.dataCells[s];
858
+ const want = expected[s];
859
+ const got = result.symbols[s];
860
+ this.samples[idx]++;
861
+ this.confusion[want * m + got]++;
862
+ if (want === got) continue;
863
+ this.errors[idx]++;
864
+ this.totalErrors++;
865
+ const c = idx % w;
866
+ const r = idx / w | 0;
867
+ const area = Math.min(2, Math.floor(r * 3 / layout.h)) * 3 + Math.min(2, Math.floor(c * 3 / w));
868
+ const hits = [c > 0 && grid[idx - 1] === got, c < w - 1 && grid[idx + 1] === got, grid[idx - w] === got, grid[idx + w] === got];
869
+ if (hits.some(Boolean)) this.shiftErrors++;
870
+ hits.forEach((hit, d) => hit && this.directions[area * 4 + d]++);
871
+ }
872
+ }
873
+ addPacketLevel(result) {
874
+ if (this.mode === "exact") return;
875
+ this.measuredFrames++;
876
+ const { layout } = this;
877
+ const stride = (HEADER_SIZE + layout.packetSize) * 8;
878
+ const ok = new Uint8Array(result.expected);
879
+ for (const p of result.packets) ok[p.index] = 1;
880
+ for (let p = 0; p < result.expected; p++) {
881
+ const a = Math.floor(p * stride / layout.bits);
882
+ const b = Math.min(layout.cellCount, Math.ceil((p + 1) * stride / layout.bits));
883
+ for (let s = a; s < b; s++) {
884
+ const idx = layout.dataCells[s];
885
+ this.samples[idx]++;
886
+ if (!ok[p]) this.errors[idx]++;
887
+ }
888
+ }
889
+ }
890
+ };
891
+ function hintFor(mode, total, bias, concentration, center, edge, worst, confusions, names) {
892
+ if (total < 5e-4) return "Hampir tanpa error. Grid bisa dinaikkan atau fps dipercepat.";
893
+ const parts = [];
894
+ if (mode === "exact" && bias > 0.47) {
895
+ parts.push("Error berupa sel yang bergeser ke arah yang sama di tiap area: masalah geometri, misalnya distorsi lensa atau marker kurang presisi. Alignment marker tambahan akan membantu.");
896
+ } else if (concentration > 2.5) {
897
+ parts.push(`Error terkumpul di satu area (${concentration.toFixed(1)}\xD7 rata-rata): biasanya pantulan cahaya, bagian yang tidak fokus, atau distorsi lokal. Lihat bentuknya di peta.`);
898
+ } else if (edge > center * 2 && edge > 2e-3) {
899
+ parts.push("Error menumpuk di tepi: kemungkinan distorsi lensa atau cahaya tepi layar lebih gelap.");
900
+ } else if (center > edge * 2 && center > 2e-3) {
901
+ parts.push("Error menumpuk di tengah: kemungkinan pantulan cahaya, fokus, atau layar tidak rata.");
902
+ } else {
903
+ parts.push("Error tersebar merata: lebih mungkin masalah warna, blur, atau sel terlalu kecil.");
904
+ }
905
+ if (worst && concentration <= 2.5) parts.push(`Area terburuk: ${worst}.`);
906
+ else if (worst) parts.push(`Area: ${worst}.`);
907
+ const top = confusions[0];
908
+ if (mode === "exact" && bias <= 0.47 && top && top.rate > 0.01) parts.push(`Warna yang paling sering tertukar: ${names[top.from]} terbaca ${names[top.to]}.`);
909
+ if (mode === "packet") parts.push("Untuk peta per sel yang akurat, aktifkan Pola uji di pengirim.");
910
+ return parts.join(" ");
911
+ }
912
+
913
+ // src/core/receiver.ts
914
+ var ORDERS = ["rows", "cols"];
915
+ var COARSE_WIDTH = 640;
916
+ function codeRing(layout, rotation) {
917
+ const c = layout.markerCenters;
918
+ return [0, 1, 2, 3].map((i) => c[(i + rotation) % 4]);
919
+ }
920
+ var Receiver = class {
921
+ constructor() {
922
+ __publicField(this, "decoder", null);
923
+ __publicField(this, "lock", null);
924
+ __publicField(this, "validPackets", 0);
925
+ __publicField(this, "expectedPackets", 0);
926
+ __publicField(this, "useAlignment", true);
927
+ __publicField(this, "ring", null);
928
+ __publicField(this, "misses", 0);
929
+ __publicField(this, "offsets", /* @__PURE__ */ new Map());
930
+ }
931
+ reset() {
932
+ this.decoder = null;
933
+ this.validPackets = 0;
934
+ this.expectedPackets = 0;
935
+ }
936
+ process(src) {
937
+ let tracked = false;
938
+ let ring = this.ring ? this.refineAll(src, this.ring) : null;
939
+ if (ring) tracked = true;
940
+ else ring = this.detect(src);
941
+ this.ring = ring;
942
+ const report = { corners: ring?.map((m) => [m.x, m.y]) ?? null, tracked, lock: this.lock, packets: 0, expected: 0, finished: false };
943
+ if (!ring) return report;
944
+ if (!this.lock) this.lock = this.search(src, ring);
945
+ report.lock = this.lock;
946
+ if (!this.lock) return report;
947
+ const layout = getLayout(this.lock.preset, this.lock.bits, this.lock.order);
948
+ const mesh = this.mesh(src, layout, this.lock.rotation, ring);
949
+ if (!mesh) return report;
950
+ report.alignment = { nodes: mesh.nodes, found: mesh.found, total: mesh.total };
951
+ report.cellPx = ring.reduce((a, m) => a + m.size, 0) / ring.length / (7 * layout.u);
952
+ const decoded = decodeCells(layout, src.rectify(mesh.patches, layout.w, layout.h));
953
+ const { packets, expected } = decoded;
954
+ report.decoded = decoded;
955
+ report.layout = layout;
956
+ report.packets = packets.length;
957
+ report.expected = expected;
958
+ this.expectedPackets += expected;
959
+ if (!packets.length) {
960
+ if (++this.misses > 30) {
961
+ this.lock = null;
962
+ this.misses = 0;
963
+ }
964
+ return report;
965
+ }
966
+ this.misses = 0;
967
+ for (const p of packets) {
968
+ if (p.fileId === TEST_FILE_ID) {
969
+ this.validPackets++;
970
+ continue;
971
+ }
972
+ if (!this.decoder || this.decoder.fileId !== p.fileId) {
973
+ if (this.decoder?.done) continue;
974
+ this.decoder = new FountainDecoder(p.fileId, p.totalSize, p.blockSize);
975
+ }
976
+ if (this.decoder.blockSize !== p.blockSize || this.decoder.totalSize !== p.totalSize) continue;
977
+ this.decoder.add(p.seed, p.data);
978
+ this.validPackets++;
979
+ }
980
+ report.finished = !!this.decoder?.done;
981
+ return report;
982
+ }
983
+ detect(src) {
984
+ const small = src.small(COARSE_WIDTH);
985
+ const corners = pickCorners(findMarkers(binarize(small.data, small.w, small.h), small.w, small.h));
986
+ if (!corners) return null;
987
+ const scaled = corners.map((m) => ({ x: m.x * small.scale + (small.scale - 1) / 2, y: m.y * small.scale + (small.scale - 1) / 2, size: m.size * small.scale, hits: m.hits }));
988
+ return this.refineAll(src, scaled);
989
+ }
990
+ refineAll(src, ring) {
991
+ const out = [];
992
+ for (const m of ring) {
993
+ const half = Math.ceil(m.size * 0.9);
994
+ const x0 = Math.max(0, Math.round(m.x - half));
995
+ const y0 = Math.max(0, Math.round(m.y - half));
996
+ const x1 = Math.min(src.width, Math.round(m.x + half));
997
+ const y1 = Math.min(src.height, Math.round(m.y + half));
998
+ if (x1 - x0 < 8 || y1 - y0 < 8) return null;
999
+ const r = refineMarker(src.region(x0, y0, x1 - x0, y1 - y0), x1 - x0, y1 - y0, [m.x - x0, m.y - y0], m.size);
1000
+ if (!r) return null;
1001
+ out.push({ x: r.x + x0, y: r.y + y0, size: r.size, hits: 1 });
1002
+ }
1003
+ const sizes = out.map((m) => m.size);
1004
+ if (Math.max(...sizes) > Math.min(...sizes) * 2) return null;
1005
+ return out;
1006
+ }
1007
+ search(src, ring) {
1008
+ const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
1009
+ const horizontal = dist(ring[0], ring[1]) + dist(ring[3], ring[2]);
1010
+ const vertical = dist(ring[0], ring[3]) + dist(ring[1], ring[2]);
1011
+ const rotations = horizontal >= vertical ? [0, 2] : [1, 3];
1012
+ for (const preset of PRESETS) {
1013
+ for (const rotation of rotations) {
1014
+ const mesh = this.mesh(src, getLayout(preset, 3), rotation, ring);
1015
+ if (!mesh) continue;
1016
+ const cells = src.rectify(mesh.patches, preset.w, preset.h);
1017
+ for (const bits of BIT_MODES) {
1018
+ for (const order of ORDERS) {
1019
+ if (decodeCells(getLayout(preset, bits, order), cells, 4).packets.length) return { preset, bits, order, rotation };
1020
+ }
1021
+ }
1022
+ }
1023
+ }
1024
+ return null;
1025
+ }
1026
+ mesh(src, layout, rotation, ring) {
1027
+ const global = homography(codeRing(layout, rotation), ring.map((m) => [m.x, m.y]));
1028
+ if (!global) return null;
1029
+ const { xs, ys, alignments, size } = layout.mesh;
1030
+ const cols = xs.length;
1031
+ const rows = ys.length;
1032
+ const nodes = new Array(cols * rows);
1033
+ const code = new Array(cols * rows);
1034
+ for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++) code[i * cols + j] = [xs[j], ys[i]];
1035
+ for (const a of alignments) code[a.row * cols + a.col] = [a.x, a.y];
1036
+ const cornerOf = (q) => ring[(q - rotation + 4) % 4];
1037
+ const corners = [[0, 0, 0], [0, cols - 1, 1], [rows - 1, cols - 1, 2], [rows - 1, 0, 3]];
1038
+ for (const [i, j, q] of corners) {
1039
+ const m = cornerOf(q);
1040
+ nodes[i * cols + j] = [m.x, m.y];
1041
+ }
1042
+ const cellPx = ring.reduce((a, m) => a + m.size, 0) / ring.length / (7 * layout.u);
1043
+ const key = `${layout.preset.id}:${rotation}`;
1044
+ const offsets = this.offsets.get(key) ?? alignments.map(() => [0, 0]);
1045
+ let found = 0;
1046
+ alignments.forEach((a, k) => {
1047
+ const [px, py] = project(global, a.x, a.y);
1048
+ const guess = [px + offsets[k][0], py + offsets[k][1]];
1049
+ let hit = null;
1050
+ if (this.useAlignment) {
1051
+ const px2 = size * cellPx;
1052
+ const half = Math.ceil(px2 * 1.3);
1053
+ const x0 = Math.max(0, Math.round(guess[0] - half));
1054
+ const y0 = Math.max(0, Math.round(guess[1] - half));
1055
+ const x1 = Math.min(src.width, Math.round(guess[0] + half));
1056
+ const y1 = Math.min(src.height, Math.round(guess[1] + half));
1057
+ if (x1 - x0 >= 8 && y1 - y0 >= 8 && px2 >= 5) {
1058
+ const r = refineMarker(src.region(x0, y0, x1 - x0, y1 - y0), x1 - x0, y1 - y0, [guess[0] - x0, guess[1] - y0], px2, 1, 0.5);
1059
+ if (r) hit = [r.x + x0, r.y + y0];
1060
+ }
1061
+ }
1062
+ if (hit) {
1063
+ found++;
1064
+ offsets[k] = [hit[0] - px, hit[1] - py];
1065
+ nodes[a.row * cols + a.col] = hit;
1066
+ } else {
1067
+ nodes[a.row * cols + a.col] = [px, py];
1068
+ }
1069
+ });
1070
+ this.offsets.set(key, offsets);
1071
+ if (!this.useAlignment || found === 0) {
1072
+ return { patches: [{ h: global, x0: 0, y0: 0, x1: layout.w, y1: layout.h }], nodes: nodes.filter((_, i) => !isCorner(i, rows, cols)), found, total: alignments.length };
1073
+ }
1074
+ const patches = [];
1075
+ for (let i = 0; i < rows - 1; i++) {
1076
+ for (let j = 0; j < cols - 1; j++) {
1077
+ const at = (r, c) => code[r * cols + c];
1078
+ const src4 = [at(i, j), at(i, j + 1), at(i + 1, j + 1), at(i + 1, j)];
1079
+ const dst4 = [nodes[i * cols + j], nodes[i * cols + j + 1], nodes[(i + 1) * cols + j + 1], nodes[(i + 1) * cols + j]];
1080
+ const h = homography(src4, dst4) ?? global;
1081
+ patches.push({
1082
+ h,
1083
+ x0: j === 0 ? 0 : Math.round(xs[j]),
1084
+ x1: j === cols - 2 ? layout.w : Math.round(xs[j + 1]),
1085
+ y0: i === 0 ? 0 : Math.round(ys[i]),
1086
+ y1: i === rows - 2 ? layout.h : Math.round(ys[i + 1])
1087
+ });
1088
+ }
1089
+ }
1090
+ return { patches, nodes: nodes.filter((_, i) => !isCorner(i, rows, cols)), found, total: alignments.length };
1091
+ }
1092
+ };
1093
+ function isCorner(index, rows, cols) {
1094
+ const i = Math.floor(index / cols);
1095
+ const j = index % cols;
1096
+ return (i === 0 || i === rows - 1) && (j === 0 || j === cols - 1);
1097
+ }
1098
+
1099
+ // src/web/compress.ts
1100
+ async function pipe(bytes, stream) {
1101
+ const out = new Blob([bytes]).stream().pipeThrough(stream);
1102
+ return new Uint8Array(await new Response(out).arrayBuffer());
1103
+ }
1104
+ async function deflate(bytes) {
1105
+ try {
1106
+ return await pipe(bytes, new CompressionStream("deflate-raw"));
1107
+ } catch {
1108
+ return null;
1109
+ }
1110
+ }
1111
+ function inflate(bytes) {
1112
+ return pipe(bytes, new DecompressionStream("deflate-raw"));
1113
+ }
1114
+
1115
+ // src/web/wake-lock.ts
1116
+ var sentinel = null;
1117
+ async function keepAwake() {
1118
+ try {
1119
+ const nav = navigator;
1120
+ sentinel ?? (sentinel = await nav.wakeLock?.request("screen") ?? null);
1121
+ } catch {
1122
+ }
1123
+ }
1124
+ async function allowSleep() {
1125
+ await sentinel?.release().catch(() => {
1126
+ });
1127
+ sentinel = null;
1128
+ }
1129
+
1130
+ // src/web/sender.ts
1131
+ var Sender = class {
1132
+ constructor(canvas, onFrame) {
1133
+ __publicField(this, "canvas", canvas);
1134
+ __publicField(this, "onFrame", onFrame);
1135
+ __publicField(this, "info", null);
1136
+ __publicField(this, "fps", 15);
1137
+ __publicField(this, "orientation", "portrait");
1138
+ __publicField(this, "encoder", null);
1139
+ __publicField(this, "buffer", document.createElement("canvas"));
1140
+ __publicField(this, "image", null);
1141
+ __publicField(this, "raf", 0);
1142
+ __publicField(this, "last", 0);
1143
+ __publicField(this, "shown", []);
1144
+ __publicField(this, "actualFps", 0);
1145
+ __publicField(this, "tick", (t) => {
1146
+ if (!this.raf || !this.info || !this.encoder || !this.image) return;
1147
+ const interval = 1e3 / this.fps;
1148
+ if (t - this.last >= interval - 3) {
1149
+ this.last = t - this.last < interval * 2 ? this.last + interval : t;
1150
+ this.shown.push(t);
1151
+ while (this.shown.length && t - this.shown[0] > 1e3) this.shown.shift();
1152
+ this.actualFps = this.shown.length;
1153
+ renderFrame(this.info.layout, encodeFrame(this.info.layout, this.encoder), this.image.data);
1154
+ this.buffer.getContext("2d").putImageData(this.image, 0, 0);
1155
+ this.draw();
1156
+ this.info.frames++;
1157
+ this.onFrame(this.info);
1158
+ }
1159
+ this.raf = requestAnimationFrame(this.tick);
1160
+ });
1161
+ }
1162
+ get running() {
1163
+ return !!this.raf;
1164
+ }
1165
+ async start(name, bytes, preset, bits) {
1166
+ this.stop();
1167
+ const packed = await deflate(bytes);
1168
+ const compressed = !!packed && packed.length < bytes.length;
1169
+ const source = packSource(name, compressed ? packed : bytes, compressed, bytes);
1170
+ const layout = this.layoutFor(preset, bits);
1171
+ const encoder = new FountainEncoder(source, layout.packetSize);
1172
+ this.begin(layout, encoder, { name, originalSize: bytes.length, packedSize: source.length, compressed, layout, blockCount: encoder.blockCount, frames: 0 });
1173
+ }
1174
+ startTestPattern(preset, bits) {
1175
+ this.stop();
1176
+ const layout = this.layoutFor(preset, bits);
1177
+ this.begin(layout, new TestPattern(), { name: "pola uji", originalSize: 0, packedSize: 0, compressed: false, layout, blockCount: 0, frames: 0 });
1178
+ }
1179
+ layoutFor(preset, bits) {
1180
+ return getLayout(preset, bits, this.orientation === "portrait" ? "cols" : "rows");
1181
+ }
1182
+ begin(layout, encoder, info) {
1183
+ this.encoder = encoder;
1184
+ this.buffer.width = layout.totalW;
1185
+ this.buffer.height = layout.totalH;
1186
+ this.image = new ImageData(layout.totalW, layout.totalH);
1187
+ this.info = info;
1188
+ this.fit();
1189
+ keepAwake();
1190
+ this.raf = requestAnimationFrame(this.tick);
1191
+ }
1192
+ stop() {
1193
+ cancelAnimationFrame(this.raf);
1194
+ this.raf = 0;
1195
+ allowSleep();
1196
+ }
1197
+ fit() {
1198
+ if (!this.info) return;
1199
+ const portrait = this.orientation === "portrait";
1200
+ const { totalW, totalH } = this.info.layout;
1201
+ const [w, h] = portrait ? [totalH, totalW] : [totalW, totalH];
1202
+ const box = this.canvas.parentElement.getBoundingClientRect();
1203
+ const dpr = devicePixelRatio || 1;
1204
+ const k = Math.max(1, Math.floor(Math.min(box.width * dpr / w, box.height * dpr / h)));
1205
+ this.canvas.width = w * k;
1206
+ this.canvas.height = h * k;
1207
+ this.canvas.style.width = `${w * k / dpr}px`;
1208
+ this.canvas.style.height = `${h * k / dpr}px`;
1209
+ }
1210
+ draw() {
1211
+ const ctx = this.canvas.getContext("2d");
1212
+ ctx.imageSmoothingEnabled = false;
1213
+ if (this.orientation === "portrait") {
1214
+ ctx.setTransform(0, 1, -1, 0, this.canvas.width, 0);
1215
+ ctx.drawImage(this.buffer, 0, 0, this.canvas.height, this.canvas.width);
1216
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
1217
+ } else ctx.drawImage(this.buffer, 0, 0, this.canvas.width, this.canvas.height);
1218
+ }
1219
+ };
1220
+
1221
+ // src/web/auto-zoom.ts
1222
+ var AutoZoom = class {
1223
+ constructor(range, initial = range.min) {
1224
+ __publicField(this, "range", range);
1225
+ __publicField(this, "target", 6);
1226
+ __publicField(this, "cooldown", 800);
1227
+ __publicField(this, "lostDelay", 1500);
1228
+ __publicField(this, "zoom");
1229
+ __publicField(this, "lastChange", -Infinity);
1230
+ __publicField(this, "lastSeen", 0);
1231
+ __publicField(this, "unlockedSince", 0);
1232
+ this.zoom = initial;
1233
+ }
1234
+ next(input) {
1235
+ const { now, corners } = input;
1236
+ if (corners) this.lastSeen = now;
1237
+ if (input.locked || !corners) this.unlockedSince = 0;
1238
+ else this.unlockedSince || (this.unlockedSince = now);
1239
+ if (now - this.lastChange < this.cooldown) return null;
1240
+ let factor = 1;
1241
+ if (!corners) {
1242
+ if (now - this.lastSeen < this.lostDelay || this.zoom <= this.range.min) return null;
1243
+ factor = 1 / 1.25;
1244
+ } else {
1245
+ const cx = input.frameW / 2;
1246
+ const cy = input.frameH / 2;
1247
+ const reach = Math.max(...corners.map(([x, y]) => Math.max(Math.abs(x - cx) / cx, Math.abs(y - cy) / cy)));
1248
+ if (reach > 0.9) factor = 1 / 1.12;
1249
+ else if (!input.locked && this.unlockedSince && now - this.unlockedSince > 600 && reach < 0.8) factor = Math.min(1.25, 0.85 / reach);
1250
+ else if (input.locked && input.cellPx && input.cellPx < this.target * 0.9) factor = Math.max(1, Math.min(this.target / input.cellPx, 0.85 / reach, 1.3));
1251
+ else return null;
1252
+ }
1253
+ const z = this.clamp(this.zoom * factor);
1254
+ if (Math.abs(z - this.zoom) < Math.max(this.range.step, 0.04)) return null;
1255
+ this.zoom = z;
1256
+ this.lastChange = now;
1257
+ return z;
1258
+ }
1259
+ clamp(z) {
1260
+ const { min, max, step } = this.range;
1261
+ const snapped = step > 0 ? Math.round(z / step) * step : z;
1262
+ return Math.min(max, Math.max(min, Number(snapped.toFixed(3))));
1263
+ }
1264
+ };
1265
+
1266
+ // src/web/camera-control.ts
1267
+ var MAX_AUTO_ZOOM = 3;
1268
+ var CameraControl = class {
1269
+ constructor(track) {
1270
+ __publicField(this, "track", track);
1271
+ __publicField(this, "autoZoom", true);
1272
+ __publicField(this, "lockExposure", true);
1273
+ __publicField(this, "zoomer", null);
1274
+ __publicField(this, "caps");
1275
+ __publicField(this, "locked", false);
1276
+ __publicField(this, "goodSince", 0);
1277
+ __publicField(this, "lostSince", 0);
1278
+ __publicField(this, "busy", false);
1279
+ this.caps = track.getCapabilities?.() ?? {};
1280
+ const z = this.caps.zoom;
1281
+ if (z && z.max > z.min) {
1282
+ const current = track.getSettings().zoom ?? z.min;
1283
+ this.zoomer = new AutoZoom({ min: z.min, max: Math.min(z.max, MAX_AUTO_ZOOM), step: z.step || 0.1 }, current);
1284
+ }
1285
+ }
1286
+ get state() {
1287
+ return { zoom: this.zoomer?.zoom ?? null, zoomSupported: !!this.zoomer, exposureLocked: this.locked };
1288
+ }
1289
+ update(report, frameW, frameH, validRate) {
1290
+ const now = performance.now();
1291
+ if (this.zoomer && this.autoZoom && !this.busy) {
1292
+ const z = this.zoomer.next({ now, locked: !!report.lock, cellPx: report.cellPx ?? null, corners: report.corners, frameW, frameH });
1293
+ if (z !== null) this.apply({ zoom: z });
1294
+ }
1295
+ this.updateExposure(report, now, validRate);
1296
+ }
1297
+ reset() {
1298
+ this.goodSince = 0;
1299
+ this.lostSince = 0;
1300
+ if (this.locked) this.unlock();
1301
+ }
1302
+ updateExposure(report, now, validRate) {
1303
+ if (!this.lockExposure) {
1304
+ if (this.locked) this.unlock();
1305
+ return;
1306
+ }
1307
+ const good = !!report.lock && report.packets > 0 && validRate > 0.6;
1308
+ if (good) {
1309
+ this.lostSince = 0;
1310
+ this.goodSince || (this.goodSince = now);
1311
+ if (!this.locked && now - this.goodSince > 1e3) this.lock();
1312
+ } else {
1313
+ this.goodSince = 0;
1314
+ if (!report.lock) {
1315
+ this.lostSince || (this.lostSince = now);
1316
+ if (this.locked && now - this.lostSince > 2e3) this.unlock();
1317
+ }
1318
+ }
1319
+ }
1320
+ lock() {
1321
+ const s = this.track.getSettings();
1322
+ const set = {};
1323
+ if (this.caps.exposureMode?.includes("manual") && s.exposureTime) Object.assign(set, { exposureMode: "manual", exposureTime: s.exposureTime });
1324
+ else if (this.caps.exposureMode?.includes("single-shot")) set.exposureMode = "single-shot";
1325
+ if (this.caps.whiteBalanceMode?.includes("manual") && s.colorTemperature) Object.assign(set, { whiteBalanceMode: "manual", colorTemperature: s.colorTemperature });
1326
+ else if (this.caps.whiteBalanceMode?.includes("single-shot")) set.whiteBalanceMode = "single-shot";
1327
+ if (!Object.keys(set).length) return;
1328
+ this.locked = true;
1329
+ this.apply(set);
1330
+ }
1331
+ unlock() {
1332
+ this.locked = false;
1333
+ const set = {};
1334
+ if (this.caps.exposureMode?.includes("continuous")) set.exposureMode = "continuous";
1335
+ if (this.caps.whiteBalanceMode?.includes("continuous")) set.whiteBalanceMode = "continuous";
1336
+ if (Object.keys(set).length) this.apply(set);
1337
+ }
1338
+ async apply(set) {
1339
+ this.busy = true;
1340
+ try {
1341
+ await this.track.applyConstraints({ advanced: [set] });
1342
+ } catch {
1343
+ }
1344
+ this.busy = false;
1345
+ }
1346
+ };
1347
+
1348
+ // src/web/gl-source.ts
1349
+ var VERTEX = `#version 300 es
1350
+ in vec2 pos;
1351
+ void main() { gl_Position = vec4(pos, 0.0, 1.0); }`;
1352
+ var SMALL = `#version 300 es
1353
+ precision highp float;
1354
+ uniform sampler2D tex;
1355
+ uniform vec2 scale;
1356
+ uniform vec2 size;
1357
+ out vec4 color;
1358
+ void main() {
1359
+ vec2 base = floor(gl_FragCoord.xy) * scale;
1360
+ vec2 q = scale * 0.25;
1361
+ vec3 s = texture(tex, (base + q) / size).rgb + texture(tex, (base + vec2(3.0, 1.0) * q) / size).rgb
1362
+ + texture(tex, (base + vec2(1.0, 3.0) * q) / size).rgb + texture(tex, (base + 3.0 * q) / size).rgb;
1363
+ color = vec4(s * 0.25, 1.0);
1364
+ }`;
1365
+ var RECTIFY = `#version 300 es
1366
+ precision highp float;
1367
+ uniform sampler2D tex;
1368
+ uniform mat3 hm;
1369
+ uniform vec2 size;
1370
+ out vec4 color;
1371
+ vec3 tap(vec2 uv) {
1372
+ vec3 p = hm * vec3(uv, 1.0);
1373
+ return texture(tex, (p.xy / p.z + 0.5) / size).rgb;
1374
+ }
1375
+ void main() {
1376
+ vec2 c = floor(gl_FragCoord.xy) + 0.5;
1377
+ float d = 0.22;
1378
+ vec3 s = tap(c) + tap(c + vec2(d, 0.0)) + tap(c - vec2(d, 0.0)) + tap(c + vec2(0.0, d)) + tap(c - vec2(0.0, d));
1379
+ color = vec4(s / 5.0, 1.0);
1380
+ }`;
1381
+ var GlSource = class {
1382
+ constructor() {
1383
+ __publicField(this, "width", 0);
1384
+ __publicField(this, "height", 0);
1385
+ __publicField(this, "gl");
1386
+ __publicField(this, "video");
1387
+ __publicField(this, "videoFb");
1388
+ __publicField(this, "smallProg");
1389
+ __publicField(this, "rectProg");
1390
+ __publicField(this, "targets", /* @__PURE__ */ new Map());
1391
+ const gl = document.createElement("canvas").getContext("webgl2", { preserveDrawingBuffer: false, antialias: false });
1392
+ if (!gl) throw new Error("WebGL2 tidak tersedia");
1393
+ this.gl = gl;
1394
+ this.smallProg = this.program(SMALL);
1395
+ this.rectProg = this.program(RECTIFY);
1396
+ const buf = gl.createBuffer();
1397
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
1398
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
1399
+ this.video = this.texture();
1400
+ this.videoFb = gl.createFramebuffer();
1401
+ }
1402
+ static supported() {
1403
+ try {
1404
+ return !!document.createElement("canvas").getContext("webgl2");
1405
+ } catch {
1406
+ return false;
1407
+ }
1408
+ }
1409
+ update(frame, width, height) {
1410
+ const gl = this.gl;
1411
+ gl.bindTexture(gl.TEXTURE_2D, this.video);
1412
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
1413
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, frame);
1414
+ if (width !== this.width || height !== this.height) {
1415
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.videoFb);
1416
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.video, 0);
1417
+ }
1418
+ this.width = width;
1419
+ this.height = height;
1420
+ }
1421
+ small(maxWidth) {
1422
+ const scale = Math.max(1, Math.ceil(this.width / maxWidth));
1423
+ const w = Math.floor(this.width / scale);
1424
+ const h = Math.floor(this.height / scale);
1425
+ this.draw(this.smallProg, w, h, (gl, p) => {
1426
+ gl.uniform2f(gl.getUniformLocation(p, "scale"), scale, scale);
1427
+ });
1428
+ return { data: this.read(w, h), w, h, scale };
1429
+ }
1430
+ region(x, y, w, h) {
1431
+ const gl = this.gl;
1432
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.videoFb);
1433
+ const out = new Uint8Array(w * h * 4);
1434
+ gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, out);
1435
+ return out;
1436
+ }
1437
+ rectify(patches, w, h) {
1438
+ const gl = this.gl;
1439
+ gl.enable(gl.SCISSOR_TEST);
1440
+ for (const patch of patches) {
1441
+ const m = patch.h;
1442
+ gl.scissor(patch.x0, patch.y0, patch.x1 - patch.x0, patch.y1 - patch.y0);
1443
+ this.draw(this.rectProg, w, h, (g, p) => {
1444
+ g.uniformMatrix3fv(g.getUniformLocation(p, "hm"), false, [m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8]]);
1445
+ });
1446
+ }
1447
+ gl.disable(gl.SCISSOR_TEST);
1448
+ return this.read(w, h);
1449
+ }
1450
+ draw(prog, w, h, setup) {
1451
+ const gl = this.gl;
1452
+ const t = this.target(w, h);
1453
+ gl.bindFramebuffer(gl.FRAMEBUFFER, t.fb);
1454
+ gl.viewport(0, 0, w, h);
1455
+ gl.useProgram(prog);
1456
+ const loc = gl.getAttribLocation(prog, "pos");
1457
+ gl.enableVertexAttribArray(loc);
1458
+ gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
1459
+ gl.activeTexture(gl.TEXTURE0);
1460
+ gl.bindTexture(gl.TEXTURE_2D, this.video);
1461
+ gl.uniform1i(gl.getUniformLocation(prog, "tex"), 0);
1462
+ gl.uniform2f(gl.getUniformLocation(prog, "size"), this.width, this.height);
1463
+ setup(gl, prog);
1464
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
1465
+ }
1466
+ read(w, h) {
1467
+ const out = new Uint8Array(w * h * 4);
1468
+ this.gl.readPixels(0, 0, w, h, this.gl.RGBA, this.gl.UNSIGNED_BYTE, out);
1469
+ return out;
1470
+ }
1471
+ target(w, h) {
1472
+ const key = `${w}x${h}`;
1473
+ let t = this.targets.get(key);
1474
+ if (t) return t;
1475
+ const gl = this.gl;
1476
+ const tex = this.texture();
1477
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
1478
+ const fb = gl.createFramebuffer();
1479
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
1480
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
1481
+ t = { fb, tex, w, h };
1482
+ this.targets.set(key, t);
1483
+ return t;
1484
+ }
1485
+ texture() {
1486
+ const gl = this.gl;
1487
+ const tex = gl.createTexture();
1488
+ gl.bindTexture(gl.TEXTURE_2D, tex);
1489
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
1490
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
1491
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1492
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1493
+ return tex;
1494
+ }
1495
+ program(fragment) {
1496
+ const gl = this.gl;
1497
+ const compile = (type, src) => {
1498
+ const s = gl.createShader(type);
1499
+ gl.shaderSource(s, src);
1500
+ gl.compileShader(s);
1501
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) ?? "shader");
1502
+ return s;
1503
+ };
1504
+ const p = gl.createProgram();
1505
+ gl.attachShader(p, compile(gl.VERTEX_SHADER, VERTEX));
1506
+ gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fragment));
1507
+ gl.linkProgram(p);
1508
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p) ?? "link");
1509
+ return p;
1510
+ }
1511
+ };
1512
+
1513
+ // src/web/scanner.ts
1514
+ var Scanner = class {
1515
+ constructor(video, onStats, onFile) {
1516
+ __publicField(this, "video", video);
1517
+ __publicField(this, "onStats", onStats);
1518
+ __publicField(this, "onFile", onFile);
1519
+ __publicField(this, "receiver", new Receiver());
1520
+ __publicField(this, "gl", null);
1521
+ __publicField(this, "stream", null);
1522
+ __publicField(this, "frames", 0);
1523
+ __publicField(this, "tracked", 0);
1524
+ __publicField(this, "startedAt", 0);
1525
+ __publicField(this, "processMs", 0);
1526
+ __publicField(this, "delivered", false);
1527
+ __publicField(this, "camera", null);
1528
+ __publicField(this, "autoZoom", true);
1529
+ __publicField(this, "lockExposure", true);
1530
+ __publicField(this, "frameRate", 30);
1531
+ __publicField(this, "fps", { requested: 30, reported: null, camera: 0, processed: 0, width: 0, height: 0 });
1532
+ __publicField(this, "window", { start: 0, presented: 0, processed: 0, frames: 0 });
1533
+ __publicField(this, "loop", (now = performance.now(), meta) => {
1534
+ if (!this.stream) return;
1535
+ this.measure(now, meta);
1536
+ const { videoWidth: w, videoHeight: h } = this.video;
1537
+ if (w && h && this.gl) {
1538
+ const t0 = performance.now();
1539
+ this.gl.update(this.video, w, h);
1540
+ const report = this.receiver.process(this.gl);
1541
+ const ms = performance.now() - t0;
1542
+ this.processMs = this.frames ? this.processMs * 0.9 + ms * 0.1 : ms;
1543
+ this.frames++;
1544
+ if (report.tracked) this.tracked++;
1545
+ if (report.packets && !this.startedAt) this.startedAt = performance.now();
1546
+ const rate = report.expected ? report.packets / report.expected : 0;
1547
+ this.camera?.update(report, w, h, rate);
1548
+ this.emit(report);
1549
+ }
1550
+ if (this.video.requestVideoFrameCallback) this.video.requestVideoFrameCallback(this.loop);
1551
+ else requestAnimationFrame((t) => this.loop(t));
1552
+ });
1553
+ }
1554
+ get active() {
1555
+ return !!this.stream;
1556
+ }
1557
+ async start() {
1558
+ if (!navigator.mediaDevices?.getUserMedia) throw new Error("Kamera tidak tersedia. Buka halaman ini lewat HTTPS atau localhost.");
1559
+ if (!GlSource.supported()) throw new Error("Browser ini tidak mendukung WebGL2.");
1560
+ this.gl ?? (this.gl = new GlSource());
1561
+ this.stream = await navigator.mediaDevices.getUserMedia({
1562
+ audio: false,
1563
+ video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1920 }, frameRate: { ideal: this.frameRate } }
1564
+ });
1565
+ const track = this.stream.getVideoTracks()[0];
1566
+ try {
1567
+ const caps = track.getCapabilities?.() ?? {};
1568
+ if (caps.focusMode?.includes("continuous")) await track.applyConstraints({ advanced: [{ focusMode: "continuous" }] });
1569
+ } catch {
1570
+ }
1571
+ const settings = track.getSettings();
1572
+ this.fps = { requested: this.frameRate, reported: settings.frameRate ?? null, camera: 0, processed: 0, width: settings.width ?? 0, height: settings.height ?? 0 };
1573
+ this.window = { start: 0, presented: 0, processed: 0, frames: 0 };
1574
+ this.camera = new CameraControl(track);
1575
+ this.camera.autoZoom = this.autoZoom;
1576
+ this.camera.lockExposure = this.lockExposure;
1577
+ this.video.srcObject = this.stream;
1578
+ await this.video.play();
1579
+ keepAwake();
1580
+ this.loop();
1581
+ }
1582
+ stop() {
1583
+ this.stream?.getTracks().forEach((t) => t.stop());
1584
+ this.stream = null;
1585
+ this.camera = null;
1586
+ allowSleep();
1587
+ }
1588
+ reset() {
1589
+ this.receiver.reset();
1590
+ this.frames = 0;
1591
+ this.tracked = 0;
1592
+ this.startedAt = 0;
1593
+ this.processMs = 0;
1594
+ this.delivered = false;
1595
+ this.camera?.reset();
1596
+ }
1597
+ get resolution() {
1598
+ return [this.video.videoWidth, this.video.videoHeight];
1599
+ }
1600
+ measure(now, meta) {
1601
+ const win = this.window;
1602
+ if (!win.start) {
1603
+ win.start = now;
1604
+ win.presented = meta?.presentedFrames ?? 0;
1605
+ win.processed = this.frames;
1606
+ win.frames = 0;
1607
+ return;
1608
+ }
1609
+ win.frames++;
1610
+ const dt = (now - win.start) / 1e3;
1611
+ if (dt < 1) return;
1612
+ const presented = meta?.presentedFrames;
1613
+ this.fps.camera = presented !== void 0 ? (presented - win.presented) / dt : win.frames / dt;
1614
+ this.fps.processed = (this.frames - win.processed) / dt;
1615
+ this.fps.width = this.video.videoWidth;
1616
+ this.fps.height = this.video.videoHeight;
1617
+ win.start = now;
1618
+ win.presented = presented ?? 0;
1619
+ win.processed = this.frames;
1620
+ win.frames = 0;
1621
+ }
1622
+ emit(report) {
1623
+ const d = this.receiver.decoder;
1624
+ const elapsed = this.startedAt ? (performance.now() - this.startedAt) / 1e3 : 0;
1625
+ this.onStats({
1626
+ report,
1627
+ frames: this.frames,
1628
+ trackedFrames: this.tracked,
1629
+ validPackets: this.receiver.validPackets,
1630
+ expectedPackets: this.receiver.expectedPackets,
1631
+ known: d?.known ?? 0,
1632
+ received: d?.received ?? 0,
1633
+ needed: d ? Math.max(estimatePackets(d.blockCount), d.received) : 0,
1634
+ blockCount: d?.blockCount ?? 0,
1635
+ blockSize: d?.blockSize ?? 0,
1636
+ elapsed,
1637
+ processMs: this.processMs,
1638
+ camera: this.camera?.state ?? null,
1639
+ fps: this.fps
1640
+ });
1641
+ if (d?.done && !this.delivered) {
1642
+ this.delivered = true;
1643
+ this.finish(d.result(), elapsed);
1644
+ }
1645
+ }
1646
+ async finish(source, seconds) {
1647
+ const info = unpackSource(source);
1648
+ const data = info.compressed ? await inflate(info.payload) : info.payload.slice();
1649
+ this.onFile({ name: info.name, data, valid: data.length === info.originalSize && crc32(data) === info.originalCrc, seconds });
1650
+ }
1651
+ };
1652
+
1653
+ // src/web/debug-panel.ts
1654
+ var NAMES = {
1655
+ 3: ["hitam", "biru", "hijau", "cyan", "merah", "magenta", "kuning", "putih"],
1656
+ 2: ["putih", "merah", "hijau", "biru"],
1657
+ 1: ["hitam", "putih"]
1658
+ };
1659
+ var pct = (v, digits = 2) => `${(v * 100).toFixed(digits)}%`;
1660
+ function heatColor(rate) {
1661
+ const t = Math.min(1, Math.sqrt(rate / 0.25));
1662
+ if (t < 0.5) {
1663
+ const k2 = t / 0.5;
1664
+ return [40 + 210 * k2, 40 + 170 * k2, 40 - 20 * k2];
1665
+ }
1666
+ const k = (t - 0.5) / 0.5;
1667
+ return [250, 210 - 190 * k, 20];
1668
+ }
1669
+ var DebugPanel = class {
1670
+ constructor(root, canvas, text) {
1671
+ __publicField(this, "root", root);
1672
+ __publicField(this, "canvas", canvas);
1673
+ __publicField(this, "text", text);
1674
+ __publicField(this, "enabled", false);
1675
+ __publicField(this, "map", null);
1676
+ __publicField(this, "lastSummary", null);
1677
+ __publicField(this, "portrait", false);
1678
+ __publicField(this, "frames", 0);
1679
+ }
1680
+ setEnabled(on) {
1681
+ this.enabled = on;
1682
+ this.root.hidden = !on;
1683
+ }
1684
+ reset() {
1685
+ this.map = null;
1686
+ this.lastSummary = null;
1687
+ this.frames = 0;
1688
+ this.text.textContent = "Menunggu frame terkunci\u2026";
1689
+ this.canvas.getContext("2d")?.clearRect(0, 0, this.canvas.width, this.canvas.height);
1690
+ }
1691
+ update(report) {
1692
+ if (!this.enabled || !report.decoded || !report.layout) return;
1693
+ if (!this.map || this.map.layout !== report.layout) this.map = new ErrorMap(report.layout);
1694
+ this.portrait = report.layout.order === "cols";
1695
+ this.map.add(report.decoded);
1696
+ if (++this.frames % 4 === 1) this.render();
1697
+ }
1698
+ copyReport() {
1699
+ if (!this.map || !this.lastSummary) return "";
1700
+ const l = this.map.layout;
1701
+ return JSON.stringify({ grid: `${l.w}x${l.h}`, colors: l.palette.length, order: l.order, ...this.lastSummary }, null, 2);
1702
+ }
1703
+ render() {
1704
+ const map = this.map;
1705
+ const layout = map.layout;
1706
+ const { w, h } = layout;
1707
+ const [cw, ch] = this.portrait ? [h, w] : [w, h];
1708
+ if (this.canvas.width !== cw || this.canvas.height !== ch) {
1709
+ this.canvas.width = cw;
1710
+ this.canvas.height = ch;
1711
+ }
1712
+ const ctx = this.canvas.getContext("2d");
1713
+ const img = ctx.createImageData(cw, ch);
1714
+ const isData = new Uint8Array(w * h);
1715
+ for (const idx of layout.dataCells) isData[idx] = 1;
1716
+ for (let r = 0; r < h; r++) {
1717
+ for (let c = 0; c < w; c++) {
1718
+ const idx = r * w + c;
1719
+ const [x, y] = this.portrait ? [h - 1 - r, c] : [c, r];
1720
+ const o = (y * cw + x) * 4;
1721
+ const col = isData[idx] ? map.samples[idx] ? heatColor(map.rate(idx)) : [30, 30, 30] : [90, 90, 90];
1722
+ img.data[o] = col[0];
1723
+ img.data[o + 1] = col[1];
1724
+ img.data[o + 2] = col[2];
1725
+ img.data[o + 3] = 255;
1726
+ }
1727
+ }
1728
+ ctx.putImageData(img, 0, 0);
1729
+ const names = NAMES[layout.palette.length === 8 ? 3 : layout.palette.length === 4 ? 2 : 1];
1730
+ const s = map.summary(names);
1731
+ this.lastSummary = s;
1732
+ const confusions = s.mode === "exact" && s.confusions.length ? s.confusions.map((c) => `${names[c.from]}\u2192${names[c.to]} ${pct(c.rate, 1)}`).join(" \xB7 ") : "-";
1733
+ this.text.innerHTML = [
1734
+ `<div><span>Mode</span><b>${s.mode === "exact" ? "pola uji (per sel)" : "per paket (perkiraan)"}</b></div>`,
1735
+ `<div><span>Error sel</span><b>${pct(s.cellErrorRate, 3)}</b></div>`,
1736
+ `<div><span>Tengah / tepi</span><b>${pct(s.centerRate)} / ${pct(s.edgeRate)}</b></div>`,
1737
+ `<div><span>Arah geser</span><b>${s.mode === "exact" ? s.directionBias.toFixed(2) : "-"}</b></div>`,
1738
+ `<div class="wide"><span>Tertukar</span><b>${confusions}</b></div>`,
1739
+ `<p>${s.hint}</p>`
1740
+ ].join("");
1741
+ }
1742
+ };
1743
+
1744
+ // src/config.ts
1745
+ var defaultConfig = {
1746
+ debug: false,
1747
+ testPattern: false,
1748
+ defaultPreset: "320x180",
1749
+ defaultBits: 1,
1750
+ defaultFps: 20,
1751
+ defaultOrientation: "portrait",
1752
+ maxFps: 30,
1753
+ cameraFps: 30,
1754
+ autoZoom: true,
1755
+ lockExposure: true
1756
+ };
1757
+ function resolveConfig(overrides) {
1758
+ return { ...defaultConfig, ...overrides };
1759
+ }
1760
+
1761
+ export {
1762
+ __publicField,
1763
+ HEADER_SIZE,
1764
+ TARGET_PACKET,
1765
+ BIT_MODES,
1766
+ PRESETS,
1767
+ PALETTES,
1768
+ crc32,
1769
+ crc32Parts,
1770
+ getLayout,
1771
+ packSource,
1772
+ unpackSource,
1773
+ neighbors,
1774
+ FountainEncoder,
1775
+ FountainDecoder,
1776
+ estimatePackets,
1777
+ encodeFrame,
1778
+ parsePackets,
1779
+ renderFrame,
1780
+ homography,
1781
+ project,
1782
+ binarize,
1783
+ findMarkers,
1784
+ pickCorners,
1785
+ refineMarker,
1786
+ decodeCells,
1787
+ TEST_FILE_ID,
1788
+ TestPattern,
1789
+ ErrorMap,
1790
+ Receiver,
1791
+ deflate,
1792
+ inflate,
1793
+ Sender,
1794
+ AutoZoom,
1795
+ CameraControl,
1796
+ GlSource,
1797
+ Scanner,
1798
+ DebugPanel,
1799
+ defaultConfig,
1800
+ resolveConfig
1801
+ };