On a phone the camera view took the photo too soon: a second of a
readable band, while the hand still moved. Now it takes the photo by
itself only when the band has looked readable and the picture has stood
still (mean change of a band pixel between checks under 6 of 255) for ten
checks in a row, 2.5 s, and never in the first 1.5 s. The hint counts
down ("the photo is taken in 2 s, or press Take the photo"), and says
"Hold still: the picture still moves" while it moves. Take the photo
still takes it at once.
Checked with fake cameras in Edge at 390x844: glare and dark keep their
hints and never take a photo, a feed that moves is never taken in 8 s, a
still good one is taken after 4.0 s and read with every check digit.
786 lines
27 KiB
JavaScript
786 lines
27 KiB
JavaScript
// The passport's machine-readable zone from a photo: taken in a camera view
|
|
// with a frame for the photo page and a band for the two lines, which says
|
|
// when there is glare, too little light or no sharp picture yet; or any
|
|
// picture of the page. Tesseract.js reads it in the browser with a model
|
|
// trained on MRZ lines, so the photo stays on the device; only the lines it
|
|
// finds go into the zone's field, and the server reads them as if they
|
|
// were typed (check digits and all).
|
|
(function () {
|
|
"use strict";
|
|
|
|
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<";
|
|
// the longest side kept of a photo, and the one of the first look for the
|
|
// lines
|
|
var KEEP = 3200;
|
|
var LOOK = 1600;
|
|
// the height of a letter for the second, closer read
|
|
var LETTER = 40;
|
|
|
|
var reader = null;
|
|
var onProgress = function () {};
|
|
|
|
function supported() {
|
|
return (
|
|
typeof WebAssembly === "object" &&
|
|
typeof Worker === "function" &&
|
|
typeof Promise === "function" &&
|
|
!!document.createElement("canvas").getContext
|
|
);
|
|
}
|
|
|
|
// WebAssembly SIMD (the test of wasm-feature-detect): the faster core
|
|
function simd() {
|
|
try {
|
|
return WebAssembly.validate(
|
|
new Uint8Array([
|
|
0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10,
|
|
10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11,
|
|
])
|
|
);
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function loadScript(src) {
|
|
return new Promise(function (resolve, reject) {
|
|
if (window.Tesseract) return resolve();
|
|
var s = document.createElement("script");
|
|
s.src = src;
|
|
s.onload = function () {
|
|
resolve();
|
|
};
|
|
s.onerror = function () {
|
|
reject(new Error("could not load " + src));
|
|
};
|
|
document.head.appendChild(s);
|
|
});
|
|
}
|
|
|
|
// One worker per page, made at the first photo: the core (about 3 MB) and
|
|
// the model (about 1 MB) load once, then stay in the browser's cache.
|
|
function startReader(input) {
|
|
if (reader) return reader;
|
|
var vendor = input.getAttribute("data-vendor");
|
|
var lang = input.getAttribute("data-lang");
|
|
reader = loadScript(vendor + "/tesseract.min.js")
|
|
.then(function () {
|
|
return window.Tesseract.createWorker(lang, 1, {
|
|
workerPath: vendor + "/worker.min.js",
|
|
// a file of its own rather than the directory: the worker then
|
|
// fetches the .wasm beside it instead of a build with it inlined
|
|
corePath:
|
|
vendor + (simd() ? "/tesseract-core-simd-lstm.js" : "/tesseract-core-lstm.js"),
|
|
langPath: input.getAttribute("data-langpath"),
|
|
gzip: input.getAttribute("data-gzip") === "1",
|
|
cachePath: "visa-mrz-" + (input.getAttribute("data-model") || lang),
|
|
// a worker from a blob: URL would take the page's policy
|
|
workerBlobURL: false,
|
|
logger: function (m) {
|
|
onProgress(m);
|
|
},
|
|
});
|
|
})
|
|
.then(function (w) {
|
|
return w
|
|
.setParameters({ tessedit_char_whitelist: ALPHABET })
|
|
.then(function () {
|
|
return w;
|
|
});
|
|
});
|
|
reader.catch(function () {
|
|
reader = null;
|
|
});
|
|
return reader;
|
|
}
|
|
|
|
function viaImg(file) {
|
|
return new Promise(function (resolve, reject) {
|
|
var url = URL.createObjectURL(file);
|
|
var img = new Image();
|
|
img.onload = function () {
|
|
URL.revokeObjectURL(url);
|
|
resolve(img);
|
|
};
|
|
img.onerror = function () {
|
|
URL.revokeObjectURL(url);
|
|
reject(new Error("not a picture"));
|
|
};
|
|
img.src = url;
|
|
});
|
|
}
|
|
|
|
// The picture upright as the camera's EXIF orientation says.
|
|
function loadImage(file) {
|
|
if (window.createImageBitmap) {
|
|
return createImageBitmap(file, { imageOrientation: "from-image" }).catch(function () {
|
|
return viaImg(file);
|
|
});
|
|
}
|
|
return viaImg(file);
|
|
}
|
|
|
|
function canvas(w, h) {
|
|
var c = document.createElement("canvas");
|
|
c.width = Math.max(1, Math.round(w));
|
|
c.height = Math.max(1, Math.round(h));
|
|
return c;
|
|
}
|
|
|
|
// The picture turned by quarter turns and `tilt` degrees more, and scaled
|
|
// to fit `max`.
|
|
function turned(src, w, h, quarter, max, tilt) {
|
|
var s = Math.min(1, max / Math.max(w, h));
|
|
var side = quarter % 2 === 1;
|
|
var c = canvas(side ? h * s : w * s, side ? w * s : h * s);
|
|
var ctx = c.getContext("2d");
|
|
ctx.fillStyle = "#fff";
|
|
ctx.fillRect(0, 0, c.width, c.height);
|
|
ctx.translate(c.width / 2, c.height / 2);
|
|
ctx.rotate((quarter * Math.PI) / 2 + ((tilt || 0) * Math.PI) / 180);
|
|
ctx.drawImage(src, (-w * s) / 2, (-h * s) / 2, w * s, h * s);
|
|
return c;
|
|
}
|
|
|
|
// Even light: each pixel against the mean of the square of radius `r`
|
|
// around it, so a shadow or a bright corner does not swallow the letters;
|
|
// ink becomes black, paper and its pattern white.
|
|
function flatten(c, r) {
|
|
var w = c.width;
|
|
var h = c.height;
|
|
var ctx = c.getContext("2d");
|
|
var img = ctx.getImageData(0, 0, w, h);
|
|
var d = img.data;
|
|
var g = new Float32Array(w * h);
|
|
var i, p, x, y;
|
|
for (i = 0, p = 0; i < g.length; i++, p += 4) {
|
|
g[i] = 0.299 * d[p] + 0.587 * d[p + 1] + 0.114 * d[p + 2];
|
|
}
|
|
var W = w + 1;
|
|
var sum = new Float64Array(W * (h + 1));
|
|
for (y = 0; y < h; y++) {
|
|
var row = 0;
|
|
for (x = 0; x < w; x++) {
|
|
row += g[y * w + x];
|
|
sum[(y + 1) * W + x + 1] = sum[y * W + x + 1] + row;
|
|
}
|
|
}
|
|
for (y = 0; y < h; y++) {
|
|
var y0 = Math.max(0, y - r);
|
|
var y1 = Math.min(h, y + r + 1);
|
|
for (x = 0; x < w; x++) {
|
|
var x0 = Math.max(0, x - r);
|
|
var x1 = Math.min(w, x + r + 1);
|
|
var mean =
|
|
(sum[y1 * W + x1] - sum[y0 * W + x1] - sum[y1 * W + x0] + sum[y0 * W + x0]) /
|
|
((y1 - y0) * (x1 - x0));
|
|
var ratio = g[y * w + x] / (mean + 1);
|
|
var v = ratio >= 0.95 ? 255 : Math.max(0, Math.min(255, (255 * (ratio - 0.5)) / 0.45));
|
|
p = (y * w + x) * 4;
|
|
d[p] = d[p + 1] = d[p + 2] = v;
|
|
d[p + 3] = 255;
|
|
}
|
|
}
|
|
ctx.putImageData(img, 0, 0);
|
|
return c;
|
|
}
|
|
|
|
// The lines found, with the pieces of one line joined: a shadow or a
|
|
// fold across the zone makes the reader see a line as several blocks.
|
|
function linesOf(data) {
|
|
var all = [];
|
|
(data.blocks || []).forEach(function (b) {
|
|
(b.paragraphs || []).forEach(function (p) {
|
|
(p.lines || []).forEach(function (l) {
|
|
all.push({ text: clean(l.text), bbox: l.bbox, baseline: l.baseline });
|
|
});
|
|
});
|
|
});
|
|
all.sort(function (a, b) {
|
|
return a.bbox.x0 - b.bbox.x0;
|
|
});
|
|
var rows = [];
|
|
all.forEach(function (l) {
|
|
var h = l.bbox.y1 - l.bbox.y0;
|
|
var row = rows.find(function (r) {
|
|
var overlap = Math.min(r.bbox.y1, l.bbox.y1) - Math.max(r.bbox.y0, l.bbox.y0);
|
|
return (
|
|
overlap > 0.5 * Math.min(h, r.bbox.y1 - r.bbox.y0) &&
|
|
l.bbox.x0 - r.bbox.x1 < 3 * h &&
|
|
l.bbox.x0 >= r.bbox.x1 - h
|
|
);
|
|
});
|
|
if (!row) {
|
|
rows.push({
|
|
text: l.text,
|
|
bbox: { x0: l.bbox.x0, y0: l.bbox.y0, x1: l.bbox.x1, y1: l.bbox.y1 },
|
|
baseline: l.baseline,
|
|
});
|
|
return;
|
|
}
|
|
row.text += l.text;
|
|
row.bbox.y0 = Math.min(row.bbox.y0, l.bbox.y0);
|
|
row.bbox.y1 = Math.max(row.bbox.y1, l.bbox.y1);
|
|
row.bbox.x1 = Math.max(row.bbox.x1, l.bbox.x1);
|
|
});
|
|
return rows;
|
|
}
|
|
|
|
function clean(t) {
|
|
return (t || "")
|
|
.toUpperCase()
|
|
.replace(/«/g, "<<")
|
|
.replace(/[^A-Z0-9<]/g, "");
|
|
}
|
|
|
|
function count(s, re) {
|
|
var m = s.match(re);
|
|
return m ? m.length : 0;
|
|
}
|
|
|
|
// A line that may belong to the zone: long, of filler or of digits.
|
|
function zoneLike(t) {
|
|
var c = clean(t);
|
|
return c.length >= 28 && (count(c, /</g) >= 2 || count(c, /[0-9]/g) >= 14);
|
|
}
|
|
|
|
// The first line starts with P and holds names: filler, few digits.
|
|
function firstLine(t) {
|
|
var c = clean(t);
|
|
return /^.?P/.test(c) && count(c, /</g) >= 2 && count(c, /[0-9]/g) < 8;
|
|
}
|
|
|
|
// The zone's lines among those found, lying across the picture: the
|
|
// first line (it starts with P) and the line below it, or the one there
|
|
// is. `sure` says whether the first line is among them.
|
|
function pickLines(lines) {
|
|
var z = lines
|
|
.filter(function (l) {
|
|
return zoneLike(l.text) && l.bbox.x1 - l.bbox.x0 > 2 * (l.bbox.y1 - l.bbox.y0);
|
|
})
|
|
.sort(function (a, b) {
|
|
return a.bbox.y0 - b.bbox.y0;
|
|
});
|
|
if (!z.length) return null;
|
|
for (var i = z.length - 1; i >= 0; i--) {
|
|
if (firstLine(z[i].text)) {
|
|
return { lines: z[i + 1] ? [z[i], z[i + 1]] : [z[i]], sure: true };
|
|
}
|
|
}
|
|
return { lines: z.slice(-2), sure: false };
|
|
}
|
|
|
|
// The band of the zone cut from `base` (the turned picture; the lines
|
|
// were found at `scale` of it), levelled along the lines' baselines and
|
|
// scaled so a letter is LETTER pixels high.
|
|
function cutBand(lines, base, scale) {
|
|
var x0 = Infinity;
|
|
var y0 = Infinity;
|
|
var x1 = -Infinity;
|
|
var y1 = -Infinity;
|
|
var angle = 0;
|
|
var n = 0;
|
|
lines.forEach(function (l) {
|
|
x0 = Math.min(x0, l.bbox.x0);
|
|
y0 = Math.min(y0, l.bbox.y0);
|
|
x1 = Math.max(x1, l.bbox.x1);
|
|
y1 = Math.max(y1, l.bbox.y1);
|
|
var b = l.baseline;
|
|
if (b && b.x1 > b.x0) {
|
|
angle += Math.atan2(b.y1 - b.y0, b.x1 - b.x0);
|
|
n++;
|
|
}
|
|
});
|
|
if (n) angle /= n;
|
|
var first = lines[0].bbox;
|
|
var lh = Math.max(
|
|
6,
|
|
first.y1 - first.y0 - Math.abs(Math.sin(angle)) * (first.x1 - first.x0)
|
|
);
|
|
if (lines.length === 1) {
|
|
// the other line lies below the first, above the second
|
|
if (firstLine(lines[0].text)) y1 += 1.8 * lh;
|
|
else y0 -= 1.8 * lh;
|
|
}
|
|
var cx = (x0 + x1) / 2 / scale;
|
|
var cy = (y0 + y1) / 2 / scale;
|
|
var bw = ((x1 - x0) * 1.08) / scale;
|
|
var bh = (y1 - y0 + 1.4 * lh) / scale;
|
|
var s = Math.min(LETTER / (lh / scale), 2600 / bw);
|
|
var c = canvas(bw * s, bh * s);
|
|
var ctx = c.getContext("2d");
|
|
ctx.fillStyle = "#fff";
|
|
ctx.fillRect(0, 0, c.width, c.height);
|
|
ctx.translate(c.width / 2, c.height / 2);
|
|
ctx.rotate(-angle);
|
|
ctx.scale(s, s);
|
|
ctx.translate(-cx, -cy);
|
|
ctx.drawImage(base, 0, 0);
|
|
return flatten(c, Math.round(1.5 * LETTER));
|
|
}
|
|
|
|
// How the picture is tried: as it came, the quarter turns, then slightly
|
|
// tilted either way (a long line on a tilted page breaks apart).
|
|
var TRIES = [
|
|
[0, 0],
|
|
[1, 0],
|
|
[3, 0],
|
|
[2, 0],
|
|
[0, -7],
|
|
[0, 7],
|
|
];
|
|
|
|
// The zone's lines in a picture of `w` by `h`, or null: those of the
|
|
// closer read first, then those of the first look. The server picks the
|
|
// two that make a zone, by their check digits.
|
|
async function readZone(worker, img, w, h, say, debug) {
|
|
var fallback = null;
|
|
for (var k = 0; k < TRIES.length; k++) {
|
|
say(k ? "Turning the photo..." : "Looking for the two lines...");
|
|
var base = turned(img, w, h, TRIES[k][0], KEEP, TRIES[k][1]);
|
|
var look = turned(base, base.width, base.height, 0, LOOK);
|
|
var scale = look.width / base.width;
|
|
flatten(look, Math.max(8, Math.round(Math.min(look.width, look.height) / 16)));
|
|
await worker.setParameters({ tessedit_pageseg_mode: "3" });
|
|
var first = await worker.recognize(look, {}, { text: true, blocks: true });
|
|
var found = pickLines(linesOf(first.data));
|
|
debug(
|
|
"try " + TRIES[k] + ": " +
|
|
(found ? found.lines.map(function (l) { return l.text; }).join(" / ") : "nothing")
|
|
);
|
|
if (!found) continue;
|
|
say("Reading the two lines...");
|
|
var lines = (await readBand(worker, cutBand(found.lines, base, scale))).concat(
|
|
found.lines.map(function (l) {
|
|
return l.text;
|
|
})
|
|
);
|
|
debug("lines: " + lines.join(" / "));
|
|
if (found.sure) return lines;
|
|
fallback = fallback || lines;
|
|
}
|
|
return fallback;
|
|
}
|
|
|
|
// The lines of a band that holds the zone, read as one block.
|
|
async function readBand(worker, band) {
|
|
await worker.setParameters({ tessedit_pageseg_mode: "6" });
|
|
var r = await worker.recognize(band, {}, { text: true, blocks: true });
|
|
return linesOf(r.data)
|
|
.map(function (l) {
|
|
return l.text;
|
|
})
|
|
.filter(function (t) {
|
|
return t.length >= 20;
|
|
});
|
|
}
|
|
|
|
// Whether lines hold a zone: a first line and one with the digits.
|
|
function zoneIn(lines) {
|
|
return (
|
|
lines.some(firstLine) &&
|
|
lines.some(function (t) {
|
|
return count(t, /[0-9]/g) >= 10;
|
|
})
|
|
);
|
|
}
|
|
|
|
// The share of near-white pixels: glare on the laminate.
|
|
function glare(c) {
|
|
var small = turned(c, c.width, c.height, 0, 400);
|
|
var d = small.getContext("2d").getImageData(0, 0, small.width, small.height).data;
|
|
var n = 0;
|
|
for (var p = 0; p < d.length; p += 4) {
|
|
if (d[p] > 248 && d[p + 1] > 248 && d[p + 2] > 248) n++;
|
|
}
|
|
return n / (d.length / 4);
|
|
}
|
|
|
|
var NOT_FOUND =
|
|
"No passport lines found in this photo. Take it again with the two lines at the " +
|
|
"bottom of the photo page sharp, straight and without glare, or type them in.";
|
|
var GLARE =
|
|
"No passport lines found: there is glare on the photo. Take it again with the passport " +
|
|
"tilted a little or away from the lamp, or type the lines in.";
|
|
|
|
// ---- the form: runs `work` (which gives the lines, or null) with the
|
|
// reader's status shown, then puts the lines in the zone's field and
|
|
// presses Read.
|
|
function run(form, wrap, work) {
|
|
var status = form.querySelector("[data-mrz-status]");
|
|
var input = wrap.querySelector("input[data-mrz-photo]");
|
|
var debug = input.hasAttribute("data-debug")
|
|
? function (m) {
|
|
console.log("mrz: " + m);
|
|
}
|
|
: function () {};
|
|
function say(text, state) {
|
|
if (!status) return;
|
|
status.textContent = text;
|
|
status.setAttribute("data-state", state || "busy");
|
|
status.hidden = false;
|
|
}
|
|
onProgress = function (m) {
|
|
if (/^loading/.test(m.status) && m.progress < 1) {
|
|
say("Loading the reader (about 4 MB, the first time)...");
|
|
}
|
|
};
|
|
wrap.classList.add("busy");
|
|
var started = Date.now();
|
|
say("Loading the reader...");
|
|
return startReader(input)
|
|
.then(function (worker) {
|
|
return work(worker, say, debug);
|
|
})
|
|
.then(function (lines) {
|
|
debug("took " + (Date.now() - started) + " ms");
|
|
if (typeof lines === "string") {
|
|
say(lines, "error");
|
|
return;
|
|
}
|
|
form.querySelector("textarea[name=mrz]").value = lines.join("\n");
|
|
var source = form.querySelector("input[name=mrz_source]");
|
|
if (source) source.value = "photo";
|
|
say("Read. Filling in the form...", "done");
|
|
var read = form.querySelector("button[value=read-mrz]");
|
|
if (form.requestSubmit) form.requestSubmit(read);
|
|
else read.click();
|
|
})
|
|
.catch(function (e) {
|
|
debug("error " + (e && e.stack ? e.stack : e));
|
|
say(
|
|
"This browser could not read the photo (" +
|
|
(e && e.message ? e.message : e) +
|
|
"). Type the two lines in instead.",
|
|
"error"
|
|
);
|
|
})
|
|
.then(function () {
|
|
input.value = "";
|
|
wrap.classList.remove("busy");
|
|
});
|
|
}
|
|
|
|
// A picture chosen from the device.
|
|
function readPicture(form, wrap, file) {
|
|
return run(form, wrap, async function (worker, say, debug) {
|
|
var img = await loadImage(file);
|
|
var w = img.naturalWidth || img.width;
|
|
var h = img.naturalHeight || img.height;
|
|
var lines = await readZone(worker, img, w, h, say, debug);
|
|
if (lines) return lines;
|
|
return glare(turned(img, w, h, 0, 800)) > 0.01 ? GLARE : NOT_FOUND;
|
|
});
|
|
}
|
|
|
|
// ---- the camera view
|
|
|
|
// The photo page is 125 by 88 mm; its zone is the band at the bottom.
|
|
var PAGE = 88 / 125;
|
|
var BAND = { x: 0.03, y: 0.7, w: 0.94, h: 0.27 };
|
|
// the variance of the band's Laplacian below which it is not sharp yet,
|
|
// measured on the band scaled to 320 pixels across
|
|
var SHARP = 150;
|
|
// The photo takes itself only once the band has looked readable and the
|
|
// picture has stood still for HOLD checks in a row (one every 250 ms, so
|
|
// 2.5 s), and never in the first START ms, while the passport is still
|
|
// being put into the frame. A second was too quick on a phone: it took
|
|
// the photo while the hand still moved.
|
|
var HOLD = 10;
|
|
var START = 1500;
|
|
// the mean change of a band pixel from one check to the next (0 to 255)
|
|
// above which the picture still moves
|
|
var STILL = 6;
|
|
|
|
// What is wrong with the band in the picture, or "" when it looks
|
|
// readable: too dark, glare, no lines in it, or not sharp.
|
|
function judge(ctx, w, h) {
|
|
var d = ctx.getImageData(0, 0, w, h).data;
|
|
var g = new Float32Array(w * h);
|
|
var sum = 0;
|
|
var bright = 0;
|
|
for (var i = 0, p = 0; i < g.length; i++, p += 4) {
|
|
var v = 0.299 * d[p] + 0.587 * d[p + 1] + 0.114 * d[p + 2];
|
|
g[i] = v;
|
|
sum += v;
|
|
if (v > 248) bright++;
|
|
}
|
|
var mean = sum / g.length;
|
|
var ink = 0;
|
|
for (i = 0; i < g.length; i++) if (g[i] < 0.6 * mean) ink++;
|
|
var s1 = 0;
|
|
var s2 = 0;
|
|
var n = 0;
|
|
for (var y = 1; y < h - 1; y++) {
|
|
for (var x = 1; x < w - 1; x++) {
|
|
var k = y * w + x;
|
|
var lap = 4 * g[k] - g[k - 1] - g[k + 1] - g[k - w] - g[k + w];
|
|
s1 += lap;
|
|
s2 += lap * lap;
|
|
n++;
|
|
}
|
|
}
|
|
var sharp = n ? s2 / n - (s1 / n) * (s1 / n) : 0;
|
|
var m = { mean: Math.round(mean), glare: bright / g.length, ink: ink / g.length, sharp: Math.round(sharp) };
|
|
if (mean < 50) return { why: "Too dark: find more light.", m: m, g: g };
|
|
if (m.glare > 0.02) {
|
|
return {
|
|
why: "Glare on the two lines: tilt the passport a little, or turn away from the lamp.",
|
|
m: m,
|
|
g: g,
|
|
};
|
|
}
|
|
if (m.ink < 0.04) {
|
|
return { why: "Put the two lines at the bottom of the photo page into the yellow band.", m: m, g: g };
|
|
}
|
|
if (sharp < SHARP) return { why: "Hold still: the lines are not sharp yet.", m: m, g: g };
|
|
return { why: "", m: m, g: g };
|
|
}
|
|
|
|
// The mean change of a pixel between two looks at the band; Infinity
|
|
// when there is no earlier look of the same size.
|
|
function moved(a, b) {
|
|
if (!a || !b || a.length !== b.length) return Infinity;
|
|
var sum = 0;
|
|
for (var i = 0; i < a.length; i++) sum += Math.abs(a[i] - b[i]);
|
|
return sum / a.length;
|
|
}
|
|
|
|
function el(tag, cls, text) {
|
|
var e = document.createElement(tag);
|
|
if (cls) e.className = cls;
|
|
if (text) e.textContent = text;
|
|
return e;
|
|
}
|
|
|
|
function cameraWorks() {
|
|
return !!(
|
|
window.isSecureContext &&
|
|
navigator.mediaDevices &&
|
|
navigator.mediaDevices.getUserMedia
|
|
);
|
|
}
|
|
|
|
// Opens the camera view over the page. Its photo goes to the reader;
|
|
// closing it, or the browser refusing the camera, leaves the form as it
|
|
// was.
|
|
async function openCamera(form, wrap, opener) {
|
|
var status = form.querySelector("[data-mrz-status]");
|
|
var stream;
|
|
try {
|
|
stream = await navigator.mediaDevices.getUserMedia({
|
|
audio: false,
|
|
video: {
|
|
facingMode: { ideal: "environment" },
|
|
width: { ideal: 2560 },
|
|
height: { ideal: 1440 },
|
|
},
|
|
});
|
|
} catch (e) {
|
|
if (status) {
|
|
status.textContent =
|
|
"The camera is not available (" +
|
|
(e && e.name ? e.name : e) +
|
|
"). Choose a picture instead, or allow the camera in the browser's settings.";
|
|
status.setAttribute("data-state", "error");
|
|
status.hidden = false;
|
|
}
|
|
return;
|
|
}
|
|
var root = el("div", "cam");
|
|
root.setAttribute("role", "dialog");
|
|
root.setAttribute("aria-modal", "true");
|
|
root.setAttribute("aria-label", "Photo of the passport");
|
|
var video = el("video", "cam-video");
|
|
video.setAttribute("playsinline", "");
|
|
video.muted = true;
|
|
var frame = el("div", "cam-frame");
|
|
var band = el("div", "cam-band");
|
|
band.appendChild(el("span", "", "the two lines"));
|
|
frame.appendChild(band);
|
|
var hint = el("p", "cam-hint", "Fit the photo page into the frame, the two lines into the yellow band.");
|
|
hint.setAttribute("role", "status");
|
|
var bar = el("div", "cam-bar");
|
|
var cancel = el("button", "btn", "Cancel");
|
|
cancel.type = "button";
|
|
var shot = el("button", "btn pri", "Take the photo");
|
|
shot.type = "button";
|
|
bar.appendChild(cancel);
|
|
bar.appendChild(shot);
|
|
root.appendChild(video);
|
|
root.appendChild(frame);
|
|
root.appendChild(hint);
|
|
root.appendChild(bar);
|
|
document.body.appendChild(root);
|
|
document.documentElement.classList.add("cam-open");
|
|
|
|
var box = null;
|
|
function layout() {
|
|
var W = root.clientWidth;
|
|
var H = root.clientHeight;
|
|
var room = bar.offsetHeight + hint.offsetHeight + 48;
|
|
var fw = Math.min(W * 0.92, ((H - room) * 0.92) / PAGE);
|
|
var fh = fw * PAGE;
|
|
var left = (W - fw) / 2;
|
|
var top = Math.max(12, (H - room - fh) / 2);
|
|
frame.style.left = left + "px";
|
|
frame.style.top = top + "px";
|
|
frame.style.width = fw + "px";
|
|
frame.style.height = fh + "px";
|
|
box = { W: W, H: H, left: left, top: top, fw: fw, fh: fh };
|
|
}
|
|
// the frame in the video's own pixels (the video covers the view)
|
|
function inVideo() {
|
|
var vw = video.videoWidth;
|
|
var vh = video.videoHeight;
|
|
var s = Math.max(box.W / vw, box.H / vh);
|
|
var ox = (box.W - vw * s) / 2;
|
|
var oy = (box.H - vh * s) / 2;
|
|
return { x: (box.left - ox) / s, y: (box.top - oy) / s, w: box.fw / s, h: box.fh / s };
|
|
}
|
|
|
|
var timer = 0;
|
|
var good = 0;
|
|
var last = null;
|
|
var opened = Date.now();
|
|
var done = false;
|
|
var small = canvas(320, 80);
|
|
var sctx = small.getContext("2d", { willReadFrequently: true });
|
|
function close() {
|
|
done = true;
|
|
clearTimeout(timer);
|
|
stream.getTracks().forEach(function (t) {
|
|
t.stop();
|
|
});
|
|
window.removeEventListener("resize", layout);
|
|
document.removeEventListener("keydown", onKey);
|
|
root.remove();
|
|
document.documentElement.classList.remove("cam-open");
|
|
if (opener) opener.focus();
|
|
}
|
|
function onKey(ev) {
|
|
if (ev.key === "Escape") close();
|
|
}
|
|
function take() {
|
|
if (done || !video.videoWidth) return;
|
|
var f = inVideo();
|
|
var photo = canvas(video.videoWidth, video.videoHeight);
|
|
photo.getContext("2d").drawImage(video, 0, 0);
|
|
close();
|
|
readShot(form, wrap, photo, f);
|
|
}
|
|
function check() {
|
|
if (done) return;
|
|
if (video.videoWidth && box) {
|
|
var f = inVideo();
|
|
var bx = f.x + f.w * BAND.x;
|
|
var by = f.y + f.h * BAND.y;
|
|
var bw = f.w * BAND.w;
|
|
var bh = f.h * BAND.h;
|
|
small.height = Math.max(8, Math.round((bh * 320) / bw));
|
|
sctx.drawImage(video, bx, by, bw, bh, 0, 0, 320, small.height);
|
|
var j = judge(sctx, 320, small.height);
|
|
var change = moved(last, j.g);
|
|
last = j.g;
|
|
j.m.moved = Math.round(change * 10) / 10;
|
|
// the first look has nothing to compare with: not still yet, but
|
|
// nothing to say about it either
|
|
var why = j.why || (change > STILL && change !== Infinity ? "Hold still: the picture still moves." : "");
|
|
var early = Date.now() - opened < START;
|
|
good = why || early || change > STILL ? 0 : good + 1;
|
|
if (why) {
|
|
hint.textContent = why;
|
|
} else if (early) {
|
|
hint.textContent = "Good. Hold still...";
|
|
} else {
|
|
var left = Math.max(1, Math.ceil(((HOLD - good) * 250) / 1000));
|
|
hint.textContent = "Good. Hold still: the photo is taken in " + left + " s, or press Take the photo.";
|
|
}
|
|
root.classList.toggle("good", !why);
|
|
root.setAttribute("data-measure", JSON.stringify(j.m));
|
|
// a readable band that stands still for HOLD checks takes the photo
|
|
if (good >= HOLD) {
|
|
take();
|
|
return;
|
|
}
|
|
}
|
|
timer = setTimeout(check, 250);
|
|
}
|
|
cancel.addEventListener("click", close);
|
|
shot.addEventListener("click", take);
|
|
window.addEventListener("resize", layout);
|
|
document.addEventListener("keydown", onKey);
|
|
layout();
|
|
video.srcObject = stream;
|
|
try {
|
|
await video.play();
|
|
} catch (e) {
|
|
/* autoplay of a muted video is allowed; check() waits for frames */
|
|
}
|
|
shot.focus();
|
|
check();
|
|
}
|
|
|
|
// The camera's photo: the band where the frame showed it is read first;
|
|
// when that holds no zone, the whole frame is searched as a picture.
|
|
function readShot(form, wrap, photo, f) {
|
|
return run(form, wrap, async function (worker, say, debug) {
|
|
say("Reading the two lines...");
|
|
// the band with room on every side: a page is never held exactly in
|
|
// the frame
|
|
var bx = Math.max(0, f.x - f.w * 0.06);
|
|
var by = Math.max(0, f.y + f.h * 0.6);
|
|
var bw = Math.min(photo.width - bx, f.w * 1.12);
|
|
var bh = Math.min(photo.height - by, f.h * 0.46);
|
|
// a letter of the zone is about 2.4 mm of the page's 88
|
|
var s = Math.min(LETTER / ((f.h * 2.4) / 88), 2600 / bw);
|
|
var band = canvas(bw * s, bh * s);
|
|
var ctx = band.getContext("2d");
|
|
ctx.fillStyle = "#fff";
|
|
ctx.fillRect(0, 0, band.width, band.height);
|
|
ctx.drawImage(photo, bx, by, bw, bh, 0, 0, band.width, band.height);
|
|
var lines = await readBand(worker, flatten(band, Math.round(1.5 * LETTER)));
|
|
debug("band: " + lines.join(" / "));
|
|
if (zoneIn(lines)) return lines;
|
|
// the page around the frame, with room for a page held off centre
|
|
var mx = f.w * 0.15;
|
|
var my = f.h * 0.15;
|
|
var x0 = Math.max(0, f.x - mx);
|
|
var y0 = Math.max(0, f.y - my);
|
|
var x1 = Math.min(photo.width, f.x + f.w + mx);
|
|
var y1 = Math.min(photo.height, f.y + f.h + my);
|
|
var page = canvas(x1 - x0, y1 - y0);
|
|
page.getContext("2d").drawImage(photo, x0, y0, x1 - x0, y1 - y0, 0, 0, page.width, page.height);
|
|
var found = await readZone(worker, page, page.width, page.height, say, debug);
|
|
if (found) return lines.concat(found);
|
|
return glare(page) > 0.01 ? GLARE : NOT_FOUND;
|
|
});
|
|
}
|
|
|
|
document.addEventListener("DOMContentLoaded", function () {
|
|
if (!supported()) return;
|
|
document.querySelectorAll("[data-mrz-photo-wrap]").forEach(function (wrap) {
|
|
wrap.hidden = false;
|
|
var cam = wrap.querySelector("[data-mrz-camera]");
|
|
if (cam && !cameraWorks()) cam.hidden = true;
|
|
});
|
|
});
|
|
|
|
document.addEventListener("click", function (ev) {
|
|
var b = ev.target.closest && ev.target.closest("[data-mrz-camera]");
|
|
if (!b || !b.form) return;
|
|
var wrap = b.closest("[data-mrz-photo-wrap]");
|
|
if (wrap.classList.contains("busy")) return;
|
|
openCamera(b.form, wrap, b);
|
|
});
|
|
|
|
document.addEventListener("change", function (ev) {
|
|
var input = ev.target;
|
|
if (!input || !input.matches || !input.matches("input[data-mrz-photo]")) return;
|
|
var file = input.files && input.files[0];
|
|
var wrap = input.closest("[data-mrz-photo-wrap]");
|
|
if (!file || !input.form || !wrap) return;
|
|
readPicture(input.form, wrap, file);
|
|
});
|
|
})();
|