byoussef commited on
Commit
3caa2b4
·
verified ·
1 Parent(s): 8ddb12f

Camera, error and accessibility fixes

Browse files
Files changed (2) hide show
  1. index.html +66 -15
  2. style.css +0 -28
index.html CHANGED
@@ -18,6 +18,7 @@
18
  --line-2: #aab1b9;
19
  --accent: #c2410c;
20
  --caution: #8a4b00;
 
21
  --radius: 6px;
22
  }
23
  @media (prefers-color-scheme: dark) {
@@ -36,6 +37,7 @@
36
 
37
  * { box-sizing: border-box; }
38
  [hidden] { display: none !important; }
 
39
  ::selection { background: color-mix(in srgb, var(--accent) 28%, transparent); }
40
  html { background: var(--ground); }
41
  body {
@@ -285,7 +287,7 @@
285
  height: 20px;
286
  margin: 0;
287
  border-radius: 10px;
288
- background: var(--line-2);
289
  cursor: pointer;
290
  transition: background-color 0.15s;
291
  appearance: none;
@@ -344,7 +346,7 @@
344
  <span class="tag" id="tag-photo">Photo</span>
345
  <span class="tag" id="tag-depth">Depth</span>
346
  <span class="spot" id="spot" hidden></span>
347
- <output class="probe" id="probe" hidden></output>
348
  <div class="progress" id="progress" hidden>
349
  <span id="progress-text"></span>
350
  <div class="bar"><i></i></div>
@@ -360,7 +362,8 @@
360
  <div class="ticks" id="ticks"></div>
361
  </div>
362
  <p class="status" id="status" role="status"></p>
363
- <p class="caution" id="caution" hidden></p>
 
364
  </section>
365
 
366
  <aside class="panel" id="panel" aria-label="Settings">
@@ -482,11 +485,15 @@
482
  $('progress').classList.toggle('waiting', fraction === undefined);
483
  $('progress').style.setProperty('--done', `${100 * (fraction ?? 0)}%`);
484
  $('progress-text').textContent = text;
 
 
 
485
  document.documentElement.dataset.state = 'busy';
486
  }
487
 
488
  function settle() {
489
  $('progress').hidden = true;
 
490
  document.documentElement.dataset.state = $('notice').hidden ? 'ready' : 'blocked';
491
  }
492
 
@@ -525,20 +532,24 @@
525
  adapter = await navigator.gpu.requestAdapter({powerPreference: 'high-performance'});
526
  if (!adapter) await new Promise((resolve) => setTimeout(resolve, 250));
527
  }
528
- if (!adapter) throw new Error('WebGPU is on in this browser, but it found no GPU to use.');
 
 
529
  try {
530
  litert = await import(`${LITERT}/+esm`);
531
  await litert.loadLiteRt(`${LITERT}/wasm/`);
532
  } catch (error) {
533
  console.error(error);
534
- throw new Error('LiteRT.js did not load. Check the connection and reload the page.');
535
  }
536
  const device = litert.getWebGpuDevice();
537
  device.lost.then((loss) => {
538
  if (loss.reason !== 'destroyed') stop('The GPU stopped responding. Reload the page to start again.');
539
  });
540
  const info = device.adapterInfo ?? adapter.info ?? {};
541
- gpu = info.description || [info.vendor, info.architecture].filter(Boolean).join(' ');
 
 
542
  return device.features.has('shader-f16');
543
  }
544
 
@@ -623,6 +634,7 @@
623
  const [w, h] = [image.videoWidth ?? image.width, image.videoHeight ?? image.height];
624
  const scale = Math.max(width / w, height / h);
625
  context.imageSmoothingQuality = 'high';
 
626
  context.setTransform(mirrored ? -1 : 1, 0, 0, 1, mirrored ? width : 0, 0);
627
  context.drawImage(image, (width - w * scale) / 2, (height - h * scale) / 2, w * scale, h * scale);
628
  context.setTransform(1, 0, 0, 1, 0, 0);
@@ -700,6 +712,7 @@
700
  const [width, height] = [Math.round(cropWidth * shrink), Math.round(cropHeight * shrink)];
701
  if (crop.canvas.width !== width || crop.canvas.height !== height) Object.assign(crop.canvas, {width, height});
702
  crop.imageSmoothingQuality = 'high';
 
703
  crop.setTransform(mirrored ? -1 : 1, 0, 0, 1, mirrored ? width : 0, 0);
704
  crop.drawImage(image, Math.floor((w - cropWidth) / 2), Math.floor((h - cropHeight) / 2), cropWidth, cropHeight, 0, 0, width, height);
705
  crop.setTransform(1, 0, 0, 1, 0, 0);
