Scanner: gpu canvases (cpu ones copied whole frames in software), back to 1080p with a 720p fallback on slow phones; lab frame save works on android

This commit is contained in:
2026-11-17 14:06:03 +01:00
parent 7765f22f61
commit 70d09b1008
5 changed files with 35 additions and 17 deletions
+5 -2
View File
@@ -6,8 +6,11 @@ const WIDE = 960, CROP = 360;
export function makeRingScanner(opts = {}) { export function makeRingScanner(opts = {}) {
const reader = makeReader(opts); const reader = makeReader(opts);
const wide = document.createElement("canvas"), wctx = wide.getContext("2d", { willReadFrequently: true }); // no willReadFrequently: it moves the canvas to the cpu, and drawing a video frame into it then copies and
const crop = document.createElement("canvas"), cctx = crop.getContext("2d", { willReadFrequently: true }); // scales the whole frame in software (2 s per frame for a 4k stream on a mid-range android). on the gpu the
// scaling is free and only these small canvases are read back
const wide = document.createElement("canvas"), wctx = wide.getContext("2d");
const crop = document.createElement("canvas"), cctx = crop.getContext("2d");
let track = null; let track = null;
// source px of the square around a code of the given unit // source px of the square around a code of the given unit
+14 -5
View File
@@ -77,7 +77,7 @@ async function startScanner() {
// calls onToken(token) for every code of this poll it reads // calls onToken(token) for every code of this poll it reads
function makeScanner(video, onToken, onOther) { function makeScanner(video, onToken, onOther) {
let stream = null, running = false; let stream = null, running = false;
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true }); const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
const rings = makeRingScanner(); const rings = makeRingScanner();
async function loop() { async function loop() {
if (!running) return; if (!running) return;
@@ -86,9 +86,10 @@ function makeScanner(video, onToken, onOther) {
try { try {
if (codeStyle === "ring") { if (codeStyle === "ring") {
// reads a crop at sensor resolution: a far code keeps all its pixels // reads a crop at sensor resolution: a far code keeps all its pixels
const d = rings.scan(video, video.videoWidth, video.videoHeight); const ts = performance.now(), d = rings.scan(video, video.videoWidth, video.videoHeight);
if (d.token) onToken(d.token); if (d.token) onToken(d.token);
steer(d); steer(d);
pace(performance.now() - ts);
} else { } else {
// 960 px is plenty for a qr and keeps low-end phones near 7 fps // 960 px is plenty for a qr and keeps low-end phones near 7 fps
const k = Math.min(1, 960 / video.videoWidth); const k = Math.min(1, 960 / video.videoWidth);
@@ -117,6 +118,14 @@ function makeScanner(video, onToken, onOther) {
zoom.textContent = `${(Math.round(z * 10) / 10).toLocaleString("fr-FR")}×`; zoom.textContent = `${(Math.round(z * 10) / 10).toLocaleString("fr-FR")}×`;
track.applyConstraints({ advanced: [{ zoom: z }] }).catch(() => { zs = null; zoom.hidden = true; }); track.applyConstraints({ advanced: [{ zoom: z }] }).catch(() => { zs = null; zoom.hidden = true; });
} }
// a slow phone reads few frames and misses codes: past ~300 ms a frame, drop the stream to 720p once
let slow = 0, frames = 0, dropped = false;
function pace(ms) {
slow = frames++ ? slow * 0.8 + ms * 0.2 : ms;
if (dropped || frames < 6 || slow < 300 || video.videoWidth * video.videoHeight <= 1280 * 720) return;
dropped = true;
stream?.getVideoTracks()[0]?.applyConstraints({ width: { ideal: 1280 }, height: { ideal: 720 } }).catch(() => {});
}
function steer(d) { function steer(d) {
// people keep their seat between votes: a zoom that read the ring is where the next scan starts // people keep their seat between votes: a zoom that read the ring is where the next scan starts
if (zs && d.token) lsSet(ZOOM_KEY, String(zs.now)); if (zs && d.token) lsSet(ZOOM_KEY, String(zs.now));
@@ -183,9 +192,9 @@ const ZOOM_KEY = `rv_zoom_${pid}`;
const FRONT = /front|user|avant|facetime|selfie/i, ODD = /ultra|wide|grand.angle|macro|tele|télé|depth|infra|dual|triple|double/i, BACK = /back|rear|arri[eè]re|environment/i; const FRONT = /front|user|avant|facetime|selfie/i, ODD = /ultra|wide|grand.angle|macro|tele|télé|depth|infra|dual|triple|double/i, BACK = /back|rear|arri[eè]re|environment/i;
function openCamera(deviceId) { function openCamera(deviceId) {
// rings from the back of a room are a few dozen pixels wide at 720p: ask for up to 4k, the browser hands over // rings from the back of a room are a few dozen pixels wide at 720p. 4k was tried: a mid-range android took
// the closest it has. only a crop around the ring is read at that size, so the cost per frame stays flat // it and fell to one frame every 2 s, so 1080p, and 720p on phones too slow for that (pace)
const [w, h] = codeStyle === "ring" ? [3840, 2160] : [1280, 720]; const [w, h] = codeStyle === "ring" ? [1920, 1080] : [1280, 720];
const base = { width: { ideal: w }, height: { ideal: h } }; const base = { width: { ideal: w }, height: { ideal: h } };
return navigator.mediaDevices.getUserMedia({ return navigator.mediaDevices.getUserMedia({
audio: false, video: deviceId ? { ...base, deviceId: { exact: deviceId } } : { ...base, facingMode: { ideal: "environment" } }, audio: false, video: deviceId ? { ...base, deviceId: { exact: deviceId } } : { ...base, facingMode: { ideal: "environment" } },
+1
View File
@@ -12,3 +12,4 @@ html, body { margin: 0; height: 100%; background: #f5f6fa; color: #1c2036; font:
button { font: 600 16px system-ui; padding: 12px 18px; border-radius: 99px; border: 0; background: #ffcc00; color: #1c2036; width: 100%; margin-top: 8px; } button { font: 600 16px system-ui; padding: 12px 18px; border-radius: 99px; border: 0; background: #ffcc00; color: #1c2036; width: 100%; margin-top: 8px; }
button.ghost { background: #fff; } button.ghost { background: #fff; }
.hist { font-size: 14px; color: #4a4f66; } .hist { font-size: 14px; color: #4a4f66; }
#shot { width: 100%; border-radius: 12px; margin-top: 12px; }
+1
View File
@@ -20,4 +20,5 @@
<button id="snap" class="ghost">Enregistrer l'image vidéo</button> <button id="snap" class="ghost">Enregistrer l'image vidéo</button>
<button id="again" class="ghost">Nouvel essai</button> <button id="again" class="ghost">Nouvel essai</button>
<p class="hist" id="hist"></p> <p class="hist" id="hist"></p>
<img id="shot" alt="Image vidéo enregistrée" hidden>
</main></body></html> </main></body></html>
+12 -8
View File
@@ -3,7 +3,7 @@ import { makeRingScanner } from "/static/js/ringscan.js";
const rings = makeRingScanner(); const rings = makeRingScanner();
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true }); const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0; let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0;
let tokens = new Set(), mode = "aucun", msAvg = 0; let tokens = new Set(), mode = "aucun", msAvg = 0;
const history = []; const history = [];
@@ -17,7 +17,7 @@ async function start() {
engine = await QrScanner.createQrEngine(); engine = await QrScanner.createQrEngine();
// same request as the vote page, so what this page measures is what voters get // same request as the vote page, so what this page measures is what voters get
const stream = await navigator.mediaDevices.getUserMedia({ const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "environment" }, width: { ideal: 3840 }, height: { ideal: 2160 } }, video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } },
}); });
const set = stream.getVideoTracks()[0].getSettings(); const set = stream.getVideoTracks()[0].getSettings();
$("res").textContent = `${set.width}×${set.height} ${set.frameRate ? Math.round(set.frameRate) + " i/s" : ""}`; $("res").textContent = `${set.width}×${set.height} ${set.frameRate ? Math.round(set.frameRate) + " i/s" : ""}`;
@@ -69,17 +69,21 @@ async function loop() {
$("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; })); $("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; }));
$("again").addEventListener("click", reset); $("again").addEventListener("click", reset);
// one raw frame of the stream as the decoder sees it, to send back when a phone can't read the ring // one raw frame of the stream as the decoder sees it, to send back when a phone can't read the ring.
// built and clicked in the same tap: android drops a download started after an async step (toBlob)
$("snap").addEventListener("click", () => { $("snap").addEventListener("click", () => {
if (!video.videoWidth) return; if (!video.videoWidth) return;
const c = document.createElement("canvas"); const c = document.createElement("canvas");
c.width = video.videoWidth; c.height = video.videoHeight; c.width = video.videoWidth; c.height = video.videoHeight;
c.getContext("2d").drawImage(video, 0, 0); c.getContext("2d").drawImage(video, 0, 0);
c.toBlob((b) => { const url = c.toDataURL("image/jpeg", 0.95);
const a = document.createElement("a"); const a = document.createElement("a");
a.href = URL.createObjectURL(b); a.href = url;
a.download = `rotatyvote-frame-${video.videoWidth}x${video.videoHeight}-${Date.now()}.png`; a.download = `rotatyvote-frame-${video.videoWidth}x${video.videoHeight}-${Date.now()}.jpg`;
document.body.append(a);
a.click(); a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000); a.remove();
}, "image/png"); // fallback: long press the picture to save it
$("shot").src = url;
$("shot").hidden = false;
}); });