byoussef commited on
Commit
3dbc696
·
verified ·
1 Parent(s): 34f0034

Photo and Video tabs: sample clips, video upload, playback; How it works

Browse files
.gitattributes CHANGED
@@ -37,3 +37,6 @@ samples/forest.jpg filter=lfs diff=lfs merge=lfs -text
37
  samples/kitchen.jpg filter=lfs diff=lfs merge=lfs -text
38
  samples/macaques.jpg filter=lfs diff=lfs merge=lfs -text
39
  samples/mountains.jpg filter=lfs diff=lfs merge=lfs -text
 
 
 
 
37
  samples/kitchen.jpg filter=lfs diff=lfs merge=lfs -text
38
  samples/macaques.jpg filter=lfs diff=lfs merge=lfs -text
39
  samples/mountains.jpg filter=lfs diff=lfs merge=lfs -text
40
+ samples/elephants.mp4 filter=lfs diff=lfs merge=lfs -text
41
+ samples/horses.mp4 filter=lfs diff=lfs merge=lfs -text
42
+ samples/wildebeests.mp4 filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -8,7 +8,7 @@ pinned: false
8
  license: other
9
  license_name: apple-amlr
10
  license_link: https://github.com/apple-aiml-research/ml-depth-pro-2/blob/main/LICENSE_MODEL
11
- short_description: Depth from a photo or the camera, in a browser on WebGPU
12
  models:
13
  - byoussef/DepthPro2-litert
14
  tags:
@@ -19,12 +19,13 @@ tags:
19
 
20
  # Depth Pro 2 on WebGPU
21
 