@@ -758,6 +771,7 @@
758
  async function refresh() {
759
  again = true;
760
  if (running || stopped || !ready) return;
 
761
  running = true;
762
  while (again && !stopped) {
763
  again = false;
@@ -811,6 +825,7 @@
811
  if (!shot) return;
812
  // Whether this step is of a camera frame, even if the camera stops while it runs.
813
  const live = shot.live;
 
814
  if (live) grab(video, shot.mirrored);
815
  if (want.metric && !shot.focal) {
816
  if (!live) progress('Estimating the field of view');
@@ -934,7 +949,8 @@
934
  const [model, precision] = current.key.split(' ');
935
  status = `Model ${MODELS[model].name} in ${precision === 'fp16' ? 'float16' : 'float32'}`;
936
  if (current.shot.live && current.shot.rate) status += `: ${current.shot.rate.toFixed(1)} frames a second`;
937
- if (!current.shot.live && current.milliseconds) status += `: ${Math.round(current.milliseconds)} ms`;
 
938
  status += gpu ? ` on ${gpu}.` : '.';
939
  if (want.metric && current.shot.focal) {
940
  const angle = (pixels) => {
@@ -944,6 +960,7 @@
944
  status += ` Estimated field of view: ${angle(WIDTH)}° by ${angle(HEIGHT)}°.`;
945
  }
946
  }
 
947
  $('status').textContent = status;
948
  probe();
949
  }
@@ -987,14 +1004,18 @@
987
  render();
988
  }
989
 
 
 
 
 
990
  function look(next, sample) {
991
  endCamera();
992
- source = next;
993
  pointer = null;
994
  cancelAnimationFrame(sweep);
995
  delete viewer.dataset.depth;
996
  split(100);
997
- for (const button of $('samples').children) button.setAttribute('aria-pressed', String(button.dataset.sample === sample));
998
  warn('');
999
  render();
1000
  refresh();
@@ -1016,29 +1037,58 @@
1016
 
1017
  async function choose(sample) {
1018
  const turn = ++asked;
 
1019
  try {
1020
  const response = await fetch(`samples/${sample}.jpg`);
1021
  if (!response.ok) throw new Error(response.status);
1022
  await open(await response.blob(), sample, turn);
1023
  } catch {
 
1024
  warn('That sample photo did not load.');
1025
  }
1026
  }
1027
 
 
 
 
 
 
 
 
 
 
1028
  async function camera() {
1029
  if (source?.live) return endCamera();
 
 
 
 
1030
  let stream;
 
1031
  try {
1032
  stream = await navigator.mediaDevices.getUserMedia({
1033
  video: {facingMode: {ideal: 'environment'}, width: {ideal: 1280}, height: {ideal: 720}},
1034
  });
1035
- video.srcObject = stream;
1036
- await video.play();
 
 
 
 
1037
  } catch (error) {
 
 
 
 
 
1038
  for (const track of stream?.getTracks() ?? []) track.stop();
1039
- return warn(error?.name === 'NotAllowedError'
1040
- ? 'The camera is blocked for this page. Allow it in the browser\'s site settings, then press Camera again.'
1041
- : 'No camera could be started.');
 
 
 
 
1042
  }
1043
  // A camera that faces its user shows them as a mirror does.
1044
  const mirrored = stream.getVideoTracks()[0].getSettings().facingMode !== 'environment';
@@ -1048,6 +1098,7 @@
1048
  $('camera').setAttribute('aria-pressed', 'true');
1049
  $('camera-label').textContent = 'Stop camera';
1050
  $('tag-photo').textContent = 'Camera';
 
1051
  }
1052
 
1053
  // ---- Controls -----------------------------------------------------------------------------
@@ -1189,7 +1240,7 @@
1189
  } catch (error) {
1190
  stopped = true;
1191
  $('panel').inert = true;
1192
- notify(error.message);
1193
  }
1194
  </script>
1195
  </body>
 
18
  --line-2: #aab1b9;
19
  --accent: #c2410c;
20
  --caution: #8a4b00;
21
+ --off: #6b747d;
22
  --radius: 6px;
23
  }
