File size: 90,995 Bytes
5020d28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
// QR Scan Difficulty. Every number on the page is computed here from data/site.json.
const SVGNS = 'http://www.w3.org/2000/svg';
const PILE_LO = -6; // codes every scanner read at every resolution
const PILE_HI = 106; // codes no scanner read at any resolution
const X_MIN = -12;
const X_MAX = 112;
const RELIABLE = 0.9; // a group of codes counts as read by a scanner that reads 9 in 10 of them
const BASE_FRAME = 1280; // a typical phone camera image; the default everywhere
const LADDER_WINDOW = 360; // a factor picture's usual window of the camera image (site.json gives each ladder's own)
// Android Settings' Wi-Fi QR scanner: QrCamera, which decodes with ZXing (AOSP source)
const ANDROID_SOURCE = 'https://cs.android.com/android/_/android/platform/frameworks/base/+/2ecfdb1d2dd832c637aacfa15c257822b94f10b1:packages/SettingsLib/src/com/android/settingslib/qrcode/QrCamera.java;bpv=1;bpt=0';
// Smartphones in the world (not our data; each figure quoted from its publisher, checked 2026-10-27)
const WORLD_PHONES = {
  // unique people using a smartphone of their own to go online, end of 2025 (p. 32)
  people: { billions: 4.6, share: 56, source: 'GSMA, 2026', url: 'https://www.gsma.com/somic/wp-content/uploads/2026/09/The-State-of-Mobile-Internet-Connectivity-2026.pdf' },
  // Active smartphones by brand, 2025. Its text: "Nearly one in four active smartphones is an iPhone, while nearly one in
  // five is a Samsung"; "Only Apple and Samsung have surpassed the one-billion active devices milestone"; each of the eight
  // leaders (starred in its chart: Apple, Samsung, Xiaomi, OPPO, vivo, Transsion, Huawei, HONOR) has over 200 million.
  // Shares read from its chart: Xiaomi 12%, OPPO 8%, vivo 7%, Transsion 5%, HONOR 4% (36% together), Huawei 4%, Google 0.8%.
  inUse: {
    source: 'Counterpoint Research, 2026', url: 'https://counterpointresearch.com/en/insights/Active-Installed-Base-8-Smartphone-OEMs-Top-200-mn-Nearly-1-in-4-is-an-iPhone',
    apple: 'estimated at over a billion actively used devices', samsung: 'estimated at over a billion actively used devices',
    otherFive: 'each estimated at over 200 million actively used devices', huawei: 'estimated at over 200 million actively used devices',
  },
  // Devices with Google Play, which carries Google's scanner: "we expanded enhanced fraud protection to 185 markets, now covering
  // more than 2.8 billion Android devices" (Google, 19 February 2026); a floor, and it may count tablets
  googlePlay: { billions: 2.8, source: 'Google, 2026', url: 'https://blog.google/security/keeping-google-play-android-app-ecosystem-safe-2025/' },
  // Apple shipped 247.8 million of 1,260.3 million smartphones in 2025
  shipped: { share: 19.7, total: 1.26, url: 'https://www.idc.com/resource-center/press-releases/q425mobilephonetop5/' },
  // "Globally, 82 per cent of individuals 10 years or older own a mobile phone."
  anyPhone: { share: 82, url: 'https://www.itu.int/itu-d/reports/statistics/2025/10/15/ff25-mobile-phone-ownership/' },
  // web page views, not phones: Android 69.31%, iOS 30.66% of mobile page views, September 2026
  web: { ios: 31, url: 'https://gs.statcounter.com/os-market-share/mobile/worldwide' },
};
const CAMERAX_DOCS = 'https://developer.android.com/media/camera/camerax/configuration';
const AOSP_ZXING = 'https://android.googlesource.com/platform/external/zxing/+/refs/heads/main/METADATA';
// Android's QR button opens the scanner a setting names: "On the eligible devices this activity is provided by GMS core"
const AOSP_QR_BUTTON = 'https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java';
// ...and the phone maker's own default for it, empty in Android's code
const AOSP_QR_DEFAULT = 'https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/core/res/res/values/config.xml';
// the scanners' roles on the page
const APPLE = 'apple-vision'; // Apple's scanner: the iPhone Camera and any app
const GOOGLE = 'mlkit-gms'; // Google's ML Kit from Google Play services: what Android's QR button opens
const SETTINGS = 'zxing-java'; // ZXing in Android's Settings app, for Wi-Fi codes
const HUAWEI = 'hms-scankit'; // Huawei's Scan Kit: the scanner in HarmonyOS and in HMS Core on Huawei phones
// Huawei's documentation of Scan Kit, for Android phones (HMS Core) and for HarmonyOS
const HUAWEI_KIT = 'https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/service-introduction-0000001050041994';
const HUAWEI_HARMONY = 'https://developer.huawei.com/consumer/en/doc/harmonyos-guides/scan-introduction';
// What we measured, credited to its maker: each one's own page (checked 2026-10-28)
const ML_KIT = 'https://developers.google.com/ml-kit'; // ML Kit's home page
const ML_KIT_BARCODE = 'https://developers.google.com/ml-kit/vision/barcode-scanning'; // its barcode scanning API
const SCAN_KIT = 'https://developer.huawei.com/consumer/en/hms/huawei-scankit/'; // Scan Kit's home page
const APPLE_VISION = 'https://developer.apple.com/documentation/vision/vndetectbarcodesrequest'; // Apple Vision's barcode request
// Samsung's guide to its "Scan QR code" button, which opens the Gallery too: the way we read each picture. Samsung
// doesn't name the decoder inside; the phone shows it is Quram's (Quramsoft), credited openly by the user's decision
// of 2026-10-28: the Camera app decodes with a library carrying Quram's name, and the engine names itself in the log.
const SAMSUNG_QR = 'https://www.samsung.com/us/support/answer/ANS10001925/';
const QURAM = 'https://www.quramsoft.com/';
const SYNTH_DATASET = 'https://huggingface.co/datasets/devmandan/qr-scan-difficulty'; // the codes made for this page
// Denso Wave's history of the QR code: "it declared that it would not exercise" its patent rights
const QR_HISTORY = 'https://www.qrcode.com/en/history/';
// Denso's QR code page (the corner squares' 1:1:3:1:1 ratio, the alignment square) and Denso Wave's error correction page
const DENSO_QR = 'https://www.denso.com/global/en/business/innovation/qrcode/';
const QR_EC = 'https://www.qrcode.com/en/about/error_correction.html';
// Why the page exists, and who it is not affiliated with: every company and organization the page names (the audit checks
// that each one named in the page's text is listed), and the trademark notice DENSO WAVE asks for when the words "QR Code" are used
const PURPOSE = 'To show how unevenly the world’s phones read QR codes, and to help everyone who builds a scanner see where theirs falls short and improve it. A measurement this broad has become practical only recently, thanks to AI models that help write the software behind it.';
const AFFILIATIONS = ['Apple', 'Google', 'Samsung', 'Quram (Quramsoft)', 'Huawei', 'Honor', 'Xiaomi', 'OPPO', 'vivo', 'Transsion', 'Tencent', 'Meta',
  'Denso', 'DENSO WAVE', 'Toyota', 'GS1', 'Counterpoint Research', 'GSMA', 'ITU', 'IDC', 'StatCounter'];
const DISCLOSURE = `Independent work, not affiliated with or endorsed by any company or organization named on this page: ${AFFILIATIONS.slice(0, -1).join(', ')} or ${AFFILIATIONS[AFFILIATIONS.length - 1]}; nor by the open-source projects and dataset authors credited above. QR Code is a registered trademark of DENSO WAVE INCORPORATED. Apple and iPhone are trademarks of Apple Inc.; Android, Google Play, ML Kit and Pixel of Google LLC; Samsung and Galaxy of Samsung Electronics Co., Ltd.; Huawei and HarmonyOS of Huawei Technologies Co., Ltd.; WeChat of Tencent; WhatsApp and Instagram of Meta Platforms, Inc. Other names are trademarks of their owners.`;
// How a scanner reads a code: each factor's "breaks" line in site.json names one of these steps
const READ_STEPS = ['Telling dark from light', 'Finding the code', 'Fitting the grid', 'Reading the squares', 'Error correction']; // Quram's own site; its Machine Eye page sells a QR and barcode scanner, MI.CODE
const ZXING = 'https://github.com/zxing/zxing/releases/tag/zxing-3.5.2';
const ZXING_CPP = 'https://github.com/zxing-cpp/zxing-cpp/releases/tag/v3.1.1';
const WECHAT_QR = 'https://docs.opencv.org/4.12.0/d5/d04/classcv_1_1wechat__qrcode_1_1WeChatQRCode.html';
const OPENCV_ARUCO = 'https://docs.opencv.org/4.12.0/d3/db0/classcv_1_1QRCodeDetectorAruco.html';
const OPENCV_QR = 'https://docs.opencv.org/4.12.0/de/dc3/classcv_1_1QRCodeDetector.html';
const SCANNER_PAGES = { // each scanner's own pages, for exactly what we measured
  'apple-vision': [[APPLE_VISION, 'Apple’s documentation of VNDetectBarcodesRequest']],
  'mlkit-gms': [[ML_KIT_BARCODE, 'ML Kit’s barcode scanning'], [AOSP_QR_BUTTON, 'Android’s source for the QR button']],
  'hms-scankit': [[SCAN_KIT, 'Scan Kit'], [HUAWEI_KIT, 'its HMS Core guide'], [HUAWEI_HARMONY, 'its HarmonyOS guide']],
  'zxing-java': [[ZXING, 'ZXing 3.5.2'], [ANDROID_SOURCE, 'QrCamera.java in Android’s Settings library']],
  wechat: [[WECHAT_QR, 'OpenCV’s WeChatQRCode']],
  'zxing-cpp': [[ZXING_CPP, 'zxing-cpp 3.1.1']],
  'opencv-aruco': [[OPENCV_ARUCO, 'OpenCV’s QRCodeDetectorAruco']],
  opencv: [[OPENCV_QR, 'OpenCV’s QRCodeDetector']],
};
/** "See a, b and c.": a scanner's pages, each a link that opens in a new tab. */
function see(pages) {
  const sep = (i) => (i === 0 ? '' : i === pages.length - 1 ? ' and ' : ', ');
  return ['See ', ...pages.flatMap(([href, text], i) => [sep(i), el('a', { href, text, target: '_blank', rel: 'noopener' })]), '.'];
}
// the same scanner on Google's image for each Android version, and the Play services versions it came in
function versionsNote() {
  const v = DATA.googleVersions;
  if (!v) return '';
  const now = percent(pctRead(GOOGLE, () => true).rate);
  return `It read the same on each up-to-date Android version we tried, from ${v.androidSame[0]} to ${v.androidSame[1]}: what matters is Google Play services, which updates itself. Older versions read a little less (${percent(v.older.rate)} in ${v.older.year}, ${now} since ${v.sinceYear}).`;
}
// ZXing as Android's Settings app runs it reads light-on-dark codes only on its second, inverted pass
function invertedNote() {
  const inv = DATA.zxingInvertedPass;
  return inv ? `It reads light-on-dark codes only by retrying on an inverted image, as Android’s Settings app does: ${inv.read} of our ${inv.n} light-on-dark codes, and ${inv.read - inv.second} without the retry.` : '';
}
// Samsung's scanner: its Camera app's, read on a real phone borrowed through Samsung's Remote Test Lab, on a random
// sample of each set at one resolution (DATA.samsung), so its figures are estimates
const SAMSUNG_RTL = 'https://developer.samsung.com/remote-test-lab';
const WORDS = ['none', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
// One rule everywhere: how many of the scanners read it. A single code is read or not;
// a group of codes (a factor step, a set) is read by a scanner that reads 9 in 10 of them.
let ZONES; // all, most (more than half), some, none: set once the number of scanners is known
function makeZones(n) {
  const half = Math.floor(n / 2);
  return [
    { min: n, name: `All ${WORDS[n]}`, words: `all ${WORDS[n]}`, tone: '--z-every' },
    { min: half + 1, name: 'Most', words: `most (${half + 1} to ${n - 1})`, range: `${half + 1}–${n - 1}`, tone: '--z-most' },
    { min: 1, name: 'Some', words: `some (1 to ${half})`, range: `1–${half}`, tone: '--z-some' },
    { min: 0, name: 'None', words: 'none', tone: '--z-none' },
  ];
}
const allWord = () => WORDS[ORDER.length]; // "seven"
const mostMin = () => ZONES[1].min; // the fewest scanners that still count as most
// the image resolution a scanner gets: larger images shrunk to this long side, smaller ones left as they are
const RESOLUTIONS = [
  { frame: 1920, label: 'High', note: 'Larger images were shrunk to 1920 pixels on the long side, like 1080p video.' },
  { frame: 1280, label: 'Medium', note: 'Larger images were shrunk to 1280 pixels on the long side, like 720p video.' },
  { frame: 640, label: 'Low', note: 'Larger images were shrunk to 640 pixels on the long side. CameraX, Google’s camera library for Android apps, analyses 640 × 480 unless an app asks for more.' },
];
const WORLD = { pristine: 0.2, everyday: 0.5, tough: 0.2, dataset: 0.1 }; // the curve's illustrative mix
const PLAIN = { // a name anyone can place, then what it is, for the specialist
  'apple-vision': ['Apple’s scanner', 'Apple Vision, built into iOS'],
  'mlkit-gms': ['Google’s scanner', 'ML Kit, opened by Android’s QR button'],
  'hms-scankit': ['Huawei’s scanner', 'Scan Kit, built into Huawei phones'],
  'zxing-java': ['Android Settings’ scanner', 'ZXing (Java), for Wi-Fi codes'],
  wechat: ['WeChat’s scanner', 'neural network, open-sourced in OpenCV'],
  'zxing-cpp': ['zxing-cpp', 'grew out of ZXing; in open-source apps'],
  'opencv-aruco': ['OpenCV, newer', 'OpenCV’s ArUco-based detector'],
  opencv: ['OpenCV, original', 'OpenCV’s first QR detector'],
};
const SPOKEN = { // the same names inside sentences
  'apple-vision': 'Apple’s scanner', 'mlkit-gms': 'Google’s scanner', 'hms-scankit': 'Huawei’s scanner', 'zxing-java': 'Android Settings’ scanner',
  wechat: 'WeChat’s scanner',
  'zxing-cpp': 'zxing-cpp', 'opencv-aruco': 'OpenCV’s newer detector', opencv: 'OpenCV’s original detector',
};
const SETS = [
  { label: 'Clean', noun: 'clean prints', match: (s) => s.key === 'pristine' },
  { label: 'Everyday', noun: 'everyday prints', match: (s) => s.key === 'everyday' },
  { label: 'Tough', noun: 'tough prints', match: (s) => s.key === 'tough' },
  { label: 'Hardest cases', noun: 'hardest cases', match: (s) => s.group === 'dataset' },
];
const SOURCE_PLAIN = { // what an example is; QR-DN1.0's examples carry their kind (site.json), its tiled ones are never shown
  pristine: 'Clean print, simulated for this test',
  everyday: 'Everyday print, simulated for this test',
  tough: 'Tough print, simulated for this test',
  boofcv: 'Real photo, BoofCV research set',
  'qrdn/clean': 'Clean code, QR-DN1.0 research set',
  'qrdn/distorted': 'Distorted, noisy code, QR-DN1.0 research set',
  syn10k: 'Computer-made warped code, syn10k research set',
  broken104: 'Real code that fails, collected from the web',
};
const PAIRS = [
  { key: 'size', title: 'Squares too small' },
  { key: 'version', title: 'Too much data for the size' },
  { key: 'blur', title: 'Out of focus' },
  { key: 'contrast', title: 'Faded ink' },
  { key: 'curve', title: 'Tight curves' },
  { key: 'corner', title: 'A covered corner square' },
];

const state = { d: 40, offset: 0, laneFrame: BASE_FRAME, gridFrame: BASE_FRAME, showPct: false, factor: 'size', level: 0 };
let DATA;
let RES;
let NF;
let N;
let COUNT; // per code: how many of the scanners read it at BASE_FRAME
let ORDER;
let BELL;
let HIGH_NOTE; // what going above BASE_FRAME does, measured

const $ = (id) => document.getElementById(id);
const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
// a picture's address carries the build, so a browser never pairs new data with a cached old picture
const imgUrl = (path) => `img/${path}?v=${DATA.build}`;

function el(tag, attrs = {}, children = []) {
  const node = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs)) {
    if (k === 'text') node.textContent = v;
    else if (k === 'class') node.className = v;
    else node.setAttribute(k, v);
  }
  for (const c of [].concat(children)) if (c != null) node.append(c);
  return node;
}

