File size: 51,525 Bytes
0c0b8d6
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
 
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
 
 
8ddb12f
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
 
 
8ddb12f
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
3caa2b4
 
 
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
 
8ddb12f
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
 
 
 
8ddb12f
 
3caa2b4
8ddb12f
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
3caa2b4
8ddb12f
 
 
 
3caa2b4
 
 
 
 
 
 
 
 
8ddb12f
 
3caa2b4
 
 
 
8ddb12f
3caa2b4
8ddb12f
 
 
 
3caa2b4
 
 
 
 
 
8ddb12f
3caa2b4
 
 
 
 
8ddb12f
3caa2b4
 
 
 
 
 
 
8ddb12f
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3caa2b4
8ddb12f
 
 
0c0b8d6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
<!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 single photo, 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>
  :root {
    color-scheme: light dark;
    --ground: #f2f4f6;
    --surface: #ffffff;
    --hover: #e6e9ed;
    --ink: #15181b;
    --ink-2: #4b535a;
    --line: #d3d8dd;
    --line-2: #aab1b9;
    --accent: #c2410c;
    --caution: #8a4b00;
    --off: #6b747d;
    --radius: 6px;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --ground: #111315;
      --surface: #1b1e21;
      --hover: #262a2e;
      --ink: #eceef0;
      --ink-2: #aab1b8;
      --line: #2b3035;
      --line-2: #4a525a;
      --accent: #ff8f3d;
      --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 { background: var(--ground); }
  body {
    margin: 0;
    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; }
  .lede { flex: 1 1 30ch; margin: 0; color: var(--ink-2); }
  header nav { display: flex; gap: 16px; }
  main { display: grid; grid-template-columns: minmax(0, 1fr) 296px; gap: 24px; align-items: start; }

  /* 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: #0c0e10;
    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: #fff;
    box-shadow: 0 0 0 1px rgb(0 0 0 / 0.28);
  }
  .grip {
    position: relative;
    display: grid;
    place-items: center;
    width: 34px;
    height: 34px;
    border-radius: 50%;
    background: #fff;
    color: #15181b;
    box-shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 4px 12px rgb(0 0 0 / 0.28);
  }
  .divider:focus-visible .grip { box-shadow: 0 0 0 2px #15181b, 0 0 0 4px #fff; }
  .viewer:not([data-depth]) .divider, .viewer:not([data-depth]) #tag-depth { display: none; }
  .tag {
    position: absolute;
    bottom: 10px;
    padding: 3px 8px;
    border-radius: 4px;
    background: rgb(12 14 16 / 0.74);
    color: #fff;
    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: #fff;
    color: #15181b;
    font-size: 0.8125rem;
    font-weight: 600;
    font-variant-numeric: tabular-nums;
    white-space: nowrap;
    box-shadow: 0 1px 2px rgb(0 0 0 / 0.3), 0 3px 10px rgb(0 0 0 / 0.25);
  }
  .spot {
    width: 9px;
    height: 9px;
    margin: -4.5px 0 0 -4.5px;
    border: 1.5px solid #fff;
    border-radius: 50%;
    box-shadow: 0 0 0 1px rgb(0 0 0 / 0.5);
  }
  .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: rgb(12 14 16 / 0.88);
    color: #fff;
    font-size: 0.8125rem;
    font-variant-numeric: tabular-nums;
    transform: translateX(-50%);
  }
  .bar { height: 3px; margin-top: 7px; overflow: hidden; border-radius: 2px; background: rgb(255 255 255 / 0.22); }
  .bar i { display: block; width: var(--done, 0%); height: 100%; border-radius: 2px; background: #fff; transition: width 0.15s linear; }
  .progress.waiting .bar i { width: 35%; 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: rgb(12 14 16 / 0.8);
    color: #fff;
    text-align: center;
  }
  .notice p { max-width: 44ch; margin: 0; font-size: 0.9375rem; text-wrap: balance; }
  .notice .button { border-color: #fff; background: #fff; color: #15181b; }

  /* 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; }
  .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[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 { opacity: 0.45; }
  .switch { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 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: #fff;
    box-shadow: 0 1px 2px rgb(0 0 0 / 0.3);
    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; }
  footer { max-width: 86ch; margin-top: 26px; color: var(--ink-2); font-size: 0.8125rem; }
  footer p { margin: 0; }

  @media (max-width: 860px) {
    .page { max-width: none; padding: 14px 16px 20px; }
    main { grid-template-columns: minmax(0, 1fr); gap: 18px; }
    .samples { grid-template-columns: repeat(4, 1fr); }
  }
  @media (prefers-reduced-motion: reduce) {
    *, *::before, *::after { transition: none !important; }
    .progress.waiting .bar i { width: 100%; opacity: 0.5; animation: none; }
  }
</style>
</head>
<body>
<div class="page">
  <header>
    <h1>Depth Pro 2 on WebGPU</h1>
    <p class="lede">Depth from a single photo, computed in this browser on your GPU. Photos stay on your device.</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 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="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">
      <section class="group">
        <h2>Photo</h2>
        <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
            <input id="file" type="file" accept="image/*">
          </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">Or drop a photo anywhere on the page. It is cropped to 16:9, the shape the models take.</p>
      </section>

      <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>
  </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.
    </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/85da0e06b4f3d2a733c84d4527ab45e235648654/';
  const MODELS = {
    s: {name: 'S', label: 'model S', file: 'depthpro2-s_480x854.tflite', bytes: 98344368},
    b: {name: 'B', label: 'model B', file: 'depthpro2-b_480x854.tflite', bytes: 387119408},
    fov: {label: 'the field-of-view model', file: 'depthpro2-fov_480x832.tflite', bytes: 95280716},
  };
  const SAMPLES = [
    ['macaques', 'Two macaques'], ['kitchen', 'A kitchen'], ['forest', 'A forest path'], ['mountains', 'A mountain reservoir'],
  ];
  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 = {model: 's', precision: 'fp16', metric: false};  // what the controls ask for
  const loaded = {depth: null, fov: null};  // the compiled models
  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;  // LiteRT.js is up, and the visitor agreed to the download where asked

  // ---- Messages -----------------------------------------------------------------------------

  function progress(text, fraction) {
    $('progress').hidden = false;
    $('progress').classList.toggle('waiting', fraction === undefined);
    $('progress').style.setProperty('--done', `${100 * (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.
  function notify(text, action, act) {
    $('notice').hidden = false;
    $('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 ---------------------------------------------------------------------------

  async function start() {
    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.');
    }
    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}`;
  const needed = (file) => file === MODELS[want.model].file || (want.metric && file === MODELS.fov.file);

  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};
  }

  // ---- 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);
      }
    }
    running = false;
  }

  async function step() {
    const key = keyOf(want);
    if (loaded.depth?.key !== key) {
      const model = MODELS[want.model];
      const bytes = await download(model);
      if (keyOf(want) !== key) return;
      progress(`Preparing ${model.label} for your GPU`);
      // One depth model at a time: LiteRT.js aborts when it holds too many.
      loaded.depth?.compiled.delete();
      loaded.depth = null;
      loaded.depth = {key, compiled: await compile(model, bytes, want.precision), warm: false};
      if (keyOf(want) !== key) return;
    }
    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;
    if (live) grab(video, shot.mirrored);
    if (want.metric && !shot.focal) {
      if (!live) 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);
    }
    if (live || depth?.shot !== shot || depth.key !== key) {
      if (!live) progress('Estimating depth');
      const input = planes(frame, WIDTH, HEIGHT);
      let run = await infer(loaded.depth.compiled, input, [1, 3, HEIGHT, WIDTH]);
      if (shot !== source) return;
      show(shot, 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 infer(loaded.depth.compiled, input, [1, 3, HEIGHT, WIDTH]);
        if (depth.shot === shot && depth.key === key) depth.milliseconds = run.milliseconds;
      }
      loaded.depth.warm = true;
    }
    render();
  }

  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'}`;
      if (current.shot.live && current.shot.rate) status += `: ${current.shot.rate.toFixed(1)} frames a second`;
      const took = current.milliseconds;
      if (!current.shot.live && took) status += took < 1000 ? `: ${Math.round(took)} ms` : `: ${(took / 1000).toFixed(1)} s`;
      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)}°.`;
      }
    }
    $('status').setAttribute('aria-live', current?.shot.live ? '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 --------------------------------------------------------------------

  function endCamera() {
    if (!source?.live) return;
    // The last frame stays, as a still, with its depth.
    source.live = false;
    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 $('samples').children) button.setAttribute('aria-pressed', String(button.dataset.sample === sample));
  }

  function look(next, sample) {
    endCamera();
    source = Object.assign(next, {sample});
    pointer = null;
    cancelAnimationFrame(sweep);
    delete viewer.dataset.depth;
    split(100);
    mark(sample);
    warn('');
    render();
    refresh();
  }

  async function open(blob, sample, turn = ++asked) {
    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();
    grab(image);
    present();
    image.close();
    look({}, 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.');
    }
  }

  // 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) return endCamera();
    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() {
    if (transfer && !needed(transfer.file)) transfer.controller.abort();
    for (const file of held.keys()) if (!needed(file)) held.delete(file);
    render();
    refresh();
  }

  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 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 dropped or pasted anywhere.
  const dropped = (transferred) => [...(transferred?.files ?? [])].find((file) => file.type.startsWith('image/'));
  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');
    const file = dropped(event.dataTransfer);
    if (file && !stopped) open(file);
  });
  addEventListener('paste', (event) => {
    const file = dropped(event.clipboardData);
    if (file && !stopped) open(file);
  });

  // 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();
  choose(SAMPLES[0][0]);

  try {
    progress('Starting');
    const float16 = await start();
    if (!float16) {
      // Nothing to choose: without the shader-f16 feature LiteRT computes in float32.
      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.';
    }
    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('');
    }
    if (navigator.connection?.saveData) {
      notify(`This runs after a ${Math.round(MODELS.s.bytes / 1e6)} MB download, and data saving is on.`, 'Download and run', () => {
        $('notice').hidden = true;
        ready = true;
        refresh();
      });
    } else {
      ready = true;
      refresh();
    }
  } catch (error) {
    stopped = true;
    $('panel').inert = true;
    notify(error.message, error.reload ? 'Reload the page' : undefined, () => location.reload());
  }
</script>
</body>
</html>