24
  @media (prefers-color-scheme: dark) {
 
37
 
38
  * { box-sizing: border-box; }
39
  [hidden] { display: none !important; }
40
+ .unseen { position: absolute; width: 1px; height: 1px; overflow: hidden; white-space: nowrap; clip-path: inset(50%); }
41
  ::selection { background: color-mix(in srgb, var(--accent) 28%, transparent); }
42
  html { background: var(--ground); }
43
  body {
 
287
  height: 20px;
288
  margin: 0;
289
  border-radius: 10px;
290
+ background: var(--off);
291
  cursor: pointer;
292
  transition: background-color 0.15s;
293
  appearance: none;
 
346
  <span class="tag" id="tag-photo">Photo</span>
347
  <span class="tag" id="tag-depth">Depth</span>
348
  <span class="spot" id="spot" hidden></span>
349
+ <span class="probe" id="probe" hidden></span>
350
  <div class="progress" id="progress" hidden>
351
  <span id="progress-text"></span>
352
  <div class="bar"><i></i></div>
 
362
  <div class="ticks" id="ticks"></div>
363
  </div>
364
  <p class="status" id="status" role="status"></p>
365
+ <p class="caution" id="caution" role="alert" hidden></p>
366
+ <span class="unseen" id="phase" role="status"></span>
367
  </section>
368
 
369
  <aside class="panel" id="panel" aria-label="Settings">
 
485
  $('progress').classList.toggle('waiting', fraction === undefined);
486
  $('progress').style.setProperty('--done', `${100 * (fraction ?? 0)}%`);
487
  $('progress-text').textContent = text;
488
+ // Read out once a phase, not at every megabyte.
489
+ const phase = text.split(':')[0];
490
+ if ($('phase').textContent !== phase) $('phase').textContent = phase;
491
  document.documentElement.dataset.state = 'busy';
492
  }
493
 
494
  function settle() {
495
  $('progress').hidden = true;
496
+ $('phase').textContent = '';
497
  document.documentElement.dataset.state = $('notice').hidden ? 'ready' : 'blocked';
498
  }
499
 
 
532
  adapter = await navigator.gpu.requestAdapter({powerPreference: 'high-performance'});
533
  if (!adapter) await new Promise((resolve) => setTimeout(resolve, 250));
534
  }
535
+ if (!adapter) {
536
+ throw new Error('This browser found no GPU for WebGPU. Turn on graphics acceleration in its settings, or try Chrome or Edge on another computer.');
537
+ }
538
  try {
539
  litert = await import(`${LITERT}/+esm`);
540
  await litert.loadLiteRt(`${LITERT}/wasm/`);
541
  } catch (error) {
542
  console.error(error);
543
+ throw Object.assign(new Error('LiteRT.js did not load. Check the connection, then reload the page.'), {reload: true});
544
  }
545
  const device = litert.getWebGpuDevice();
546
  device.lost.then((loss) => {
547
  if (loss.reason !== 'destroyed') stop('The GPU stopped responding. Reload the page to start again.');
548
  });
549
  const info = device.adapterInfo ?? adapter.info ?? {};
550
+ const makers = {apple: 'an Apple', amd: 'an AMD', intel: 'an Intel', nvidia: 'an NVIDIA', arm: 'an Arm', qualcomm: 'a Qualcomm'};
551
+ if (info.isFallbackAdapter || info.architecture === 'swiftshader') gpu = 'a software renderer';
552
+ else if (makers[info.vendor]) gpu = `${makers[info.vendor]} GPU`;
553
  return device.features.has('shader-f16');
554
  }
555
 
 
634
  const [w, h] = [image.videoWidth ?? image.width, image.videoHeight ?? image.height];
635
  const scale = Math.max(width / w, height / h);
636
  context.imageSmoothingQuality = 'high';
637
+ context.fillRect(0, 0, width, height);
638
  context.setTransform(mirrored ? -1 : 1, 0, 0, 1, mirrored ? width : 0, 0);
639
  context.drawImage(image, (width - w * scale) / 2, (height - h * scale) / 2, w * scale, h * scale);
640
  context.setTransform(1, 0, 0, 1, 0, 0);
 
712
  const [width, height] = [Math.round(cropWidth * shrink), Math.round(cropHeight * shrink)];
713
  if (crop.canvas.width !== width || crop.canvas.height !== height) Object.assign(crop.canvas, {width, height});
714
  crop.imageSmoothingQuality = 'high';
715
+ crop.fillRect(0, 0, width, height);
716
  crop.setTransform(mirrored ? -1 : 1, 0, 0, 1, mirrored ? width : 0, 0);
717
  crop.drawImage(image, Math.floor((w - cropWidth) / 2), Math.floor((h - cropHeight) / 2), cropWidth, cropHeight, 0, 0, width, height);
718
  crop.setTransform(1, 0, 0, 1, 0, 0);
 
