am-freescan/integrations/freescan-service/tests/measure-preview.mjs
Codex a16f16e19a feat(scanner): show native calibration window and SDK progress
Use the existing successful calibration-enter workflow to display the same SDK manufacturer's window and actual callback progress in the task UI. Bind metadata, JPEG and MJPEG to the execution, SDK session, calibration ID and trusted process/window identity; closing the monitor only stops viewing.

Include source-only FreeScanCpp integration, WGC capture lifecycle fixes and immediate ENTER acknowledgement cache synchronization. Preserve original scanner project guards, regression sources and third-party licensing; exclude private runtime configuration and generated artifacts.

Validated platform Java compilation/regressions, frontend type checks and standalone build, native compilation/offline and HTTP regressions, immediate calibration identity checks and ten synthetic window close/reopen cycles. Production installation/restart and real scanner calibration remain pending.
2026-11-21 19:52:07 +08:00

111 lines
8.3 KiB
JavaScript

import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { dirname, resolve, join } from 'node:path';
import { setTimeout as sleep } from 'node:timers/promises';
import { MjpegParser, boundaryFromContentType } from '../../FreeScanWeb/public/preview-pipeline.js';
// Explicit read-only real-device transport measurement. This file is outside
// *.test.mjs and sends GET requests only; no device action can be submitted.
const workspace = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const settings = JSON.parse(await readFile(join(workspace, 'FreeScanViewer', 'api-settings.json'), 'utf8'));
const base = new URL(settings.prefix);
if (base.protocol !== 'http:' || base.hostname !== '127.0.0.1' || base.port !== '18888') throw new Error('Read-only real-device measurement requires the configured 127.0.0.1:18888 endpoint.');
const headers = { 'X-Api-Key': settings.apiKey };
const seconds = 10;
const round = value => Math.round(value * 100) / 100;
async function get(path) {
const response = await fetch(new URL(path, base), { headers, signal: AbortSignal.timeout(7000), cache: 'no-store' });
if (!response.ok) throw new Error(`Read-only GET ${path} returned HTTP ${response.status}`);
return response;
}
async function json(path) { return (await get(path)).json(); }
function summary(values) {
const sorted = values.filter(Number.isFinite).toSorted((a, b) => a - b);
if (!sorted.length) return { samples: 0, minimum: null, median: null, p95: null, maximum: null };
const middle = sorted.length >> 1;
return { samples: sorted.length, minimum: round(sorted[0]), median: round(sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2),
p95: round(sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * .95) - 1)]), maximum: round(sorted.at(-1)) };
}
function dimensions(jpeg) {
const bytes = Buffer.from(jpeg); if (bytes.readUInt16BE(0) !== 0xffd8) throw new Error('Live preview was not a JPEG.');
let offset = 2;
while (offset + 4 < bytes.length) {
if (bytes[offset++] !== 0xff) throw new Error('Invalid JPEG marker.');
while (bytes[offset] === 0xff) offset++;
const marker = bytes[offset++]; if (marker === 0xd9 || marker === 0xda) break;
if (marker === 0x01 || marker >= 0xd0 && marker <= 0xd7) continue;
const length = bytes.readUInt16BE(offset);
if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) return { width: bytes.readUInt16BE(offset + 5), height: bytes.readUInt16BE(offset + 3) };
if (length < 2) break; offset += length;
}
throw new Error('Live JPEG did not contain a SOF dimension marker.');
}
const [beforeStatus, beforeMetrics] = await Promise.all([json('api/v1/status'), json('api/v1/preview/metrics')]);
if (!beforeStatus.initialized || !beforeStatus.projectReady || !beforeStatus.previewEnabled || beforeStatus.simulated) throw new Error('A real initialized project with preview enabled is required; no control action was sent.');
const controller = new AbortController();
const response = await fetch(new URL('api/v1/preview/stream', base), { headers, signal: controller.signal, cache: 'no-store' });
if (!response.ok) throw new Error(`Read-only live MJPEG returned HTTP ${response.status}`);
const arrived = [], ages = [], sizes = [], sequences = [], imageHeaderAges = [], headerFailures = [];
const encodedDimensions = new Set(), sourceDimensions = new Set();
const startedUtc = new Date().toISOString(), startedAt = performance.now();
const parser = new MjpegParser(boundaryFromContentType(response.headers.get('content-type') || ''), frame => {
arrived.push(performance.now()); sizes.push(frame.bytes.byteLength); sequences.push(Number(frame.sequence));
ages.push(Date.now() - Date.parse(frame.capturedUtc));
const size = dimensions(frame.bytes); encodedDimensions.add(`${size.width}x${size.height}`);
sourceDimensions.add(`${frame.sourceWidth}x${frame.sourceHeight}`);
});
const sampler = (async () => {
while (!controller.signal.aborted) {
try {
const image = await fetch(new URL('api/v1/preview/image', base), { headers, signal: controller.signal, cache: 'no-store' });
if (!image.ok) throw new Error(`Image HTTP ${image.status}`);
imageHeaderAges.push(Number(image.headers.get('x-frame-age-ms')));
await image.arrayBuffer();
} catch (error) { if (!controller.signal.aborted) headerFailures.push(error.message); }
try { await sleep(500, undefined, { signal: controller.signal }); } catch { break; }
}
})();
const timer = setTimeout(() => controller.abort(), seconds * 1000);
const reader = response.body.getReader();
try {
for (;;) { const { done, value } = await reader.read(); if (done) break; parser.push(value); }
} catch (error) { if (!controller.signal.aborted) throw error; }
finally { clearTimeout(timer); controller.abort(); await reader.cancel().catch(() => {}); await sampler; }
const measuredMs = performance.now() - startedAt;
const [afterStatus, afterMetrics] = await Promise.all([json('api/v1/status'), json('api/v1/preview/metrics')]);
const counterNames = ['offeredFrames', 'encodedFrames', 'replacedFrames', 'throttledFrames', 'encodingFailures'];
const counterDelta = Object.fromEntries(counterNames.filter(name => Number.isFinite(beforeMetrics[name]) && Number.isFinite(afterMetrics[name])).map(name => [name, afterMetrics[name] - beforeMetrics[name]]));
const report = {
mode: 'real_device_read_only_transport', implementation: afterStatus.implementation || afterMetrics.implementation || 'C++17',
endpoint: base.href,
startedUtc, finishedUtc: new Date().toISOString(), requestedSeconds: seconds, measuredMs: round(measuredMs),
frames: arrived.length,
framesPerWindowSecond: round(arrived.length * 1000 / measuredMs),
observedIntervalFps: arrived.length > 1 ? round((arrived.length - 1) * 1000 / (arrived.at(-1) - arrived[0])) : 0,
receivedFrameAgeMs: summary(ages),
xFrameAgeHeaderMs: summary(imageHeaderAges),
streamInitialXFrameAgeMs: Number(response.headers.get('x-frame-age-ms')),
xFrameAgeSampling: 'GET preview/image at 2 Hz; real X-Frame-Age-Ms header, independent of MJPEG frame arrival age',
jpegBytes: summary(sizes), encodedDimensions: [...encodedDimensions], sourceDimensions: [...sourceDimensions],
sequence: { first: sequences[0] ?? null, last: sequences.at(-1) ?? null, uniqueFrames: new Set(sequences).size, monotonic: sequences.every((value, index) => index === 0 || value > sequences[index - 1]) },
statusBefore: beforeStatus, statusAfter: afterStatus, metricsBefore: beforeMetrics, metricsAfter: afterMetrics, metricCounterDelta: counterDelta,
counterResetObserved: Object.values(counterDelta).some(value => value < 0), headerSampleFailures: headerFailures,
sessionPreserved: beforeStatus.sessionId === afterStatus.sessionId, projectPreserved: beforeStatus.projectId === afterStatus.projectId,
acquisitionStatePreserved: beforeStatus.scanning === afterStatus.scanning,
notes: [
'All requests were GET. No connection/project/acquisition/preview control, restart or deployment was performed.',
'MJPEG was decoded with the existing shared FreeScanWeb MjpegParser; JPEG markers were inspected for dimensions without image recompression.',
'MJPEG multipart headers do not repeat X-Frame-Age-Ms; receivedFrameAgeMs is arrival time minus each frame X-Frame-Captured-Utc.',
'averageEncodedFps is the worker lifetime cumulative average including initialization and periods without a project; observedIntervalFps and framesPerWindowSecond measure this window.',
'This measures HTTP transport and managed/native receipt timestamps, excluding browser JPEG decoding, display latency and hardware exposure time.',
],
};
const output = join(workspace, 'FreeScanCpp', 'verification', 'real-preview-window.json');
await mkdir(dirname(output), { recursive: true }); await writeFile(output, JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify({ output, frames: report.frames, observedIntervalFps: report.observedIntervalFps, measuredMs: report.measuredMs,
xFrameAgeHeaderMs: report.xFrameAgeHeaderMs, receivedFrameAgeMs: report.receivedFrameAgeMs, encodedDimensions: report.encodedDimensions,
sourceDimensions: report.sourceDimensions, metricCounterDelta: report.metricCounterDelta, sessionPreserved: report.sessionPreserved,
projectPreserved: report.projectPreserved, acquisitionStatePreserved: report.acquisitionStatePreserved }, null, 2));