main.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. // main.js
  2. // Entry point. Wires up MediaPipe FaceMesh initialization, the Camera,
  3. // the "Retry" button on the error overlay, the CDN-timeout fallback, and
  4. // the first-time auto-calibration trigger. All DOM bindings and runtime
  5. // state live in the other modules; this file just stitches them together.
  6. import { dbgSet, dbgSetError, setLoaderText, fmtBytes } from './utils.js';
  7. import { onResults } from './gaze.js';
  8. import {
  9. bindRecalibrateButton, tryRestoreCalibration,
  10. startCalibration, calibrationData, calActive
  11. } from './calibration.js';
  12. import { setFaceMeshRef } from './renderer.js';
  13. // ---- DOM references ----
  14. const video = document.getElementById('webcam');
  15. const loader = document.getElementById('loader');
  16. const loaderText = document.getElementById('loader-text');
  17. const loaderSub = document.getElementById('loader-sub');
  18. const errOverlay = document.getElementById('error-overlay');
  19. const errTitle = document.getElementById('err-title');
  20. const errMsg = document.getElementById('err-msg');
  21. const errRetry = document.getElementById('err-retry');
  22. const statusDot = document.getElementById('status-dot');
  23. const statusText = document.getElementById('status-text');
  24. // Debug panel
  25. const dbgModel = document.getElementById('dbg-model');
  26. const dbgCamera = document.getElementById('dbg-camera');
  27. const dbgBytes = document.getElementById('dbg-bytes');
  28. const dbgCdn3 = document.getElementById('dbg-cdn3');
  29. // ---- Shared runtime state ----
  30. let faceMesh = null;
  31. let camera = null;
  32. let frameCount = 0; // for frame skipping (process every 2nd frame)
  33. let lastMeshSendAt = 0;
  34. // ---- Error overlay ----
  35. function showError(title, msg) {
  36. console.error('[error]', title, '—', msg);
  37. errTitle.textContent = title;
  38. errMsg.textContent = msg;
  39. errOverlay.classList.add('show');
  40. loader.classList.add('hidden');
  41. statusDot.className = 'dot err';
  42. statusText.className = 'value err';
  43. statusText.textContent = 'ERROR';
  44. dbgSetError((title ? title + ' — ' : '') + (msg || ''));
  45. // Renderer also writes its own stage row; update here for consistency.
  46. const dbgStage = document.getElementById('dbg-stage');
  47. dbgSet(dbgStage, 'error', 'err');
  48. }
  49. errRetry.addEventListener('click', () => {
  50. errOverlay.classList.remove('show');
  51. location.reload();
  52. });
  53. // ---- Model asset pre-fetch with byte-level progress ----
  54. // Pre-fetch a list of MediaPipe WASM / data files with byte-level progress.
  55. // Returns a map { filename -> blob: URL } suitable for locateFile().
  56. // If any file fails, the function still resolves with whatever succeeded
  57. // (MediaPipe will retry from the network as a fallback).
  58. async function prefetchAssets(files) {
  59. console.log('[model] pre-fetching', files.length, 'asset(s)…');
  60. dbgSet(dbgModel, 'loading…', 'run');
  61. const out = {};
  62. let totalBytes = 0;
  63. for (let i = 0; i < files.length; i++) {
  64. const file = files[i];
  65. const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
  66. setLoaderText(
  67. 'Downloading model (' + (i + 1) + '/' + files.length + ')',
  68. file + ' (0 MB)'
  69. );
  70. console.log('[model] GET', file);
  71. try {
  72. const resp = await fetch(url, { mode: 'cors', cache: 'force-cache' });
  73. if (!resp.ok) throw new Error('HTTP ' + resp.status);
  74. const len = parseInt(resp.headers.get('content-length') || '0', 10);
  75. // Stream the body so we can show incremental progress.
  76. const reader = resp.body && resp.body.getReader ? resp.body.getReader() : null;
  77. const chunks = [];
  78. let received = 0;
  79. if (reader) {
  80. // eslint-disable-next-line no-constant-condition
  81. while (true) {
  82. const { done, value } = await reader.read();
  83. if (done) break;
  84. chunks.push(value);
  85. received += value.byteLength;
  86. totalBytes += value.byteLength;
  87. const pct = len ? Math.round((received / len) * 100) : 0;
  88. setLoaderText(
  89. 'Downloading model (' + (i + 1) + '/' + files.length + ' · ' + pct + '%)',
  90. file + ' — ' + fmtBytes(received) + (len ? ' / ' + fmtBytes(len) : '')
  91. );
  92. dbgSet(dbgBytes, fmtBytes(totalBytes));
  93. }
  94. const blob = new Blob(chunks, { type: resp.headers.get('content-type') || 'application/octet-stream' });
  95. out[file] = URL.createObjectURL(blob);
  96. } else {
  97. const blob = await resp.blob();
  98. out[file] = URL.createObjectURL(blob);
  99. totalBytes += blob.size;
  100. dbgSet(dbgBytes, fmtBytes(totalBytes));
  101. }
  102. console.log('[model] OK', file, fmtBytes(received || (out[file] ? 0 : 0)));
  103. } catch (e) {
  104. console.warn('[model] pre-fetch failed for', file, e && e.message);
  105. // leave out[file] undefined → MediaPipe will fall back to the URL
  106. }
  107. }
  108. dbgSet(dbgModel, 'ready (' + fmtBytes(totalBytes) + ')', 'ok');
  109. console.log('[model] pre-fetch done, total', fmtBytes(totalBytes));
  110. return out;
  111. }
  112. async function initFaceMesh() {
  113. console.log('[init] initFaceMesh start');
  114. setLoaderText(
  115. 'Initializing face mesh…',
  116. 'Preparing the iris-tracking model. This may take a moment.'
  117. );
  118. dbgSet(dbgModel, 'init…', 'run');
  119. try {
  120. // 1) Pre-fetch the big WASM / data files so the user can see progress
  121. // instead of a silent stall. The list mirrors the files MediaPipe
  122. // requests at runtime when refineLandmarks is enabled.
  123. const assetMap = await prefetchAssets([
  124. 'face_mesh_solution_simd_wasm_bin.js',
  125. 'face_mesh_solution_simd_wasm_bin.wasm',
  126. 'face_mesh_solution_packed_assets.data'
  127. ]);
  128. setLoaderText(
  129. 'Initializing face mesh…',
  130. 'WASM runtime ready. Constructing the model.'
  131. );
  132. // 2) Construct FaceMesh. If we pre-fetched a file, serve it from the
  133. // blob URL so the browser uses the cached bytes; otherwise let
  134. // MediaPipe fall back to the CDN.
  135. faceMesh = new FaceMesh({
  136. locateFile: (file) => {
  137. if (assetMap[file]) {
  138. console.log('[model] locateFile (cached)', file);
  139. return assetMap[file];
  140. }
  141. const url = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/' + file;
  142. console.log('[model] locateFile (remote)', file);
  143. return url;
  144. }
  145. });
  146. faceMesh.setOptions({
  147. maxNumFaces: 1,
  148. refineLandmarks: true, // gives 468-477 iris
  149. minDetectionConfidence: 0.5,
  150. minTrackingConfidence: 0.5
  151. });
  152. faceMesh.onResults(onResults);
  153. setFaceMeshRef(faceMesh);
  154. console.log('[init] FaceMesh constructed, calling .initialize()');
  155. setLoaderText(
  156. 'Initializing face mesh…',
  157. 'Calling MediaPipe .initialize() — finalizing WASM.'
  158. );
  159. if (typeof faceMesh.initialize === 'function') {
  160. await faceMesh.initialize();
  161. }
  162. console.log('[init] FaceMesh ready');
  163. dbgSet(dbgModel, 'ready', 'ok');
  164. startCamera();
  165. } catch (e) {
  166. console.error('FaceMesh init failed:', e);
  167. dbgSetError('FaceMesh init failed: ' + (e && e.message ? e.message : e));
  168. dbgSet(dbgModel, 'failed', 'err');
  169. showError(
  170. 'Initialization Failed',
  171. 'Could not load MediaPipe Face Mesh (' + ((e && e.message) || 'unknown error') +
  172. '). Check your network connection and reload the page.'
  173. );
  174. }
  175. }
  176. function startCamera() {
  177. console.log('[camera] startCamera');
  178. setLoaderText(
  179. 'Connecting camera…',
  180. 'Requesting webcam access. Please click "Allow" in the browser prompt.'
  181. );
  182. dbgSet(dbgCamera, 'requesting…', 'run');
  183. if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
  184. dbgSet(dbgCamera, 'unsupported', 'err');
  185. showError(
  186. 'Browser Not Supported',
  187. 'Your browser does not support getUserMedia. Please use a modern browser (Chrome, Firefox, Edge, Safari).'
  188. );
  189. return;
  190. }
  191. camera = new Camera(video, {
  192. onFrame: async () => {
  193. // Frame-skip: only send every 2nd frame to MediaPipe. This roughly
  194. // halves CPU usage on the face-mesh pass and noticeably improves
  195. // responsiveness on mid-range laptops.
  196. frameCount++;
  197. if (frameCount % 2 !== 0) return;
  198. if (faceMesh) {
  199. const t0 = performance.now();
  200. try {
  201. await faceMesh.send({ image: video });
  202. } catch (e) {
  203. // swallow individual frame errors
  204. console.warn('[frame] send error', e && e.message);
  205. } finally {
  206. lastMeshSendAt = performance.now() - t0;
  207. if (lastMeshSendAt > 5) {
  208. // Only log slow frames to keep the console quiet
  209. // console.log('[frame] send', lastMeshSendAt.toFixed(1), 'ms');
  210. }
  211. }
  212. }
  213. },
  214. width: 640,
  215. height: 480
  216. });
  217. camera.start()
  218. .then(() => {
  219. // wait for metadata
  220. return new Promise(resolve => {
  221. if (video.readyState >= 1) return resolve();
  222. video.addEventListener('loadedmetadata', resolve, { once: true });
  223. });
  224. })
  225. .then(() => {
  226. console.log('[camera] stream ready, hiding loader');
  227. loader.classList.add('hidden');
  228. statusText.textContent = 'READY';
  229. dbgSet(dbgCamera, 'streaming', 'ok');
  230. const dbgStage = document.getElementById('dbg-stage');
  231. dbgSet(dbgStage, 'live', 'ok');
  232. // First-time calibration: no localStorage → kick off the 9-point flow
  233. if (!calibrationData && !calActive) {
  234. // small delay so the user can settle in front of the camera
  235. setTimeout(() => { if (!calibrationData && !calActive) startCalibration(); }, 800);
  236. }
  237. })
  238. .catch(err => {
  239. console.error('Camera error:', err);
  240. dbgSet(dbgCamera, 'error', 'err');
  241. const name = err && err.name;
  242. if (name === 'NotAllowedError' || name === 'PermissionDeniedError' || name === 'SecurityError') {
  243. showError(
  244. 'Camera Access Denied',
  245. 'We need your camera to track your gaze. Please click the camera icon in your browser\'s address bar, grant permission, then click Retry.'
  246. );
  247. } else if (name === 'NotFoundError' || name === 'OverconstrainedError') {
  248. showError(
  249. 'No Camera Found',
  250. 'No webcam was detected on this device. Please connect a camera and reload the page.'
  251. );
  252. } else if (name === 'NotReadableError' || name === 'TrackStartError') {
  253. showError(
  254. 'Camera Busy',
  255. 'Your camera appears to be in use by another application. Please close other apps (Zoom, Skype, etc.) and try again.'
  256. );
  257. } else {
  258. showError(
  259. 'Camera Error',
  260. (err && err.message) || 'An unknown error occurred while accessing the camera.'
  261. );
  262. }
  263. });
  264. }
  265. // Wait for the global FaceMesh symbol to be available
  266. function waitFor(predicate, timeout = 20000) {
  267. return new Promise((resolve, reject) => {
  268. const start = performance.now();
  269. (function check() {
  270. if (predicate()) return resolve();
  271. if (performance.now() - start > timeout) return reject(new Error('Timeout waiting for MediaPipe'));
  272. requestAnimationFrame(check);
  273. })();
  274. });
  275. }
  276. // ---- Boot sequence ----
  277. // 1) Restore any previously-saved calibration (synchronous, before camera).
  278. tryRestoreCalibration();
  279. // 2) Wire up the "Recalibrate" button so it's ready once the model is up.
  280. bindRecalibrateButton(() => !!faceMesh);
  281. // 3) Wait for the MediaPipe CDN script to register window.FaceMesh.
  282. setLoaderText(
  283. 'Loading MediaPipe JS…',
  284. 'Downloading the MediaPipe scripts from the CDN.'
  285. );
  286. console.log('[boot] waiting for window.FaceMesh…');
  287. waitFor(() => typeof window.FaceMesh === 'function', 20000)
  288. .then(() => {
  289. console.log('[boot] window.FaceMesh available');
  290. initFaceMesh();
  291. })
  292. .catch((e) => {
  293. console.error('[boot] FaceMesh never appeared:', e && e.message);
  294. dbgSet(dbgCdn3, 'TIMEOUT', 'err');
  295. dbgSetError('Timed out waiting for MediaPipe JS. The CDN may be blocked.');
  296. showError(
  297. 'Failed to Load MediaPipe',
  298. '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.'
  299. );
  300. });
  301. // Safety: if a CDN script failed before waitFor() could resolve, bail out
  302. // promptly with a clear message instead of waiting for the timeout.
  303. window.addEventListener('cdnError', () => {
  304. if (typeof window.FaceMesh !== 'function') {
  305. console.error('[boot] CDN error before FaceMesh became available');
  306. showError(
  307. 'CDN Load Failed',
  308. '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.'
  309. );
  310. }
  311. });