771
  async function refresh() {
772
  again = true;
773
  if (running || stopped || !ready) return;
774
+ $('notice').hidden = true;
775
  running = true;
776
  while (again && !stopped) {
777
  again = false;
 
825
  if (!shot) return;
826
  // Whether this step is of a camera frame, even if the camera stops while it runs.
827
  const live = shot.live;
828
+ if (live && !video.videoWidth) return;
829
  if (live) grab(video, shot.mirrored);
830
  if (want.metric && !shot.focal) {
831
  if (!live) progress('Estimating the field of view');
 
949
  const [model, precision] = current.key.split(' ');
950
  status = `Model ${MODELS[model].name} in ${precision === 'fp16' ? 'float16' : 'float32'}`;
951
  if (current.shot.live && current.shot.rate) status += `: ${current.shot.rate.toFixed(1)} frames a second`;
952
+ const took = current.milliseconds;
953
+ if (!current.shot.live && took) status += took < 1000 ? `: ${Math.round(took)} ms` : `: ${(took / 1000).toFixed(1)} s`;
954
  status += gpu ? ` on ${gpu}.` : '.';
955
  if (want.metric && current.shot.focal) {
956
  const angle = (pixels) => {
 
960
  status += ` Estimated field of view: ${angle(WIDTH)}° by ${angle(HEIGHT)}°.`;
961
  }
962
  }
963
+ $('status').setAttribute('aria-live', current?.shot.live ? 'off' : 'polite');
964
  $('status').textContent = status;
965
  probe();
966
  }
 
1004
  render();
1005
  }
1006
 
1007
+ function mark(sample) {
1008
+ for (const button of $('samples').children) button.setAttribute('aria-pressed', String(button.dataset.sample === sample));
1009
+ }
1010
+
1011
  function look(next, sample) {
1012
  endCamera();
1013
+ source = Object.assign(next, {sample});
1014
  pointer = null;
1015
  cancelAnimationFrame(sweep);
1016
  delete viewer.dataset.depth;
1017
  split(100);
1018
+ mark(sample);
1019
  warn('');
1020
  render();
1021
  refresh();
 
1037
 
1038
  async function choose(sample) {
1039
  const turn = ++asked;
1040
+ mark(sample);
1041
  try {
1042
  const response = await fetch(`samples/${sample}.jpg`);
1043
  if (!response.ok) throw new Error(response.status);
1044
  await open(await response.blob(), sample, turn);
1045
  } catch {
1046
+ if (turn === asked) mark(source?.sample);
1047
  warn('That sample photo did not load.');
1048
  }
1049
  }
1050
 
1051
+ // Until its first depth arrives, the camera shows as it comes.
1052
+ function preview() {
1053
+ if (!source?.live || viewer.dataset.depth !== undefined) return;
1054
+ if (video.videoWidth) cover(photo, photo.canvas.width, photo.canvas.height, video, source.mirrored);
1055
+ requestAnimationFrame(preview);
1056
+ }
1057
+
1058
+ let starting = false;
1059
+
1060
  async function camera() {
1061
  if (source?.live) return endCamera();
1062
+ if (starting) return;
1063
+ starting = true;
1064
+ $('camera-label').textContent = 'Starting';
1065
+ const turn = ++asked;
1066
  let stream;
1067
+ let failure;
1068
  try {
1069
  stream = await navigator.mediaDevices.getUserMedia({
1070
  video: {facingMode: {ideal: 'environment'}, width: {ideal: 1280}, height: {ideal: 720}},
1071
  });
1072
+ // A photo picked while the browser asked for permission wins.
1073
+ if (turn === asked) {
1074
+ video.srcObject = stream;
1075
+ await video.play();
1076
+ if (!video.videoWidth) throw new Error('The camera gave no picture.');
1077
+ }
1078
  } catch (error) {
1079
+ failure = error;
1080
+ }
1081
+ starting = false;
1082
+ $('camera-label').textContent = 'Camera';
1083
+ if (failure || turn !== asked) {
1084
  for (const track of stream?.getTracks() ?? []) track.stop();
1085
+ if (stream && video.srcObject === stream) video.srcObject = null;
1086
+ if (failure) {
1087
+ warn(failure.name === 'NotAllowedError'
1088
+ ? 'The camera is blocked for this page. Allow it in the browser\'s site settings, then press Camera again.'
1089
+ : 'No camera could be started.');
1090
+ }
1091
+ return;
1092
  }
1093
  // A camera that faces its user shows them as a mirror does.
1094
  const mirrored = stream.getVideoTracks()[0].getSettings().facingMode !== 'environment';
 
1098
  $('camera').setAttribute('aria-pressed', 'true');
1099
  $('camera-label').textContent = 'Stop camera';
1100
  $('tag-photo').textContent = 'Camera';
1101
+ preview();
1102
  }
1103
 
1104
  // ---- Controls -----------------------------------------------------------------------------
 
1240
  } catch (error) {
1241
  stopped = true;
1242
  $('panel').inert = true;
1243
+ notify(error.message, error.reload ? 'Reload the page' : undefined, () => location.reload());
1244
  }
1245
  </script>
1246
  </body>
style.css DELETED
@@ -1,28 +0,0 @@
1
- body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
4
- }
5
-
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
10
-
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
17
-
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
25
-
26
- .card p:last-child {
27
- margin-bottom: 0;
28
- }