DepthPro2-WebGPU / index.html
byoussef's picture
Credit the horses clip to Coverr
80bce41 verified
Raw History Blame Contribute Delete
82.7 kB
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Depth Pro 2 on WebGPU</title> <meta name="description" content="Depth from a photo, a video or the camera, computed in your browser on WebGPU with LiteRT.js."> <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"> <style> /* Hallmark · checked: 2026-11-24 · genre: modern-minimal (inferred) * floor: 0 FAIL · fixed: 7 (10a, 26a, 26b, 34, 39a, 48, F1) · structural: 0 printed * finish-review: subagent · 3 findings · 3 resolved * built: the project · shape: app screen · redesign: polish · v2.0.0 */ /* Hallmark · dismissed 25 · the start bar holds one sentence beside its button, a caption and not running prose */ /* Hallmark · waive 28b · the video is hidden and only feeds the camera's frames to a canvas, never the LCP · a camera stream has no poster frame to show before the visitor turns the camera on */ :root { color-scheme: light dark; --ground: #f2f4f6; --surface: #ffffff; --hover: #e6e9ed; --ink: #15181b; --ink-2: #4b535a; --line: #d3d8dd; --line-2: #aab1b9; --accent: #c2410c; --accent-ink: #ffffff; --caution: #8a4b00; --off: #6b747d; --radius: 6px; /* What lies over the picture is the same in both themes: the picture is its ground. */ --stage: #0c0e10; --on-stage: #ffffff; --on-stage-ink: #15181b; --scrim: rgb(12 14 16 / 0.8); --chip: rgb(12 14 16 / 0.74); --chip-solid: rgb(12 14 16 / 0.88); --track: rgb(255 255 255 / 0.22); --shadow-edge: 0 0 0 1px rgb(0 0 0 / 0.28); --shadow-knob: 0 1px 2px rgb(0 0 0 / 0.3); --shadow-lift: 0 1px 2px rgb(0 0 0 / 0.3), 0 4px 12px rgb(0 0 0 / 0.28); --shadow-label: 0 1px 2px rgb(0 0 0 / 0.3), 0 3px 10px rgb(0 0 0 / 0.25); --shadow-spot: 0 0 0 1px rgb(0 0 0 / 0.5); --ring-stage: 0 0 0 2px #15181b, 0 0 0 4px #ffffff; } @media (prefers-color-scheme: dark) { :root { --ground: #111315; --surface: #1b1e21; --hover: #262a2e; --ink: #eceef0; --ink-2: #aab1b8; --line: #2b3035; --line-2: #4a525a; --accent: #ff8f3d; --accent-ink: #15181b; --caution: #ffb86b; } } * { box-sizing: border-box; } [hidden] { display: none !important; } .unseen { position: absolute; width: 1px; height: 1px; overflow: hidden; white-space: nowrap; clip-path: inset(50%); } ::selection { background: color-mix(in srgb, var(--accent) 28%, transparent); } html { overflow-x: clip; background: var(--ground); accent-color: var(--accent); caret-color: var(--accent); } body { margin: 0; overflow-x: clip; background: var(--ground); color: var(--ink); font: 0.875rem/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; -webkit-font-smoothing: antialiased; } a { color: inherit; text-decoration-color: var(--line-2); text-decoration-thickness: 1px; text-underline-offset: 3px; } a:hover { text-decoration-color: currentColor; } :focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; } /* The page is no wider than what keeps the picture inside the window. */ .page { max-width: min(1240px, max(780px, calc((100dvh - 190px) * 854 / 480 + 368px))); margin: 0 auto; padding: 18px 24px 24px; } header { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 16px; margin-bottom: 14px; } h1 { margin: 0; font-size: 1.125rem; font-weight: 650; letter-spacing: -0.01em; text-wrap: balance; } .lede { flex: 1 1 30ch; margin: 0; color: var(--ink-2); text-wrap: pretty; } header nav { display: flex; gap: 16px; } main { display: grid; grid-template-areas: "result panel" "about panel"; grid-template-columns: minmax(0, 1fr) 296px; gap: 24px; align-items: start; } .result { grid-area: result; min-width: 0; } .panel { grid-area: panel; } .about { grid-area: about; } /* The picture: depth underneath, the photo on top of it, clipped at the divider. */ .viewer { --split: 100; position: relative; aspect-ratio: 854 / 480; overflow: hidden; border-radius: var(--radius); background: var(--stage); touch-action: pan-y; user-select: none; -webkit-user-select: none; } .viewer canvas { position: absolute; inset: 0; display: block; width: 100%; height: 100%; } #photo { clip-path: inset(0 calc(100% - var(--split) * 1%) 0 0); } .viewer.dropping { outline: 2px solid var(--accent); outline-offset: 2px; } .viewer[data-probing] { cursor: crosshair; } .divider { position: absolute; top: 0; bottom: 0; left: calc(var(--split) * 1%); display: grid; place-items: center; width: 44px; margin-left: -22px; cursor: ew-resize; touch-action: none; outline: none; } .divider::before { content: ""; position: absolute; top: 0; bottom: 0; left: 21px; width: 2px; background: var(--on-stage); box-shadow: var(--shadow-edge); } .grip { position: relative; display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; background: var(--on-stage); color: var(--on-stage-ink); box-shadow: var(--shadow-lift); } .divider:focus-visible .grip { box-shadow: var(--ring-stage); } .viewer:not([data-depth]) .divider, .viewer:not([data-depth]) #tag-depth { display: none; } .viewer:has(.notice.start:not([hidden])) .tag { display: none; } .tag { position: absolute; bottom: 10px; padding: 3px 8px; border-radius: 4px; background: var(--chip); color: var(--on-stage); font-size: 0.75rem; font-weight: 600; pointer-events: none; } #tag-photo { left: 10px; } #tag-depth { right: 10px; } .probe, .spot { position: absolute; top: 0; left: 0; pointer-events: none; } .probe { padding: 3px 7px; border-radius: 4px; background: var(--on-stage); color: var(--on-stage-ink); font-size: 0.8125rem; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; box-shadow: var(--shadow-label); } .spot { width: 9px; height: 9px; margin: -4.5px 0 0 -4.5px; border: 1.5px solid var(--on-stage); border-radius: 50%; box-shadow: var(--shadow-spot); } .progress { position: absolute; bottom: 14px; left: 50%; width: max-content; min-width: 200px; max-width: calc(100% - 28px); padding: 9px 12px 10px; border-radius: var(--radius); background: var(--chip-solid); color: var(--on-stage); font-size: 0.8125rem; font-variant-numeric: tabular-nums; transform: translateX(-50%); } .bar { height: 3px; margin-top: 7px; overflow: hidden; border-radius: 2px; background: var(--track); } .bar i { display: block; height: 100%; border-radius: 2px; background: var(--on-stage); transform: scaleX(var(--done, 0)); transform-origin: 0 50%; transition: transform 0.15s linear; } .progress.waiting .bar i { width: 35%; transform: none; transition: none; animation: slide 1.15s cubic-bezier(0.4, 0, 0.2, 1) infinite; } @keyframes slide { from { transform: translateX(-100%); } to { transform: translateX(290%); } } .notice { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 14px; padding: 24px; background: var(--scrim); color: var(--on-stage); text-align: center; } .notice p { max-width: 44ch; margin: 0; font-size: 0.9375rem; text-wrap: balance; } .notice .button { border-color: var(--on-stage); background: var(--on-stage); color: var(--on-stage-ink); } .notice .button:hover { border-color: var(--on-stage); background: color-mix(in srgb, var(--on-stage) 92%, var(--stage)); } .notice .button:active { background: color-mix(in srgb, var(--on-stage) 84%, var(--stage)); } .notice .button:focus-visible { outline-color: var(--on-stage); } /* Before anything is loaded: a bar docked where the progress will show, and the picture left clear. */ .notice.start { inset: auto auto 14px 50%; display: flex; align-items: center; gap: 16px; width: max-content; max-width: calc(100% - 28px); padding: 10px 10px 10px 16px; border-radius: var(--radius); background: var(--chip-solid); text-align: left; transform: translateX(-50%); } .notice.start p { max-width: 40ch; font-size: 0.875rem; text-wrap: pretty; } .notice.start .button { flex: none; padding: 8px 20px; border-color: var(--accent); background: var(--accent); color: var(--accent-ink); font-size: 0.9375rem; white-space: nowrap; } .notice.start .button:hover { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 92%, var(--stage)); } .notice.start .button:active { background: color-mix(in srgb, var(--accent) 84%, var(--stage)); } /* The colors as distances: laid out like the distance scale of a lens, which is also linear in inverse depth and ends at infinity. */ .scale { position: relative; margin-top: 12px; } #ramp { display: block; width: 100%; height: 10px; border-radius: 2px; } #index { position: absolute; top: -3px; width: 3px; height: 16px; margin-left: -1.5px; border-radius: 1.5px; background: var(--ink); box-shadow: 0 0 0 1.5px var(--ground); } .ticks { position: relative; height: 26px; color: var(--ink-2); font-size: 0.75rem; font-variant-numeric: tabular-nums; } .ticks span { position: absolute; top: 0; padding-top: 8px; white-space: nowrap; transform: translateX(-50%); } .ticks span::before { content: ""; position: absolute; top: 2px; left: 50%; width: 1px; height: 5px; background: var(--line-2); } .ticks .first { transform: none; } .ticks .first::before { left: 0; } .ticks .last { transform: translateX(-100%); } .ticks .infinity { font-size: 1rem; line-height: 1; } .ticks .last::before { right: 0; left: auto; } .status, .caution { min-height: 1.45em; margin: 6px 0 0; font-variant-numeric: tabular-nums; } .status { color: var(--ink-2); } .caution { color: var(--caution); } /* The controls. */ .panel { display: grid; gap: 22px; } .group { min-width: 0; margin: 0; padding: 0; border: 0; } .group h2, .group legend, .switch { margin: 0 0 8px; padding: 0; font-size: 0.8125rem; font-weight: 600; } .hint { margin: 7px 0 0; color: var(--ink-2); font-size: 0.8125rem; text-wrap: pretty; } .samples { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; } .samples button { aspect-ratio: 16 / 9; padding: 0; overflow: hidden; border: 0; border-radius: 4px; background: var(--line); cursor: pointer; } .samples img { display: block; width: 100%; height: 100%; object-fit: cover; } .samples button:hover { outline: 2px solid var(--line-2); outline-offset: 2px; } .samples button[aria-pressed="true"] { outline: 2px solid var(--accent); outline-offset: 2px; } .samples button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; } .row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 10px; } .button { position: relative; display: inline-flex; align-items: center; justify-content: center; gap: 7px; padding: 7px 12px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface); color: var(--ink); font: inherit; font-weight: 600; cursor: pointer; transition: background-color 0.15s, border-color 0.15s; } .button:hover { border-color: var(--ink-2); } .button:active { background: var(--hover); } .button:disabled { border-color: var(--line); background: var(--hover); color: var(--ink-2); cursor: not-allowed; } .button[aria-pressed="true"] { border-color: var(--ink); background: var(--ink); color: var(--ground); } .button:has(:focus-visible) { outline: 2px solid var(--ink); outline-offset: 2px; } .button svg, .grip svg { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; } .button input { position: absolute; width: 1px; height: 1px; opacity: 0; } .segmented { display: grid; grid-auto-columns: 1fr; grid-auto-flow: column; gap: 2px; padding: 2px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface); } .segmented label { position: relative; } .segmented input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: pointer; } .segmented span { display: flex; align-items: baseline; justify-content: center; gap: 6px; padding: 5px 8px; border-radius: 4px; font-weight: 600; transition: background-color 0.15s, color 0.15s; } .segmented small { color: var(--ink-2); font-size: 0.75rem; font-weight: 400; } .segmented label:hover input:not(:checked, :disabled) + span { background: var(--hover); } .segmented input:checked + span { background: var(--ink); color: var(--ground); } .segmented input:checked + span small { color: inherit; opacity: 0.75; } .segmented input:focus-visible + span { outline: 2px solid var(--ink); outline-offset: 3px; } .segmented input:disabled { cursor: not-allowed; } .segmented input:disabled + span { background: var(--hover); color: var(--ink-2); text-decoration: line-through; cursor: not-allowed; } /* Padded to the height of the other controls, and pulled back by as much, so nothing moves. */ .switch { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: -8px 0; padding: 8px 0; cursor: pointer; } .switch input { position: relative; flex: none; width: 36px; height: 20px; margin: 0; border-radius: 10px; background: var(--off); cursor: pointer; transition: background-color 0.15s; appearance: none; -webkit-appearance: none; } .switch input::after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: var(--on-stage); box-shadow: var(--shadow-knob); transition: transform 0.18s cubic-bezier(0.16, 1, 0.3, 1); } .switch input:checked { background: var(--accent); } .switch input:checked::after { transform: translateX(16px); } .panel[inert] { opacity: 0.5; } /* Photo or video: the choice on top of the panel, and what each offers under it. */ .kinds { margin-bottom: 12px; } .row > :only-child { grid-column: 1 / -1; } .samples.clips { grid-template-columns: repeat(3, 1fr); } .samples button { position: relative; } .samples .length { position: absolute; right: 4px; bottom: 4px; padding: 1px 5px; border-radius: 3px; background: var(--chip); color: var(--on-stage); font-size: 0.6875rem; font-weight: 600; font-variant-numeric: tabular-nums; pointer-events: none; } /* A video's frames, once estimated: play, pause, and go to any of them. */ .transport { display: flex; align-items: center; gap: 12px; margin-top: 10px; } .button.icon { flex: none; width: 34px; height: 34px; padding: 0; } .transport .when-paused, .transport[data-paused] .when-playing { display: none; } .transport[data-paused] .when-paused { display: block; } #scrub { flex: 1; min-width: 0; margin: 0; } #scrub:disabled { opacity: 0.6; } .clock { flex: none; min-width: 11ch; color: var(--ink-2); font-size: 0.8125rem; font-variant-numeric: tabular-nums; text-align: right; } .about { max-width: 70ch; } .about h2 { margin: 6px 0 6px; font-size: 0.9375rem; font-weight: 650; } .about p { margin: 0 0 10px; color: var(--ink-2); text-wrap: pretty; } footer { max-width: 86ch; margin-top: 26px; color: var(--ink-2); font-size: 0.8125rem; } footer p { margin: 0; text-wrap: pretty; } @media (max-width: 860px) { .page { max-width: none; padding: 14px 16px 20px; } main { grid-template-areas: "result" "panel" "about"; grid-template-columns: minmax(0, 1fr); gap: 18px; } .samples { grid-template-columns: repeat(4, 1fr); } .samples.clips { grid-template-columns: repeat(3, 1fr); } } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; } .progress.waiting .bar i { width: 100%; opacity: 0.5; transform: none; animation: none; } } </style> </head> <body> <div class="page"> <header> <h1>Depth Pro 2 on WebGPU</h1> <p class="lede">Depth from a photo, a video or the camera, computed on your GPU. Nothing is uploaded.</p> <nav> <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">Model files</a> <a href="https://huggingface.co/apple/DepthPro2" target="_blank" rel="noopener">Original model</a> <a href="https://arxiv.org/abs/2611.26603" target="_blank" rel="noopener">Paper</a> </nav> </header> <main> <section class="result" aria-label="Result"> <div class="viewer" id="viewer"> <canvas id="depth" width="854" height="480" role="img" aria-label="Depth map: red is near, blue is far"></canvas> <canvas id="photo" width="854" height="480" role="img" aria-label="The photo"></canvas> <div class="divider" id="divider" role="slider" tabindex="0" aria-label="Photo on the left, depth on the right" aria-orientation="horizontal" aria-valuemin="0" aria-valuemax="100" aria-valuenow="100"> <span class="grip"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M6 4.5 2.5 8 6 11.5M10 4.5 13.5 8 10 11.5"/></svg></span> </div> <span class="tag" id="tag-photo">Photo</span> <span class="tag" id="tag-depth">Depth</span> <span class="spot" id="spot" hidden></span> <span class="probe" id="probe" hidden></span> <div class="progress" id="progress" hidden> <span id="progress-text"></span> <div class="bar"><i></i></div> </div> <div class="notice" id="notice" role="alert" hidden> <p id="notice-text"></p> <button class="button" id="notice-action" type="button"></button> </div> </div> <div class="transport" id="transport" hidden> <button class="button icon" id="play" type="button" aria-label="Pause" disabled> <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> <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> </button> <input id="scrub" type="range" min="0" max="0" value="0" step="1" aria-label="Frame" disabled> <span class="clock" id="clock"></span> </div> <div class="scale"> <canvas id="ramp" width="213" height="1" aria-hidden="true"></canvas> <span id="index" hidden></span> <div class="ticks" id="ticks"></div> </div> <p class="status" id="status" role="status"></p> <p class="caution" id="caution" role="alert" hidden></p> <span class="unseen" id="phase" role="status"></span> </section> <aside class="panel" id="panel" aria-label="Settings"> <fieldset class="group"> <legend class="unseen">What to look at</legend> <div class="segmented kinds"> <label><input type="radio" name="kind" value="photo" checked><span>Photo</span></label> <label><input type="radio" name="kind" value="video"><span>Video</span></label> </div> <div class="pane" id="pane-photo"> <div class="samples" id="samples"></div> <div class="row"> <label class="button"> <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> Upload photo <input id="file" type="file" accept="image/*"> </label> </div> <p class="hint">Or drop a photo anywhere on the page. It is cropped to 16:9, the shape the models take.</p> </div> <div class="pane" id="pane-video" hidden> <div class="samples clips" id="clips"></div> <div class="row"> <label class="button"> <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> Upload video <input id="clip-file" type="file" accept="video/*"> </label> <button class="button" id="camera" type="button" aria-pressed="false"> <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> <span id="camera-label">Camera</span> </button> </div> <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> </div> </fieldset> <fieldset class="group"> <legend>Model</legend> <div class="segmented"> <label><input type="radio" name="model" value="s" checked><span>S <small>98 MB</small></span></label> <label><input type="radio" name="model" value="b"><span>B <small>387 MB</small></span></label> </div> <p class="hint">B is sharper and takes about 2.5 times as long.</p> </fieldset> <fieldset class="group"> <legend>Precision</legend> <div class="segmented"> <label><input type="radio" name="precision" value="fp16" checked><span>float16</span></label> <label><input type="radio" name="precision" value="fp32"><span>float32</span></label> </div> <p class="hint" id="precision-hint">float16 is about twice as fast and within a percent or so of float32.</p> </fieldset> <div class="group"> <label class="switch">Depth in meters <input id="metric" type="checkbox" role="switch"></label> <p class="hint">Adds a second model (95 MB) that estimates the camera’s field of view. Without it the depth is relative.</p> </div> </aside> <section class="about" aria-labelledby="about-title"> <h2 id="about-title">How it works</h2> <p> Depth Pro 2 is Apple’s model for metric depth from images and video. This page runs it as LiteRT files with LiteRT.js on WebGPU: photos and videos are processed on your GPU and never uploaded, and the model files stay in this browser for the next visit. </p> <p> Colors show inverse depth, from red for near to blue for far. Photos use the model’s single-image version. Videos and the camera use its video version, in which each frame also attends to the three frames before it, so the depth flickers less from frame to frame. With Depth in meters on, a second model estimates the field of view, and pointing at the picture reads the distance. </p> </section> </main> <footer> <p> Depth Pro 2 is Apple’s model. The files here are unofficial <a href="https://huggingface.co/byoussef/DepthPro2-litert" target="_blank" rel="noopener">LiteRT conversions</a>, not endorsed by Apple, under the <a href="https://huggingface.co/byoussef/DepthPro2-litert/blob/main/LICENSE" target="_blank" rel="noopener">Apple Machine Learning Research Model License</a>: research use only. The sample photos are CC0, from Wikimedia Commons. Of the sample videos, the <a href="https://coverr.co/videos/dogs-horses-and-a-cowboy-smkbjpndal" target="_blank" rel="noopener">horses</a> are from Coverr, and the <a href="https://commons.wikimedia.org/wiki/File:Mum_and_baby_Elephant_walking_toward_us..webm" target="_blank" rel="noopener">elephants</a> (John Gowland) and the <a href="https://commons.wikimedia.org/wiki/File:Wildebeests_at_Grumeti_River.webm" target="_blank" rel="noopener">wildebeests</a> (Bettina May) are <a href="https://creativecommons.org/licenses/by/3.0/" target="_blank" rel="noopener">CC BY 3.0</a>, cut to 8 seconds and re-encoded. </p> </footer> </div> <video id="video" playsinline muted hidden></video> <script type="module"> const LITERT = 'https://cdn.jsdelivr.net/npm/@litertjs/core@2.6.0'; // A fixed revision: what the browser has stored of it stays right. const FILES = 'https://huggingface.co/byoussef/DepthPro2-litert/resolve/d45bcfa0544d8ce5c351b2d5a8069f7a1be999a4/'; // A photo runs the photo file of its size. A video and the camera run the video file, in which // each frame also sees the frames before it. const MODELS = { s: {name: 'S', label: 'model S', file: 'depthpro2-s_480x854.tflite', bytes: 98417420, video: {label: 'model S for video', file: 'depthpro2-s_480x854_w4.tflite', bytes: 99144436}}, b: {name: 'B', label: 'model B', file: 'depthpro2-b_480x854.tflite', bytes: 387092196, video: {label: 'model B for video', file: 'depthpro2-b_480x854_w4.tflite', bytes: 388424320}}, fov: {label: 'the field-of-view model', file: 'depthpro2-fov_480x832.tflite', bytes: 95245968}, }; // What a video model hands from one frame to the next, as inputs and as outputs named next_*. const STATE = ['valid', 'keys', 'values', 'prefixes']; const SAMPLES = [ ['macaques', 'Two macaques'], ['kitchen', 'A kitchen'], ['forest', 'A forest path'], ['mountains', 'A mountain reservoir'], ]; const CLIPS = [ // name, description, seconds ['horses', 'A herd of horses running past the camera', 8], ['elephants', 'An elephant and her calf walking toward the camera', 8], ['wildebeests', 'Wildebeests standing in a river', 8], ]; // A video file is estimated at this many frames a second, over at most its first seconds. const [CLIP_RATE, CLIP_SECONDS] = [10, 10]; const [WIDTH, HEIGHT] = [854, 480]; // the frame the depth models take // The field-of-view model takes the frame resized to 864x480 and cropped to its middle 832 columns. const [FOV_WIDTH, FOV_CROP] = [864, 832]; // As the original code colors it: Turbo from inverse depth 0, infinitely far, to 1.2 times the nearest. const HEADROOM = 1.2; const TURBO = Uint8Array.from(atob( 'MBI7MRVCMhhKNBtRNR5YNiFfNyNlOCZsOSlyOix5Oy9/PDKFPDWLPTeRPjqWPz2cQEChQEOmQUWrQUiwQku1Q066Q1C+Q1PCRFbHRFjLRVvORV7SRWDW' + 'RWPZRmbdRmjgRmvjRm3mRnDoRnPrRnXtRnjwRnryRn30Rn/2RoL4RYT5RYf7RYn8RIz9Q479QpH+QZP+QJb+P5j+Ppv+PJ39O6D8OaL8OKX7Nqj5NKr4' + 'M6z2Ma/1L7HzLbTxK7bvKrntKLvrJr3pJcDmI8LkIcThIMbfHsncHcvaHM3XG8/UGtHSGdPPGNXMGNfKF9nHF9rEF9zCF96/GOC9GOG6GeO4GuS2G+W0' + 'HeexHuivIOmsIuupJOymJ+2jKe6gLO+dL/CaMvGXNfOUOPSRO/SNP/WKQvaHRveDSviATfl8Ufl5Vfp2WftyXftvYfxsZfxoaf1lbf1icf1fdP5ceP5Z' + 'fP5WgP5ThP5Qh/5Ni/5Ljv5Ikv5Glf5EmP5Cm/1Anv0+ofw9pPw7pvs6qfs5rPo3rvk3sfg2s/g1tvc1ufU0u/Q0vvM0wPIzw/Ezxe8zyO4zyu0zzes0' + 'z+o00eg01Oc11uU12OM12uI23eA239424dw349o35dg459c46NU46tM57NE57c8578058Ms68sg688Y69MQ69sI698A5+L45+bw5+bo4+rc3+7U3+7M2' + '/LA1/K40/asz/aky/aYx/aMw/qEv/p4u/pst/pgs/ZUr/ZIp/Y8o/Ywn/Ikm/IYk+4Mj+4Ai+n0g+nof+Xce+HQc93Eb924a9msY9WgX9GUW82MV8mAU' + '8V0T71oR7lgQ7VUP7FIO6lAN6U0N6EsM5kkL5UYK40QK4kIJ4EAI3j4I3TwH2zoH2TgG1zYG1jQF1DIF0jAF0C8Ezi0EyysDySkDxygDxSYCwyQCwCMC' + 'viECux8BuR4BthwBtBsBsRkBrhgBrBYBqRUBphQBoxIBoBEBnRABmg4Blw0BlAwBkQsBjgoBiwkBhwgBhAcBgQYCfQUCegQC'), (character) => character.charCodeAt(0)); const $ = (id) => document.getElementById(id); const viewer = $('viewer'); const video = $('video'); const photo = $('photo').getContext('2d'); const depthContext = $('depth').getContext('2d'); const depthPixels = new ImageData(WIDTH, HEIGHT); // What the photo side shows, and the pixels the models take: made together, so the two sides // of the divider are always of the same moment. const capture = document.createElement('canvas').getContext('2d'); const crop = document.createElement('canvas').getContext('2d', {willReadFrequently: true}); let frame = null; // RGB of the frame, row by row, 0 to 255 const calm = matchMedia('(prefers-reduced-motion: reduce)'); const want = {kind: 'photo', model: 's', precision: 'fp16', metric: false}; // what the controls ask for // The compiled models; a video model with the empty state a video starts from. const loaded = {depth: null, fov: null}; // What the last frame of a video or the camera hands the next: {model, shot, state}. let carried = null; // What each tab last showed, to show again on coming back to it. const shown = {photo: null, video: null}; const held = new Map(); // files downloaded and not compiled yet let litert; let gpu = ''; let transfer = null; // the download in progress let source = null; // what is looked at: a photo or the camera let depth = null; // the depth on screen let stopped = false; // nothing more can run before a reload let resting = 50; // where the divider settles let pointer = null; // the place being probed, as fractions of the picture let standing = ''; // a caution that holds for the whole visit let asked = 0; // the photos asked for so far let ready = false; // the visitor pressed Start, and LiteRT.js is up // ---- Messages ----------------------------------------------------------------------------- function progress(text, fraction) { $('progress').hidden = false; $('progress').classList.toggle('waiting', fraction === undefined); $('progress').style.setProperty('--done', fraction ?? 0); $('progress-text').textContent = text; // Read out once a phase, not at every megabyte. const phase = text.split(':')[0]; if ($('phase').textContent !== phase) $('phase').textContent = phase; document.documentElement.dataset.state = 'busy'; } function settle() { $('progress').hidden = true; $('phase').textContent = ''; document.documentElement.dataset.state = $('notice').hidden ? 'ready' : 'blocked'; } // A message over the picture, with what to do about it; `docked`, a bar that leaves the picture clear. function notify(text, action, act, docked = false) { $('notice').hidden = false; $('notice').classList.toggle('start', docked); $('notice-text').textContent = text; $('notice-action').hidden = !action; $('notice-action').textContent = action ?? ''; $('notice-action').onclick = act ?? null; settle(); } function stop(text) { if (stopped) return; stopped = true; endCamera(); $('panel').inert = true; notify(text, 'Reload the page', () => location.reload()); } // A line under the picture; with no text, back to what holds for the whole visit. function warn(text) { $('caution').textContent = text || standing; $('caution').hidden = !$('caution').textContent; } // ---- The models --------------------------------------------------------------------------- // The GPU this browser gives WebGPU, asked for without loading anything. async function survey() { if (!navigator.gpu) { throw new Error('This browser has no WebGPU, which the models run on. Chrome, Edge and Firefox on a computer have it.'); } let adapter = null; for (let attempt = 0; attempt < 8 && !adapter; attempt++) { adapter = await navigator.gpu.requestAdapter({powerPreference: 'high-performance'}); if (!adapter) await new Promise((resolve) => setTimeout(resolve, 250)); } if (!adapter) { 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.'); } return adapter; } // Loads LiteRT.js and takes its GPU device; returns whether that computes in float16. async function start(adapter) { try { litert = await import(`${LITERT}/+esm`); await litert.loadLiteRt(`${LITERT}/wasm/`); } catch (error) { console.error(error); throw Object.assign(new Error('LiteRT.js did not load. Check the connection, then reload the page.'), {reload: true}); } const device = litert.getWebGpuDevice(); device.lost.then((loss) => { if (loss.reason !== 'destroyed') stop('The GPU stopped responding. Reload the page to start again.'); }); const info = device.adapterInfo ?? adapter.info ?? {}; const makers = {apple: 'an Apple', amd: 'an AMD', intel: 'an Intel', nvidia: 'an NVIDIA', arm: 'an Arm', qualcomm: 'a Qualcomm'}; if (info.isFallbackAdapter || info.architecture === 'swiftshader') gpu = 'a software renderer'; else if (makers[info.vendor]) gpu = `${makers[info.vendor]} GPU`; return device.features.has('shader-f16'); } const keyOf = ({model, precision}) => `${model} ${precision}`; // Whether a source's next frame continues from its last: the camera, and a video file until // all its frames are estimated. const streaming = (shot) => Boolean(shot?.live || (shot?.clip && !shot.clip.done)); const moving = (shot) => Boolean(shot?.live || shot?.clip); // The files the controls and the picture need: the depth model's, its video file for a video // or the camera, and the field-of-view model's when asked for. const needed = (file) => (want.metric && file === MODELS.fov.file) || file === (moving(source) ? MODELS[want.model].video.file : MODELS[want.model].file); // Stops a download, and forgets downloaded files, that are no longer needed. function drop() { if (transfer && !needed(transfer.file)) transfer.controller.abort(); for (const file of held.keys()) if (!needed(file)) held.delete(file); } // The depth model the picture needs: the video file for the camera and for a video file not yet // estimated with this size and precision, the photo file for a photo. None for a video whose // frames are all estimated, and for a still that has its depth already from this size and // precision, as the camera's last frame has once the camera stops. function demand() { const key = keyOf(want); const video = {key: `${key} video`, model: MODELS[want.model].video, video: true}; if (source?.live) return video; if (source?.clip) return source.clip.done && source.clip.key === video.key ? null : video; if (depth && depth.shot === source && (depth.key === key || depth.key === video.key)) return null; return {key, model: MODELS[want.model], video: false}; } class DownloadError extends Error {} // The bytes of a model file: from what this browser stored on an earlier visit, or downloaded // and stored for the next one. async function download(model) { if (held.has(model.file)) return held.get(model.file); const url = FILES + model.file; const megabytes = (bytes) => Math.round(bytes / 1e6); const store = await globalThis.caches?.open('depthpro2-litert').catch(() => null); const stored = await store?.match(url).catch(() => null); if (stored) { progress(`Loading ${model.label}`); const bytes = await stored.arrayBuffer().catch(() => null); if (bytes?.byteLength === model.bytes) { held.set(model.file, new Uint8Array(bytes)); return held.get(model.file); } await store.delete(url).catch(() => {}); } transfer = {file: model.file, controller: new AbortController()}; try { progress(`Downloading ${model.label}: 0 of ${megabytes(model.bytes)} MB`, 0); const response = await fetch(url, {signal: transfer.controller.signal}); if (!response.ok) throw new Error(`${url}: ${response.status}`); const [mine, theirs] = response.body.tee(); if (store) store.put(url, new Response(theirs)).catch(() => {}); else theirs.cancel(); const bytes = new Uint8Array(model.bytes); const reader = mine.getReader(); let received = 0; for (;;) { const {done, value} = await reader.read(); if (done) break; if (received + value.length > bytes.length) throw new Error(`${url}: longer than expected`); bytes.set(value, received); received += value.length; progress(`Downloading ${model.label}: ${megabytes(received)} of ${megabytes(model.bytes)} MB`, received / model.bytes); } if (received !== bytes.length) throw new Error(`${url}: shorter than expected`); held.set(model.file, bytes); return bytes; } catch (error) { if (error?.name === 'AbortError') throw error; console.error(error); throw new DownloadError(model.label); } finally { transfer = null; } } async function compile(model, bytes, precision) { const compiled = await litert.loadAndCompile(bytes, {accelerator: 'webgpu', gpuOptions: {precision}}); held.delete(model.file); return compiled; } // Runs a model of one input and one output; the milliseconds include reading the output back. async function infer(model, values, shape) { const tensor = new litert.Tensor(values, shape); const begun = performance.now(); const [onGpu] = await model.run(tensor); const onHost = await onGpu.moveTo('wasm'); const output = onHost.toTypedArray().slice(); const milliseconds = performance.now() - begun; tensor.delete(); onHost.delete(); return {output, milliseconds}; } // The state of a video that has shown no frame yet: zeros, kept on the GPU for every first // frame of a video or the camera. async function emptyState(compiled) { const empty = {}; for (const {name, shape} of compiled.getInputDetails()) { if (!STATE.includes(name)) continue; const zeros = new litert.Tensor(new Float32Array(shape.reduce((a, b) => a * b, 1)), Array.from(shape)); empty[name] = await zeros.moveTo('webgpu'); } return empty; } const release = (state) => { for (const tensor of Object.values(state ?? {})) tensor.delete(); }; // Lets go of a video's state once nothing can take it up: the camera stopped, the video's frames // are all estimated or another picture is shown, or the model changed. Called only between // runs, never while one could still be reading it. function prune() { if (carried && !(carried.shot === source && streaming(source) && carried.model === loaded.depth)) { release(carried.state); carried = null; } } // Depth of a frame of a video or the camera with the video model, and the milliseconds that // took. The first frame starts from the empty state; each later one from the state the one // before handed on, which stays on the GPU. async function estimate(values, shot) { const model = loaded.depth; const past = carried?.shot === shot && carried.model === model ? carried.state : model.empty; const tensor = new litert.Tensor(values, [1, 3, HEIGHT, WIDTH]); const begun = performance.now(); const outputs = await model.compiled.run({frame: tensor, ...past}); const onHost = await outputs.inverse_depth.moveTo('wasm'); const output = onHost.toTypedArray().slice(); const milliseconds = performance.now() - begun; tensor.delete(); onHost.delete(); const next = Object.fromEntries(STATE.map((name) => [name, outputs[`next_${name}`]])); // A camera stopped, or a video left, while this ran has no next frame to hand the state to. if (streaming(shot) && shot === source) { release(carried?.state); carried = {model, shot, state: next}; } else { release(next); } return {output, milliseconds}; } // ---- Pictures ----------------------------------------------------------------------------- // Draws an image or a video frame scaled to cover width x height, cropped to its center. function cover(context, width, height, image, mirrored) { const canvas = context.canvas; if (canvas.width !== width || canvas.height !== height) Object.assign(canvas, {width, height}); const [w, h] = [image.videoWidth ?? image.width, image.videoHeight ?? image.height]; const scale = Math.max(width / w, height / h); context.imageSmoothingQuality = 'high'; context.fillRect(0, 0, width, height); context.setTransform(mirrored ? -1 : 1, 0, 0, 1, mirrored ? width : 0, 0); context.drawImage(image, (width - w * scale) / 2, (height - h * scale) / 2, w * scale, h * scale); context.setTransform(1, 0, 0, 1, 0, 0); } // For each of `to` pixels along a line of `from`, the first pixel it averages and their weights: // a triangle as wide as the step between pixels, as in Pillow's and PyTorch's antialiased bilinear. function weights(from, to) { const step = from / to; const reach = Math.max(step, 1); return Array.from({length: to}, (unused, index) => { const center = (index + 0.5) * step; const first = Math.max(0, Math.floor(center - reach)); const row = new Float32Array(Math.min(from, Math.ceil(center + reach)) - first); let sum = 0; for (let k = 0; k < row.length; k++) sum += row[k] = Math.max(0, 1 - Math.abs(first + k + 0.5 - center) / reach); return {first, row: row.map((weight) => weight / sum)}; }); } // Resizes pixels of `channels` values each, of which the first three are RGB, to RGB of // toWidth x toHeight. Written out because the original code resizes this way and the field of // view it estimates moves by several percent with a browser's own filter. function resized(pixels, width, height, channels, toWidth, toHeight) { const across = weights(width, toWidth); const narrowed = new Float32Array(3 * toWidth * height); for (let y = 0; y < height; y++) { for (let x = 0; x < toWidth; x++) { const {first, row} = across[x]; let r = 0; let g = 0; let b = 0; for (let k = 0, at = (y * width + first) * channels; k < row.length; k++, at += channels) { r += row[k] * pixels[at]; g += row[k] * pixels[at + 1]; b += row[k] * pixels[at + 2]; } const to = 3 * (y * toWidth + x); narrowed[to] = r; narrowed[to + 1] = g; narrowed[to + 2] = b; } } const down = weights(height, toHeight); const result = new Float32Array(3 * toWidth * toHeight); for (let y = 0; y < toHeight; y++) { const {first, row} = down[y]; for (let x = 0; x < toWidth; x++) { let r = 0; let g = 0; let b = 0; for (let k = 0, at = 3 * (first * toWidth + x); k < row.length; k++, at += 3 * toWidth) { r += row[k] * narrowed[at]; g += row[k] * narrowed[at + 1]; b += row[k] * narrowed[at + 2]; } const to = 3 * (y * toWidth + x); result[to] = r; result[to + 1] = g; result[to + 2] = b; } } return result; } // Takes a still or the camera's current frame: for the photo side at up to twice the frame's // size, and as the frame itself, resized from the middle of the picture in its own pixels. function grab(image, mirrored = false) { const [w, h] = [image.videoWidth ?? image.width, image.videoHeight ?? image.height]; const sharper = Math.min(2, Math.max(1, Math.min(w / WIDTH, h / HEIGHT))); cover(capture, Math.round(WIDTH * sharper), Math.round(HEIGHT * sharper), image, mirrored); const [cropWidth, cropHeight] = [Math.min(w, Math.round(h * WIDTH / HEIGHT)), Math.min(h, Math.round(w * HEIGHT / WIDTH))]; // Beyond 4 times the frame the browser shrinks the picture first, to keep the resize quick. const shrink = Math.min(1, 4 * WIDTH / cropWidth); const [width, height] = [Math.round(cropWidth * shrink), Math.round(cropHeight * shrink)]; if (crop.canvas.width !== width || crop.canvas.height !== height) Object.assign(crop.canvas, {width, height}); crop.imageSmoothingQuality = 'high'; crop.fillRect(0, 0, width, height); crop.setTransform(mirrored ? -1 : 1, 0, 0, 1, mirrored ? width : 0, 0); crop.drawImage(image, Math.floor((w - cropWidth) / 2), Math.floor((h - cropHeight) / 2), cropWidth, cropHeight, 0, 0, width, height); crop.setTransform(1, 0, 0, 1, 0, 0); frame = resized(crop.getImageData(0, 0, width, height).data, width, height, 4, WIDTH, HEIGHT); } function present() { const {width, height} = capture.canvas; if (photo.canvas.width !== width || photo.canvas.height !== height) Object.assign(photo.canvas, {width, height}); photo.drawImage(capture.canvas, 0, 0); } // RGB pixels as the models take them: planes (1, 3, height, columns) in [0, 1], from the // column `left` on. function planes(pixels, width, height, left = 0, columns = width) { const size = columns * height; const values = new Float32Array(3 * size); for (let y = 0; y < height; y++) { for (let x = 0; x < columns; x++) { const from = 3 * (y * width + left + x); const to = y * columns + x; values[to] = pixels[from] / 255; values[size + to] = pixels[from + 1] / 255; values[2 * size + to] = pixels[from + 2] / 255; } } return values; } // What the field-of-view model takes: the frame resized to 864x480, then its middle 832 columns. function fieldOfViewInput() { const widened = resized(frame, WIDTH, HEIGHT, 3, FOV_WIDTH, HEIGHT); return planes(widened, FOV_WIDTH, HEIGHT, (FOV_WIDTH - FOV_CROP) / 2, FOV_CROP); } function paint(inverse, scale) { const pixels = depthPixels.data; const step = 256 / scale; for (let i = 0; i < inverse.length; i++) { const color = 3 * Math.min(255, Math.max(0, (inverse[i] * step) | 0)); pixels[4 * i] = TURBO[color]; pixels[4 * i + 1] = TURBO[color + 1]; pixels[4 * i + 2] = TURBO[color + 2]; pixels[4 * i + 3] = 255; } depthContext.putImageData(depthPixels, 0, 0); } // ---- The work ----------------------------------------------------------------------------- // Does whatever the controls and the photo now ask for that is not done yet. A change that // arrives meanwhile is taken up when this one finishes, or cuts short a download it makes useless. let running = false; let again = false; async function refresh() { again = true; if (running || stopped || !ready) return; $('notice').hidden = true; running = true; while (again && !stopped) { again = false; try { await step(); settle(); } catch (error) { if (error?.name === 'AbortError') continue; endCamera(); if (error instanceof DownloadError) { notify(`Downloading ${error.message} failed. Check the connection, then try again.`, 'Try again', () => { $('notice').hidden = true; refresh(); }); } else { console.error(error); stop('The GPU runtime stopped, most likely out of memory. Reload the page to start again.'); } break; } if (source?.live) { again = true; await new Promise(requestAnimationFrame); } } if (!stopped) prune(); running = false; } async function step() { prune(); drop(); const need = demand(); if (need && loaded.depth?.key !== need.key) { const bytes = await download(need.model); // The picture or the controls changed meanwhile: go around for what they need now. if (demand()?.key !== need.key) return void (again = true); progress(`Preparing ${need.model.label} for your GPU`); // One depth model at a time: LiteRT.js aborts when it holds too many. const old = loaded.depth; loaded.depth = null; if (old) { prune(); release(old.empty); old.compiled.delete(); } const compiled = await compile(need.model, bytes, want.precision); const empty = need.video ? await emptyState(compiled) : null; loaded.depth = {key: need.key, compiled, empty, warm: false}; if (demand()?.key !== need.key) return void (again = true); } if (want.metric && !loaded.fov) { const bytes = await download(MODELS.fov); if (!want.metric) return; progress(`Preparing ${MODELS.fov.label} for your GPU`); // In float32 always: float16 moves its angles, and with them every distance, by up to 2%. loaded.fov = await compile(MODELS.fov, bytes, 'fp32'); } const shot = source; if (!shot) return; // Whether this step is of a camera frame, even if the camera stops while it runs. const live = shot.live; if (live && !video.videoWidth) return; // The model loaded is not the one this picture needs, as when the camera started while it loaded. const wanted = demand(); if (wanted && loaded.depth?.key !== wanted.key) return void (again = true); if (shot.clip) return clipStep(shot, wanted); if (live) grab(video, shot.mirrored); if (want.metric && !shot.focal) await fieldOfView(shot); if (shot !== source) return; if (wanted && (live || depth?.shot !== shot || depth.key !== wanted.key)) { if (!live) progress('Estimating depth'); const input = planes(frame, WIDTH, HEIGHT); const once = () => loaded.depth.empty ? estimate(input, shot) : infer(loaded.depth.compiled, input, [1, 3, HEIGHT, WIDTH]); let run = await once(); if (shot !== source) return; // A camera stopped during its first run shows a later frame now, which goes around as a photo. if (live && !shot.live && depth?.shot !== shot) return void (again = true); show(shot, wanted.key, run, live); if (!loaded.depth.warm && !live) { // The first run of a model also sets up the GPU: the depth is shown, and a second run times it. depth.milliseconds = null; $('progress').hidden = true; render(); run = await once(); if (depth.shot === shot && depth.key === wanted.key) depth.milliseconds = run.milliseconds; } loaded.depth.warm = true; } render(); } // The focal length of the picture, from the field-of-view model on the frame grabbed last. async function fieldOfView(shot) { if (!moving(shot)) progress('Estimating the field of view'); const {output} = await infer(loaded.fov, fieldOfViewInput(), [1, 3, HEIGHT, FOV_CROP]); if (shot !== source) return; // Its second output is the vertical angle, in degrees. shot.focal = 0.5 * HEIGHT / Math.tan(output[1] * Math.PI / 360); } // ---- Video files -------------------------------------------------------------------------- // A video file's next frame: estimated from the frames before it, shown, and kept. Once all are // kept they play in a loop, and nothing more is estimated. async function clipStep(shot, wanted) { const clip = shot.clip; if (!wanted) { if (want.metric && !shot.focal && clip.frames.length) { // Asked for once the frames are kept: the field of view of the first. const first = await createImageBitmap(clip.frames[0].picture); grab(first); first.close(); await fieldOfView(shot); } return render(); } // A new size or precision, or a state let go of: start again from the first frame. const continued = carried?.shot === shot && carried.model === loaded.depth; if (clip.key !== wanted.key || (clip.frames.length && !continued)) { Object.assign(clip, {key: wanted.key, frames: [], milliseconds: [], done: false, at: 0}); } const index = clip.frames.length; const count = clip.times.length; transport(); if (!await seek(clip.element, clip.times[index])) { if (shot !== source) return; // A file the browser cannot read to its end ends where it can. if (!index) return warn('This browser could not read that video.'); clip.times.length = index; warn(`This browser could read only the first ${(index / CLIP_RATE).toFixed(1)} s of that video.`); return finish(shot); } if (shot !== source) return; grab(clip.element); if (want.metric && !shot.focal) await fieldOfView(shot); if (shot !== source) return; const run = await estimate(planes(frame, WIDTH, HEIGHT), shot); if (shot !== source || clip.key !== wanted.key) return; show(shot, wanted.key, run, true); clip.frames.push(await keep(run.output, shot.scale)); clip.milliseconds.push(run.milliseconds); if (shot !== source) return; if (clip.frames.length < count) again = true; else finish(shot); transport(); render(); } // Moves a video file to a time; resolves to whether that frame can now be drawn. A file let go // of meanwhile empties instead of seeking. function seek(element, time) { return new Promise((resolve) => { const failures = ['error', 'emptied', 'abort']; const end = (ok) => { clearTimeout(timer); element.removeEventListener('seeked', yes); for (const type of failures) element.removeEventListener(type, no); resolve(ok); }; const yes = () => end(true); const no = () => end(false); const timer = setTimeout(no, 10000); element.addEventListener('seeked', yes); for (const type of failures) element.addEventListener(type, no); element.currentTime = time; }); } // One estimated frame of a video, kept small: the picture as a JPEG, the inverse depth in 16 bits. async function keep(inverse, scale) { let peak = 0; for (let i = 0; i < inverse.length; i++) if (inverse[i] > peak) peak = inverse[i]; const levels = new Uint16Array(inverse.length); const step = peak > 0 ? 65535 / peak : 0; for (let i = 0; i < inverse.length; i++) levels[i] = Math.max(0, inverse[i]) * step + 0.5; const picture = await new Promise((resolve) => capture.canvas.toBlob(resolve, 'image/jpeg', 0.88)); return {picture, levels, peak, scale}; } // All of a video's frames are kept: they play in a loop, from the first. function finish(shot) { Object.assign(shot.clip, {done: true, at: 0, playing: !calm.matches}); transport(); if (shot.clip.playing) play(shot); else display(shot, 0); } // Shows the kept frames one after another, at the rate they were estimated at. A later call // takes over from an earlier one. async function play(shot) { const clip = shot.clip; const turn = clip.player = {}; clearTimeout(clip.timer); while (clip.player === turn && shot === source && clip.done && clip.playing) { const begun = performance.now(); try { await display(shot, clip.at); } catch (error) { console.error(error); clip.playing = false; transport(); break; } await new Promise((resolve) => { clip.timer = setTimeout(resolve, Math.max(0, 1000 / CLIP_RATE - (performance.now() - begun))); }); if (clip.player === turn && clip.done && clip.playing) clip.at = (clip.at + 1) % clip.frames.length; } } // One kept frame of a video: its picture and its depth, of the same moment. Only the last one // asked for is shown, when several are decoding at once. async function display(shot, index) { const clip = shot.clip; const kept = clip.frames[index]; if (!kept) return; const ticket = clip.ticket = (clip.ticket ?? 0) + 1; const picture = await createImageBitmap(kept.picture); if (shot !== source || clip.frames[index] !== kept || clip.ticket !== ticket) return picture.close(); if (photo.canvas.width !== picture.width || photo.canvas.height !== picture.height) { Object.assign(photo.canvas, {width: picture.width, height: picture.height}); } photo.drawImage(picture, 0, 0); picture.close(); // One buffer for every frame: the depth on screen is always the frame shown. const inverse = clip.inverse ??= new Float32Array(kept.levels.length); const unit = kept.peak / 65535; for (let i = 0; i < inverse.length; i++) inverse[i] = kept.levels[i] * unit; depth = {shot, key: clip.key, inverse, scale: kept.scale, milliseconds: null}; paint(inverse, kept.scale); clip.at = index; if (!shot.revealed) { shot.revealed = true; reveal(); } transport(); render(); } // The bar under a video: how far its estimation is, or where it plays. function transport() { const clip = source?.clip; $('transport').hidden = !clip; if (!clip) return; const count = clip.times.length; const kept = clip.frames.length; $('play').disabled = $('scrub').disabled = !clip.done; $('transport').toggleAttribute('data-paused', !clip.done || !clip.playing); $('play').setAttribute('aria-label', clip.done && clip.playing ? 'Pause' : 'Play'); $('scrub').max = String(Math.max(0, count - 1)); $('scrub').value = String(clip.done ? clip.at : Math.max(0, kept - 1)); $('clock').textContent = clip.done ? `${(clip.at / CLIP_RATE).toFixed(1)} of ${(count / CLIP_RATE).toFixed(1)} s` : kept ? `frame ${kept} of ${count}` : `${count} frames`; $('scrub').setAttribute('aria-valuetext', $('clock').textContent); } // Lets go of a video file that is no longer shown or remembered. function forget(shot) { const clip = shot?.clip; if (!clip) return; Object.assign(clip, {playing: false, done: false, frames: [], inverse: null, player: null}); clearTimeout(clip.timer); clip.element.removeAttribute('src'); clip.element.load(); if (clip.url) URL.revokeObjectURL(clip.url); } function show(shot, key, run, live) { const inverse = run.output; let nearest = 0; for (let i = 0; i < inverse.length; i++) if (inverse[i] > nearest) nearest = inverse[i]; let scale = nearest > 0 ? nearest * HEADROOM : 1; // A camera's colors follow the scene slowly, not frame by frame. if (live && shot.scale) scale = shot.scale + 0.15 * (scale - shot.scale); const now = performance.now(); if (live && shot.shownAt) { const rate = 1000 / (now - shot.shownAt); shot.rate = shot.rate ? shot.rate + 0.3 * (rate - shot.rate) : rate; } Object.assign(shot, {scale, shownAt: now}); depth = {shot, key, inverse, scale, milliseconds: run.milliseconds}; paint(inverse, scale); if (live) present(); if (!shot.revealed) { shot.revealed = true; reveal(); } } // ---- The divider -------------------------------------------------------------------------- let sweep = 0; function split(percent) { const value = Math.min(100, Math.max(0, percent)); viewer.style.setProperty('--split', value); $('divider').setAttribute('aria-valuenow', Math.round(value)); $('tag-photo').hidden = value < 14; $('tag-depth').hidden = value > 86; } // The photo gives way to its depth, from the right edge to where the divider rests. function reveal() { viewer.dataset.depth = ''; cancelAnimationFrame(sweep); if (calm.matches) return split(resting); const begun = performance.now(); const move = (now) => { const part = Math.min(1, Math.max(0, (now - begun) / 900)); split(part === 1 ? resting : 100 + (resting - 100) * (1 - 2 ** (-10 * part))); if (part < 1) sweep = requestAnimationFrame(move); }; sweep = requestAnimationFrame(move); } function drag(percent) { cancelAnimationFrame(sweep); resting = Math.min(100, Math.max(0, percent)); split(resting); } // ---- Reading the depth -------------------------------------------------------------------- const distance = (meters) => meters >= 1000 ? `${(meters / 1000).toFixed(1)} km` : `${meters.toFixed(meters < 10 ? 2 : meters < 100 ? 1 : 0)} m`; // Meters of an inverse depth, for the photo on screen, once its field of view is estimated. function metersOf(inverse) { return want.metric && depth?.shot.focal ? depth.shot.focal / (WIDTH * inverse) : null; } function render() { const current = depth && depth.shot === source ? depth : null; const ticks = $('ticks'); const tick = (at, text, edge) => { const mark = Object.assign(document.createElement('span'), {textContent: text, className: edge ?? ''}); mark.style.left = `${100 * at}%`; ticks.append(mark); }; ticks.replaceChildren(); const nearest = current && metersOf(current.scale / HEADROOM); if (nearest) { // Like a lens's distance scale: even steps of inverse depth, so the far marks crowd toward infinity. const width = ticks.clientWidth || 600; tick(0, distance(nearest), 'first'); let free = 70 / width; for (const meters of [0.1, 0.2, 0.3, 0.5, 1, 2, 3, 5, 10, 20, 30, 50, 100, 200, 500]) { const at = 1 - nearest / meters; if (at < free || at > 1 - 28 / width) continue; tick(at, String(meters)); free = at + 34 / width; } tick(1, '∞', 'last infinity'); } else { tick(0, 'Near', 'first'); tick(1, 'Far', 'last'); } let status = ''; if (current) { const [model, precision] = current.key.split(' '); status = `Model ${MODELS[model].name} in ${precision === 'fp16' ? 'float16' : 'float32'}`; const time = (took) => took < 1000 ? `${Math.round(took)} ms` : `${(took / 1000).toFixed(1)} s`; const clip = current.shot.clip; if (current.shot.live && current.shot.rate) status += `: ${current.shot.rate.toFixed(1)} frames a second`; if (clip) { const sorted = [...clip.milliseconds].sort((a, b) => a - b); const each = sorted[sorted.length >> 1]; // How far estimating is shows under the picture; this line says what it costs. if (clip.done) status += `: ${clip.frames.length} frames`; if (each) status += clip.done ? `, ${time(each)} each` : `: ${time(each)} a frame`; } const took = current.milliseconds; if (!moving(current.shot) && took) status += `: ${time(took)}`; status += gpu ? ` on ${gpu}.` : '.'; if (want.metric && current.shot.focal) { const angle = (pixels) => { const degrees = 2 * Math.atan(pixels / (2 * current.shot.focal)) * 180 / Math.PI; return degrees.toFixed(degrees < 10 ? 1 : 0); }; status += ` Estimated field of view: ${angle(WIDTH)}° by ${angle(HEIGHT)}°.`; } } // Read out when it settles: not for each frame of the camera or of a video being estimated. $('status').setAttribute('aria-live', streaming(current?.shot) ? 'off' : 'polite'); $('status').textContent = status; probe(); } // The depth under the pointer: a mark on the scale, and the distance when it is known. function probe() { const current = depth && depth.shot === source && viewer.dataset.depth !== undefined ? depth : null; viewer.toggleAttribute('data-probing', Boolean(current)); const shown = Boolean(current && pointer); $('index').hidden = $('spot').hidden = !shown; $('probe').hidden = true; if (!shown) return; const column = Math.min(WIDTH - 1, Math.floor(pointer.x * WIDTH)); const row = Math.min(HEIGHT - 1, Math.floor(pointer.y * HEIGHT)); const inverse = Math.max(0, current.inverse[row * WIDTH + column]) || 0; $('index').style.left = `${100 * Math.max(0, 1 - inverse / (current.scale / HEADROOM))}%`; const box = viewer.getBoundingClientRect(); const [x, y] = [pointer.x * box.width, pointer.y * box.height]; $('spot').style.transform = `translate(${x}px, ${y}px)`; const meters = metersOf(inverse); if (meters === null) return; const label = $('probe'); label.hidden = false; label.textContent = Number.isFinite(meters) ? distance(meters) : '∞'; const left = x + 14 + label.offsetWidth > box.width ? x - 14 - label.offsetWidth : x + 14; const top = y - 12 - label.offsetHeight < 0 ? y + 14 : y - 12 - label.offsetHeight; label.style.transform = `translate(${left}px, ${top}px)`; } // ---- What is looked at -------------------------------------------------------------------- // Stops the camera. Stopped with its button, its last frame stays as a still with its depth; // `still` is false when another picture takes its place. function endCamera(still = false) { if (!source?.live) return; source.live = false; // Stopped before its first depth, the camera leaves the frame it shows now, estimated as a photo. if (still && depth?.shot !== source && video.videoWidth) { grab(video, source.mirrored); present(); } for (const track of video.srcObject?.getTracks() ?? []) track.stop(); video.srcObject = null; $('camera').setAttribute('aria-pressed', 'false'); $('camera-label').textContent = 'Camera'; $('tag-photo').textContent = 'Photo'; render(); } function mark(sample) { for (const button of document.querySelectorAll('.samples button')) { button.setAttribute('aria-pressed', String(button.dataset.sample === sample)); } } function look(next, sample) { endCamera(); // The tab shows one video at a time: one it no longer shows is let go of. const before = shown[want.kind]; if (before?.clip && before.clip !== next.clip) forget(before); source = Object.assign(next, {sample}); shown[want.kind] = source; drop(); pointer = null; cancelAnimationFrame(sweep); delete viewer.dataset.depth; split(100); mark(sample); warn(''); $('tag-photo').textContent = next.live ? 'Camera' : next.clip ? 'Video' : 'Photo'; $('photo').setAttribute('aria-label', next.live ? 'The camera' : next.clip ? 'The video' : 'The photo'); transport(); render(); refresh(); } // Opens a photo. `before` runs once it is readable, just before it is shown. async function open(blob, sample, turn = ++asked, before = null) { let image; try { image = await createImageBitmap(blob, {imageOrientation: 'from-image'}); } catch { return warn('This browser cannot read that file as a photo.'); } if (turn !== asked) return image.close(); before?.(); grab(image); present(); image.close(); // An uploaded photo keeps its file, to show again on coming back to the tab. look({blob: sample ? null : blob}, sample); } async function choose(sample) { const turn = ++asked; mark(sample); try { const response = await fetch(`samples/${sample}.jpg`); if (!response.ok) throw new Error(response.status); await open(await response.blob(), sample, turn); } catch { if (turn === asked) mark(source?.sample); warn('That sample photo did not load.'); } } // Opens a video file: its first frame shows at once, and its frames are estimated from there. // `before` runs once it is readable, just before it is shown. async function openClip(url, sample, owned = false, turn = ++asked, before = null) { const element = Object.assign(document.createElement('video'), {muted: true, playsInline: true, preload: 'auto'}); const readable = await new Promise((resolve) => { setTimeout(() => resolve(false), 20000); element.addEventListener('loadeddata', () => resolve(true), {once: true}); element.addEventListener('error', () => resolve(false), {once: true}); element.src = url; }); let duration = element.duration; // A file that does not say how long it is, as a browser recording, says so once sought to its end. if (readable && !Number.isFinite(duration)) { await seek(element, 1e7); duration = element.duration; } const times = readable && element.videoWidth && Number.isFinite(duration) && duration > 0 ? Array.from({length: Math.max(1, Math.round(Math.min(CLIP_SECONDS, duration) * CLIP_RATE))}, (unused, index) => Math.min(Math.max(0, duration - 0.05), index / CLIP_RATE + 0.01)) : null; if (times && turn === asked && await seek(element, times[0]) && turn === asked) { before?.(); grab(element); present(); const clip = {element, url: owned ? url : null, times, frames: [], milliseconds: [], key: null, done: false, at: 0}; look({clip}, sample); if (element.videoHeight > element.videoWidth) warn('A portrait video is cropped to the 16:9 band across its middle.'); return; } element.removeAttribute('src'); if (owned) URL.revokeObjectURL(url); if (turn !== asked) return; mark(source?.sample); warn(sample ? 'That sample video did not load.' : 'This browser cannot play that video file.'); } function chooseClip(sample) { // The video already shown plays again from its start; its frames stay. if (source?.clip && source.sample === sample) { const clip = source.clip; if (clip.done) { Object.assign(clip, {at: 0, playing: true}); transport(); play(source); } return; } mark(sample); // Fetched whole, so that the video is of this page's origin: the Space serves it from another, // and the browser does not let a page read the pixels of a video from elsewhere. const turn = ++asked; fetch(`samples/${sample}.mp4`) .then((response) => response.ok ? response.blob() : Promise.reject(new Error(response.status))) .then((blob) => { if (turn === asked) openClip(URL.createObjectURL(blob), sample, true, turn); }) .catch(() => { if (turn !== asked) return; mark(source?.sample); warn('That sample video did not load.'); }); } // Coming back to a tab shows what it showed last: a video with its kept frames, or the photo. function restore(kind) { const back = shown[kind]; if (kind === 'photo') { if (back?.blob) return open(back.blob); return choose(back?.sample ?? SAMPLES[0][0]); } if (!back?.clip) return chooseClip(CLIPS[0][0]); ++asked; const clip = back.clip; // Frames half estimated have lost the state they need: those start again. const restarted = !clip.done && clip.frames.length > 0; if (!clip.done) Object.assign(clip, {frames: [], milliseconds: [], key: null, at: 0}); look({clip}, back.sample); if (restarted) warn('The video is estimated again from its first frame: leaving it stopped the frames before from carrying over.'); if (clip.done) { clip.playing = !calm.matches; if (clip.playing) play(source); else display(source, clip.at); return; } const shot = source; seek(clip.element, clip.times[0]).then((ok) => { if (ok && shot === source && !clip.frames.length) { grab(clip.element); present(); } }); } // Photo or video: each has its own samples, upload and models. function switchKind(kind, back = true) { if (want.kind === kind) return; want.kind = kind; document.querySelector(`input[name="kind"][value="${kind}"]`).checked = true; $('pane-photo').hidden = kind !== 'photo'; $('pane-video').hidden = kind !== 'video'; sizes(); if (back) restore(kind); if (!ready && adapter && !booting && !stopped) invite(); } // The sizes the model choice shows: of the photo files or of the video files. function sizes() { for (const letter of ['s', 'b']) { const file = want.kind === 'video' ? MODELS[letter].video : MODELS[letter]; document.querySelector(`input[name="model"][value="${letter}"] + span small`).textContent = `${Math.round(file.bytes / 1e6)} MB`; } } // A file dropped, pasted or picked: a photo goes to the photo tab, a video to the video tab. function take(file) { if (!file || stopped) return; // The tab changes only once the file turns out readable. if (file.type.startsWith('video/')) { openClip(URL.createObjectURL(file), undefined, true, ++asked, () => switchKind('video', false)); } else { open(file, undefined, ++asked, () => switchKind('photo', false)); } } // Until its first depth arrives, the camera shows as it comes. function preview() { if (!source?.live || viewer.dataset.depth !== undefined) return; if (video.videoWidth) cover(photo, photo.canvas.width, photo.canvas.height, video, source.mirrored); requestAnimationFrame(preview); } let starting = false; async function camera() { if (source?.live) { endCamera(true); drop(); return refresh(); } if (starting) return; starting = true; $('camera-label').textContent = 'Starting'; const turn = ++asked; let stream; let failure; try { stream = await navigator.mediaDevices.getUserMedia({ video: {facingMode: {ideal: 'environment'}, width: {ideal: 1280}, height: {ideal: 720}}, }); // A photo picked while the browser asked for permission wins. if (turn === asked) { video.srcObject = stream; await video.play(); if (!video.videoWidth) throw new Error('The camera gave no picture.'); } } catch (error) { failure = error; } starting = false; $('camera-label').textContent = 'Camera'; if (failure || turn !== asked) { for (const track of stream?.getTracks() ?? []) track.stop(); if (stream && video.srcObject === stream) video.srcObject = null; if (failure) { warn(failure.name === 'NotAllowedError' ? 'The camera is blocked for this page. Allow it in the browser’s site settings, then press Camera again.' : 'No camera could be started.'); } return; } // A camera that faces its user shows them as a mirror does. const mirrored = stream.getVideoTracks()[0].getSettings().facingMode !== 'environment'; grab(video, mirrored); present(); look({live: true, mirrored}); $('camera').setAttribute('aria-pressed', 'true'); $('camera-label').textContent = 'Stop camera'; $('tag-photo').textContent = 'Camera'; preview(); } // ---- Controls ----------------------------------------------------------------------------- function changed() { drop(); render(); if (ready) refresh(); else if (adapter && !booting && !stopped) invite(); } for (const [sample, label] of SAMPLES) { const button = Object.assign(document.createElement('button'), {type: 'button'}); button.dataset.sample = sample; button.setAttribute('aria-pressed', 'false'); button.append(Object.assign(new Image(), {src: `samples/${sample}-thumb.jpg`, alt: label, width: 320, height: 180})); button.addEventListener('click', () => choose(sample)); $('samples').append(button); } for (const [sample, label, seconds] of CLIPS) { const button = Object.assign(document.createElement('button'), {type: 'button'}); button.dataset.sample = sample; button.setAttribute('aria-pressed', 'false'); button.append( Object.assign(new Image(), {src: `samples/${sample}-thumb.jpg`, alt: label, width: 320, height: 180}), Object.assign(document.createElement('span'), {className: 'length', textContent: `0:${String(seconds).padStart(2, '0')}`})); button.addEventListener('click', () => chooseClip(sample)); $('clips').append(button); } for (const input of document.querySelectorAll('input[name="kind"]')) { input.addEventListener('change', () => switchKind(input.value)); } $('play').addEventListener('click', () => { const clip = source?.clip; if (!clip?.done) return; clip.playing = !clip.playing; transport(); if (clip.playing) play(source); }); $('scrub').addEventListener('input', () => { const clip = source?.clip; if (!clip?.done) return; clip.playing = false; display(source, Number($('scrub').value)); }); $('clip-file').addEventListener('change', () => { take($('clip-file').files[0]); $('clip-file').value = ''; }); for (const input of document.querySelectorAll('input[name="model"], input[name="precision"]')) { input.addEventListener('change', () => { want[input.name] = input.value; changed(); }); } $('metric').addEventListener('change', () => { want.metric = $('metric').checked; changed(); }); $('file').addEventListener('change', () => { const [file] = $('file').files; if (file) open(file); $('file').value = ''; }); if (navigator.mediaDevices?.getUserMedia) $('camera').addEventListener('click', camera); else $('camera').disabled = true; // A photo or a video dropped or pasted anywhere. const dropped = (transferred) => [...(transferred?.files ?? [])].find((file) => /^(image|video)\//.test(file.type)); addEventListener('dragover', (event) => { event.preventDefault(); viewer.classList.add('dropping'); }); addEventListener('dragleave', (event) => { if (!event.relatedTarget) viewer.classList.remove('dropping'); }); addEventListener('drop', (event) => { event.preventDefault(); viewer.classList.remove('dropping'); take(dropped(event.dataTransfer)); }); addEventListener('paste', (event) => { take(dropped(event.clipboardData)); }); // Dragging sideways anywhere on the picture moves the divider; pointing reads the depth. let press = null; const place = (event) => { const box = viewer.getBoundingClientRect(); return { x: Math.min(1, Math.max(0, (event.clientX - box.left) / box.width)), y: Math.min(1, Math.max(0, (event.clientY - box.top) / box.height)), }; }; viewer.addEventListener('pointerdown', (event) => { if (viewer.dataset.depth === undefined || event.button !== 0 || event.target.closest('.notice')) return; const onDivider = Boolean(event.target.closest('.divider')); press = {id: event.pointerId, x: event.clientX, dragging: onDivider}; viewer.setPointerCapture(event.pointerId); pointer = onDivider ? null : place(event); probe(); }); viewer.addEventListener('pointermove', (event) => { if (press?.id === event.pointerId) { if (Math.abs(event.clientX - press.x) > 5) press.dragging = true; if (press.dragging) { pointer = null; probe(); return drag(100 * place(event).x); } } if (event.pointerType !== 'mouse' && !press) return; pointer = event.target.closest('.divider, .notice') ? null : place(event); probe(); }); for (const type of ['pointerup', 'pointercancel']) { viewer.addEventListener(type, (event) => { if (press?.id === event.pointerId) press = null; }); } viewer.addEventListener('pointerleave', (event) => { if (event.pointerType !== 'mouse' || press) return; pointer = null; probe(); }); $('divider').addEventListener('keydown', (event) => { const moves = {ArrowLeft: -2, ArrowRight: 2, ArrowDown: -2, ArrowUp: 2, PageDown: -10, PageUp: 10, Home: -100, End: 100}; if (!(event.key in moves)) return; event.preventDefault(); drag(resting + moves[event.key] * (event.shiftKey ? 5 : 1)); }); new ResizeObserver(render).observe($('ticks')); // ---- Start -------------------------------------------------------------------------------- const ramp = $('ramp').getContext('2d'); const colors = ramp.createImageData(213, 1); for (let i = 0; i < 213; i++) colors.data.set([...TURBO.subarray(3 * (212 - i), 3 * (213 - i)), 255], 4 * i); ramp.putImageData(colors, 0, 0); render(); sizes(); choose(SAMPLES[0][0]); // Nothing to choose: without the shader-f16 feature LiteRT computes in float32. function float32Only() { want.precision = 'fp32'; document.querySelector('input[value="fp16"]').disabled = true; document.querySelector('input[value="fp32"]').checked = true; $('precision-hint').textContent = 'This GPU or browser has no float16 shaders, so the models run in float32.'; } function fail(error) { stopped = true; $('panel').inert = true; notify(error.message, error.reload ? 'Reload the page' : undefined, () => location.reload()); } // Until the visitor starts, nothing is loaded. The bar over the picture says what starting takes, // for the model and the options chosen so far. let adapter = null; let invited = 0; let booting = false; async function invite() { const turn = ++invited; const depthModel = want.kind === 'video' ? MODELS[want.model].video : MODELS[want.model]; const models = [depthModel, ...(want.metric ? [MODELS.fov] : [])]; const store = await globalThis.caches?.open('depthpro2-litert').catch(() => null); const missing = []; for (const model of models) { if (!await store?.match(FILES + model.file).catch(() => null)) missing.push(model); } if (turn !== invited || ready || booting || stopped) return; const named = (list) => list.map((model) => model.label).join(' and ').replace(/^./, (first) => first.toUpperCase()); const megabytes = Math.round(missing.reduce((sum, model) => sum + model.bytes, 0) / 1e6); const text = missing.length ? `${named(missing)} ${missing.length > 1 ? 'are' : 'is'} a ${megabytes} MB download` + (navigator.connection?.saveData ? ', and data saving is on.' : '.') : `${named(models)} ${models.length > 1 ? 'are' : 'is'} stored in this browser: nothing to download.`; notify(text, 'Start', begin, true); } async function begin() { if (ready || booting) return; booting = true; $('notice').hidden = true; try { progress('Starting'); const float16 = await start(adapter); if (!float16 && want.precision === 'fp16') float32Only(); ready = true; refresh(); } catch (error) { fail(error); } } // A browser that finds no GPU takes two seconds to say so: past a moment, the wait shows. const waiting = setTimeout(() => progress('Checking the GPU'), 400); try { adapter = await survey().finally(() => clearTimeout(waiting)); if (!adapter.features.has('shader-f16')) float32Only(); if (/AppleWebKit/.test(navigator.userAgent) && !/Chrome|Chromium|Edg\//.test(navigator.userAgent)) { standing = 'Safari’s WebGPU gives wrong depth with these models (seen in Safari 27.2). Chrome and Firefox on a computer work.'; warn(''); } invite(); } catch (error) { fail(error); } </script> </body> </html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Depth Pro 2 on WebGPU</title>
<meta name="description" content="Depth from a photo, a video or the camera, computed in your browser on WebGPU with LiteRT.js.">
<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">
<style>
/* Hallmark · checked: 2026-11-24 · genre: modern-minimal (inferred)
* floor: 0 FAIL · fixed: 7 (10a, 26a, 26b, 34, 39a, 48, F1) · structural: 0 printed
* finish-review: subagent · 3 findings · 3 resolved
* built: the project · shape: app screen · redesign: polish · v2.0.0 */
/* Hallmark · dismissed 25 · the start bar holds one sentence beside its button, a caption and not running prose */
/* Hallmark · waive 28b · the video is hidden and only feeds the camera's frames to a canvas, never the LCP · a camera stream has no poster frame to show before the visitor turns the camera on */
:root {
color-scheme: light dark;
--ground: #f2f4f6;
--surface: #ffffff;
--hover: #e6e9ed;
--ink: #15181b;
--ink-2: #4b535a;
--line: #d3d8dd;
--line-2: #aab1b9;
--accent: #c2410c;
--accent-ink: #ffffff;
--caution: #8a4b00;
--off: #6b747d;
--radius: 6px;
/* What lies over the picture is the same in both themes: the picture is its ground. */
--stage: #0c0e10;
--on-stage: #ffffff;
--on-stage-ink: #15181b;
--scrim: rgb(12 14 16 / 0.8);
--chip: rgb(12 14 16 / 0.74);
--chip-solid: rgb(12 14 16 / 0.88);
--track: rgb(255 255 255 / 0.22);
--shadow-edge: 0 0 0 1px rgb(0 0 0 / 0.28);
--shadow-knob: 0 1px 2px rgb(0 0 0 / 0.3);
--shadow-lift: 0 1px 2px rgb(0 0 0 / 0.3), 0 4px 12px rgb(0 0 0 / 0.28);
--shadow-label: 0 1px 2px rgb(0 0 0 / 0.3), 0 3px 10px rgb(0 0 0 / 0.25);
--shadow-spot: 0 0 0 1px rgb(0 0 0 / 0.5);
--ring-stage: 0 0 0 2px #15181b, 0 0 0 4px #ffffff;
}
@media (prefers-color-scheme: dark) {
:root {
--ground: #111315;
--surface: #1b1e21;
--hover: #262a2e;
--ink: #eceef0;
--ink-2: #aab1b8;
--line: #2b3035;
--line-2: #4a525a;
--accent: #ff8f3d;
--accent-ink: #15181b;
--caution: #ffb86b;
}
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
.unseen { position: absolute; width: 1px; height: 1px; overflow: hidden; white-space: nowrap; clip-path: inset(50%); }
::selection { background: color-mix(in srgb, var(--accent) 28%, transparent); }
html { overflow-x: clip; background: var(--ground); accent-color: var(--accent); caret-color: var(--accent); }
body {
margin: 0;
overflow-x: clip;
background: var(--ground);
color: var(--ink);
font: 0.875rem/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
-webkit-font-smoothing: antialiased;
}
a { color: inherit; text-decoration-color: var(--line-2); text-decoration-thickness: 1px; text-underline-offset: 3px; }
a:hover { text-decoration-color: currentColor; }
:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
/* The page is no wider than what keeps the picture inside the window. */
.page {
max-width: min(1240px, max(780px, calc((100dvh - 190px) * 854 / 480 + 368px)));
margin: 0 auto;
padding: 18px 24px 24px;
}
header { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 16px; margin-bottom: 14px; }
h1 { margin: 0; font-size: 1.125rem; font-weight: 650; letter-spacing: -0.01em; text-wrap: balance; }
.lede { flex: 1 1 30ch; margin: 0; color: var(--ink-2); text-wrap: pretty; }
header nav { display: flex; gap: 16px; }
main {
display: grid;
grid-template-areas: "result panel" "about panel";
grid-template-columns: minmax(0, 1fr) 296px;
gap: 24px;
align-items: start;
}
.result { grid-area: result; min-width: 0; }
.panel { grid-area: panel; }
.about { grid-area: about; }
/* The picture: depth underneath, the photo on top of it, clipped at the divider. */
.viewer {
--split: 100;