// main.js // Entry point. Wires up MediaPipe FaceMesh initialization, the Camera, // the "Retry" button on the error overlay, the CDN-timeout fallback, and // the first-time auto-calibration trigger. All DOM bindings and runtime // state live in the other modules; this file just stitches them together. import { dbgSet, dbgSetError, setLoaderText, fmtBytes } from './utils.js'; import { onResults } from './gaze.js'; import { bindRecalibrateButton, tryRestoreCalibration, startCalibration, calibrationData, calActive } from './calibration.js'; import { setFaceMeshRef } from './renderer.js'; // ---- DOM references ---- const video = document.getElementById('webcam'); const loader = document.getElementById('loader'); const loaderText = document.getElementById('loader-text'); const loaderSub = document.getElementById('loader-sub'); const errOverlay = document.getElementById('error-overlay'); const errTitle = document.getElementById('err-title'); const errMsg = document.getElementById('err-msg'); const errRetry = document.getElementById('err-retry'); const statusDot = document.getElementById('status-dot'); const statusText = document.getElementById('status-text'); // Debug panel const dbgModel = document.getElementById('dbg-model'); const dbgCamera = document.getElementById('dbg-camera'); const dbgBytes = document.getElementById('dbg-bytes'); const dbgCdn3 = document.getElementById('dbg-cdn3'); // ---- Shared runtime state ---- let faceMesh = null; let camera = null; let frameCount = 0; // for frame skipping (process every 2nd frame) let lastMeshSendAt = 0; // ---- Error overlay ---- function showError(title, msg) { console.error('[error]', title, '—', msg); errTitle.textContent = title; errMsg.textContent = msg; errOverlay.classList.add('show'); loader.classList.add('hidden'); statusDot.className = 'dot err'; statusText.className = 'value err'; statusText.textContent = 'ERROR'; dbgSetError((title ? title + ' — ' : '') + (msg || '')); // Renderer also writes its own stage row; update here for consistency. const dbgStage = document.getElementById('dbg-stage'); dbgSet(dbgStage, 'error', 'err'); } errRetry.addEventListener('click', () => { errOverlay.classList.remove('show'); location.reload(); }); // ---- Model asset pre-fetch with byte-level progress ---- // Pre-fetch a list of MediaPipe WASM / data files with byte-level progress. // Returns a map { filename -> blob: URL } suitable for locateFile(). // If any file fails, the function still resolves with whatever succeeded // (MediaPipe will retry from the network as a fallback). async function prefetchAssets(files) { console.log('[model] pre-fetching', files.length, 'asset(s)…'); dbgSet(dbgModel, 'loading…', 'run'); const out = {}; let totalBytes = 0; for (let i = 0; i < files.length; i++) { const file = files[i]; const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file; setLoaderText( 'Downloading model (' + (i + 1) + '/' + files.length + ')', file + ' (0 MB)' ); console.log('[model] GET', file); try { const resp = await fetch(url, { mode: 'cors', cache: 'force-cache' }); if (!resp.ok) throw new Error('HTTP ' + resp.status); const len = parseInt(resp.headers.get('content-length') || '0', 10); // Stream the body so we can show incremental progress. const reader = resp.body && resp.body.getReader ? resp.body.getReader() : null; const chunks = []; let received = 0; if (reader) { // eslint-disable-next-line no-constant-condition while (true) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); received += value.byteLength; totalBytes += value.byteLength; const pct = len ? Math.round((received / len) * 100) : 0; setLoaderText( 'Downloading model (' + (i + 1) + '/' + files.length + ' · ' + pct + '%)', file + ' — ' + fmtBytes(received) + (len ? ' / ' + fmtBytes(len) : '') ); dbgSet(dbgBytes, fmtBytes(totalBytes)); } const blob = new Blob(chunks, { type: resp.headers.get('content-type') || 'application/octet-stream' }); out[file] = URL.createObjectURL(blob); } else { const blob = await resp.blob(); out[file] = URL.createObjectURL(blob); totalBytes += blob.size; dbgSet(dbgBytes, fmtBytes(totalBytes)); } console.log('[model] OK', file, fmtBytes(received || (out[file] ? 0 : 0))); } catch (e) { console.warn('[model] pre-fetch failed for', file, e && e.message); // leave out[file] undefined → MediaPipe will fall back to the URL } } dbgSet(dbgModel, 'ready (' + fmtBytes(totalBytes) + ')', 'ok'); console.log('[model] pre-fetch done, total', fmtBytes(totalBytes)); return out; } async function initFaceMesh() { console.log('[init] initFaceMesh start'); setLoaderText( 'Initializing face mesh…', 'Preparing the iris-tracking model. This may take a moment.' ); dbgSet(dbgModel, 'init…', 'run'); try { // 1) Pre-fetch the big WASM / data files so the user can see progress // instead of a silent stall. The list mirrors the files MediaPipe // requests at runtime when refineLandmarks is enabled. const assetMap = await prefetchAssets([ 'face_mesh_solution_simd_wasm_bin.js', 'face_mesh_solution_simd_wasm_bin.wasm', 'face_mesh_solution_packed_assets.data' ]); setLoaderText( 'Initializing face mesh…', 'WASM runtime ready. Constructing the model.' ); // 2) Construct FaceMesh. If we pre-fetched a file, serve it from the // blob URL so the browser uses the cached bytes; otherwise let // MediaPipe fall back to the CDN. faceMesh = new FaceMesh({ locateFile: (file) => { if (assetMap[file]) { console.log('[model] locateFile (cached)', file); return assetMap[file]; } const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file; console.log('[model] locateFile (remote)', file); return url; } }); faceMesh.setOptions({ maxNumFaces: 1, refineLandmarks: true, // gives 468-477 iris minDetectionConfidence: 0.5, minTrackingConfidence: 0.5 }); faceMesh.onResults(onResults); setFaceMeshRef(faceMesh); console.log('[init] FaceMesh constructed, calling .initialize()'); setLoaderText( 'Initializing face mesh…', 'Calling MediaPipe .initialize() — finalizing WASM.' ); if (typeof faceMesh.initialize === 'function') { await faceMesh.initialize(); } console.log('[init] FaceMesh ready'); dbgSet(dbgModel, 'ready', 'ok'); startCamera(); } catch (e) { console.error('FaceMesh init failed:', e); dbgSetError('FaceMesh init failed: ' + (e && e.message ? e.message : e)); dbgSet(dbgModel, 'failed', 'err'); showError( 'Initialization Failed', 'Could not load MediaPipe Face Mesh (' + ((e && e.message) || 'unknown error') + '). Check your network connection and reload the page.' ); } } function startCamera() { console.log('[camera] startCamera'); setLoaderText( 'Connecting camera…', 'Requesting webcam access. Please click "Allow" in the browser prompt.' ); dbgSet(dbgCamera, 'requesting…', 'run'); if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { dbgSet(dbgCamera, 'unsupported', 'err'); showError( 'Browser Not Supported', 'Your browser does not support getUserMedia. Please use a modern browser (Chrome, Firefox, Edge, Safari).' ); return; } camera = new Camera(video, { onFrame: async () => { // Frame-skip: only send every 2nd frame to MediaPipe. This roughly // halves CPU usage on the face-mesh pass and noticeably improves // responsiveness on mid-range laptops. frameCount++; if (frameCount % 2 !== 0) return; if (faceMesh) { const t0 = performance.now(); try { await faceMesh.send({ image: video }); } catch (e) { // swallow individual frame errors console.warn('[frame] send error', e && e.message); } finally { lastMeshSendAt = performance.now() - t0; if (lastMeshSendAt > 5) { // Only log slow frames to keep the console quiet // console.log('[frame] send', lastMeshSendAt.toFixed(1), 'ms'); } } } }, width: 640, height: 480 }); camera.start() .then(() => { // wait for metadata return new Promise(resolve => { if (video.readyState >= 1) return resolve(); video.addEventListener('loadedmetadata', resolve, { once: true }); }); }) .then(() => { console.log('[camera] stream ready, hiding loader'); loader.classList.add('hidden'); statusText.textContent = 'READY'; dbgSet(dbgCamera, 'streaming', 'ok'); const dbgStage = document.getElementById('dbg-stage'); dbgSet(dbgStage, 'live', 'ok'); // First-time calibration: no localStorage → kick off the 9-point flow if (!calibrationData && !calActive) { // small delay so the user can settle in front of the camera setTimeout(() => { if (!calibrationData && !calActive) startCalibration(); }, 800); } }) .catch(err => { console.error('Camera error:', err); dbgSet(dbgCamera, 'error', 'err'); const name = err && err.name; if (name === 'NotAllowedError' || name === 'PermissionDeniedError' || name === 'SecurityError') { showError( 'Camera Access Denied', 'We need your camera to track your gaze. Please click the camera icon in your browser\'s address bar, grant permission, then click Retry.' ); } else if (name === 'NotFoundError' || name === 'OverconstrainedError') { showError( 'No Camera Found', 'No webcam was detected on this device. Please connect a camera and reload the page.' ); } else if (name === 'NotReadableError' || name === 'TrackStartError') { showError( 'Camera Busy', 'Your camera appears to be in use by another application. Please close other apps (Zoom, Skype, etc.) and try again.' ); } else { showError( 'Camera Error', (err && err.message) || 'An unknown error occurred while accessing the camera.' ); } }); } // Wait for the global FaceMesh symbol to be available function waitFor(predicate, timeout = 20000) { return new Promise((resolve, reject) => { const start = performance.now(); (function check() { if (predicate()) return resolve(); if (performance.now() - start > timeout) return reject(new Error('Timeout waiting for MediaPipe')); requestAnimationFrame(check); })(); }); } // ---- Boot sequence ---- // 1) Restore any previously-saved calibration (synchronous, before camera). tryRestoreCalibration(); // 2) Wire up the "Recalibrate" button so it's ready once the model is up. bindRecalibrateButton(() => !!faceMesh); // 3) Wait for the MediaPipe CDN script to register window.FaceMesh. setLoaderText( 'Loading MediaPipe JS…', 'Downloading the MediaPipe scripts from the CDN.' ); console.log('[boot] waiting for window.FaceMesh…'); waitFor(() => typeof window.FaceMesh === 'function', 20000) .then(() => { console.log('[boot] window.FaceMesh available'); initFaceMesh(); }) .catch((e) => { console.error('[boot] FaceMesh never appeared:', e && e.message); dbgSet(dbgCdn3, 'TIMEOUT', 'err'); dbgSetError('Timed out waiting for MediaPipe JS. The CDN may be blocked.'); showError( 'Failed to Load MediaPipe', 'The MediaPipe library could not be loaded (timeout). The CDN may be blocked in your region — try a VPN or a different network, then reload.' ); }); // Safety: if a CDN script failed before waitFor() could resolve, bail out // promptly with a clear message instead of waiting for the timeout. window.addEventListener('cdnError', () => { if (typeof window.FaceMesh !== 'function') { console.error('[boot] CDN error before FaceMesh became available'); showError( 'CDN Load Failed', 'Could not download the MediaPipe library from the CDN. The CDN may be blocked in your region — try a VPN, a different network, or self-host the files, then reload.' ); } });