function sv(tag, attrs = {}, parent = null) {
  const node = document.createElementNS(SVGNS, tag);
  for (const [k, v] of Object.entries(attrs)) {
    if (k === 'text') node.textContent = v;
    else node.setAttribute(k, v);
  }
  if (parent) parent.append(node);
  return node;
}

// ---- data -------------------------------------------------------------------------------

function decodeResults(data) {
  const F = data.frames.length;
  const n = data.items.s.length;
  const res = new Uint8Array(n * F);
  for (let i = 0; i < n; i++) {
    const s = data.items.r[i];
    for (let f = 0; f < F; f++) res[i * F + f] = parseInt(s.slice(2 * f, 2 * f + 2), 16); // bit k: scanner k read it
  }
  return res;
}

const decIndex = (key) => DATA.decoders.findIndex((d) => d.key === key);
const decoder = (key) => DATA.decoders[decIndex(key)];
const reads = (i, fi, k) => (RES[i * NF + fi] >> k) & 1;
const source = (i) => DATA.sources[DATA.items.s[i]];
const isAndroid = (key) => decoder(key).platform.startsWith('Android');
const otherApps = () => ORDER.filter((k) => ![APPLE, GOOGLE, HUAWEI, SETTINGS].includes(k)); // scanners other apps are built on
const zoneFor = (count) => ZONES.find((z) => count >= z.min);
const snap = (d) => (d > 103 ? PILE_HI : d > 100 ? 100 : d < -3 ? PILE_LO : d < 0 ? 0 : d); // the piles, or the scale
const zoneIndex = (count) => ZONES.indexOf(zoneFor(count));
function luminance(hex) {
  const c = hex.match(/\w\w/g).map((h) => parseInt(h, 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
  return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
}
/** Text colour for a label sitting on a tone: whichever of ink and surface contrasts more. */
function onTone(z) {
  const t = luminance(css(z.tone));
  const ratio = (name) => { const l = luminance(css(name)); return (Math.max(t, l) + 0.05) / (Math.min(t, l) + 0.05); };
  return ratio('--surface') >= ratio('--ink') ? css('--surface') : css('--ink');
}

/** A percent that never rounds onto 0%, 90% (9 in 10) or 100% unless it is really there. */
function percent(v) {
  const r = Math.round(100 * v);
  if (!((v > 0 && r === 0) || (v < RELIABLE && r === 90) || (v < 1 && r === 100))) return `${r}%`;
  const t = (100 * v).toFixed(1);
  return `${t === '0.0' ? '0.1' : t === '90.0' ? '89.9' : t === '100.0' ? '99.9' : t}%`;
}

/** Scanners that read a group of codes: at least 9 in 10 of them. */
function readsGroup(items, fi) {
  return ORDER.filter((key) => {
    const k = decIndex(key);
    return items.reduce((s, i) => s + reads(i, fi, k), 0) >= RELIABLE * items.length;
  });
}

/** Scanners that read a ladder step: at least 9 in 10 of its codes, at the ladder frame. */
const stepScanners = (level) => ORDER.filter((key) => level.reads[decIndex(key)] >= RELIABLE * level.n);

/** Index of the last step, counting from the easy end, that at least `min` scanners still read. */
function lastStep(lad, min) {
  let last = -1;
  for (let li = 0; li < lad.levels.length; li++) {
    if (stepScanners(lad.levels[li]).length < min) break;
    last = li;
  }
  return last;
}

/** Index of the first step that fewer than `min` scanners read, or -1. */
const firstBelow = (lad, min) => lad.levels.findIndex((lv) => stepScanners(lv).length < min);

const ladder = (key) => DATA.ladders.find((l) => l.key === key);
// the base code's settings a factor sets itself, so the explorer doesn't quote the base value for them
const OWN_SETTINGS = { size: ['ppm'], version: ['version', 'ppm'], version_big: ['version', 'ppm'], contrast: ['contrast'], tilt: ['tilt'], blur: ['blur'] };

/** A pair's two steps: the last one every scanner reads, and the first harder one that one scanner or none reads. */
function pairSteps(lad) {
  const counts = lad.levels.map((lv) => stepScanners(lv).length);
  const good = Math.max(0, lastStep(lad, ORDER.length));
  const bad = counts.findIndex((c, li) => li > good && c <= 1);
  return { good, bad: bad < 0 ? lad.levels.length - 1 : bad };
}

/** A version-ladder step's codes printed bigger, from the "version_big" ladder (same codes, squares kept the same size). */
function printedBigger(lv) {
  const big = ladder('version_big');
  const found = big ? big.levels.find((l) => l.short === lv.short) : null;
  return found ? { lad: big, lv: found } : null;
}
const pxOf = (lv) => lv.label.match(/([\d.]+) camera pixels/)[1]; // a data step's camera pixels per square, from its label

// ---- small shared pieces ----------------------------------------------------------------

function showTip(evt, lines) {
  const tip = $('tip');
  tip.replaceChildren(...lines.map(([cls, text]) => el('div', { class: cls, text })));
  tip.hidden = false;
  const w = tip.offsetWidth;
  const h = tip.offsetHeight;
  let x = evt.clientX + 14;
  let y = evt.clientY + 14;
  if (x + w > window.innerWidth - 8) x = evt.clientX - w - 14;
  if (y + h > window.innerHeight - 8) y = evt.clientY - h - 14;
  tip.style.left = `${x}px`;
  tip.style.top = `${y}px`;
}
const hideTip = () => { $('tip').hidden = true; };
// on a touch screen, lifting the finger ends the pointer: the tip stays until the next tap or a scroll
const leaveTip = (e) => { if (e.pointerType !== 'touch') hideTip(); };

const swatch = (z) => el('i', { class: 'swatch', style: `background:${css(z.tone)}` });

/** The image-resolution choice: it names what it sets, gives each setting in pixels, and says what
 *  the chosen one means. Picking re-renders the section, so focus returns to the chosen button. */
function resolutionControl(container, current, onPick) {
  const refocus = container.contains(document.activeElement);
  const id = `${container.id}Label`;
  const note = RESOLUTIONS.find((r) => r.frame === current).note;
  container.replaceChildren(
    el('span', { class: 'res-label', id, text: 'Image resolution' }),
    el('div', { class: 'seg', role: 'group', 'aria-labelledby': id }, RESOLUTIONS.map((o) => {
      const b = el('button', { type: 'button', 'aria-pressed': String(o.frame === current) }, [`${o.label} `, el('span', { class: 'px', text: `${o.frame} px` })]);
      b.addEventListener('click', () => onPick(o.frame));
      return b;
    })),
    el('p', { class: 'res-note', text: current === RESOLUTIONS[0].frame ? `${note} ${HIGH_NOTE}` : note }),
  );
  if (refocus) container.querySelector('[aria-pressed="true"]').focus();
}

function countText(n) {
  const all = ORDER.length;
  if (n === all) return `Read by all ${WORDS[all]} scanners`;
  if (n === 0) return `Read by none of the ${WORDS[all]}`;
  return `Read by ${n} of the ${all} scanners`;
}

function groupText(n) {
  const all = ORDER.length;
  if (n === all) return `Read reliably by all ${WORDS[all]} scanners`;
  if (n === 0) return `Read reliably by none of the ${WORDS[all]}`;
  return `Read reliably by ${n} of the ${all} scanners`;
}

/** A shade's swatch that names its shade, for a line that gives the count in words. */
const namedSwatch = (z) => { const s = swatch(z); s.title = z.name; return s; };

/** Scanner names for a sentence; both OpenCV detectors together read as one phrase. */
function sayNames(keys) {
  const both = keys.includes('opencv-aruco') && keys.includes('opencv');
  const names = keys.filter((k) => !(both && k.startsWith('opencv'))).map((k) => SPOKEN[k]);
  return both ? [...names, 'both OpenCV detectors'] : names;
}
const join = (xs) => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);
const capital = (s) => s.replace(/^./, (c) => c.toUpperCase());
const pctText = (v) => (v > 0 && v < 0.005 ? '<1%' : `${Math.round(100 * v)}%`);

// ---- Apple's scanner, Android's QR button, Android Settings, other apps -----------------

function pctRead(key, match, frame = BASE_FRAME) {
  const fi = DATA.frames.indexOf(frame);
  const k = decIndex(key);
  let r = 0;
  let n = 0;
  for (let i = 0; i < N; i++) {
    if (!match(source(i))) continue;
    r += reads(i, fi, k);
    n += 1;
  }
  return { rate: r / Math.max(1, n), n };
}

/** Samsung's scanner read a random sample of each set: its estimated share of the matching sets' codes, each set's
 *  estimate weighed by the set's size, as pctRead weighs the other scanners' sets. */
function samsungRate(match) {
  let r = 0;
  let n = 0;
  for (const s of DATA.sources) {
    const v = DATA.samsung.sets[s.key];
    if (!v || !match(s)) continue;
    r += v.of * v.estimate;
    n += v.of;
  }
  return { rate: r / Math.max(1, n), n };
}
const about = (v) => `≈${Math.round(100 * v)}%`; // an estimate, to the nearest percent

/** Against the iPhone, on the same codes: of every 100 codes Apple's scanner read, how many this one missed, and how many
 *  codes it read that Apple's missed, per 100 of Apple's reads; with the counts behind them (read, missedN). */
function vsApple(key, match = () => true) {
  const fi = DATA.frames.indexOf(BASE_FRAME);
  const a = decIndex(APPLE);
  const k = decIndex(key);
  let appleRead = 0;
  let missed = 0;
  let extra = 0;
  for (let i = 0; i < N; i++) {
    if (!match(source(i))) continue;
    const ra = reads(i, fi, a);
    const rk = reads(i, fi, k);
    appleRead += ra;
    missed += ra && !rk ? 1 : 0;
    extra += !ra && rk ? 1 : 0;
  }
  return { missed: (100 * missed) / appleRead, extra: (100 * extra) / appleRead, read: appleRead, missedN: missed };
}

/** The same for Samsung's scanner, from its sample: each set's shares, weighed by how many of the set's codes Apple's
 *  scanner read (the misses) or by the set's size (the extra reads), as samsungRate weighs its estimates. */
function samsungVsApple(match = () => true) {
  const fi = DATA.frames.indexOf(BASE_FRAME);
  const a = decIndex(APPLE);
  let appleRead = 0;
  let missed = 0;
  let extra = 0;
  DATA.sources.forEach((s, si) => {
    const v = DATA.samsung.sets[s.key];
    if (!v || !match(s)) return;
    let read = 0;
    let n = 0;
    for (let i = 0; i < N; i++) {
      if (DATA.items.s[i] !== si) continue;
      read += reads(i, fi, a);
      n += 1;
    }
    appleRead += read;
    if (v.vsApple.appleRead) missed += (read * v.vsApple.missed) / v.vsApple.appleRead;
    extra += (n * v.vsApple.extra) / v.n;
  });
  return { missed: (100 * missed) / appleRead, extra: (100 * extra) / appleRead };
}
const SAMSUNG_RES = () => RESOLUTIONS.find((r) => r.frame === DATA.samsung.frame)?.label ?? `${DATA.samsung.frame} px`;

function renderVersus() {
  const link = (href, text) => el('a', { href, text, target: '_blank', rel: 'noopener' });
  const all = () => true;
  const apple = pctRead(APPLE, all);
  const google = pctRead(GOOGLE, all);
  const samsung = samsungRate(all);
  const huawei = pctRead(HUAWEI, all);
  const zx = pctRead(SETTINGS, all);
  const others = otherApps().map((k) => pctRead(k, all).rate);
  const lo = Math.min(...others);
  const hi = Math.max(...others);
  const builtIn = [google.rate, samsung.rate, huawei.rate, zx.rate]; // the scanners Android phones come with
  const hard = (s) => s.group === 'dataset';
  const count = (pred) => DATA.sources.filter(pred).reduce((acc, s) => acc + s.count, 0);
  const made = count((s) => s.group === 'made' && s.key !== 'ladder');
  const real = count(hard);
  const label = (name, what) => el('span', { class: 'vlabel' }, [el('span', { class: 'name', text: name }), el('span', { class: 'what' }, what)]);
  const bar = (name, what, v, estimate = false) => el('div', { class: 'vbar' }, [
    label(name, what),
    el('span', { class: 'vtrack' }, el('span', { class: estimate ? 'vfill est' : 'vfill', style: `width:${100 * v.rate}%` })),
    el('span', { class: 'vval', text: estimate ? about(v.rate) : percent(v.rate) }),
  ]);
  $('versus').replaceChildren(
    el('p', { class: 'versus-lede' }, [
      `We tested ${apple.n.toLocaleString()} QR codes, most of them deliberately hard, on the scanners phones use. `,
      'Every iPhone, about ', link(WORLD_PHONES.inUse.url, '1 in 4 smartphones'), `, has Apple’s scanner; it read ${percent(apple.rate)}. `,
      `The other 3 in 4, more than 3 billion phones, use other scanners; those measured so far read ${percent(Math.min(...builtIn))} to ${percent(Math.max(...builtIn))}.`,
    ]),
    el('div', { class: 'vbars' }, [ // the iPhone's, then the scanners Android phones come with, then those inside apps
      bar('iPhone', ['Apple’s scanner (', link(APPLE_VISION, 'Vision'), ')'], apple),
      bar('Samsung phones', ['Samsung’s scanner (', link(SAMSUNG_QR, 'Camera'), ')'], samsung, true),
      bar('Android’s QR button', ['Google’s scanner (', link(ML_KIT, 'ML Kit'), ')'], google),
      bar('Huawei phones', ['Huawei’s scanner (', link(SCAN_KIT, 'Scan Kit'), ')'], huawei),
      bar('Android Settings', [link(ZXING, 'ZXing'), ', for ', link(ANDROID_SOURCE, 'Wi-Fi codes')], zx),
      el('div', { class: 'vbar' }, [
        label('Other apps', `${others.length} scanners apps are built on`),
        el('span', { class: 'vtrack spread' }, [
          el('span', { class: 'vband', style: `left:${100 * lo}%;width:${100 * (hi - lo)}%` }),
          ...others.map((v) => el('span', { class: 'vdot', style: `left:${100 * v}%` })),
        ]),
        el('span', { class: 'vval wide', text: `${percent(lo)}–${percent(hi)}` }),
      ]),
    ]),
    el('p', { class: 'takeaway', text: 'The same code can scan on one phone and fail on the next.' }),
    el('p', { class: 'fine' }, `The codes: ${made.toLocaleString()} prints we simulated, and ${real.toLocaleString()} from research datasets, mostly hardest cases that researchers collected or built to copy the toughest conditions real codes meet. ≈ Samsung’s figure is an estimate.`),
  );
}

/** The intro's closing point, from the reads: a picture one scanner read was readable, so another scanner's miss on
 *  it is the software's, not the code's. Then why that matters, and how far one better scanner reaches. */
function renderIntro() {
  const link = (href, text) => el('a', { href, text, target: '_blank', rel: 'noopener' });
  const split = COUNT.filter((c) => c >= 1 && c < ORDER.length).length;
  $('introNote').textContent = `Codes in daily life meet the same mess: faded signs, spilled-on menus, crumpled receipts. A scanner built only for pristine codes misses why the QR code exists. When one scanner reads a picture that another misses, the difference is the software: that happened with ${split.toLocaleString()} of our codes.`;
  const v = DATA.googleVersions;
  const now = percent(pctRead(GOOGLE, () => true).rate);
  $('introClose').replaceChildren(
    'The QR code is still the best two-dimensional code for phones: ',
    link(QR_HISTORY, 'free for anyone to use'), ', readable from any direction, and built to repair itself. ',
    'It doesn’t need replacing; the scanners need to catch up with what it was built for.',
    v ? ` Updates alone can help: Google’s ML Kit scanner, delivered and updated through Google Play services, went from reading ${percent(v.older.rate)} of our codes in ${v.older.year} to ${now} since ${v.sinceYear}, with no new phone needed.` : '',
  );
}

/** Which phones use which scanner, how many phones that is, how many codes each reads, and how many of the codes an
 *  iPhone reads each one misses: on everyday prints and on the hardest cases, where the gap is. */
function renderWho() {
  const link = (href, text) => el('a', { href, text, target: '_blank', rel: 'noopener' });
  const all = () => true;
  const everyday = (s) => s.key === 'everyday';
  const hard = (s) => s.group === 'dataset';
  const { inUse, googlePlay } = WORLD_PHONES;
  const apple = pctRead(APPLE, all).rate;
  const samsung = samsungRate(all).rate;
  const others = otherApps();
  const n = (v) => String(Math.round(v));
  const range = (vals) => (n(Math.min(...vals)) === n(Math.max(...vals)) ? n(vals[0]) : `${n(Math.min(...vals))}–${n(Math.max(...vals))}`);
  const misses = (key) => [vsApple(key, everyday).missed, vsApple(key, hard).missed].map(n);
  const samEvery = samsungVsApple(everyday);
  const samHard = samsungVsApple(hard);
  const appRead = others.map((k) => pctRead(k, all).rate);
  const rows = [ // phones, how many (Counterpoint), their scanner, codes read, misses of every 100 the iPhone reads (everyday, hard)
    ['iPhone', inUse.apple, 'Apple’s', percent(apple), '—', '—'],
    // Google's scanner comes with Google Play services: apps reach it on most Android phones, and Pixel's QR button opens it
    ['Most Android phones, in apps', `over ${googlePlay.billions} billion devices with Google Play, by Google’s count; also Pixel’s QR button`,
      'Google’s ML Kit, in Google Play services', percent(pctRead(GOOGLE, all).rate), ...misses(GOOGLE)],
    ['Samsung', inUse.samsung, 'Samsung’s own, in its Camera app', about(samsung), `≈${n(samEvery.missed)}`, `≈${n(samHard.missed)}`], // estimates
    ['Xiaomi, OPPO, vivo, Transsion, Honor', inUse.otherFive, 'each maker’s own', 'not yet measured', '—', '—'],
    ['Huawei', inUse.huawei, 'Huawei’s Scan Kit', percent(pctRead(HUAWEI, all).rate), ...misses(HUAWEI)],
    ['Android’s own Settings app', 'for Wi-Fi codes', 'ZXing', percent(pctRead(SETTINGS, all).rate), ...misses(SETTINGS)],
    ['Other apps, on any phone', 'each brings its own', `${capital(WORDS[others.length])} that apps are built on`,
      `${percent(Math.min(...appRead))}–${percent(Math.max(...appRead))}`,
      range(others.map((k) => vsApple(k, everyday).missed)), range(others.map((k) => vsApple(k, hard).missed))],
  ];
  const th = (text, attrs = {}) => el('th', { scope: 'col', text, ...attrs });
  $('who').replaceChildren(
    el('thead', {}, [
      el('tr', {}, [th('Phones', { class: 'left', rowspan: '2' }), th('Their scanner', { class: 'left', rowspan: '2' }),
        th(`Reads, of all ${N.toLocaleString()} codes`, { rowspan: '2' }), th('Misses, of every 100 codes an iPhone reads', { colspan: '2', scope: 'colgroup' })]),
      el('tr', {}, [th('Everyday prints'), th('Hardest cases')]),
    ]),
    el('tbody', {}, rows.map(([phones, many, scanner, read, ev, hd]) => el('tr', {}, [
      el('th', { scope: 'row' }, [el('span', { class: 'name', text: phones }), el('span', { class: 'what', text: many })]),
      el('td', { class: 'left', text: scanner }),
      el('td', { text: read }),
      el('td', { text: ev }),
      el('td', { text: hd }),
    ]))),
  );
  // how the misses are counted, with the real counts behind one row
  const zxEvery = vsApple(SETTINGS, everyday);
  const zxHard = vsApple(SETTINGS, hard);
  $('whoHow').textContent = `How the misses are counted, for Android Settings’ scanner: of the ${zxEvery.read.toLocaleString()} everyday prints an iPhone read, it missed ${zxEvery.missedN.toLocaleString()}, about ${n(zxEvery.missed)} in 100; of the ${zxHard.read.toLocaleString()} hardest cases an iPhone read, it missed ${zxHard.missedN.toLocaleString()}, about ${n(zxHard.missed)} in 100.`;
  $('whoTitle').textContent = samsung < apple ? 'More than a billion phones read fewer codes than an iPhone' : 'Which phones read which codes';
  // the phones' main scanners on everyday prints (Android Settings' reads Wi-Fi codes only; its row and whoHow show it)
  const everydayMost = n(Math.max(vsApple(GOOGLE, everyday).missed, samEvery.missed, vsApple(HUAWEI, everyday).missed));
  const googleHard = vsApple(GOOGLE, hard);
  const both = n(samHard.missed) === n(googleHard.missed)
    ? `Samsung’s and Google’s scanners each miss about ${n(samHard.missed)}`
    : `Samsung’s scanner misses about ${n(samHard.missed)} and Google’s ${n(googleHard.missed)}`;
  $('whoNote').textContent = `On everyday prints, Google’s, Samsung’s and Huawei’s scanners miss ${everydayMost === '0' ? 'almost none' : `at most ${everydayMost} in 100`} of the codes an iPhone reads. On the hardest cases, ${both} of every 100 an iPhone reads. Phones from Xiaomi, OPPO, vivo, Transsion and Honor, together more than a billion, are not yet measured.`;
  const sam = samsungVsApple(all);
  const g = vsApple(GOOGLE);
  const h = vsApple(HUAWEI);
  $('whoSource').replaceChildren(
    `Some scanners also read codes an iPhone misses: for every 100 it reads, Huawei’s read ${n(h.extra)} more, Google’s ${n(g.extra)} and Samsung’s about ${n(sam.extra)}. Samsung’s figures are estimates; why the other makers wait is under How we measured. Phones in use: `,
    link(inUse.url, inUse.source), '; devices with Google Play: ', link(googlePlay.url, googlePlay.source), '.',
  );
}

// ---- the spectrum -----------------------------------------------------------------------

/** The illustrative mix over difficulty, split by how many scanners read each code. */
function bellData() {
  const counts = {};
  for (let i = 0; i < N; i++) counts[source(i).key] = (counts[source(i).key] || 0) + 1;
  const nSets = DATA.sources.filter((s) => s.group === 'dataset' && counts[s.key]).length;
  const weight = (s) => (s.group === 'dataset' ? WORLD.dataset / nSets : WORLD[s.key]) / counts[s.key];
  const dens = ZONES.map(() => new Float64Array(101));
  const piles = { lo: ZONES.map(() => 0), hi: ZONES.map(() => 0) };
  let total = 0;
  for (let i = 0; i < N; i++) {
    const w = weight(source(i));
    const d = DATA.items.d[i];
    const z = zoneIndex(COUNT[i]);
    total += w;
    if (d < 0) piles.lo[z] += w;
    else if (d > 100) piles.hi[z] += w;
    else dens[z][Math.round(d)] += w;
  }
  const sigma = 4.5;
  const medians = {};
  for (const key of ['pristine', 'everyday', 'tough']) {
    const ds = [];
    for (let i = 0; i < N; i++) if (source(i).key === key) ds.push(DATA.items.d[i]);
    ds.sort((a, b) => a - b);
    medians[key] = ds[Math.floor(ds.length / 2)];
  }
  const smooth = dens.map((arr) => Array.from(arr, (_, j) => {
    let s = 0;
    let ws = 0;
    for (let k = Math.max(0, j - 14); k <= Math.min(100, j + 14); k++) {
      const w = Math.exp(-((k - j) ** 2) / (2 * sigma * sigma));
      s += arr[k] * w;
      ws += w;
    }
    return s / ws;
  }));
  return { smooth, piles, total, medians };
}

/** Shares of the four tones among the codes at difficulty d (the same smoothing as the bell). */
function mixAt(d) {
  let v;
  if (d <= PILE_LO) v = BELL.piles.lo;
  else if (d >= PILE_HI) v = BELL.piles.hi;
  else {
    const j = Math.max(0, Math.min(99, Math.floor(d)));
    v = BELL.smooth.map((s) => s[j] + (s[j + 1] - s[j]) * (d - j));
  }
  const t = v.reduce((a, b) => a + b, 0) || 1;
  return v.map((x) => x / t);
}

function renderKey() {
  $('bellKey').replaceChildren(
    el('span', { class: 'key-title', text: `How many of the ${allWord()} scanners read each code:` }),
    ...ZONES.map((z) => el('span', {}, [swatch(z), z.range ? `${z.name} (${z.range})` : z.name])),
  );
}

function renderBell() {
  const svg = $('bell');
  const W = svg.clientWidth || 700;
  const padTop = 18;
  const plotH = 170;
  const base = padTop + plotH;
  const H = base + 46;
  const x = (d) => 4 + ((d - X_MIN) / (X_MAX - X_MIN)) * (W - 8);
  const xInv = (px) => X_MIN + ((px - 4) / (W - 8)) * (X_MAX - X_MIN);
  svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
  svg.setAttribute('height', H);
  svg.replaceChildren();

  // stacked: all of them at the bottom, then most, some, none; piles keep the same area scale
  const { smooth, piles } = BELL;
  const cum = [];
  smooth.forEach((s, z) => cum.push(s.map((v, j) => v + (z ? cum[z - 1][j] : 0))));
  const at = (arr, d) => {
    const j = Math.max(0, Math.min(99, Math.floor(d)));
    return arr[j] + (arr[j + 1] - arr[j]) * (d - j);
  };
  const pileH = (p) => p.reduce((a, b) => a + b, 0) / 8;
  const yMax = Math.max(...cum[cum.length - 1], pileH(piles.lo), pileH(piles.hi)) * 1.12;
  const y = (v) => base - (Math.min(v, yMax) / yMax) * plotH;
  ZONES.forEach((z, zi) => {
    let path = '';
    for (let d = 0; d <= 100 + 1e-9; d += 0.5) path += `${path ? 'L' : 'M'}${x(d)},${y(at(cum[zi], d))}`;
    for (let d = 100; d >= -1e-9; d -= 0.5) path += `L${x(d)},${zi ? y(at(cum[zi - 1], d)) : base}`;
    sv('path', { d: `${path}Z`, fill: css(z.tone) }, svg);
  });
  ZONES.slice(0, -1).forEach((_, zi) => { // a thin surface line between tones
    let path = '';
    for (let d = 0; d <= 100 + 1e-9; d += 0.5) path += `${path ? 'L' : 'M'}${x(d)},${y(at(cum[zi], d))}`;
    sv('path', { d: path, fill: 'none', stroke: css('--surface'), 'stroke-width': 1.5 }, svg);
  });
  for (const [c, p, what] of [[PILE_LO, piles.lo, 'Read by every scanner at every resolution'], [PILE_HI, piles.hi, 'Read by no scanner at any resolution']]) {
    let v0 = 0;
    p.forEach((w, zi) => {
      if (!w) return;
      const top = y((v0 + w) / 8);
      sv('rect', { x: x(c - 4), y: top, width: x(c + 4) - x(c - 4), height: y(v0 / 8) - top, fill: css(ZONES[zi].tone) }, svg);
      v0 += w;
    });
    const hit = sv('rect', { x: x(c - 5), y: padTop, width: x(c + 5) - x(c - 5), height: plotH, fill: 'transparent' }, svg);
    const tip = (e) => showTip(e, [['v', `${Math.round((100 * p.reduce((a, b) => a + b, 0)) / BELL.total)}% of the mix`], ['k', what]]);
    hit.addEventListener('pointermove', tip);
    hit.addEventListener('pointerdown', tip);
    hit.addEventListener('pointerleave', leaveTip);
  }
  sv('line', { x1: x(X_MIN), x2: x(X_MAX), y1: base + 0.5, y2: base + 0.5, stroke: css('--rule') }, svg);

  // a name inside each tone, only where the tone is thick enough under the whole word
  const halfWord = (24 / (W - 8)) * (X_MAX - X_MIN);
  ZONES.forEach((z, zi) => {
    let best = null;
    for (let d = 2 + halfWord; d <= 98 - halfWord; d += 1) {
      const mid = ((zi ? y(at(cum[zi - 1], d)) : base) + y(at(cum[zi], d))) / 2;
      // room left above and below the word, at its two ends and its middle
      const room = Math.min(...[d - halfWord, d, d + halfWord].map((dd) =>
        Math.min(mid - 9 - y(at(cum[zi], dd)), (zi ? y(at(cum[zi - 1], dd)) : base) - (mid + 5))));
      if (!best || room > best.room) best = { d, room, mid };
    }
    if (best && best.room >= 2) {
      sv('text', { x: x(best.d), y: best.mid + 4, 'text-anchor': 'middle', style: `fill:${onTone(z)};font-weight:600`, text: z.name }, svg);
    }
  });
  // the axis: easier and harder at the ends, and the middle code of each set we made
  const placed = [{ cx: x(X_MIN) + 30, w: 64, r: 0 }, { cx: x(X_MAX) - 30, w: 64, r: 0 }];
  sv('text', { x: x(X_MIN), y: base + 20, class: 'muted', text: '← Easier' }, svg);
  sv('text', { x: x(X_MAX), y: base + 20, class: 'muted', 'text-anchor': 'end', text: 'Harder →' }, svg);
  const ticks = [];
  for (const [key, text] of [['pristine', 'clean prints'], ['everyday', 'everyday prints'], ['tough', 'tough prints']]) {
    const cx = x(BELL.medians[key]);
    const w = text.length * 6.4 + 10;
    let r = 0;
    while (placed.some((q) => q.r === r && Math.abs(q.cx - cx) < (q.w + w) / 2)) r += 1;
    placed.push({ cx, w, r });
    ticks.push({ cx, r, text });
  }
  // the lines first; then each label on a patch of the page's color, so a lower label's line passes behind a higher label
  for (const { cx, r } of ticks) sv('line', { x1: cx, x2: cx, y1: base, y2: base + 6 + 15 * r, stroke: css('--ink-3') }, svg);
  for (const { cx, r, text } of ticks) {
    const label = sv('text', { x: cx, y: base + 20 + 15 * r, 'text-anchor': 'middle', class: 'muted', text }, svg);
    const bb = label.getBBox();
    svg.insertBefore(sv('rect', { x: bb.x - 3, y: bb.y, width: bb.width + 6, height: bb.height, fill: css('--surface') }), label);
  }

  // the movable cursor
  const cx = x(state.d);
  const g = sv('g', { 'pointer-events': 'none' }, svg);
  sv('line', { x1: cx, x2: cx, y1: padTop - 8, y2: base, stroke: css('--accent'), 'stroke-width': 2 }, g);
  sv('circle', { cx, cy: padTop - 8, r: 7, fill: css('--accent'), stroke: css('--surface'), 'stroke-width': 2 }, g);

  const move = (e) => {
    const rect = svg.getBoundingClientRect();
    const d = xInv(((e.clientX - rect.left) / rect.width) * W);
    setCursor(snap(d));
  };
  svg.onpointerdown = (e) => { svg.setPointerCapture(e.pointerId); move(e); svg.onpointermove = (ev) => { if (ev.buttons) move(ev); }; };
  svg.onpointerup = () => { svg.onpointermove = null; };
  svg.setAttribute('aria-label', `QR codes from easiest to hardest, shaded by how many of the ${allWord()} scanners read each one: all ${allWord()}, most, some or none.`);
}

function renderReadout() {
  const mix = mixAt(state.d);
  let text;
  if (state.d <= PILE_LO) text = 'Codes here were read by every scanner at every image resolution.';
  else if (state.d >= PILE_HI) text = 'Codes here were read by no scanner at any image resolution.';
  else {
    const parts = ZONES.map((z, zi) => [z, mix[zi]]).filter(([, v]) => v > 0);
    text = `Codes here: ${parts.map(([z, v], k) => `${pctText(v)} ${k ? 'by' : 'read by'} ${z.words}`).join(' · ')}.`;
  }
  $('readout').textContent = text;
}

/** The eight example codes nearest this spot; the first one shown has the spot's most common tone. */
function nearest(d) {
  const c = [];
  for (let i = 0; i < N; i++) {
    if (DATA.items.x[i] < 0) continue;
    c.push([Math.abs(DATA.items.d[i] - d), i]);
  }
  const picks = c.sort((a, b) => a[0] - b[0]).slice(0, 8).map(([, i]) => i);
  const mix = mixAt(d);
  const common = mix.indexOf(Math.max(...mix));
  const first = picks.findIndex((i) => zoneIndex(COUNT[i]) === common);
  return first > 0 ? [picks[first], ...picks.filter((_, k) => k !== first)] : picks;
}

function renderSpecimen() {
  const picks = nearest(state.d);
  const i = picks[state.offset % picks.length];
  const fi = DATA.frames.indexOf(BASE_FRAME);
  const readKeys = ORDER.filter((k) => reads(i, fi, decIndex(k)));
  const z = zoneFor(readKeys.length);
  const yes = (k) => (readKeys.includes(k) ? 'read' : 'missed');
  const others = otherApps();
  const ex = DATA.examples[DATA.items.x[i]];
  const plain = SOURCE_PLAIN[ex.kind ? `${source(i).key}/${ex.kind}` : source(i).key] || source(i).name;
  const next = el('button', { class: 'linklike', type: 'button', text: 'Another code from here' });
  next.addEventListener('click', () => { state.offset += 1; renderSpecimen(); });
  const full = /^https?:/.test(ex.href) ? ex.href : imgUrl(ex.href); // the exact picture the scanners read
  $('specimen').replaceChildren(
    el('img', { src: imgUrl(ex.img), alt: `A QR code from this spot: ${plain}` }),
    el('a', { class: 'scan-it', href: full, target: '_blank', rel: 'noopener', text: 'Open the full picture, and try it with your phone ↗' }),
    el('div', { class: 'big' }, [namedSwatch(z), countText(readKeys.length)]),
    el('div', { class: 'small', text: `Apple’s: ${yes(APPLE)} · Google’s: ${yes(GOOGLE)} · Huawei’s: ${yes(HUAWEI)} · Android Settings’: ${yes(SETTINGS)} · apps’ scanners: ${others.filter((k) => readKeys.includes(k)).length} of ${others.length}` }),
    el('div', { class: 'src', text: plain }),
    next,
  );
}

function setCursor(d) {
  state.d = d;
  state.offset = 0;
  $('cursor').value = String(d);
  renderBell();
  renderReadout();
  renderSpecimen();
}

function renderTakeaway() {
  const fi = DATA.frames.indexOf(BASE_FRAME);
  const every = [];
  for (let i = 0; i < N; i++) if (source(i).key === 'everyday') every.push(i);
  const allRead = every.filter((i) => COUNT[i] === ORDER.length).length / every.length;
  const ok = readsGroup(every, fi);
  const no = [...new Set(ORDER.filter((k) => !ok.includes(k)).map((k) => SPOKEN[k]))];
  const missed = 100 - Math.round(100 * allRead);
  $('spectrumTitle').textContent = missed >= 10 ? 'Even everyday prints fail on some scanners' : 'Easy codes scan everywhere. Hard ones split the phones.';
  $('takeaway').textContent = `Of everyday prints, ${missed}% are missed by at least one of the ${allWord()} scanners` + (no.length
    ? `; ${join(no)} read fewer than 9 in 10 of them.`
    : ', though each reads 9 in 10 or more of them.');
  $('bellNote').textContent = 'The curve’s shape is an illustrative mix of the sets, not a count of them.';
}

// ---- each scanner (inside "See each scanner") ---------------------------------------------

function renderLanes() {
  resolutionControl($('laneRes'), state.laneFrame, (f) => { state.laneFrame = f; renderLanes(); });
  const svg = $('lanes');
  const W = svg.clientWidth || 700;
  const stacked = W < 640; // phones: each name above its lane, without the technical line
  const rowH = stacked ? 50 : 34;
  const H = ORDER.length * rowH + 30;
  svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
  svg.setAttribute('height', H);
  svg.replaceChildren();
  const labels = ORDER.flatMap((key, r) => [
    sv('text', { x: 0, y: r * rowH + 15, class: 'strong', text: PLAIN[key][0] }, svg),
    ...(stacked ? [] : [sv('text', { x: 0, y: r * rowH + 29, class: 'muted', style: 'font-size:11px', text: PLAIN[key][1] }, svg)]),
  ]);
  const left = stacked ? 0 : Math.ceil(Math.max(...labels.map((t) => t.getComputedTextLength()))) + 16;
  const barY = stacked ? 22 : 6; // the lane's top, within its row
  const barH = 20;
  const x = (d) => left + ((d - X_MIN) / (X_MAX - X_MIN)) * (W - left - 4);
  $('lanesKey').replaceChildren(
    el('span', {}, [el('i', { class: 'ramp' }), 'Share of the codes read']),
    el('span', {}, [el('i', { class: 'uline' }), 'At least 9 in 10 read']),
  );
  $('lanesNote').textContent = 'Each cell holds codes of about the same difficulty. An orange line under a cell means the scanner read at least 9 in 10 of them; where its line stops and the others go on, it misses codes they read. Hover over or tap a cell for its count.';
  const fi = DATA.frames.indexOf(state.laneFrame);
  const rgb = (hex) => hex.match(/\w\w/g).map((h) => parseInt(h, 16));
  const a = rgb(css('--lane-0'));
  const b = rgb(css('--z-every'));
  const mix = (t) => `rgb(${a.map((c, j) => Math.round(c + (b[j] - c) * t)).join(',')})`;
  const span = (bin) => (bin === 0 ? [-10, -2] : bin === 51 ? [102, 110] : [(bin - 1) * 2, bin * 2]);
  const binOf = (d) => (d < 0 ? 0 : d > 100 ? 51 : 1 + Math.min(49, Math.floor(d / 2)));
  ORDER.forEach((key, r) => {
    const k = decIndex(key);
    const top = r * rowH;
    const bins = Array.from({ length: 52 }, () => [0, 0]);
    for (let i = 0; i < N; i++) {
      const bin = binOf(DATA.items.d[i]);
      bins[bin][0] += reads(i, fi, k);
      bins[bin][1] += 1;
    }
    bins.forEach(([rd, n], bin) => {
      if (!n) return;
      const [from, to] = span(bin);
      sv('rect', { x: x(from), y: top + barY, width: Math.max(1, x(to) - x(from) - 0.5), height: barH, fill: mix(rd / n) }, svg);
    });
    // the page's one rule, cell by cell: one line under each run of cells where it read at least 9 in 10
    let run = null;
    const flush = () => {
      if (run) sv('rect', { x: x(span(run[0])[0]), y: top + barY + barH + 2, width: Math.max(1, x(span(run[1])[1]) - x(span(run[0])[0]) - 0.5), height: 3,
        fill: css('--accent'), class: 'ok', 'data-key': key, 'data-cells': `${run[0]}-${run[1]}` }, svg);
      run = null;
    };
    bins.forEach(([rd, n], bin) => {
      const ok = n > 0 && rd >= RELIABLE * n;
      if (!ok || bin === 1 || bin === 51) flush(); // the end blocks stand apart from the scale
      if (ok) run = run ? [run[0], bin] : [bin, bin];
    });
    flush();
    const hit = sv('rect', { x: x(X_MIN), y: top, width: x(X_MAX) - x(X_MIN), height: rowH, fill: 'transparent' }, svg);
    const tipAt = (e) => {
      const rect = svg.getBoundingClientRect();
      const d = X_MIN + ((((e.clientX - rect.left) / rect.width) * W - left) / (W - left - 4)) * (X_MAX - X_MIN);
      const bin = d > 101 ? 51 : d < -1 ? 0 : binOf(Math.max(0, Math.min(100, d)));
      if (!bins[bin][1]) { hideTip(); return; }
      const [rd, n] = bins[bin];
      showTip(e, [['v', `${percent(rd / n)} read`], ['k', `${PLAIN[key][0]}: ${rd.toLocaleString()} of ${n.toLocaleString()} codes here`]]);
    };
    hit.addEventListener('pointermove', tipAt);
    hit.addEventListener('pointerdown', tipAt);
    hit.addEventListener('pointerleave', leaveTip);
  });
  sv('text', { x: x(X_MIN), y: H - 6, class: 'muted', text: '← Easier' }, svg);
  sv('text', { x: x(X_MAX), y: H - 6, class: 'muted', 'text-anchor': 'end', text: 'Harder →' }, svg);
}

// ---- what makes a code hard -------------------------------------------------------------

/** One sentence per pair, every number read off the ladder. */
function pairRule(key, lad) {
  const all = lastStep(lad, ORDER.length);
  const most = lastStep(lad, mostMin());
  const s = (li) => (li < 0 ? null : lad.levels[li].short);
  const grid = (v) => { const n = Number(v.replace('v', '')); return `version ${n} (${17 + 4 * n} squares across)`; };
  if (all < 0 || most < 0) return 'Even the easiest step did not scan reliably on most scanners.';
  switch (key) {
    case 'size':
      return `What counts is how many camera pixels cover each small square: most scanners need at least ${s(most)}, all ${allWord()} need ${s(all)}.`;
    case 'version': { // the captions carry the numbers; the sentence says why
      const lv = lad.levels[pairSteps(lad).bad];
      const big = printedBigger(lv);
      const squeezed = 'More data means more squares, so in the same space each one shrinks.';
      if (!big) return `${squeezed} At ${grid(lv.short)}, ${stepScanners(lv).length} of ${ORDER.length} scanners read it.`;
      const miss = ORDER.length - stepScanners(big.lv).length;
      return `${squeezed} Printed bigger, the same code reads again ` + (miss
        ? `on all but ${WORDS[miss]} scanner${miss === 1 ? ', which handles' : 's, which handle'} that many squares poorly.`
        : 'on every scanner.');
    }
    case 'blur':
      return all > 0
        ? `A little blur is fine: all ${allWord()} read up to ${s(all)} px of blur, most up to ${s(most)} px, on squares ${DATA.ladderBase.ppm} px wide.`
        : `Only a sharp image read on all ${allWord()}; most read up to ${s(most)} px of blur, on squares ${DATA.ladderBase.ppm} px wide.`;
    case 'contrast':
      return `All ${allWord()} need at least ${s(all)} contrast between ink and paper; most read faded ink down to ${s(most)}.`;
    case 'curve':
      return all > 0
        ? `Wrapped round a curve, the grid bends. All ${allWord()} read down to a bend radius of ${s(all)}× the code’s width; most, down to ${s(most)}×.`
        : `Wrapped round a curve, the grid bends. Most scanners read down to a bend radius of ${s(most)}× the code’s width.`;
    case 'corner': {
      const c = cornerFacts();
      if (!c) return 'Some scanner still read 9 in 10 codes at every step.';
      return `Scanners find a code by its corner squares, which error correction doesn’t protect: covering ${c.step.short} of one, ${c.share} of the whole code, left no scanner reading 9 codes in 10. A ${c.smudge.short} smudge elsewhere still left ${c.smudgeCount} of the ${ORDER.length} reading.`;
    }
    default:
      return '';
  }
}

/** The corner-square story, read off two ladders: the first corner step no scanner reads, its
 *  share of the whole code, and the first smudge step (kept off the corners) for comparison. */
function cornerFacts() {
  const corner = ladder('corner');
  const damage = ladder('damage');
  const li = corner.levels.findIndex((lv) => stepScanners(lv).length === 0);
  if (li < 0) return null;
  const side = 17 + 4 * DATA.ladderBase.version;
  const pct = parseFloat(corner.levels[li].short) / 100;
  const smudge = damage.levels[1];
  return { step: corner.levels[li], share: `${((100 * pct * 49) / (side * side)).toFixed(1)}%`, smudge, smudgeCount: stepScanners(smudge).length };
}

function renderPairs() {
  $('factorsLede').textContent = `Each pair changes one thing about a code all ${allWord()} scanners read. Under each picture: how many still read at least 9 in 10 codes like it.`;
  $('pairs').replaceChildren(...PAIRS.map(({ key, title }) => {
    const lad = ladder(key);
    const { good, bad } = pairSteps(lad);
    const fig = (lv, label = lv.label, from = lad) => {
      const ok = stepScanners(lv);
      return el('figure', {}, [
        el('img', { src: imgUrl(lv.img), alt: `${from.name}: ${label}`, loading: 'lazy' }),
        el('figcaption', {}, [
          el('span', { text: label }),
          el('span', { class: 'count', text: `${ok.length} of ${ORDER.length} scanners`, title: ok.length ? `Read reliably by ${join(ok.map((k) => PLAIN[k][0]))}` : 'Read reliably by none' }),
        ]),
      ]);
    };
    // too much data: the same codes printed bigger beside them squeezed into the space a smaller version reads in
    const big = key === 'version' ? printedBigger(lad.levels[bad]) : null;
    const v = (lv) => lv.short.replace('v', 'Version ');
    const figs = big
      ? [fig(big.lv, `${v(big.lv)}, printed bigger: ${pxOf(big.lv)} camera pixels per square`, big.lad),
        fig(lad.levels[bad], `${v(lad.levels[bad])}, squeezed: ${pxOf(lad.levels[bad])} camera pixels per square`)]
      : [fig(lad.levels[good]), fig(lad.levels[bad])];
    return el('article', { class: 'pair' }, [
      el('h3', { text: title }),
      el('div', { class: 'two' }, figs),
      el('p', { text: pairRule(key, lad) }),
    ]);
  }));
}

function renderExplorer() {
  const box = $('explorer');
  const lad = ladder(state.factor);
  state.level = Math.min(state.level, lad.levels.length - 1);
  const lv = lad.levels[state.level];
  const ok = stepScanners(lv);
  const z = zoneFor(ok.length);
  const need = Math.ceil(RELIABLE * lv.n);
  const pick = (li) => { state.level = li; renderExplorer(); };
  const pills = el('div', { class: 'pills', role: 'group', 'aria-label': 'Factor' }, DATA.ladders.map((l) => {
    const b = el('button', { type: 'button', 'aria-pressed': String(l.key === state.factor), text: l.name });
    b.addEventListener('click', () => { state.factor = l.key; state.level = 0; renderExplorer(); });
    return b;
  }));
  let control;
  if (lad.levels.length <= 3) { // a choice, not a scale: one button per step
    control = el('div', { class: 'seg', role: 'group', 'aria-label': lad.name }, lad.levels.map((l, li) => {
      const b = el('button', { type: 'button', 'aria-pressed': String(li === state.level), text: l.label });
      b.addEventListener('click', () => pick(li));
      return b;
    }));
  } else {
    const slider = el('input', { type: 'range', class: 'range', min: '0', max: String(lad.levels.length - 1), step: '1',
      value: String(state.level), 'aria-label': `${lad.name}: step`, 'aria-valuetext': lv.label });
    slider.addEventListener('input', () => { pick(Number(slider.value)); box.querySelector('input.range')?.focus(); });
    control = el('div', {}, [slider, el('div', { class: 'ends' }, [el('span', { text: 'Easier' }), el('span', { text: `Step ${state.level + 1} of ${lad.levels.length}` }), el('span', { text: 'Harder' })])]);
  }
  const rows = el('div', { class: 'rows' }, ORDER.map((key) => {
    const r = lv.reads[decIndex(key)];
    return el('div', { class: `row${r >= need ? ' ok' : ''}` }, [
      el('span', { class: 'label', text: PLAIN[key][0] }),
      el('span', { class: 'track' }, [el('span', { class: 'fill', style: `width:${(100 * r) / lv.n}%` }), el('span', { class: 'mark', style: `left:${100 * RELIABLE}%` })]),
      el('span', { class: 'val', text: `${r}/${lv.n}` }),
    ]);
  }));
  // a factor's steps, one column each; printed bigger lines up under the same versions of "Amount of data" (-1: none)
  const columns = (l) => (l.key === 'version_big'
    ? ladder('version').levels.map((lv) => l.levels.findIndex((s) => s.short === lv.short))
    : l.levels.map((_, li) => li));
  const tips = el('div', { class: 'tips' }, [
    el('h3', { text: 'Every factor, every step' }),
    ...DATA.ladders.map((l) => el('div', { class: 'tip-row' }, [
      el('span', { class: 'label', text: l.name }),
      el('div', { class: 'tip-cells', style: `grid-template-columns:repeat(${columns(l).length}, minmax(0, 1fr))` },
        columns(l).map((li, col) => {
          if (li < 0) { // printed bigger, this version would not fit the picture
            const short = ladder('version').levels[col].short;
            return el('span', { class: 'tip-none', text: short, title: `${short.replace('v', 'Version ')} at ${pxOf(l.levels[0])} pixels per square doesn’t fit a ${DATA.ladderFrame} × ${DATA.ladderFrame * 3 / 4} picture at every angle` });
          }
          const step = l.levels[li];
          const n = stepScanners(step).length;
          const zz = zoneFor(n);
          const b = el('button', { type: 'button', text: step.short, 'aria-label': `${l.name}, ${step.label}: ${n} of ${ORDER.length} scanners`,
            style: `background:${css(zz.tone)};color:${onTone(zz)}` });
          const tip = (e) => showTip(e, [['v', `${n} of ${ORDER.length} scanners`], ['k', `${l.name}: ${step.label}`]]);
          b.addEventListener('pointermove', tip);
          b.addEventListener('pointerdown', tip);
          b.addEventListener('pointerleave', leaveTip);
          b.addEventListener('click', () => { state.factor = l.key; state.level = li; renderExplorer(); box.scrollIntoView({ behavior: 'smooth', block: 'start' }); });
          return b;
        })),
    ])),
    el('div', { class: 'key' }, ZONES.map((zz) => el('span', {}, [swatch(zz), zz.range ? `${zz.name} (${zz.range})` : zz.name]))),
    el('p', { class: 'fine', text: `A step counts as read when a scanner reads at least ${need} of its ${lv.n} codes, at a ${DATA.ladderFrame}-px camera image.` }),
  ]);
  const b = DATA.ladderBase;
  const link = (href, text) => el('a', { href, text, target: '_blank', rel: 'noopener' });
  const primer = el('div', { class: 'primer' }, [ // the steps every factor below breaks one of
    el('h3', { text: 'How a scanner reads a QR code' }),
    el('ol', {}, [
      el('li', {}, [el('strong', { text: `${READ_STEPS[0]}.` })]),
      el('li', {}, [el('strong', { text: `${READ_STEPS[1]}` }), ' by its three corner squares, whose ', link(DENSO_QR, '1:1:3:1:1 stripes'), ' stand out from other print.']),
      el('li', {}, [el('strong', { text: `${READ_STEPS[2]}` }), ' between them, helped on bigger codes by smaller ', link(DENSO_QR, 'alignment squares'), '.']),
      el('li', {}, [el('strong', { text: `${READ_STEPS[3]}` }), ', each at its place in the grid.']),
      el('li', {}, [el('strong', { text: `${READ_STEPS[4]}` }), ', which repairs damaged squares by the ', link(QR_EC, 'Reed–Solomon method'), '.']),
    ]),
    el('p', { class: 'fine', text: 'Each factor names the step it breaks.' }),
  ]);
  box.replaceChildren(
    primer,
    pills,
    el('p', { class: 'about', text: lad.about }),
    ...(lad.breaks ? [el('p', { class: 'about breaks' }, [ // the step it breaks, in bold as in the list of steps
      el('strong', { text: `${lad.breaks.split(': ')[0]}. ` }), capital(lad.breaks.split(': ').slice(1).join(': '))])] : []),
    el('div', { class: 'explore' }, [
      el('figure', { style: 'margin:0' }, [
        el('img', { src: imgUrl(lv.img), alt: `${lad.name}: ${lv.label}` }),
        el('div', { class: 'step', text: lv.label }),
        el('p', { class: 'fine', text: lad.window > LADDER_WINDOW
          ? `Shown at ${lad.window === 2 * LADDER_WINDOW ? 'half' : `1/${lad.window / LADDER_WINDOW} of`} the camera’s scale, so bigger codes fit: one pixel here is ${WORDS[lad.window / LADDER_WINDOW] ?? lad.window / LADDER_WINDOW} pixels of a ${DATA.ladderFrame}-pixel-wide image.`
          : `Shown at the camera’s scale: one pixel here is one pixel of a ${DATA.ladderFrame}-pixel-wide image.` }),
        el('p', { class: 'fine', text: `How it is made: ${lad.how} Everything else stays as the base code: ${join([['version', `version ${b.version}`],
          ['ppm', `${b.ppm} camera pixels per square`], ['contrast', `contrast ${Math.round(100 * b.contrast)}%`], ['tilt', `tilted ${b.tilt}°`],
          ['blur', `blur ${b.blur} px`]].filter(([k]) => !(OWN_SETTINGS[lad.key] || []).includes(k)).map(([, text]) => text))}.` }),
      ]),
      el('div', {}, [
        control,
        el('div', { class: 'headline' }, el('span', { class: 'step' }, [namedSwatch(z), groupText(ok.length)])),
        rows,
        el('p', { class: 'fine', text: `Each bar: how many of the ${lv.n} codes the scanner read. Dark bars pass the line at ${need} of ${lv.n}.` }),
      ]),
    ]),
    tips,
  );
}

// ---- Android: the scanner depends on the app ---------------------------------------------

/** Each set's codes and every scanner's read rate on them, at frame index fi. */
function setRates(fi) {
  return SETS.map((set) => {
    const items = [];
    for (let i = 0; i < N; i++) if (set.match(source(i))) items.push(i);
    const rate = Object.fromEntries(ORDER.map((k) => [k, items.reduce((acc, i) => acc + reads(i, fi, decIndex(k)), 0) / items.length]));
    return { ...set, items, rate };
  });
}

/** Going from the base resolution to the highest, in one sentence: on any set, does a scanner read
 *  at least a point more, or a point fewer? */
function highNote() {
  const top = RESOLUTIONS[0].frame;
  const high = setRates(DATA.frames.indexOf(top));
  const base = setRates(DATA.frames.indexOf(BASE_FRAME));
  const diffs = high.flatMap((set, si) => ORDER.map((k) => set.rate[k] - base[si].rate[k]));
  const more = diffs.some((d) => d >= 0.01);
  const fewer = diffs.some((d) => d <= -0.01);
  const from = `From ${BASE_FRAME} to ${top} pixels`;
  if (more && fewer) return `${from}, some scanners read more and some read fewer.`;
  if (more) return `${from}, scanners read as many codes or more.`;
  if (fewer) return `${from}, scanners read as many codes or fewer.`;
  return '';
}

function renderAndroid() {
  resolutionControl($('gridRes'), state.gridFrame, (f) => { state.gridFrame = f; renderAndroid(); });
  const sets = setRates(DATA.frames.indexOf(state.gridFrame));
  const sam = state.gridFrame === DATA.samsung.frame; // Samsung's scanner was read at one resolution
  for (const set of sets) set.samsung = sam ? samsungRate(set.match).rate : null;
  const android = ORDER.filter(isAndroid);
  const others = otherApps();
  const kind = (k) => (k === APPLE ? 'apple' : k === GOOGLE ? 'google' : k === HUAWEI ? 'huawei' : k === SETTINGS ? 'own' : 'other');
  const mark = (k, set) => el('span', { class: `mark ${kind(k)}`, style: `left:${100 * set.rate[k]}%`,
    title: `${PLAIN[k][0]}: ${percent(set.rate[k])} of ${set.items.length.toLocaleString()} ${set.noun}` });
  const samsungMark = (set) => (sam ? [el('span', { class: 'mark samsung', style: `left:${100 * set.samsung}%`,
    title: `Samsung’s scanner: about ${about(set.samsung).slice(1)} of ${set.noun}, estimated from a sample` })] : []);
  const spread = (set) => { // the measured Android scanners: Samsung's estimate stays a mark of its own
    const v = android.map((k) => set.rate[k]);
    return [Math.min(...v), Math.max(...v)];
  };
  $('skey').replaceChildren(
    el('span', {}, [el('span', { class: 'mark apple' }), 'Apple’s scanner']),
    el('span', {}, [el('span', { class: 'mark google' }), 'Google’s scanner']),
    el('span', {}, [el('span', { class: 'mark samsung' }), sam ? 'Samsung’s scanner, estimated' : `Samsung’s scanner: ${SAMSUNG_RES()} only`]),
    el('span', {}, [el('span', { class: 'mark huawei' }), 'Huawei’s scanner']),
    el('span', {}, [el('span', { class: 'mark own' }), 'Android Settings’ scanner']),
    el('span', {}, [el('span', { class: 'mark other' }), `${others.length} scanners other apps are built on`]),
  );
  $('strips').replaceChildren(
    el('div', { class: 'srow shead', 'aria-hidden': 'true' }, [el('span'), el('span'), el('span', { class: 'sval', text: 'Android range' })]),
    ...sets.map((set) => {
      const [lo, hi] = spread(set);
      return el('div', { class: 'srow', role: 'listitem', 'aria-label': `${set.label}: Apple’s scanner ${percent(set.rate[APPLE])}; Google’s ${percent(set.rate[GOOGLE])}; ${sam ? `Samsung’s about ${about(set.samsung).slice(1)}; ` : ''}Huawei’s ${percent(set.rate[HUAWEI])}; Android Settings’ ${percent(set.rate[SETTINGS])}; Android scanners from ${percent(lo)} to ${percent(hi)}` }, [
        el('span', { class: 'slabel', text: set.label }),
        el('span', { class: 'strack' }, [
          el('span', { class: 'sband', style: `left:${100 * lo}%;width:${100 * (hi - lo)}%` }),
          ...others.map((k) => mark(k, set)),
          mark(SETTINGS, set),
          mark(APPLE, set),
          ...samsungMark(set), // a hollow square: above Apple's ring, below Huawei's and Google's marks
          mark(HUAWEI, set), // above Apple's ring, so it shows where they meet
          mark(GOOGLE, set), // last: where it meets Apple's ring it shows inside it
        ]),
        el('span', { class: 'sval', text: percent(lo) === percent(hi) ? percent(lo) : `${percent(lo)}–${percent(hi)}` }),
      ]);
    }),
    el('div', { class: 'srow saxis', 'aria-hidden': 'true' }, [el('span'), el('span', { class: 'strack' }, [el('span', { text: '0%' }), el('span', { text: '50%' }), el('span', { text: '100% read' })]), el('span')]),
  );
  const [cleanLo] = spread(sets[0]);
  const [toughLo, toughHi] = spread(sets[2]);
  const width = (set) => spread(set)[1] - spread(set)[0];
  const widens = width(sets[0]) < width(sets[1]) && width(sets[1]) < width(sets[2]); // clean, everyday, tough prints
  $('androidTitle').textContent = widens ? 'The gap opens on harder codes' : 'The gap, set by set';
  $('stripNote').textContent = `On clean prints every Android scanner read at least ${percent(cleanLo)}. On tough prints an iPhone read ${percent(sets[2].rate[APPLE])}, and Android scanners from ${percent(toughLo)} to ${percent(toughHi)}.`;
  const head = el('thead', {}, el('tr', {}, [el('th', { scope: 'col', text: '' }), ...sets.map((set) => el('th', { scope: 'col', text: set.label }))]));
  const samsungRow = el('tr', {}, [
    el('th', { scope: 'row' }, [el('span', { class: 'name', text: 'Samsung’s scanner' }), el('span', { class: 'what', text: `Samsung’s Camera app; estimated from a sample, ${SAMSUNG_RES()} only` })]),
    ...sets.map((set) => el('td', sam
      ? { 'aria-label': `Samsung’s scanner, ${set.noun}: about ${about(set.samsung).slice(1)} read, estimated`, text: about(set.samsung) }
      : { 'aria-label': `Samsung’s scanner, ${set.noun}: read at ${SAMSUNG_RES()} resolution only`, text: '—' })),
  ]);
  const body = el('tbody', {}, ORDER.flatMap((k) => [el('tr', {}, [
    el('th', { scope: 'row' }, [el('span', { class: 'name', text: PLAIN[k][0] }), el('span', { class: 'what', text: PLAIN[k][1] })]),
    ...sets.map((set) => el('td', { 'aria-label': `${PLAIN[k][0]}, ${set.noun}: ${percent(set.rate[k])} read`, title: `${percent(set.rate[k])} of ${set.items.length.toLocaleString()} ${set.noun}`, text: percent(set.rate[k]) })),
  ]), ...(k === GOOGLE ? [samsungRow] : [])]));
  $('phones').replaceChildren(head, body);
  $('numbers').hidden = !state.showPct;
  const toggle = el('button', { class: 'linklike', type: 'button', text: state.showPct ? 'Hide the numbers' : 'Show the numbers' });
  toggle.addEventListener('click', () => { state.showPct = !state.showPct; renderAndroid(); });
  $('gridNote').replaceChildren(toggle);
}

// ---- advice -----------------------------------------------------------------------------

function renderAdvice() {
  const fi = DATA.frames.indexOf(BASE_FRAME);
  const size = ladder('size');
  const colors = ladder('colors');
  const dots_ = ladder('dots');
  const pxMost = size.levels[Math.max(0, lastStep(size, mostMin()))].short;
  const pxAll = size.levels[Math.max(0, lastStep(size, ORDER.length))].short;
  const lightOk = stepScanners(colors.levels[colors.levels.length - 1]);
  const lost = sayNames(ORDER.filter((k) => !lightOk.includes(k)));
  const dotStep = dots_.levels[firstBelow(dots_, ORDER.length)];
  const dotLost = dotStep ? sayNames(ORDER.filter((k) => !stepScanners(dotStep).includes(k))) : [];
  const c = cornerFacts();
  const tough = [];
  for (let i = 0; i < N; i++) if (source(i).key === 'tough') tough.push(i);
  const share = (key) => tough.reduce((acc, i) => acc + reads(i, fi, decIndex(key)), 0) / tough.length;
  const rate = (key) => percent(share(key));
  const otherRates = otherApps().map(share);
  const items = [
    ['Size the print for the data.', 'More data means smaller squares at the same printed size. Print bigger as the data grows, or keep it short, such as with a short GS1 Digital Link domain.'],
    ['Print it big enough for the distance.', `Most scanners need about ${pxMost} camera pixels per square, and all ${allWord()} need ${pxAll}. Twice the distance needs twice the size.`],
    ['Keep it dark on light, made of solid squares.', `Light-on-dark codes lost ${join(lost)}.${dotStep ? ` Round dots, even ${dotStep.short} of a square wide, lost ${join(dotLost)}.` : ''}`],
    ['Keep the three corner squares clean.', c ? `Covering ${c.step.short} of one corner square, ${c.share} of the whole code, left no scanner reading 9 codes in 10.` : 'A covered corner square cost scanners at every step.'],
    ['Test with several phones and apps, not just an iPhone.', `On our tough prints an iPhone read ${rate(APPLE)}, Samsung’s scanner about ${about(samsungRate((s) => s.key === 'tough').rate).slice(1)}, and some apps’ scanners ${percent(Math.min(...otherRates))}.`],
  ];
  $('advice').replaceChildren(...items.map(([head, body]) => el('li', {}, el('div', {}, [el('strong', { text: head }), el('span', { text: body })]))));
}

// ---- how we measured --------------------------------------------------------------------

/** The false-reading check, from the measured negatives: images with no code at all. */
function falseReadsText() {
  const neg = DATA.checks.negatives;
  const fooled = ORDER.filter((k) => neg.falseReads[k] > 0);
  const result = fooled.length
    ? fooled.map((k) => `${PLAIN[k][0]} returned something on ${neg.falseReads[k]}`).join('; ')
    : `None of the ${allWord()} returned anything`;
  const sam = DATA.samsung.negatives;
  const kinds = sam ? Object.keys(sam.otherBarcodes.read) : [];
  const other = kinds.reduce((acc, k) => acc + sam.otherBarcodes.read[k], 0);
  const samsung = sam ? ` Samsung’s scanner read them too, on its phone: ${sam.falseReads ? `${sam.falseReads} false ${sam.falseReads === 1 ? 'reading' : 'readings'}` : 'no false readings'}${other ? `. Among the other barcode types it read the ${other} ${join(kinds)} codes, each correctly: it reads ${join(kinds)} as well as QR codes, while the scanners above, as we ran them, read QR codes only` : ''}.` : '';
  return `To check for false readings, all ${allWord()} scanners also read ${neg.n} images with no code, made to fool them with look-alike corner squares, checkerboards, clutter and other barcode types. ${result}.${samsung}`;
}

/** How Samsung's scanner was read, and why its figures are estimates. */
function samsungMethod() {
  const s = DATA.samsung;
  const [lo, hi] = s.range;
  return [
    `Samsung’s scanner runs only on Samsung phones, and reading pictures through a borrowed phone is slow, so it read a random sample of each set, ${s.counted.toLocaleString()} codes in all, at ${s.frame} px only, on a real ${s.phone} (Samsung Camera ${s.camera}, One UI ${s.oneUi}, Android ${s.android}) borrowed through Samsung’s Remote Test Lab. Each picture was opened from the phone’s gallery in that scanner, as a person opens a saved photo, inside a white border so that the crop box the gallery shows first keeps all of it. Its figures are estimates: its gap to the other scanners on the codes it read, added to their results on all of a set’s codes. On all codes that comes to about ${percent(s.estimate)}, between ${percent(lo)} and ${percent(hi)} with 95% confidence. Older Samsung phones may run an older version of its scanner.`,
    `For Samsung’s scanner, a read is the text on its result card, equal to the code’s content, and a miss is its own “Couldn’t read QR code”. Some content it never shows as text: contacts, Wi-Fi, calendar, SMS, location, email and phone codes and Facebook links go straight to an app, and binary content and JSON text show as an empty card. Its log shows it read them, but nothing on screen can be checked against the code, so the ${s.uncheckable} codes holding such content were left out of its comparison, for every scanner.`,
  ];
}

function renderMethod() {
  const count = (pred) => DATA.sources.filter(pred).reduce((acc, s) => acc + s.count, 0);
  const made = count((s) => s.group === 'made' && s.key !== 'ladder');
  const real = count((s) => s.group === 'dataset');
  const ladders = count((s) => s.key === 'ladder');
  const src = (key) => count((s) => s.key === key).toLocaleString();
  const qrdn = DATA.sources.find((s) => s.key === 'qrdn').parts; // clean, tiled and distorted images
  const n = DATA.ladders[0].levels[0].n;
  const total = N * DATA.frames.length * DATA.decoders.length + ladders * DATA.decoders.length;
  const para = (t) => el('p', { text: t });
  const a = (href, text) => el('a', { href, text, target: '_blank', rel: 'noopener' });
  const list = (rows) => el('ul', {}, rows.map((t) => el('li', { text: t })));
  const strip = sv('svg', { class: 'chart', role: 'img', 'aria-label': 'Where each set of codes sits on the difficulty scale' });
  const sam = DATA.samsung;
  const [samHow, samRead] = samsungMethod();
  $('methodBody').replaceChildren(el('div', { class: 'method' }, [
    el('h3', { text: 'What we tested' }),
    para(`${made.toLocaleString()} codes made for this page: clean, everyday and tough prints captured by a simulated phone camera. ${real.toLocaleString()} codes from four public research datasets, most of them hardest cases: ${src('boofcv')} real photos (BoofCV), ${src('broken104')} real codes that fail (Broken QR 104), ${src('syn10k')} computer-made warped codes (syn10k), and ${src('qrdn')} from QR-DN1.0: ${qrdn.distorted.toLocaleString()} distorted, noisy codes, and ${(qrdn.clean + qrdn.tiled).toLocaleString()} easy ones, its clean originals (${qrdn.clean.toLocaleString()}) alone or tiled four to a picture (${qrdn.tiled.toLocaleString()}). And ${ladders.toLocaleString()} codes for the factors: one code, changed one step at a time, ${n} codes per step.`),
    el('h3', { text: 'How' }),
    para(`Every code on the scale was read at seven image resolutions, from ${DATA.frames[0]} down to ${DATA.frames[DATA.frames.length - 1]} pixels on the long side: “at ${BASE_FRAME} px” means larger images were shrunk to ${BASE_FRAME}, and smaller ones were read as they are, never enlarged. Most research-dataset images are 512 × 512, so only the settings below 640 shrink them. The factor images were read at ${DATA.ladderFrame}. All ${allWord()} scanners read every image at every setting: ${total.toLocaleString()} results. Smaller images stand in for apps with low-resolution camera feeds, and for codes seen from farther away.`),
    para(samHow),
    el('h3', { text: 'What counts as a read' }),
    para('Only the code’s exact content, byte for byte. Finding a code without reading it, or reading it wrong, is a miss; so is anything slower than 20 seconds.'),
    para(`The right content comes with each code: we made it, or its dataset published it. Two datasets come without it: BoofCV’s photos, and QR-DN, whose distorted images take the content of their clean originals. There the content is what other decoders read identically, and a code is kept only if at least two decoders other than the scanner being scored agree. That left out ${DATA.checks.dependentTruth} photos.`),
    para(samRead),
    para(falseReadsText()),
    el('h3', { text: 'How many scanners read it' }),
    para(`One rule throughout. A single code is read by a scanner, or not; its shade counts the scanners that read it at ${BASE_FRAME} px: ${ZONES[0].words}, ${ZONES[1].words}, ${ZONES[2].words} or ${ZONES[3].words}; Samsung’s, read only on a sample, is not among the ${allWord()}. A group of codes, such as a factor step or a set, counts a scanner when it reads at least 9 in 10 of them: for a factor step, ${Math.ceil(RELIABLE * DATA.ladders[0].levels[0].n)} of its ${DATA.ladders[0].levels[0].n} codes.`),
    el('h3', { text: 'Where a code sits' }),
    para(`Only the reads decide: a standard item-response model places each code where scanner-and-resolution pairs start to fail, across all seven image resolutions. Codes every pair read sit at the far left; codes none read, at the far right. The curve on the scale is an illustrative mix: half everyday prints, a fifth each clean and tough, a tenth hardest cases.`),
    strip,
    el('h3', { text: 'Scanners' }),
    el('ul', {}, ORDER.map(decoder).flatMap((d) => [
      el('li', {}, [`${d.name}: ${d.detail}. `, d.key === GOOGLE ? `${versionsNote()} ` : '', d.key === SETTINGS ? `${invertedNote()} ` : '', ...see(SCANNER_PAGES[d.key])]),
      ...(d.key === GOOGLE ? [el('li', {}, [`Samsung’s scanner: the QR scanner in Samsung’s Camera app ${sam.camera}, which the QR button in Quick Settings opens on Samsung phones, read on a real ${sam.phone} (${sam.model}, One UI ${sam.oneUi}, Android ${sam.android}), each picture opened from its gallery. Samsung doesn’t name its decoder, but the phone shows whose it is: the Camera app decodes with a library that carries the name of Quram, a Korean imaging-software company, and the decoding engine names itself in the phone’s log. Quram sells a QR and barcode scanner of its own and names Samsung among its customers. `,
        ...see([[SAMSUNG_QR, 'Samsung’s guide to scanning QR codes'], [QURAM, 'Quram (Quramsoft)'], [SAMSUNG_RTL, 'Samsung’s Remote Test Lab, where we borrowed the phone']])])] : []),
    ])),
    el('h3', { text: 'Smartphones in the world' }),
    el('p', {}, [`People: at the end of 2025, ${WORLD_PHONES.people.billions} billion people, ${WORLD_PHONES.people.share}% of the world’s population, were using their own smartphone to go online (`,
      a(WORLD_PHONES.people.url, 'GSMA, The State of Mobile Internet Connectivity 2026'), ', p. 32). It counts people, not phones or SIM cards. Counting any mobile phone, ',
      `${WORLD_PHONES.anyPhone.share}% of people aged 10 and over own one (`, a(WORLD_PHONES.anyPhone.url, 'ITU, Facts and Figures 2025'), ').']),
    el('p', {}, ['Phones in use: “nearly one in four active smartphones is an iPhone” (', a(WORLD_PHONES.inUse.url, 'Counterpoint Research'),
      ', installed base in 2025, published February 2026); with more than a billion iPhones, the other three in four are more than 3 billion. The rest are almost all Android; a few percent are Huawei phones on HarmonyOS. Devices with Google Play, which carries Google’s scanner: Google says its enhanced fraud protection now covers “more than 2.8 billion Android devices” in 185 markets (',
      a(WORLD_PHONES.googlePlay.url, 'Google, February 2026'), '). New phones: iPhones were ',
      `${WORLD_PHONES.shipped.share}% of the ${WORLD_PHONES.shipped.total} billion smartphones shipped in 2025 (`, a(WORLD_PHONES.shipped.url, 'IDC'), ').']),
    el('p', {}, ['Web counters give iPhones more: ', a(WORLD_PHONES.web.url, 'StatCounter'),
      `, often quoted, shows about ${WORLD_PHONES.web.ios}% of mobile page views in September 2026. It counts page views on the websites that carry its code, so it measures browsing, not phones.`]),
    el('h3', { text: 'Sources' }),
    el('ul', {}, [
      el('li', {}, `Every read, rate and boundary on this page: our own measurements, ${total.toLocaleString()} results, and ${(sam.measured + (sam.negatives?.n ?? 0)).toLocaleString()} read on a Samsung phone.`),
      el('li', {}, ['Android’s QR button: on the lock screen and in Quick Settings it opens the scanner a setting names; Android’s own code says that “on the eligible devices this activity is provided by GMS core”, Google Play services (', a(AOSP_QR_BUTTON, 'SystemUiDeviceConfigFlags.java'), '). The phone maker’s default is empty in Android’s code (', a(AOSP_QR_DEFAULT, 'config.xml'), '); on Google’s own Android 14 image it is set to Play services’ ML Kit barcode scanner (com.google.android.gms/.mlkit.barcode.ui.PlatformBarcodeScanningActivityProxy), which we checked on the emulator we measured.']),
      el('li', {}, [`Samsung’s QR button: on the ${sam.phone} we read, the “Scan QR code” button in Quick Settings belongs to Samsung’s Camera app and opens its scanner, though the phone’s Android setting names Google’s. We checked on the phone, borrowed through `, a(SAMSUNG_RTL, 'Samsung’s Remote Test Lab'), '.']),
      el('li', {}, ['Android Settings’ scanner: ', a(ANDROID_SOURCE, 'QrCamera.java'), ' in Android’s Settings library, which decodes Wi-Fi QR codes with ZXing; Android ships ZXing 3.5.2 (', a(AOSP_ZXING, 'METADATA'), ').']),
      el('li', {}, ['Huawei’s scanner: Scan Kit is the scanning service Huawei documents for HarmonyOS and for HMS Core, the services layer of its Android phones (', a(HUAWEI_HARMONY, 'HarmonyOS'), ', ', a(HUAWEI_KIT, 'HMS Core'), '). We checked that the three models in the kit we measured are byte-identical to those in HMS Core 6.16.2.300.']),
      el('li', {}, ['Image resolution: CameraX analyses frames at 640 × 480 unless an app asks for more (', a(CAMERAX_DOCS, 'Android developer documentation'), ').']),
      el('li', {}, 'Smartphones in the world: GSMA, ITU, Counterpoint Research, Google and IDC, as linked above, each quoted from the publisher.'),
      el('li', {}, 'Research datasets: listed under Codes and credits, each used under its own terms.'),
    ]),
    el('h3', { text: 'Not included' }),
    para('Not yet: the scanners other phone makers build into their phones, such as Xiaomi’s, OPPO’s, vivo’s, Transsion’s and Honor’s. Each runs only on its maker’s phones, so it can be measured only on real devices borrowed from a test lab, far more slowly than the scanners above. Samsung’s came first, for its more than a billion phones, and even it was read on a sample of the codes; the others are left for future work. Huawei’s is here because Huawei offers its scanner to developers as a kit.'),
    para('Never: the text inside the codes. The page doesn’t print it.'),
    el('h3', { text: 'Codes and credits' }),
    list(DATA.sources.map((s) => `${s.name}: ${s.count.toLocaleString()} images. ${s.detail}.`)),
    el('p', {}, ['The codes made for this page, with their contents and every setting used to make them, and which scanners read each one, are published as a dataset: ',
      a(SYNTH_DATASET, 'QR Scan Difficulty: synthetic codes'), '. Under each example code, a link opens the exact picture the scanners read.']),
    para('Images from the research datasets are cropped and resized here; a code in an image can be read by any phone. To have an image removed, open a discussion on its dataset page. Payloads of codes made here are invented.'),
    el('h3', { text: 'Why we made this' }),
    para(PURPOSE),
    el('h3', { text: 'Disclosures' }),
    para(DISCLOSURE),
    para(`Built ${DATA.built}.`),
  ]));
  renderStrip(strip);
}

function renderStrip(svg) {
  const W = svg.clientWidth || 700;
  const left = W < 640 ? 112 : 180;
  const rows = DATA.sources.filter((s) => s.key !== 'ladder');
  const rowH = 22;
  const H = rows.length * rowH + 26;
  const x = (d) => left + ((Math.max(X_MIN, Math.min(X_MAX, d)) - X_MIN) / (X_MAX - X_MIN)) * (W - left - 4);
  svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
  svg.setAttribute('height', H);
  svg.replaceChildren();
  rows.forEach((s, r) => {
    const si = DATA.sources.indexOf(s);
    const ds = DATA.items.d.filter((_, i) => DATA.items.s[i] === si).sort((p, q) => p - q);
    const q = (f) => ds[Math.round(f * (ds.length - 1))];
    const yy = r * rowH + rowH / 2;
    sv('text', { x: 0, y: yy + 4, text: s.name }, svg);
    sv('line', { x1: x(q(0.1)), x2: x(q(0.9)), y1: yy, y2: yy, stroke: css('--ink-3'), 'stroke-width': 1 }, svg);
    sv('rect', { x: x(q(0.25)), y: yy - 3, width: Math.max(2, x(q(0.75)) - x(q(0.25))), height: 6, rx: 3, fill: css('--ink-3') }, svg);
    sv('circle', { cx: x(q(0.5)), cy: yy, r: 4, fill: css('--ink'), stroke: css('--surface'), 'stroke-width': 2 }, svg);
  });
  sv('text', { x: x(X_MIN), y: H - 4, class: 'muted', text: '← Easier' }, svg);
  sv('text', { x: x(X_MAX), y: H - 4, class: 'muted', 'text-anchor': 'end', text: 'Harder →' }, svg);
}

// ---- wiring -----------------------------------------------------------------------------

function renderLede() {
  $('lede').textContent = `Every code on one scale, from easy to hard, shaded by how many of ${allWord()} scanners read it: Apple’s, Google’s, Huawei’s, Android Settings’ and ${WORDS[otherApps().length]} that apps use. Move the slider to see a code, and try it with your phone.`;
}

function renderAll() {
  renderVersus();
  renderIntro();
  renderWho();
  renderLede();
  renderKey();
  renderBell();
  renderReadout();
  renderSpecimen();
  renderTakeaway();
  renderPairs();
  renderAndroid();
  renderAdvice();
  if ($('lanesMore').open) renderLanes();
  if ($('factorsMore').open) renderExplorer();
  if ($('method').open) renderMethod();
}

async function main() {
  const params = new URLSearchParams(location.search);
  const theme = params.get('theme');
  if (theme === 'light' || theme === 'dark') document.documentElement.dataset.theme = theme;
  DATA = await (await fetch('data/site.json', { cache: 'no-cache' })).json(); // always ask the server: never a stale copy
  RES = decodeResults(DATA);
  NF = DATA.frames.length;
  N = DATA.items.s.length;
  ORDER = DATA.displayOrder;
  ZONES = makeZones(ORDER.length);
  const fi = DATA.frames.indexOf(BASE_FRAME);
  COUNT = Uint8Array.from({ length: N }, (_, i) => ORDER.reduce((s, k) => s + reads(i, fi, decIndex(k)), 0));
  BELL = bellData();
  HIGH_NOTE = highNote();
  if (params.has('d') && Number.isFinite(Number(params.get('d')))) state.d = Math.max(PILE_LO, Math.min(PILE_HI, Number(params.get('d'))));
  if (params.has('factor') && DATA.ladders.some((l) => l.key === params.get('factor'))) state.factor = params.get('factor');
  if (params.has('step')) state.level = Math.max(0, Number(params.get('step')) || 0);
  for (const id of ['lanesMore', 'factorsMore', 'method']) if (params.get('open')?.split(',').includes(id)) $(id).open = true;
  $('cursor').value = String(state.d);
  $('cursor').addEventListener('input', (e) => setCursor(snap(Number(e.target.value))));
  $('lanesMore').addEventListener('toggle', () => { if ($('lanesMore').open) renderLanes(); });
  $('factorsMore').addEventListener('toggle', () => { if ($('factorsMore').open) renderExplorer(); });
  $('method').addEventListener('toggle', () => { if ($('method').open) renderMethod(); });
  renderAll();
  document.addEventListener('pointerdown', (e) => { if (e.pointerType === 'touch') hideTip(); }, true); // before a tapped tip shows
  window.addEventListener('scroll', hideTip, { passive: true });
  let raf = 0;
  new ResizeObserver(() => {
    cancelAnimationFrame(raf);
    raf = requestAnimationFrame(() => {
      renderBell();
      if ($('lanesMore').open) renderLanes();
      if ($('method').open) renderMethod();
    });
  }).observe(document.querySelector('.page'));
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', renderAll);
}

main().catch((err) => {
  $('lede').textContent = `Could not load the measurements: ${err.message}`;
});