22
- [Depth Pro 2](https://huggingface.co/apple/DepthPro2) running in the browser: the [LiteRT files](https://huggingface.co/byoussef/DepthPro2-litert) on WebGPU, with [LiteRT.js](https://ai.google.dev/edge/litert/web). Photos and camera frames stay on the device.
23
 
24
- - Pick a sample, upload a photo or start the camera, then drag the divider between the photo and its depth.
25
- - Model S (98 MB) or B (387 MB), in float16 or float32. float16 needs the GPU's `shader-f16` feature; without it the page stays in float32.
26
- - The camera runs the video file of the same size, a second download of 99 or 388 MB. In it each frame also attends to the three frames before it, as in Depth Pro 2's live video mode, so the depth flickers less from frame to frame.
27
- - "Depth in meters" adds the field-of-view model (95 MB), which estimates the focal length. Point at the picture to read a distance.
 
28
 
29
  It needs WebGPU: Chrome, Edge or Firefox on a computer. Safari 27.2 runs it and returns wrong depth.
30
 
@@ -35,3 +36,5 @@ The whole demo is [`index.html`](index.html).
35
  Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement, which allows research use only. The demo and the converted files are unofficial, and Apple does not endorse them.
36
 
37
  The sample photos are CC0, from Wikimedia Commons: [macaques](https://commons.wikimedia.org/wiki/File:Bonnet_Macaque_David_raju-.jpg) by Davidvraju, [kitchen](https://commons.wikimedia.org/wiki/File:Blue_white_kitchen_interior_(Unsplash).jpg) by NeONBRAND, [forest path](https://commons.wikimedia.org/wiki/File:Forest_path_surrounded_by_green_trees.jpg) by Zed Can77 and [mountain reservoir](https://commons.wikimedia.org/wiki/File:Mountain_lake_dam.jpg) by Paul Gilmore.
 
 
 
8
  license: other
9
  license_name: apple-amlr
10
  license_link: https://github.com/apple-aiml-research/ml-depth-pro-2/blob/main/LICENSE_MODEL
11
+ short_description: Depth from photos, videos or the camera, on WebGPU
12
  models:
13
  - byoussef/DepthPro2-litert
14
  tags:
 
19
 
20
  # Depth Pro 2 on WebGPU
21
 
22
+ [Depth Pro 2](https://huggingface.co/apple/DepthPro2) running in the browser: the [LiteRT files](https://huggingface.co/byoussef/DepthPro2-litert) on WebGPU, with [LiteRT.js](https://ai.google.dev/edge/litert/web). Photos, videos and camera frames stay on the device.
23
 
24
+ - **Photo:** pick a sample or upload your own, then drag the divider between the photo and its depth.
25
+ - **Video:** pick a sample clip, upload a video or start the camera. A video's first 10 seconds are estimated at 10 frames a second, cropped to 16:9, then play back in a loop, with a pause button and a slider.
26
+ - **Models:** S (98 MB) or B (387 MB), in float16 or float32. float16 needs the GPU's `shader-f16` feature; without it the page stays in float32.
27
+ - **Video model:** videos and the camera run the video file of the same size, a second download of 99 or 388 MB. In it each frame also attends to the three frames before it, as in Depth Pro 2's live video mode, so the depth flickers less from frame to frame.
28
+ - **Depth in meters:** adds the field-of-view model (95 MB), which estimates the focal length. Point at the picture to read a distance.
29
 
30
  It needs WebGPU: Chrome, Edge or Firefox on a computer. Safari 27.2 runs it and returns wrong depth.
31
 
 
36
  Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement, which allows research use only. The demo and the converted files are unofficial, and Apple does not endorse them.
37
 
38
  The sample photos are CC0, from Wikimedia Commons: [macaques](https://commons.wikimedia.org/wiki/File:Bonnet_Macaque_David_raju-.jpg) by Davidvraju, [kitchen](https://commons.wikimedia.org/wiki/File:Blue_white_kitchen_interior_(Unsplash).jpg) by NeONBRAND, [forest path](https://commons.wikimedia.org/wiki/File:Forest_path_surrounded_by_green_trees.jpg) by Zed Can77 and [mountain reservoir](https://commons.wikimedia.org/wiki/File:Mountain_lake_dam.jpg) by Paul Gilmore.
39
+
40
+ The sample videos are 8-second cuts, re-encoded at 854x480. The horses clip is the Space author's own. The [elephants](https://commons.wikimedia.org/wiki/File:Mum_and_baby_Elephant_walking_toward_us..webm) are by John Gowland and the [wildebeests](https://commons.wikimedia.org/wiki/File:Wildebeests_at_Grumeti_River.webm) by Bettina May, both [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/), from Wikimedia Commons.
index.html CHANGED
@@ -4,7 +4,7 @@
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <title>Depth Pro 2 on WebGPU</title>
7
- <meta name="description" content="Depth from a photo or the camera, computed in your browser on WebGPU with LiteRT.js.">
8
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='8' height='16' fill='%2358626b'/%3E%3Crect x='8' width='8' height='16' fill='%23f66b19'/%3E%3Crect x='7.25' width='1.5' height='16' fill='%23fff'/%3E%3C/svg%3E">
9
  <style>
10
  /* Hallmark · checked: 2026-11-24 · genre: modern-minimal (inferred)
@@ -84,7 +84,16 @@
84
  h1 { margin: 0; font-size: 1.125rem; font-weight: 650; letter-spacing: -0.01em; text-wrap: balance; }
85
  .lede { flex: 1 1 30ch; margin: 0; color: var(--ink-2); text-wrap: pretty; }
86
  header nav { display: flex; gap: 16px; }
87
- main { display: grid; grid-template-columns: minmax(0, 1fr) 296px; gap: 24px; align-items: start; }
 
 
 
 
 
 
 
 
 
88
 
89
  /* The picture: depth underneath, the photo on top of it, clipped at the divider. */
90
  .viewer {
@@ -371,13 +380,46 @@
371
  .switch input:checked { background: var(--accent); }
372
  .switch input:checked::after { transform: translateX(16px); }
373
  .panel[inert] { opacity: 0.5; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  footer { max-width: 86ch; margin-top: 26px; color: var(--ink-2); font-size: 0.8125rem; }
375
  footer p { margin: 0; text-wrap: pretty; }
376
 
377
  @media (max-width: 860px) {
378
  .page { max-width: none; padding: 14px 16px 20px; }
379
- main { grid-template-columns: minmax(0, 1fr); gap: 18px; }
380
  .samples { grid-template-columns: repeat(4, 1fr); }
 
381
  }
382
  @media (prefers-reduced-motion: reduce) {
383
  *, *::before, *::after { transition: none !important; }
@@ -389,7 +431,7 @@
389
  <div class="page">
390
  <header>
391
  <h1>Depth Pro 2 on WebGPU</h1>
392
- <p class="lede">Depth from a photo or the camera, computed in this browser on your GPU. Pictures stay on your device.</p>
393
  <nav>
394
  <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">Model files</a>
395
  <a href="https://huggingface.co/apple/DepthPro2" target="_blank" rel="noopener">Original model</a>
@@ -398,7 +440,7 @@
398
  </header>
399
 
400
  <main>
401
- <section aria-label="Result">
402
  <div class="viewer" id="viewer">
403
  <canvas id="depth" width="854" height="480" role="img" aria-label="Depth map: red is near, blue is far"></canvas>
404
  <canvas id="photo" width="854" height="480" role="img" aria-label="The photo"></canvas>
@@ -419,6 +461,14 @@
419
  <button class="button" id="notice-action" type="button"></button>
420
  </div>
421
  </div>
 
 
 
 
 
 
 
 
422
  <div class="scale">
423
  <canvas id="ramp" width="213" height="1" aria-hidden="true"></canvas>
424
  <span id="index" hidden></span>
@@ -430,22 +480,39 @@
430
  </section>
431
 
432
  <aside class="panel" id="panel" aria-label="Settings">
433
- <section class="group">
434
- <h2>Photo</h2>
435
- <div class="samples" id="samples"></div>
436
- <div class="row">
437
- <label class="button">
438
- <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 10.5v-8M4.75 5.5 8 2.25l3.25 3.25M2.5 10.5v2a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-2"/></svg>
439
- Upload
440
- <input id="file" type="file" accept="image/*">
441
- </label>
442
- <button class="button" id="camera" type="button" aria-pressed="false">
443
- <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><rect x="1.75" y="4" width="9" height="8" rx="1.5"/><path d="m10.75 7 3.5-2v6l-3.5-2"/></svg>
444
- <span id="camera-label">Camera</span>
445
- </button>
446
  </div>
447
- <p class="hint">Or drop a photo anywhere on the page. It is cropped to 16:9, the shape the models take. The camera runs the model’s video version, a second download of the same size, in which each frame also sees the three before it: the depth holds steadier.</p>
448
- </section>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
 
450
  <fieldset class="group">
451
  <legend>Model</legend>
@@ -470,6 +537,22 @@
470
  <p class="hint">Adds a second model (95 MB) that estimates the camera’s field of view. Without it the depth is relative.</p>
471
  </div>
472
  </aside>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473
  </main>
474
 
475
  <footer>
@@ -478,7 +561,13 @@
478
  <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">LiteRT conversions</a>,
479
  not endorsed by Apple, under the
480
  <a href="https://huggingface.co/byoussef/DepthPro2-litert/blob/main/LICENSE" target="_blank" rel="noopener">Apple Machine Learning Research Model License</a>:
481
- research use only. The sample photos are CC0, from Wikimedia Commons.
 
 
 
 
 
 
482
  </p>
483
  </footer>
484
  </div>
@@ -488,8 +577,8 @@
488
  const LITERT = 'https://cdn.jsdelivr.net/npm/@litertjs/core@2.6.0';
489
  // A fixed revision: what the browser has stored of it stays right.
490
  const FILES = 'https://huggingface.co/byoussef/DepthPro2-litert/resolve/d45bcfa0544d8ce5c351b2d5a8069f7a1be999a4/';
491
- // A photo runs the photo file of its size. The camera runs the video file, in which each frame
492
- // also sees the frames before it.
493
  const MODELS = {
494
  s: {name: 'S', label: 'model S', file: 'depthpro2-s_480x854.tflite', bytes: 98417420,
495
  video: {label: 'model S for video', file: 'depthpro2-s_480x854_w4.tflite', bytes: 99144436}},
@@ -502,6 +591,13 @@
502
  const SAMPLES = [
503
  ['macaques', 'Two macaques'], ['kitchen', 'A kitchen'], ['forest', 'A forest path'], ['mountains', 'A mountain reservoir'],
504
  ];
 
 
 
 
 
 
 
505
  const [WIDTH, HEIGHT] = [854, 480]; // the frame the depth models take
506
  // The field-of-view model takes the frame resized to 864x480 and cropped to its middle 832 columns.
507
  const [FOV_WIDTH, FOV_CROP] = [864, 832];
@@ -532,10 +628,13 @@
532
  let frame = null; // RGB of the frame, row by row, 0 to 255
533
  const calm = matchMedia('(prefers-reduced-motion: reduce)');
534
 
535
- const want = {model: 's', precision: 'fp16', metric: false}; // what the controls ask for
536
- // The compiled models; a video model with the empty state the camera starts from.
537
  const loaded = {depth: null, fov: null};
538
- let carried = null; // what the camera's last frame hands the next: {model, shot, state}
 
 
 
539
  const held = new Map(); // files downloaded and not compiled yet
540
  let litert;
541
  let gpu = '';
@@ -632,10 +731,14 @@
632
  }
633
 
634
  const keyOf = ({model, precision}) => `${model} ${precision}`;
635
- // The files the controls and the picture need: the depth model's, its video file while the
636
- // camera runs, and the field-of-view model's when asked for.
 
 
 
 
637
  const needed = (file) => (want.metric && file === MODELS.fov.file) ||
638
- file === (source?.live ? MODELS[want.model].video.file : MODELS[want.model].file);
639
 
640
  // Stops a download, and forgets downloaded files, that are no longer needed.
641
  function drop() {
@@ -643,13 +746,16 @@
643
  for (const file of held.keys()) if (!needed(file)) held.delete(file);
644
  }
645
 
646
- // The depth model the picture needs: the video file while the camera runs, the photo file for
647
- // a photo. None for a still that has its depth already from this size and precision, as the
648
- // camera's last frame has once the camera stops.
 
649
  function demand() {
650
  const key = keyOf(want);
651
- if (source?.live) return {key: `${key} video`, model: MODELS[want.model].video, video: true};
652
- if (depth && depth.shot === source && (depth.key === key || depth.key === `${key} video`)) return null;
 
 
653
  return {key, model: MODELS[want.model], video: false};
654
  }
655
 
@@ -723,7 +829,7 @@
723
  }
724
 
725
  // The state of a video that has shown no frame yet: zeros, kept on the GPU for every first
726
- // frame of the camera.
727
  async function emptyState(compiled) {
728
  const empty = {};
729
  for (const {name, shape} of compiled.getInputDetails()) {
@@ -738,18 +844,19 @@
738
  for (const tensor of Object.values(state ?? {})) tensor.delete();
739
  };
740
 
741
- // Lets go of the camera's state once nothing can take it up: the camera stopped, or the model changed.
742
- // Called only between runs, never while one could still be reading it.
 
743
  function prune() {
744
- if (carried && !(carried.shot === source && source.live && carried.model === loaded.depth)) {
745
  release(carried.state);
746
  carried = null;
747
  }
748
  }
749
 
750
- // Depth of a camera frame with the video model, and the milliseconds that took. The camera's
751
- // first frame starts from the empty state; each later one from the state the one before handed
752
- // on, which stays on the GPU.
753
  async function estimate(values, shot) {
754
  const model = loaded.depth;
755
  const past = carried?.shot === shot && carried.model === model ? carried.state : model.empty;
@@ -762,8 +869,8 @@
762
  tensor.delete();
763
  onHost.delete();
764
  const next = Object.fromEntries(STATE.map((name) => [name, outputs[`next_${name}`]]));
765
- // A camera stopped while this ran has no next frame to hand the state to.
766
- if (shot.live) {
767
  release(carried?.state);
768
  carried = {model, shot, state: next};
769
  } else {
@@ -986,14 +1093,10 @@
986
  // The model loaded is not the one this picture needs, as when the camera started while it loaded.
987
  const wanted = demand();
988
  if (wanted && loaded.depth?.key !== wanted.key) return void (again = true);
 
989
  if (live) grab(video, shot.mirrored);
990
- if (want.metric && !shot.focal) {
991
- if (!live) progress('Estimating the field of view');
992
- const {output} = await infer(loaded.fov, fieldOfViewInput(), [1, 3, HEIGHT, FOV_CROP]);
993
- if (shot !== source) return;
994
- // Its second output is the vertical angle, in degrees.
995
- shot.focal = 0.5 * HEIGHT / Math.tan(output[1] * Math.PI / 360);
996
- }
997
  if (wanted && (live || depth?.shot !== shot || depth.key !== wanted.key)) {
998
  if (!live) progress('Estimating depth');
999
  const input = planes(frame, WIDTH, HEIGHT);
@@ -1016,6 +1119,183 @@
1016
  render();
1017
  }
1018
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1019
  function show(shot, key, run, live) {
1020
  const inverse = run.output;
1021
  let nearest = 0;
@@ -1111,9 +1391,18 @@
1111
  if (current) {
1112
  const [model, precision] = current.key.split(' ');
1113
  status = `Model ${MODELS[model].name} in ${precision === 'fp16' ? 'float16' : 'float32'}`;
 
 
1114
  if (current.shot.live && current.shot.rate) status += `: ${current.shot.rate.toFixed(1)} frames a second`;
 
 
 
 
 
 
 
1115
  const took = current.milliseconds;
1116
- if (!current.shot.live && took) status += took < 1000 ? `: ${Math.round(took)} ms` : `: ${(took / 1000).toFixed(1)} s`;
1117
  status += gpu ? ` on ${gpu}.` : '.';
1118
  if (want.metric && current.shot.focal) {
1119
  const angle = (pixels) => {
@@ -1123,7 +1412,8 @@
1123
  status += ` Estimated field of view: ${angle(WIDTH)}° by ${angle(HEIGHT)}°.`;
1124
  }
1125
  }
1126
- $('status').setAttribute('aria-live', current?.shot.live ? 'off' : 'polite');
 
1127
  $('status').textContent = status;
1128
  probe();
1129
  }
@@ -1155,12 +1445,13 @@
1155
 
1156
  // ---- What is looked at --------------------------------------------------------------------
1157
 
1158
- function endCamera() {
 
 
1159
  if (!source?.live) return;
1160
- // The last frame stays, as a still, with its depth.
1161
  source.live = false;
1162
  // Stopped before its first depth, the camera leaves the frame it shows now, estimated as a photo.
1163
- if (depth?.shot !== source && video.videoWidth) {
1164
  grab(video, source.mirrored);
1165
  present();
1166
  }
@@ -1173,12 +1464,18 @@
1173
  }
1174
 
1175
  function mark(sample) {
1176
- for (const button of $('samples').children) button.setAttribute('aria-pressed', String(button.dataset.sample === sample));
 
 
1177
  }
1178
 
1179
  function look(next, sample) {
1180
  endCamera();
 
 
 
1181
  source = Object.assign(next, {sample});
 
1182
  drop();
1183
  pointer = null;
1184
  cancelAnimationFrame(sweep);
@@ -1186,11 +1483,15 @@
1186
  split(100);
1187
  mark(sample);
1188
  warn('');
 
 
 
1189
  render();
1190
  refresh();
1191
  }
1192
 
1193
- async function open(blob, sample, turn = ++asked) {
 
1194
  let image;
1195
  try {
1196
  image = await createImageBitmap(blob, {imageOrientation: 'from-image'});
@@ -1198,10 +1499,12 @@
1198
  return warn('This browser cannot read that file as a photo.');
1199
  }
1200
  if (turn !== asked) return image.close();
 
1201
  grab(image);
1202
  present();
1203
  image.close();
1204
- look({}, sample);
 
1205
  }
1206
 
1207
  async function choose(sample) {
@@ -1217,6 +1520,118 @@
1217
  }
1218
  }
1219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1220
  // Until its first depth arrives, the camera shows as it comes.
1221
  function preview() {
1222
  if (!source?.live || viewer.dataset.depth !== undefined) return;
@@ -1228,7 +1643,7 @@
1228
 
1229
  async function camera() {
1230
  if (source?.live) {
1231
- endCamera();
1232
  drop();
1233
  return refresh();
1234
  }
@@ -1291,6 +1706,36 @@
1291
  button.addEventListener('click', () => choose(sample));
1292
  $('samples').append(button);
1293
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1294
  for (const input of document.querySelectorAll('input[name="model"], input[name="precision"]')) {
1295
  input.addEventListener('change', () => {
1296
  want[input.name] = input.value;
@@ -1309,8 +1754,8 @@
1309
  if (navigator.mediaDevices?.getUserMedia) $('camera').addEventListener('click', camera);
1310
  else $('camera').disabled = true;
1311
 
1312
- // A photo dropped or pasted anywhere.
1313
- const dropped = (transferred) => [...(transferred?.files ?? [])].find((file) => file.type.startsWith('image/'));
1314
  addEventListener('dragover', (event) => {
1315
  event.preventDefault();
1316
  viewer.classList.add('dropping');
@@ -1321,12 +1766,10 @@
1321
  addEventListener('drop', (event) => {
1322
  event.preventDefault();
1323
  viewer.classList.remove('dropping');
1324
- const file = dropped(event.dataTransfer);
1325
- if (file && !stopped) open(file);
1326
  });
1327
  addEventListener('paste', (event) => {
1328
- const file = dropped(event.clipboardData);
1329
- if (file && !stopped) open(file);
1330
  });
1331
 
1332
  // Dragging sideways anywhere on the picture moves the divider; pointing reads the depth.
@@ -1384,6 +1827,7 @@
1384
  for (let i = 0; i < 213; i++) colors.data.set([...TURBO.subarray(3 * (212 - i), 3 * (213 - i)), 255], 4 * i);
1385
  ramp.putImageData(colors, 0, 0);
1386
  render();
 
1387
  choose(SAMPLES[0][0]);
1388
 
1389
  // Nothing to choose: without the shader-f16 feature LiteRT computes in float32.
@@ -1408,7 +1852,8 @@
1408
 
1409
  async function invite() {
1410
  const turn = ++invited;
1411
- const models = [MODELS[want.model], ...(want.metric ? [MODELS.fov] : [])];
 
1412
  const store = await globalThis.caches?.open('depthpro2-litert').catch(() => null);
1413
  const missing = [];
1414
  for (const model of models) {
 
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <title>Depth Pro 2 on WebGPU</title>
7
+ <meta name="description" content="Depth from a photo, a video or the camera, computed in your browser on WebGPU with LiteRT.js.">
8
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='8' height='16' fill='%2358626b'/%3E%3Crect x='8' width='8' height='16' fill='%23f66b19'/%3E%3Crect x='7.25' width='1.5' height='16' fill='%23fff'/%3E%3C/svg%3E">
9
  <style>
10
  /* Hallmark · checked: 2026-11-24 · genre: modern-minimal (inferred)
 
84
  h1 { margin: 0; font-size: 1.125rem; font-weight: 650; letter-spacing: -0.01em; text-wrap: balance; }
85
  .lede { flex: 1 1 30ch; margin: 0; color: var(--ink-2); text-wrap: pretty; }
86
  header nav { display: flex; gap: 16px; }
87
+ main {
88
+ display: grid;
89
+ grid-template-areas: "result panel" "about panel";
90
+ grid-template-columns: minmax(0, 1fr) 296px;
91
+ gap: 24px;
92
+ align-items: start;
93
+ }
94
+ .result { grid-area: result; min-width: 0; }
95
+ .panel { grid-area: panel; }
96
+ .about { grid-area: about; }
97
 
98
  /* The picture: depth underneath, the photo on top of it, clipped at the divider. */
99
  .viewer {
 
380
  .switch input:checked { background: var(--accent); }
381
  .switch input:checked::after { transform: translateX(16px); }
382
  .panel[inert] { opacity: 0.5; }
383
+
384
+ /* Photo or video: the choice on top of the panel, and what each offers under it. */
385
+ .kinds { margin-bottom: 12px; }
386
+ .row > :only-child { grid-column: 1 / -1; }
387
+ .samples.clips { grid-template-columns: repeat(3, 1fr); }
388
+ .samples button { position: relative; }
389
+ .samples .length {
390
+ position: absolute;
391
+ right: 4px;
392
+ bottom: 4px;
393
+ padding: 1px 5px;
394
+ border-radius: 3px;
395
+ background: var(--chip);
396
+ color: var(--on-stage);
397
+ font-size: 0.6875rem;
398
+ font-weight: 600;
399
+ font-variant-numeric: tabular-nums;
400
+ pointer-events: none;
401
+ }
402
+
403
+ /* A video's frames, once estimated: play, pause, and go to any of them. */
404
+ .transport { display: flex; align-items: center; gap: 12px; margin-top: 10px; }
405
+ .button.icon { flex: none; width: 34px; height: 34px; padding: 0; }
406
+ .transport .when-paused, .transport[data-paused] .when-playing { display: none; }
407
+ .transport[data-paused] .when-paused { display: block; }
408
+ #scrub { flex: 1; min-width: 0; margin: 0; }
409
+ #scrub:disabled { opacity: 0.6; }
410
+ .clock { flex: none; min-width: 11ch; color: var(--ink-2); font-size: 0.8125rem; font-variant-numeric: tabular-nums; text-align: right; }
411
+
412
+ .about { max-width: 70ch; }
413
+ .about h2 { margin: 6px 0 6px; font-size: 0.9375rem; font-weight: 650; }
414
+ .about p { margin: 0 0 10px; color: var(--ink-2); text-wrap: pretty; }
415
  footer { max-width: 86ch; margin-top: 26px; color: var(--ink-2); font-size: 0.8125rem; }
416
  footer p { margin: 0; text-wrap: pretty; }
417
 
418
  @media (max-width: 860px) {
419
  .page { max-width: none; padding: 14px 16px 20px; }
420
+ main { grid-template-areas: "result" "panel" "about"; grid-template-columns: minmax(0, 1fr); gap: 18px; }
421
  .samples { grid-template-columns: repeat(4, 1fr); }
422
+ .samples.clips { grid-template-columns: repeat(3, 1fr); }
423
  }
424
  @media (prefers-reduced-motion: reduce) {
425
  *, *::before, *::after { transition: none !important; }
 
431
  <div class="page">
432
  <header>
433
  <h1>Depth Pro 2 on WebGPU</h1>
434
+ <p class="lede">Depth from a photo, a video or the camera, computed on your GPU. Nothing is uploaded.</p>
435
  <nav>
436
  <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">Model files</a>
437
  <a href="https://huggingface.co/apple/DepthPro2" target="_blank" rel="noopener">Original model</a>
 
440
  </header>
441
 
442
  <main>
443
+ <section class="result" aria-label="Result">
444
  <div class="viewer" id="viewer">
445
  <canvas id="depth" width="854" height="480" role="img" aria-label="Depth map: red is near, blue is far"></canvas>
446
  <canvas id="photo" width="854" height="480" role="img" aria-label="The photo"></canvas>
 
461
  <button class="button" id="notice-action" type="button"></button>
462
  </div>
463
  </div>
464
+ <div class="transport" id="transport" hidden>
465
+ <button class="button icon" id="play" type="button" aria-label="Pause" disabled>
466
+ <svg class="when-playing" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M5.5 3.5v9M10.5 3.5v9"/></svg>
467
+ <svg class="when-paused" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M5 3.25v9.5L12.5 8z"/></svg>
468
+ </button>
469
+ <input id="scrub" type="range" min="0" max="0" value="0" step="1" aria-label="Frame" disabled>
470
+ <span class="clock" id="clock"></span>
471
+ </div>
472
  <div class="scale">
473
  <canvas id="ramp" width="213" height="1" aria-hidden="true"></canvas>
474
  <span id="index" hidden></span>
 
480
  </section>
481
 
482
  <aside class="panel" id="panel" aria-label="Settings">
483
+ <fieldset class="group">
484
+ <legend class="unseen">What to look at</legend>
485
+ <div class="segmented kinds">
486
+ <label><input type="radio" name="kind" value="photo" checked><span>Photo</span></label>
487
+ <label><input type="radio" name="kind" value="video"><span>Video</span></label>
 
 
 
 
 
 
 
 
488
  </div>
489
+ <div class="pane" id="pane-photo">
490
+ <div class="samples" id="samples"></div>
491
+ <div class="row">
492
+ <label class="button">
493
+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 10.5v-8M4.75 5.5 8 2.25l3.25 3.25M2.5 10.5v2a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-2"/></svg>
494
+ Upload photo
495
+ <input id="file" type="file" accept="image/*">
496
+ </label>
497
+ </div>
498
+ <p class="hint">Or drop a photo anywhere on the page. It is cropped to 16:9, the shape the models take.</p>
499
+ </div>
500
+ <div class="pane" id="pane-video" hidden>
501
+ <div class="samples clips" id="clips"></div>
502
+ <div class="row">
503
+ <label class="button">
504
+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 10.5v-8M4.75 5.5 8 2.25l3.25 3.25M2.5 10.5v2a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-2"/></svg>
505
+ Upload video
506
+ <input id="clip-file" type="file" accept="video/*">
507
+ </label>
508
+ <button class="button" id="camera" type="button" aria-pressed="false">
509
+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><rect x="1.75" y="4" width="9" height="8" rx="1.5"/><path d="m10.75 7 3.5-2v6l-3.5-2"/></svg>
510
+ <span id="camera-label">Camera</span>
511
+ </button>
512
+ </div>
513
+ <p class="hint">A video’s first 10 seconds are estimated at 10 frames a second, cropped to 16:9, then play back. Each frame also sees the three before it, so the depth flickers less.</p>
514
+ </div>
515
+ </fieldset>
516
 
517
  <fieldset class="group">
518
  <legend>Model</legend>
 
537
  <p class="hint">Adds a second model (95 MB) that estimates the camera’s field of view. Without it the depth is relative.</p>
538
  </div>
539
  </aside>
540
+
541
+ <section class="about" aria-labelledby="about-title">
542
+ <h2 id="about-title">How it works</h2>
543
+ <p>
544
+ Depth Pro 2 is Apple’s model for metric depth from images and video. This page runs it
545
+ as LiteRT files with LiteRT.js on WebGPU: photos and videos are processed on your GPU and
546
+ never uploaded, and the model files stay in this browser for the next visit.
547
+ </p>
548
+ <p>
549
+ Colors show inverse depth, from red for near to blue for far. Photos use the model’s
550
+ single-image version. Videos and the camera use its video version, in which each frame
551
+ also attends to the three frames before it, so the depth flickers less from frame to
552
+ frame. With Depth in meters on, a second model estimates the field of view, and pointing
553
+ at the picture reads the distance.
554
+ </p>
555
+ </section>
556
  </main>
557
 
558
  <footer>
 
561
  <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">LiteRT conversions</a>,
562
  not endorsed by Apple, under the
563
  <a href="https://huggingface.co/byoussef/DepthPro2-litert/blob/main/LICENSE" target="_blank" rel="noopener">Apple Machine Learning Research Model License</a>:
564
+ research use only. The sample photos are CC0, from Wikimedia Commons. Of the sample videos,
565
+ the horses clip is the Space author’s own, and the
566
+ <a href="https://commons.wikimedia.org/wiki/File:Mum_and_baby_Elephant_walking_toward_us..webm" target="_blank" rel="noopener">elephants</a>
567
+ (John Gowland) and the
568
+ <a href="https://commons.wikimedia.org/wiki/File:Wildebeests_at_Grumeti_River.webm" target="_blank" rel="noopener">wildebeests</a>
569
+ (Bettina May) are <a href="https://creativecommons.org/licenses/by/3.0/" target="_blank" rel="noopener">CC BY 3.0</a>,
570
+ cut to 8 seconds and re-encoded.
571
  </p>
572
  </footer>
573
  </div>
 
577
  const LITERT = 'https://cdn.jsdelivr.net/npm/@litertjs/core@2.6.0';
578
  // A fixed revision: what the browser has stored of it stays right.
579
  const FILES = 'https://huggingface.co/byoussef/DepthPro2-litert/resolve/d45bcfa0544d8ce5c351b2d5a8069f7a1be999a4/';
580
+ // A photo runs the photo file of its size. A video and the camera run the video file, in which
581
+ // each frame also sees the frames before it.
582
  const MODELS = {
583
  s: {name: 'S', label: 'model S', file: 'depthpro2-s_480x854.tflite', bytes: 98417420,
584
  video: {label: 'model S for video', file: 'depthpro2-s_480x854_w4.tflite', bytes: 99144436}},
 
591
  const SAMPLES = [
592
  ['macaques', 'Two macaques'], ['kitchen', 'A kitchen'], ['forest', 'A forest path'], ['mountains', 'A mountain reservoir'],
593
  ];
594
+ const CLIPS = [ // name, description, seconds
595
+ ['horses', 'A herd of horses running past the camera', 8],
596
+ ['elephants', 'An elephant and her calf walking toward the camera', 8],
597
+ ['wildebeests', 'Wildebeests standing in a river', 8],
598
+ ];
599
+ // A video file is estimated at this many frames a second, over at most its first seconds.
600
+ const [CLIP_RATE, CLIP_SECONDS] = [10, 10];
601
  const [WIDTH, HEIGHT] = [854, 480]; // the frame the depth models take
602
  // The field-of-view model takes the frame resized to 864x480 and cropped to its middle 832 columns.
603
  const [FOV_WIDTH, FOV_CROP] = [864, 832];
 
628
  let frame = null; // RGB of the frame, row by row, 0 to 255
629
  const calm = matchMedia('(prefers-reduced-motion: reduce)');
630
 
631
+ const want = {kind: 'photo', model: 's', precision: 'fp16', metric: false}; // what the controls ask for
632
+ // The compiled models; a video model with the empty state a video starts from.
633
  const loaded = {depth: null, fov: null};
634
+ // What the last frame of a video or the camera hands the next: {model, shot, state}.
635
+ let carried = null;
636
+ // What each tab last showed, to show again on coming back to it.
637
+ const shown = {photo: null, video: null};
638
  const held = new Map(); // files downloaded and not compiled yet
639
  let litert;
640
  let gpu = '';
 
731
  }
732
 
733
  const keyOf = ({model, precision}) => `${model} ${precision}`;
734
+ // Whether a source's next frame continues from its last: the camera, and a video file until
735
+ // all its frames are estimated.
736
+ const streaming = (shot) => Boolean(shot?.live || (shot?.clip && !shot.clip.done));
737
+ const moving = (shot) => Boolean(shot?.live || shot?.clip);
738
+ // The files the controls and the picture need: the depth model's, its video file for a video
739
+ // or the camera, and the field-of-view model's when asked for.
740
  const needed = (file) => (want.metric && file === MODELS.fov.file) ||
741
+ file === (moving(source) ? MODELS[want.model].video.file : MODELS[want.model].file);
742
 
743
  // Stops a download, and forgets downloaded files, that are no longer needed.
744
  function drop() {
 
746
  for (const file of held.keys()) if (!needed(file)) held.delete(file);
747
  }
748
 
749
+ // The depth model the picture needs: the video file for the camera and for a video file not yet
750
+ // estimated with this size and precision, the photo file for a photo. None for a video whose
751
+ // frames are all estimated, and for a still that has its depth already from this size and
752
+ // precision, as the camera's last frame has once the camera stops.
753
  function demand() {
754
  const key = keyOf(want);
755
+ const video = {key: `${key} video`, model: MODELS[want.model].video, video: true};
756
+ if (source?.live) return video;
757
+ if (source?.clip) return source.clip.done && source.clip.key === video.key ? null : video;
758
+ if (depth && depth.shot === source && (depth.key === key || depth.key === video.key)) return null;
759
  return {key, model: MODELS[want.model], video: false};
760
  }
761
 
 
829
  }
830
 
831
  // The state of a video that has shown no frame yet: zeros, kept on the GPU for every first
832
+ // frame of a video or the camera.
833
  async function emptyState(compiled) {
834
  const empty = {};
835
  for (const {name, shape} of compiled.getInputDetails()) {
 
844
  for (const tensor of Object.values(state ?? {})) tensor.delete();
845
  };
846
 
847
+ // Lets go of a video's state once nothing can take it up: the camera stopped, the video's frames
848
+ // are all estimated or another picture is shown, or the model changed. Called only between
849
+ // runs, never while one could still be reading it.
850
  function prune() {
851
+ if (carried && !(carried.shot === source && streaming(source) && carried.model === loaded.depth)) {
852
  release(carried.state);
853
  carried = null;
854
  }
855
  }
856
 
857
+ // Depth of a frame of a video or the camera with the video model, and the milliseconds that
858
+ // took. The first frame starts from the empty state; each later one from the state the one
859
+ // before handed on, which stays on the GPU.
860
  async function estimate(values, shot) {
861
  const model = loaded.depth;
862
  const past = carried?.shot === shot && carried.model === model ? carried.state : model.empty;
 
869
  tensor.delete();
870
  onHost.delete();
871
  const next = Object.fromEntries(STATE.map((name) => [name, outputs[`next_${name}`]]));
872
+ // A camera stopped, or a video left, while this ran has no next frame to hand the state to.
873
+ if (streaming(shot) && shot === source) {
874
  release(carried?.state);
875
  carried = {model, shot, state: next};
876
  } else {
 
1093
  // The model loaded is not the one this picture needs, as when the camera started while it loaded.
1094
  const wanted = demand();
1095
  if (wanted && loaded.depth?.key !== wanted.key) return void (again = true);
1096
+ if (shot.clip) return clipStep(shot, wanted);
1097
  if (live) grab(video, shot.mirrored);
1098
+ if (want.metric && !shot.focal) await fieldOfView(shot);
1099
+ if (shot !== source) return;
 
 
 
 
 
1100
  if (wanted && (live || depth?.shot !== shot || depth.key !== wanted.key)) {
1101
  if (!live) progress('Estimating depth');
1102
  const input = planes(frame, WIDTH, HEIGHT);
 
1119
  render();
1120
  }
1121
 
1122
+ // The focal length of the picture, from the field-of-view model on the frame grabbed last.
1123
+ async function fieldOfView(shot) {
1124
+ if (!moving(shot)) progress('Estimating the field of view');
1125
+ const {output} = await infer(loaded.fov, fieldOfViewInput(), [1, 3, HEIGHT, FOV_CROP]);
1126
+ if (shot !== source) return;
1127
+ // Its second output is the vertical angle, in degrees.
1128
+ shot.focal = 0.5 * HEIGHT / Math.tan(output[1] * Math.PI / 360);
1129
+ }
1130
+
1131
+ // ---- Video files --------------------------------------------------------------------------
1132
+
1133
+ // A video file's next frame: estimated from the frames before it, shown, and kept. Once all are
1134
+ // kept they play in a loop, and nothing more is estimated.
1135
+ async function clipStep(shot, wanted) {
1136
+ const clip = shot.clip;
1137
+ if (!wanted) {
1138
+ if (want.metric && !shot.focal && clip.frames.length) {
1139
+ // Asked for once the frames are kept: the field of view of the first.
1140
+ const first = await createImageBitmap(clip.frames[0].picture);
1141
+ grab(first);
1142
+ first.close();
1143
+ await fieldOfView(shot);
1144
+ }
1145
+ return render();
1146
+ }
1147
+ // A new size or precision, or a state let go of: start again from the first frame.
1148
+ const continued = carried?.shot === shot && carried.model === loaded.depth;
1149
+ if (clip.key !== wanted.key || (clip.frames.length && !continued)) {
1150
+ Object.assign(clip, {key: wanted.key, frames: [], milliseconds: [], done: false, at: 0});
1151
+ }
1152
+ const index = clip.frames.length;
1153
+ const count = clip.times.length;
1154
+ transport();
1155
+ if (!await seek(clip.element, clip.times[index])) {
1156
+ if (shot !== source) return;
1157
+ // A file the browser cannot read to its end ends where it can.
1158
+ if (!index) return warn('This browser could not read that video.');
1159
+ clip.times.length = index;
1160
+ warn(`This browser could read only the first ${(index / CLIP_RATE).toFixed(1)} s of that video.`);
1161
+ return finish(shot);
1162
+ }
1163
+ if (shot !== source) return;
1164
+ grab(clip.element);
1165
+ if (want.metric && !shot.focal) await fieldOfView(shot);
1166
+ if (shot !== source) return;
1167
+ const run = await estimate(planes(frame, WIDTH, HEIGHT), shot);
1168
+ if (shot !== source || clip.key !== wanted.key) return;
1169
+ show(shot, wanted.key, run, true);
1170
+ clip.frames.push(await keep(run.output, shot.scale));
1171
+ clip.milliseconds.push(run.milliseconds);
1172
+ if (shot !== source) return;
1173
+ if (clip.frames.length < count) again = true;
1174
+ else finish(shot);
1175
+ transport();
1176
+ render();
1177
+ }
1178
+
1179
+ // Moves a video file to a time; resolves to whether that frame can now be drawn. A file let go
1180
+ // of meanwhile empties instead of seeking.
1181
+ function seek(element, time) {
1182
+ return new Promise((resolve) => {
1183
+ const failures = ['error', 'emptied', 'abort'];
1184
+ const end = (ok) => {
1185
+ clearTimeout(timer);
1186
+ element.removeEventListener('seeked', yes);
1187
+ for (const type of failures) element.removeEventListener(type, no);
1188
+ resolve(ok);
1189
+ };
1190
+ const yes = () => end(true);
1191
+ const no = () => end(false);
1192
+ const timer = setTimeout(no, 10000);
1193
+ element.addEventListener('seeked', yes);
1194
+ for (const type of failures) element.addEventListener(type, no);
1195
+ element.currentTime = time;
1196
+ });
1197
+ }
1198
+
1199
+ // One estimated frame of a video, kept small: the picture as a JPEG, the inverse depth in 16 bits.
1200
+ async function keep(inverse, scale) {
1201
+ let peak = 0;
1202
+ for (let i = 0; i < inverse.length; i++) if (inverse[i] > peak) peak = inverse[i];
1203
+ const levels = new Uint16Array(inverse.length);
1204
+ const step = peak > 0 ? 65535 / peak : 0;
1205
+ for (let i = 0; i < inverse.length; i++) levels[i] = Math.max(0, inverse[i]) * step + 0.5;
1206
+ const picture = await new Promise((resolve) => capture.canvas.toBlob(resolve, 'image/jpeg', 0.88));
1207
+ return {picture, levels, peak, scale};
1208
+ }
1209
+
1210
+ // All of a video's frames are kept: they play in a loop, from the first.
1211
+ function finish(shot) {
1212
+ Object.assign(shot.clip, {done: true, at: 0, playing: !calm.matches});
1213
+ transport();
1214
+ if (shot.clip.playing) play(shot);
1215
+ else display(shot, 0);
1216
+ }
1217
+
1218
+ // Shows the kept frames one after another, at the rate they were estimated at. A later call
1219
+ // takes over from an earlier one.
1220
+ async function play(shot) {
1221
+ const clip = shot.clip;
1222
+ const turn = clip.player = {};
1223
+ clearTimeout(clip.timer);
1224
+ while (clip.player === turn && shot === source && clip.done && clip.playing) {
1225
+ const begun = performance.now();
1226
+ try {
1227
+ await display(shot, clip.at);
1228
+ } catch (error) {
1229
+ console.error(error);
1230
+ clip.playing = false;
1231
+ transport();
1232
+ break;
1233
+ }
1234
+ await new Promise((resolve) => {
1235
+ clip.timer = setTimeout(resolve, Math.max(0, 1000 / CLIP_RATE - (performance.now() - begun)));
1236
+ });
1237
+ if (clip.player === turn && clip.done && clip.playing) clip.at = (clip.at + 1) % clip.frames.length;
1238
+ }
1239
+ }
1240
+
1241
+ // One kept frame of a video: its picture and its depth, of the same moment. Only the last one
1242
+ // asked for is shown, when several are decoding at once.
1243
+ async function display(shot, index) {
1244
+ const clip = shot.clip;
1245
+ const kept = clip.frames[index];
1246
+ if (!kept) return;
1247
+ const ticket = clip.ticket = (clip.ticket ?? 0) + 1;
1248
+ const picture = await createImageBitmap(kept.picture);
1249
+ if (shot !== source || clip.frames[index] !== kept || clip.ticket !== ticket) return picture.close();
1250
+ if (photo.canvas.width !== picture.width || photo.canvas.height !== picture.height) {
1251
+ Object.assign(photo.canvas, {width: picture.width, height: picture.height});
1252
+ }
1253
+ photo.drawImage(picture, 0, 0);
1254
+ picture.close();
1255
+ // One buffer for every frame: the depth on screen is always the frame shown.
1256
+ const inverse = clip.inverse ??= new Float32Array(kept.levels.length);
1257
+ const unit = kept.peak / 65535;
1258
+ for (let i = 0; i < inverse.length; i++) inverse[i] = kept.levels[i] * unit;
1259
+ depth = {shot, key: clip.key, inverse, scale: kept.scale, milliseconds: null};
1260
+ paint(inverse, kept.scale);
1261
+ clip.at = index;
1262
+ if (!shot.revealed) {
1263
+ shot.revealed = true;
1264
+ reveal();
1265
+ }
1266
+ transport();
1267
+ render();
1268
+ }
1269
+
1270
+ // The bar under a video: how far its estimation is, or where it plays.
1271
+ function transport() {
1272
+ const clip = source?.clip;
1273
+ $('transport').hidden = !clip;
1274
+ if (!clip) return;
1275
+ const count = clip.times.length;
1276
+ const kept = clip.frames.length;
1277
+ $('play').disabled = $('scrub').disabled = !clip.done;
1278
+ $('transport').toggleAttribute('data-paused', !clip.done || !clip.playing);
1279
+ $('play').setAttribute('aria-label', clip.done && clip.playing ? 'Pause' : 'Play');
1280
+ $('scrub').max = String(Math.max(0, count - 1));
1281
+ $('scrub').value = String(clip.done ? clip.at : Math.max(0, kept - 1));
1282
+ $('clock').textContent = clip.done
1283
+ ? `${(clip.at / CLIP_RATE).toFixed(1)} of ${(count / CLIP_RATE).toFixed(1)} s`
1284
+ : kept ? `frame ${kept} of ${count}` : `${count} frames`;
1285
+ $('scrub').setAttribute('aria-valuetext', $('clock').textContent);
1286
+ }
1287
+
1288
+ // Lets go of a video file that is no longer shown or remembered.
1289
+ function forget(shot) {
1290
+ const clip = shot?.clip;
1291
+ if (!clip) return;
1292
+ Object.assign(clip, {playing: false, done: false, frames: [], inverse: null, player: null});
1293
+ clearTimeout(clip.timer);
1294
+ clip.element.removeAttribute('src');
1295
+ clip.element.load();
1296
+ if (clip.url) URL.revokeObjectURL(clip.url);
1297
+ }
1298
+
1299
  function show(shot, key, run, live) {
1300
  const inverse = run.output;
1301
  let nearest = 0;
 
1391
  if (current) {
1392
  const [model, precision] = current.key.split(' ');
1393
  status = `Model ${MODELS[model].name} in ${precision === 'fp16' ? 'float16' : 'float32'}`;
1394
+ const time = (took) => took < 1000 ? `${Math.round(took)} ms` : `${(took / 1000).toFixed(1)} s`;
1395
+ const clip = current.shot.clip;
1396
  if (current.shot.live && current.shot.rate) status += `: ${current.shot.rate.toFixed(1)} frames a second`;
1397
+ if (clip) {
1398
+ const sorted = [...clip.milliseconds].sort((a, b) => a - b);
1399
+ const each = sorted[sorted.length >> 1];
1400
+ // How far estimating is shows under the picture; this line says what it costs.
1401
+ if (clip.done) status += `: ${clip.frames.length} frames`;
1402
+ if (each) status += clip.done ? `, ${time(each)} each` : `: ${time(each)} a frame`;
1403
+ }
1404
  const took = current.milliseconds;
1405
+ if (!moving(current.shot) && took) status += `: ${time(took)}`;
1406
  status += gpu ? ` on ${gpu}.` : '.';
1407
  if (want.metric && current.shot.focal) {
1408
  const angle = (pixels) => {
 
1412
  status += ` Estimated field of view: ${angle(WIDTH)}° by ${angle(HEIGHT)}°.`;
1413
  }
1414
  }
1415
+ // Read out when it settles: not for each frame of the camera or of a video being estimated.
1416
+ $('status').setAttribute('aria-live', streaming(current?.shot) ? 'off' : 'polite');
1417
  $('status').textContent = status;
1418
  probe();
1419
  }
 
1445
 
1446
  // ---- What is looked at --------------------------------------------------------------------
1447
 
1448
+ // Stops the camera. Stopped with its button, its last frame stays as a still with its depth;
1449
+ // `still` is false when another picture takes its place.
1450
+ function endCamera(still = false) {
1451
  if (!source?.live) return;
 
1452
  source.live = false;
1453
  // Stopped before its first depth, the camera leaves the frame it shows now, estimated as a photo.
1454
+ if (still && depth?.shot !== source && video.videoWidth) {
1455
  grab(video, source.mirrored);
1456
  present();
1457
  }
 
1464
  }
1465
 
1466
  function mark(sample) {
1467
+ for (const button of document.querySelectorAll('.samples button')) {
1468
+ button.setAttribute('aria-pressed', String(button.dataset.sample === sample));
1469
+ }
1470
  }
1471
 
1472
  function look(next, sample) {
1473
  endCamera();
1474
+ // The tab shows one video at a time: one it no longer shows is let go of.
1475
+ const before = shown[want.kind];
1476
+ if (before?.clip && before.clip !== next.clip) forget(before);
1477
  source = Object.assign(next, {sample});
1478
+ shown[want.kind] = source;
1479
  drop();
1480
  pointer = null;
1481
  cancelAnimationFrame(sweep);
 
1483
  split(100);
1484
  mark(sample);
1485
  warn('');
1486
+ $('tag-photo').textContent = next.live ? 'Camera' : next.clip ? 'Video' : 'Photo';
1487
+ $('photo').setAttribute('aria-label', next.live ? 'The camera' : next.clip ? 'The video' : 'The photo');
1488
+ transport();
1489
  render();
1490
  refresh();
1491
  }
1492
 
1493
+ // Opens a photo. `before` runs once it is readable, just before it is shown.
1494
+ async function open(blob, sample, turn = ++asked, before = null) {
1495
  let image;
1496
  try {
1497
  image = await createImageBitmap(blob, {imageOrientation: 'from-image'});
 
1499
  return warn('This browser cannot read that file as a photo.');
1500
  }
1501
  if (turn !== asked) return image.close();
1502
+ before?.();
1503
  grab(image);
1504
  present();
1505
  image.close();
1506
+ // An uploaded photo keeps its file, to show again on coming back to the tab.
1507
+ look({blob: sample ? null : blob}, sample);
1508
  }
1509
 
1510
  async function choose(sample) {
 
1520
  }
1521
  }
1522
 
1523
+ // Opens a video file: its first frame shows at once, and its frames are estimated from there.
1524
+ // `before` runs once it is readable, just before it is shown.
1525
+ async function openClip(url, sample, owned = false, turn = ++asked, before = null) {
1526
+ const element = Object.assign(document.createElement('video'), {muted: true, playsInline: true, preload: 'auto'});
1527
+ const readable = await new Promise((resolve) => {
1528
+ setTimeout(() => resolve(false), 20000);
1529
+ element.addEventListener('loadeddata', () => resolve(true), {once: true});
1530
+ element.addEventListener('error', () => resolve(false), {once: true});
1531
+ element.src = url;
1532
+ });
1533
+ let duration = element.duration;
1534
+ // A file that does not say how long it is, as a browser recording, says so once sought to its end.
1535
+ if (readable && !Number.isFinite(duration)) {
1536
+ await seek(element, 1e7);
1537
+ duration = element.duration;
1538
+ }
1539
+ const times = readable && element.videoWidth && Number.isFinite(duration) && duration > 0
1540
+ ? Array.from({length: Math.max(1, Math.round(Math.min(CLIP_SECONDS, duration) * CLIP_RATE))},
1541
+ (unused, index) => Math.min(Math.max(0, duration - 0.05), index / CLIP_RATE + 0.01))
1542
+ : null;
1543
+ if (times && turn === asked && await seek(element, times[0]) && turn === asked) {
1544
+ before?.();
1545
+ grab(element);
1546
+ present();
1547
+ const clip = {element, url: owned ? url : null, times, frames: [], milliseconds: [], key: null, done: false, at: 0};
1548
+ look({clip}, sample);
1549
+ if (element.videoHeight > element.videoWidth) warn('A portrait video is cropped to the 16:9 band across its middle.');
1550
+ return;
1551
+ }
1552
+ element.removeAttribute('src');
1553
+ if (owned) URL.revokeObjectURL(url);
1554
+ if (turn !== asked) return;
1555
+ mark(source?.sample);
1556
+ warn(sample ? 'That sample video did not load.' : 'This browser cannot play that video file.');
1557
+ }
1558
+
1559
+ function chooseClip(sample) {
1560
+ // The video already shown plays again from its start; its frames stay.
1561
+ if (source?.clip && source.sample === sample) {
1562
+ const clip = source.clip;
1563
+ if (clip.done) {
1564
+ Object.assign(clip, {at: 0, playing: true});
1565
+ transport();
1566
+ play(source);
1567
+ }
1568
+ return;
1569
+ }
1570
+ mark(sample);
1571
+ openClip(`samples/${sample}.mp4`, sample);
1572
+ }
1573
+
1574
+ // Coming back to a tab shows what it showed last: a video with its kept frames, or the photo.
1575
+ function restore(kind) {
1576
+ const back = shown[kind];
1577
+ if (kind === 'photo') {
1578
+ if (back?.blob) return open(back.blob);
1579
+ return choose(back?.sample ?? SAMPLES[0][0]);
1580
+ }
1581
+ if (!back?.clip) return chooseClip(CLIPS[0][0]);
1582
+ ++asked;
1583
+ const clip = back.clip;
1584
+ // Frames half estimated have lost the state they need: those start again.
1585
+ const restarted = !clip.done && clip.frames.length > 0;
1586
+ if (!clip.done) Object.assign(clip, {frames: [], milliseconds: [], key: null, at: 0});
1587
+ look({clip}, back.sample);
1588
+ if (restarted) warn('The video is estimated again from its first frame: leaving it stopped the frames before from carrying over.');
1589
+ if (clip.done) {
1590
+ clip.playing = !calm.matches;
1591
+ if (clip.playing) play(source);
1592
+ else display(source, clip.at);
1593
+ return;
1594
+ }
1595
+ const shot = source;
1596
+ seek(clip.element, clip.times[0]).then((ok) => {
1597
+ if (ok && shot === source && !clip.frames.length) {
1598
+ grab(clip.element);
1599
+ present();
1600
+ }
1601
+ });
1602
+ }
1603
+
1604
+ // Photo or video: each has its own samples, upload and models.
1605
+ function switchKind(kind, back = true) {
1606
+ if (want.kind === kind) return;
1607
+ want.kind = kind;
1608
+ document.querySelector(`input[name="kind"][value="${kind}"]`).checked = true;
1609
+ $('pane-photo').hidden = kind !== 'photo';
1610
+ $('pane-video').hidden = kind !== 'video';
1611
+ sizes();
1612
+ if (back) restore(kind);
1613
+ if (!ready && adapter && !booting && !stopped) invite();
1614
+ }
1615
+
1616
+ // The sizes the model choice shows: of the photo files or of the video files.
1617
+ function sizes() {
1618
+ for (const letter of ['s', 'b']) {
1619
+ const file = want.kind === 'video' ? MODELS[letter].video : MODELS[letter];
1620
+ document.querySelector(`input[name="model"][value="${letter}"] + span small`).textContent = `${Math.round(file.bytes / 1e6)} MB`;
1621
+ }
1622
+ }
1623
+
1624
+ // A file dropped, pasted or picked: a photo goes to the photo tab, a video to the video tab.
1625
+ function take(file) {
1626
+ if (!file || stopped) return;
1627
+ // The tab changes only once the file turns out readable.
1628
+ if (file.type.startsWith('video/')) {
1629
+ openClip(URL.createObjectURL(file), undefined, true, ++asked, () => switchKind('video', false));
1630
+ } else {
1631
+ open(file, undefined, ++asked, () => switchKind('photo', false));
1632
+ }
1633
+ }
1634
+
1635
  // Until its first depth arrives, the camera shows as it comes.
1636
  function preview() {
1637
  if (!source?.live || viewer.dataset.depth !== undefined) return;
 
1643
 
1644
  async function camera() {
1645
  if (source?.live) {
1646
+ endCamera(true);
1647
  drop();
1648
  return refresh();
1649
  }
 
1706
  button.addEventListener('click', () => choose(sample));
1707
  $('samples').append(button);
1708
  }
1709
+ for (const [sample, label, seconds] of CLIPS) {
1710
+ const button = Object.assign(document.createElement('button'), {type: 'button'});
1711
+ button.dataset.sample = sample;
1712
+ button.setAttribute('aria-pressed', 'false');
1713
+ button.append(
1714
+ Object.assign(new Image(), {src: `samples/${sample}-thumb.jpg`, alt: label, width: 320, height: 180}),
1715
+ Object.assign(document.createElement('span'), {className: 'length', textContent: `0:${String(seconds).padStart(2, '0')}`}));
1716
+ button.addEventListener('click', () => chooseClip(sample));
1717
+ $('clips').append(button);
1718
+ }
1719
+ for (const input of document.querySelectorAll('input[name="kind"]')) {
1720
+ input.addEventListener('change', () => switchKind(input.value));
1721
+ }
1722
+ $('play').addEventListener('click', () => {
1723
+ const clip = source?.clip;
1724
+ if (!clip?.done) return;
1725
+ clip.playing = !clip.playing;
1726
+ transport();
1727
+ if (clip.playing) play(source);
1728
+ });
1729
+ $('scrub').addEventListener('input', () => {
1730
+ const clip = source?.clip;
1731
+ if (!clip?.done) return;
1732
+ clip.playing = false;
1733
+ display(source, Number($('scrub').value));
1734
+ });
1735
+ $('clip-file').addEventListener('change', () => {
1736
+ take($('clip-file').files[0]);
1737
+ $('clip-file').value = '';
1738
+ });
1739
  for (const input of document.querySelectorAll('input[name="model"], input[name="precision"]')) {
1740
  input.addEventListener('change', () => {
1741
  want[input.name] = input.value;
 
1754
  if (navigator.mediaDevices?.getUserMedia) $('camera').addEventListener('click', camera);
1755
  else $('camera').disabled = true;
1756
 
1757
+ // A photo or a video dropped or pasted anywhere.
1758
+ const dropped = (transferred) => [...(transferred?.files ?? [])].find((file) => /^(image|video)\//.test(file.type));
1759
  addEventListener('dragover', (event) => {
1760
  event.preventDefault();
1761
  viewer.classList.add('dropping');
 
1766
  addEventListener('drop', (event) => {
1767
  event.preventDefault();
1768
  viewer.classList.remove('dropping');
1769
+ take(dropped(event.dataTransfer));
 
1770
  });
1771
  addEventListener('paste', (event) => {
1772
+ take(dropped(event.clipboardData));
 
1773
  });
1774
 
1775
  // Dragging sideways anywhere on the picture moves the divider; pointing reads the depth.
 
1827
  for (let i = 0; i < 213; i++) colors.data.set([...TURBO.subarray(3 * (212 - i), 3 * (213 - i)), 255], 4 * i);
1828
  ramp.putImageData(colors, 0, 0);
1829
  render();
1830
+ sizes();
1831
  choose(SAMPLES[0][0]);
1832
 
1833
  // Nothing to choose: without the shader-f16 feature LiteRT computes in float32.
 
1852
 
1853
  async function invite() {
1854
  const turn = ++invited;
1855
+ const depthModel = want.kind === 'video' ? MODELS[want.model].video : MODELS[want.model];
1856
+ const models = [depthModel, ...(want.metric ? [MODELS.fov] : [])];
1857
  const store = await globalThis.caches?.open('depthpro2-litert').catch(() => null);
1858
  const missing = [];
1859
  for (const model of models) {
samples/elephants-thumb.jpg ADDED
samples/elephants.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:319da30d744b887fa869083ad97a7f9072fc283f62aa71a7a48c0271116e9a65
3
+ size 4202054
samples/horses-thumb.jpg ADDED
samples/horses.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04a55003574670259b7775e11a7808b0e4ced6d64556f8aa6750d455ff877891
3
+ size 3229388
samples/wildebeests-thumb.jpg ADDED
samples/wildebeests.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b89f379852a8a840db4bd448c86076182b7510a7f9dd216c1cd204cc1008c985
3
+ size 5144934