openreadout-preview 0.4.0

PNG and JPEG previews of OpenReadout datasets
Documentation
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
//! Image previews: plane selection, pyramid level choice, projection, resampling to the
//! requested size, contrast and colour mapping, then the rulers frame ([`crate::rulers`]).

use openreadout_core::model::{FileInfo, ImageInfo};
use openreadout_core::pixel::{PixelType, Plane};
use openreadout_core::reader::{Dataset, PlaneIndex};
use openreadout_core::region::Region;
use openreadout_core::select::Selection;
use openreadout_core::{Error, Result};

use crate::color::{self, Rgb};
use crate::diffraction::{self as dif, Diffraction};
use crate::figure_frame::{self, FigureLayout};
use crate::rulers::{self, Layout, Mapping};
use crate::{
    Axis, Contrast, ImagePreview, Lut, PreviewChannel, PreviewOutput, PreviewRequest, SourcePoint,
    split_select,
};
use openreadout_figure::{Figure, Raster, Rect};

/// Most channels blended into one composite.
const MAX_COMPOSITE_CHANNELS: usize = 16;
/// Percentiles used by `auto` contrast.
const AUTO_PERCENTILES: (f64, f64) = (0.1, 99.9);

/// One resampled band of values (NaN where a cell had no finite sample).
struct Band {
    w: usize,
    h: usize,
    v: Vec<f32>,
}

/// All samples of a plane as f32, interleaved as stored (`samples_per_pixel` per pixel).
fn samples(p: &Plane) -> Result<Vec<f32>> {
    let n = p.width as usize * p.height as usize * p.samples_per_pixel as usize;
    let bps = p.pixel_type.bytes_per_sample();
    if p.data.len() < n * bps {
        return Err(Error::Other(format!(
            "plane holds {} bytes, expected {}",
            p.data.len(),
            n * bps
        )));
    }
    let d = &p.data[..n * bps];
    Ok(match p.pixel_type {
        PixelType::Uint8 => d.iter().map(|&b| f32::from(b)).collect(),
        PixelType::Int8 => d.iter().map(|&b| f32::from(b as i8)).collect(),
        PixelType::Uint16 => d
            .as_chunks::<2>()
            .0
            .iter()
            .map(|c| f32::from(u16::from_le_bytes([c[0], c[1]])))
            .collect(),
        PixelType::Int16 => d
            .as_chunks::<2>()
            .0
            .iter()
            .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])))
            .collect(),
        PixelType::Uint32 => d
            .as_chunks::<4>()
            .0
            .iter()
            .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32)
            .collect(),
        PixelType::Int32 => d
            .as_chunks::<4>()
            .0
            .iter()
            .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32)
            .collect(),
        PixelType::Float => d
            .as_chunks::<4>()
            .0
            .iter()
            .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
            .collect(),
        PixelType::Double => d
            .as_chunks::<8>()
            .0
            .iter()
            .map(|c| f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]) as f32)
            .collect(),
        // 64-bit integers, and complex samples drawn by their modulus
        other => d
            .chunks_exact(bps)
            .map(|c| other.sample_f64(c) as f32)
            .collect(),
    })
}

/// For each of `n_out` output cells over `n_in` source cells: the source cells it covers and
/// how much of each (an area-average box filter; fractional at the edges). Enlarging maps each
/// output cell to the one source cell under its centre, so pixels stay crisp squares.
fn weights(n_in: usize, n_out: usize) -> Vec<Vec<(usize, f32)>> {
    let scale = n_in as f64 / n_out.max(1) as f64;
    (0..n_out)
        .map(|o| {
            if scale <= 1.0 {
                let c = (((o as f64 + 0.5) * scale) as usize).min(n_in.saturating_sub(1));
                return vec![(c, 1.0)];
            }
            let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n_in as f64));
            let mut v = Vec::with_capacity(scale.ceil() as usize + 1);
            let mut i = a.floor() as usize;
            while (i as f64) < b && i < n_in {
                let lo = a.max(i as f64);
                let hi = b.min((i + 1) as f64);
                if hi > lo {
                    v.push((i, (hi - lo) as f32));
                }
                i += 1;
            }
            v
        })
        .collect()
}

/// Resample sample `s` (of `spp` interleaved) of a `w`×`h` plane to `ow`×`oh` with an area
/// average (or nearest neighbour when enlarging), separably: rows first, then columns.
/// Non-finite samples are left out of the average; a cell with none is NaN.
fn resample(src: &[f32], w: usize, h: usize, spp: usize, s: usize, ow: usize, oh: usize) -> Band {
    if ow == w && oh == h {
        return Band {
            w,
            h,
            v: (0..w * h).map(|i| src[i * spp + s]).collect(),
        };
    }
    let wx = weights(w, ow);
    let wy = weights(h, oh);
    // horizontal pass: h rows of ow (sum, weight)
    let mut rows = vec![(0f32, 0f32); h * ow];
    for y in 0..h {
        let line = &src[y * w * spp..(y + 1) * w * spp];
        for (ox, ws) in wx.iter().enumerate() {
            let (mut sum, mut wt) = (0f32, 0f32);
            for &(x, k) in ws {
                let v = line[x * spp + s];
                if v.is_finite() {
                    sum += v * k;
                    wt += k;
                }
            }
            rows[y * ow + ox] = (sum, wt);
        }
    }
    let mut v = vec![f32::NAN; ow * oh];
    for (oy, ws) in wy.iter().enumerate() {
        for ox in 0..ow {
            let (mut sum, mut wt) = (0f32, 0f32);
            for &(y, k) in ws {
                let (rs, rw) = rows[y * ow + ox];
                sum += rs * k;
                wt += rw * k;
            }
            if wt > 0.0 {
                v[oy * ow + ox] = sum / wt;
            }
        }
    }
    Band { w: ow, h: oh, v }
}

/// The drawn size of a `w`×`h` plane whose longer side should be `fit` pixels: the same aspect
/// ratio, at least 1 × 1.
fn fitted(w: u32, h: u32, fit: u32) -> (usize, usize) {
    let long = w.max(h).max(1);
    let k = f64::from(fit.max(1)) / f64::from(long);
    let side = |n: u32| ((f64::from(n) * k).round() as usize).max(1);
    (side(w), side(h))
}

/// The height a plane of `h` rows is drawn at so its pixels keep their physical aspect
/// (`physical_size.y / physical_size.x`); `h` when the pixels are square or not calibrated.
fn aspect_height(im: &ImageInfo, h: u32) -> u32 {
    match (im.physical_size.x, im.physical_size.y) {
        (Some(x), Some(y)) if x > 0.0 && y > 0.0 && ((y / x) - 1.0).abs() > 0.01 => {
            ((f64::from(h) * y / x).round() as u32).clamp(1, 1 << 16)
        }
        _ => h,
    }
}

/// `(level, width, height)` of every pyramid level the reader describes (level 0 first).
/// Levels with fewer z planes than the image (Imaris downsamples z too) are left out: the
/// picture's z index counts level-0 planes.
fn pyramid(im: &ImageInfo) -> Vec<(u32, u32, u32)> {
    if !im.resolution_levels.is_empty() {
        return im
            .resolution_levels
            .iter()
            .filter(|l| l.level < im.pyramid_levels.max(1))
            .filter(|l| l.size_z.is_none_or(|z| z == im.size_z))
            .map(|l| (l.level, l.size_x, l.size_y))
            .collect();
    }
    let mut out = vec![(0, im.size_x, im.size_y)];
    if let Some(levels) = im.extra.get("pyramid").and_then(|v| v.as_array()) {
        for l in levels {
            let get = |k: &str| l.get(k).and_then(serde_json::Value::as_u64);
            if let (Some(level), Some(w), Some(h)) = (get("level"), get("size_x"), get("size_y"))
                && level > 0
                && level < u64::from(im.pyramid_levels.max(1))
            {
                out.push((level as u32, w as u32, h as u32));
            }
        }
    }
    out
}

/// The most downsampled level whose longer side is still ≥ `max_size` (level 0 if none is).
fn choose_level(im: &ImageInfo, max_size: u32) -> u32 {
    pyramid(im)
        .into_iter()
        .filter(|&(_, w, h)| w.max(h) >= max_size)
        .min_by_key(|&(l, w, h)| (w.max(h), l))
        .map_or(0, |(l, _, _)| l)
}

/// The most downsampled level at which the full-resolution `region` still spans ≥ `max_size`
/// pixels on its longer side (level 0 if none does), and the region mapped onto it.
fn choose_region_level(im: &ImageInfo, region: Region, max_size: u32) -> (u32, Region) {
    let base = (im.size_x, im.size_y);
    pyramid(im)
        .into_iter()
        .map(|(l, w, h)| (l, region.rescale(base, (w, h))))
        .filter(|(l, r)| *l == 0 || r.width.max(r.height) >= max_size)
        .min_by_key(|(l, r)| (r.width.max(r.height), *l))
        .unwrap_or((0, region))
}

/// Size of pyramid level `level` of `im`, when the reader describes it.
fn level_dims(im: &ImageInfo, level: u32) -> Option<(u32, u32)> {
    pyramid(im)
        .into_iter()
        .find(|&(l, _, _)| l == level)
        .map(|(_, w, h)| (w, h))
}

/// The display windows a file stores (`images[].extra.windows`): `(center, width)`.
fn stored_windows(im: &ImageInfo) -> Vec<(f64, f64)> {
    im.extra
        .get("windows")
        .and_then(serde_json::Value::as_array)
        .map(|v| {
            v.iter()
                .filter_map(|w| {
                    let c = w.get("center")?.as_f64()?;
                    let wd = w.get("width")?.as_f64()?;
                    (c.is_finite() && wd.is_finite() && wd > 0.0).then_some((c, wd))
                })
                .collect()
        })
        .unwrap_or_default()
}

fn resolve_contrast(
    c: Contrast,
    im: &ImageInfo,
    rgb: bool,
    notes: &mut Vec<String>,
) -> Result<Contrast> {
    let pt = im.pixel_type;
    let hu = im
        .extra
        .get("value_unit")
        .and_then(serde_json::Value::as_str)
        == Some("HU");
    Ok(match c {
        Contrast::Auto if rgb && pt == PixelType::Uint8 => Contrast::Raw,
        // medical images carry their display window; CT without one gets the soft-tissue preset
        Contrast::Auto if !rgb => match stored_windows(im).first() {
            Some(&(center, width)) => {
                notes.push(format!(
                    "contrast: the file's display window (center {center}, width {width}); contrast window:brain, window:bone, ... for presets"
                ));
                Contrast::Window(center, width)
            }
            None if hu => {
                notes.push("contrast: CT soft-tissue window (center 40 HU, width 400 HU); contrast window:bone, window:brain, window:lung, ... for others".into());
                Contrast::Window(40.0, 400.0)
            }
            None => Contrast::Percentile(AUTO_PERCENTILES.0, AUTO_PERCENTILES.1),
        },
        Contrast::Auto => Contrast::Percentile(AUTO_PERCENTILES.0, AUTO_PERCENTILES.1),
        Contrast::StoredWindow(n) => {
            let w = stored_windows(im);
            let &(center, width) = w.get(n).ok_or_else(|| {
                Error::Usage(format!(
                    "window:file:{n}: the image stores {} display windows (images[].extra.windows)",
                    w.len()
                ))
            })?;
            Contrast::Window(center, width)
        }
        other => other,
    })
}

fn raw_range(pt: PixelType) -> (f64, f64) {
    match pt {
        PixelType::Uint8 => (0.0, 255.0),
        PixelType::Int8 => (-128.0, 127.0),
        PixelType::Uint16 => (0.0, 65_535.0),
        PixelType::Int16 => (-32_768.0, 32_767.0),
        PixelType::Uint32 => (0.0, f64::from(u32::MAX)),
        PixelType::Int32 => (f64::from(i32::MIN), f64::from(i32::MAX)),
        // Floats, and any pixel type added to the core model after this renderer.
        _ => (0.0, 1.0),
    }
}

/// Linear-interpolated percentile of sorted values.
fn percentile(sorted: &[f64], p: f64) -> f64 {
    let pos = p / 100.0 * (sorted.len() - 1) as f64;
    let lo = pos.floor() as usize;
    let hi = (lo + 1).min(sorted.len() - 1);
    sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo as f64)
}

/// What [`screen_samples`] leaves out of a channel's auto contrast (the samples stay drawn).
#[derive(Debug, Default, Clone, Copy, PartialEq)]
struct Screened {
    /// Values above this (the recorded bit depth's ceiling) do not count.
    ceiling: Option<f64>,
    /// Values equal to this (the pixel type's maximum) do not count.
    skip: Option<f64>,
}

/// Most samples above the recorded bit depth that are still read as blended fill (left out of
/// the auto contrast) rather than as a sign the recorded depth is wrong, in percent.
const MAX_OVER_RANGE_PERCENT: usize = 1;

/// The largest value of an unsigned integer pixel type: what readers and acquisition software
/// write where nothing was acquired, and what a detector clips to.
fn type_max(pt: PixelType) -> Option<f32> {
    match pt {
        PixelType::Uint8 => Some(f32::from(u8::MAX)),
        PixelType::Uint16 => Some(f32::from(u16::MAX)),
        PixelType::Uint32 => Some(u32::MAX as f32),
        _ => None,
    }
}

/// What [`screen_samples`] found in one channel, for the report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum FindingKind {
    /// Samples above the recorded depth, mostly the type's maximum: fill, now no data.
    Fill,
    /// A few samples above the recorded depth: left out of the auto contrast.
    Blended,
    /// Many samples at the type's maximum, no recorded depth: left out of the auto contrast.
    AtMaximum,
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct Finding {
    kind: FindingKind,
    /// Percent of the channel's samples concerned.
    share: f64,
    /// `Fill`: percent of those at the type's maximum.
    at_top: f64,
}

fn share(n: usize, of: usize) -> f64 {
    100.0 * n as f64 / of.max(1) as f64
}

/// Screen the samples of one channel for values that are not measurements before they are
/// drawn. Tiled scans store a fill where nothing was acquired: readers composite uncovered
/// canvas as 0, but the pyramid tiles ZEN writes for slide scans (Axioscan RAC files) carry
/// 65535 past the scanned tiles and, at their edges, 65535 averaged with data. When the file
/// records a bit depth below the pixel type's (`images[].extra.component_bit_count` 12):
/// - if most samples above its ceiling are exactly the type's maximum, all samples above the
///   ceiling are fill: they become no data (NaN), drawn as background like the uncovered
///   canvas of level 0, and do not count for the contrast;
/// - else, if at most 1% of the samples lie above it (edge pixels blended with fill), auto
///   contrast leaves them out but they are drawn;
/// - else the recorded depth does not hold (as `stats` decides) and nothing is screened.
///
/// Without a recorded depth, auto contrast leaves out the type's maximum when it holds more
/// samples than the upper percentile allows (it would otherwise set the white point).
#[allow(clippy::float_cmp)] // integer samples are exact in f32; the fill is exactly the maximum
fn screen_samples(acc: &mut [f32], im: &ImageInfo, auto: bool) -> (Screened, Option<Finding>) {
    let none = (Screened::default(), None);
    let Some(top) = type_max(im.pixel_type) else {
        return none;
    };
    let finite = acc.iter().filter(|v| v.is_finite()).count();
    if finite == 0 {
        return none;
    }
    if let Some((ceiling, _)) = openreadout_core::stats::recorded_saturation(im) {
        let ceil = ceiling as f32;
        let above = acc.iter().filter(|&&v| v > ceil).count();
        if above > 0 {
            let at_top = acc.iter().filter(|&&v| v == top).count();
            if at_top * 2 >= above {
                for v in acc.iter_mut().filter(|v| **v > ceil) {
                    *v = f32::NAN;
                }
                let f = Finding {
                    kind: FindingKind::Fill,
                    share: share(above, finite),
                    at_top: share(at_top, above),
                };
                return (Screened::default(), Some(f));
            }
            if above * 100 <= finite * MAX_OVER_RANGE_PERCENT {
                if !auto {
                    return none;
                }
                let f = Finding {
                    kind: FindingKind::Blended,
                    share: share(above, finite),
                    at_top: 0.0,
                };
                let s = Screened {
                    ceiling: Some(ceiling),
                    skip: None,
                };
                return (s, Some(f));
            }
        }
    }
    if auto {
        let at_top = acc.iter().filter(|&&v| v == top).count();
        let allowed = (100.0 - AUTO_PERCENTILES.1) / 100.0 * finite as f64;
        if at_top < finite && at_top as f64 > allowed {
            let f = Finding {
                kind: FindingKind::AtMaximum,
                share: share(at_top, finite),
                at_top: 100.0,
            };
            let s = Screened {
                ceiling: None,
                skip: Some(f64::from(top)),
            };
            return (s, Some(f));
        }
    }
    none
}

/// `12.30%`, or `12.30-13.10%` over several channels.
fn percent_range(v: &[f64]) -> String {
    let lo = v.iter().copied().fold(f64::INFINITY, f64::min);
    let hi = v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let (a, b) = (format!("{lo:.2}"), format!("{hi:.2}"));
    if a == b {
        format!("{a}%")
    } else {
        format!("{a}-{b}%")
    }
}

/// One note per kind of finding, naming the channels it concerns.
fn finding_notes(im: &ImageInfo, found: &[(u32, Finding)]) -> Vec<String> {
    let top = type_max(im.pixel_type).unwrap_or(f32::MAX);
    let (bits, field) = openreadout_core::stats::recorded_saturation(im).map_or_else(
        || (String::new(), ""),
        |(ceiling, field)| (format!("{}-bit", (ceiling + 1.0).log2().round()), field),
    );
    let mut kinds: Vec<FindingKind> = found.iter().map(|(_, f)| f.kind).collect();
    kinds.sort_unstable();
    kinds.dedup();
    kinds
        .into_iter()
        .map(|kind| {
            let of: Vec<(u32, Finding)> = found.iter().copied().filter(|(_, f)| f.kind == kind).collect();
            let chans = of
                .iter()
                .map(|(c, _)| format!("c={c}"))
                .collect::<Vec<_>>()
                .join(", ");
            let shares = percent_range(&of.iter().map(|(_, f)| f.share).collect::<Vec<_>>());
            match kind {
                FindingKind::Fill => format!(
                    "{chans}: {shares} of the samples lie above the {bits} range the file records ({field}), {} of those at {top}: the fill written where nothing was acquired (pyramid tiles past the scanned tiles); drawn as background, like uncovered canvas, and left out of the contrast",
                    percent_range(&of.iter().map(|(_, f)| f.at_top).collect::<Vec<_>>()),
                ),
                FindingKind::Blended => format!(
                    "{chans}: {shares} of the samples lie above the {bits} range the file records ({field}) (tile edges blended with fill): drawn, but left out of the contrast"
                ),
                FindingKind::AtMaximum => format!(
                    "{chans}: {shares} of the samples are {top}, the pixel type's maximum (fill where nothing was acquired, or clipping): the contrast is computed without them"
                ),
            }
        })
        .collect()
}

/// Display range `(black, white)` of the bands under a contrast rule; values `screened` out
/// do not count (unless nothing else is left).
#[allow(clippy::float_cmp)] // `skip` is an exact integer value
fn display_range(bands: &[&Band], c: Contrast, pt: PixelType, screened: Screened) -> (f64, f64) {
    let (lo, hi) = match c {
        Contrast::Raw => raw_range(pt),
        Contrast::Window(c, w) => (c - w / 2.0, c + w / 2.0),
        Contrast::StoredWindow(_) => raw_range(pt),
        Contrast::Auto | Contrast::MinMax | Contrast::Percentile(..) | Contrast::Log(..) => {
            let finite = || {
                bands
                    .iter()
                    .flat_map(|b| b.v.iter())
                    .filter(|v| v.is_finite())
                    .map(|&v| f64::from(v))
            };
            let counts = |v: &f64| {
                screened.ceiling.is_none_or(|m| *v <= m) && screened.skip.is_none_or(|s| *v != s)
            };
            let mut vals: Vec<f64> = finite().filter(counts).collect();
            if vals.is_empty() {
                vals = finite().collect();
            }
            if vals.is_empty() {
                return (0.0, 1.0);
            }
            vals.sort_by(f64::total_cmp);
            match c {
                Contrast::Percentile(a, b) | Contrast::Log(a, b) => {
                    (percentile(&vals, a), percentile(&vals, b))
                }
                _ => (vals[0], vals[vals.len() - 1]),
            }
        }
    };
    if hi > lo { (lo, hi) } else { (lo, lo + 1.0) }
}

fn level_of(v: f32, lo: f64, hi: f64) -> f32 {
    if !v.is_finite() {
        return 0.0;
    }
    ((f64::from(v) - lo) / (hi - lo)).clamp(0.0, 1.0) as f32
}

/// Brightness of `v` under logarithmic contrast: `ln(1 + v - lo) / ln(1 + hi - lo)`.
fn log_level_of(v: f32, lo: f64, hi: f64) -> f32 {
    if !v.is_finite() {
        return 0.0;
    }
    let x = (f64::from(v) - lo).max(0.0);
    ((x.ln_1p()) / (hi - lo).max(1e-12).ln_1p()).clamp(0.0, 1.0) as f32
}

/// What a diffraction preview did differently, in one note.
fn dif_note(g: &Diffraction, contrast: Contrast, lut: Lut) -> String {
    let mut parts = vec![
        "diffraction image: shrunk by the maximum of each block so single-pixel spots stay visible"
            .to_string(),
    ];
    if matches!(contrast, Contrast::Log(..)) {
        parts.push(format!("{contrast} contrast"));
    }
    if lut == Lut::Inverted {
        parts.push("dark spots on a light ground".into());
    }
    let geo = &g.geometry;
    if geo.negative_is_masked || !geo.masked_values.is_empty() {
        parts.push(
            "pixels without a measurement (module gaps, bad pixels) in pale blue-grey".into(),
        );
    }
    if let Some(o) = geo.overload {
        parts.push(format!("overloads (≥ {o}) in red"));
    }
    parts.join("; ")
}

/// Pick the single index of an axis, or all of them for a projection axis.
fn axis_indices(
    name: &str,
    sel: &[u32],
    size: u32,
    default: u32,
    project: bool,
) -> Result<Vec<u32>> {
    for &i in sel {
        if i >= size {
            return Err(Error::Usage(format!(
                "{name}={i} out of range (image has {size}, 0..{size})"
            )));
        }
    }
    if project {
        return Ok(if sel.is_empty() {
            (0..size).collect()
        } else {
            sel.to_vec()
        });
    }
    match sel {
        [] => Ok(vec![default]),
        [one] => Ok(vec![*one]),
        _ => Err(Error::Usage(format!(
            "a preview shows one {name} at a time; pass --mip {name} (maximum) or --sum {name} to project several"
        ))),
    }
}

/// Decoded bytes of one plane (or `region` of it) at `level`.
fn plane_bytes(im: &ImageInfo, level: u32, region: Option<Region>) -> u64 {
    let (w, h) = match region {
        Some(r) => (r.width, r.height),
        None if level == 0 => (im.size_x, im.size_y),
        None => level_dims(im, level).unwrap_or((im.size_x, im.size_y)),
    };
    u64::from(w)
        .saturating_mul(u64::from(h))
        .saturating_mul(u64::from(im.samples_per_pixel.max(1)))
        .saturating_mul(im.pixel_type.bytes_per_sample() as u64)
}

/// A read budget: the image and the most decoded bytes one plane read may take.
#[derive(Clone, Copy)]
struct Budget<'a> {
    im: &'a ImageInfo,
    per_plane: u64,
    planes: u64,
}

impl Budget<'_> {
    fn check(&self, level: u32, region: Option<Region>) -> Result<()> {
        let need = plane_bytes(self.im, level, region);
        if need <= self.per_plane {
            return Ok(());
        }
        let mib = |b: u64| b.div_ceil(1 << 20);
        Err(Error::unsupported(
            "preview",
            format!(
                "a quick look decoding {} MiB of pixels ({} plane(s) at level {level}; budget {} MiB)",
                mib(need.saturating_mul(self.planes)),
                self.planes,
                mib(self.per_plane.saturating_mul(self.planes))
            ),
            "Preview a region (full-resolution pixels) or a smaller pyramid level to look at part of the image.",
        ))
    }
}

/// Read one plane (or its `region`, in the coordinates of `level`) at `level`, falling back to
/// level 0 when the level was chosen automatically and the reader does not serve it (the region
/// then becomes `region0`, its full-resolution form).
#[allow(clippy::too_many_arguments)]
fn read_plane(
    ds: &mut dyn Dataset,
    image: u32,
    idx: PlaneIndex,
    level: &mut u32,
    region: &mut Option<Region>,
    region0: Option<Region>,
    auto: bool,
    budget: Option<Budget<'_>>,
    notes: &mut Vec<String>,
) -> Result<Plane> {
    if let Some(b) = budget {
        b.check(*level, *region)?;
    }
    let got = match *region {
        Some(r) => ds.read_region(image, idx, *level, r),
        None => ds.read_plane_level(image, idx, *level),
    };
    match got {
        Err(Error::Unsupported { .. }) if auto && *level > 0 => {
            notes.push(format!(
                "pyramid level {level} is listed but not readable by this reader; used level 0",
                level = *level
            ));
            if let Some(b) = budget {
                b.check(0, region0)?;
            }
            *level = 0;
            *region = region0;
            match region0 {
                Some(r) => ds.read_region(image, idx, 0, r),
                None => ds.read_plane(image, idx),
            }
        }
        other => other,
    }
}

/// Mark the samples outside `areas` (the parts of a `w`×`h` plane that hold stored tiles, from
/// [`Dataset::stored_areas`]) as no data, so they are drawn as background and left out of the
/// contrast.
fn blank_unstored(s: &mut [f32], w: usize, h: usize, spp: usize, areas: &[Region]) {
    let mut stored = vec![false; w * h];
    for a in areas {
        let (x0, y0) = (a.x as usize, a.y as usize);
        let x1 = (x0 + a.width as usize).min(w);
        let y1 = (y0 + a.height as usize).min(h);
        for y in y0.min(y1)..y1 {
            stored[y * w + x0.min(x1)..y * w + x1].fill(true);
        }
    }
    for (px, _) in s.chunks_exact_mut(spp).zip(&stored).filter(|(_, k)| !**k) {
        px.fill(f32::NAN);
    }
}

/// What frames the picture.
enum Framing {
    Rulers(Layout),
    Figure(FigureLayout),
}

impl Framing {
    fn h(&self) -> u32 {
        match self {
            Framing::Rulers(l) => l.h(),
            Framing::Figure(f) => f.h(),
        }
    }
    fn v(&self) -> u32 {
        match self {
            Framing::Rulers(l) => l.v(),
            Framing::Figure(f) => f.v(),
        }
    }
}

pub(crate) fn render(
    ds: &mut dyn Dataset,
    info: &FileInfo,
    req: &PreviewRequest,
    out: &mut PreviewOutput,
) -> Result<(Figure, crate::Frame)> {
    let image = req.image.unwrap_or(0);
    let im = info
        .images
        .iter()
        .find(|i| i.index == image)
        .ok_or_else(|| {
            Error::Usage(format!(
                "image {image} not found (file has {} images)",
                info.images.len()
            ))
        })?
        .clone();
    if im.size_c == 0 || im.size_z == 0 || im.size_t == 0 || im.size_x == 0 || im.size_y == 0 {
        return Err(Error::Usage(format!("image {image} has no pixels")));
    }
    let sel = Selection::parse(&split_select(&req.select))?;
    let rgb = im.samples_per_pixel == 3;
    if req.mip.is_some() && req.sum.is_some() {
        return Err(Error::Usage("pass mip (maximum) or sum, not both".into()));
    }
    let projection = req.mip.or(req.sum);
    let mut composite = req.composite;
    if sel.c.len() > 1 && !composite {
        composite = true;
        out.notes
            .push("several channels selected: rendered as a composite".into());
    }
    if rgb && composite {
        return Err(Error::Usage(
            "composites blend single-sample channels; this image stores RGB planes, preview one channel (c=N) at a time".into(),
        ));
    }
    // Diffraction images: masked pixels as no data, spots kept when shrinking, log contrast,
    // dark spots on a light ground.
    let geo = (!rgb && !composite).then(|| Diffraction::of(&im)).flatten();
    let lut = req.lut.unwrap_or(if composite {
        Lut::ChannelColor
    } else if geo.is_some() {
        Lut::Inverted
    } else {
        Lut::Gray
    });
    if composite && matches!(lut, Lut::Gray | Lut::Inverted) {
        return Err(Error::Usage(
            "--lut gray and inverted cannot show a composite; drop --lut or preview one channel"
                .into(),
        ));
    }
    let c_list: Vec<u32> = if composite {
        for &c in &sel.c {
            if c >= im.size_c {
                return Err(Error::Usage(format!(
                    "c={c} out of range (image has {}, 0..{})",
                    im.size_c, im.size_c
                )));
            }
        }
        let mut all: Vec<u32> = if sel.c.is_empty() {
            (0..im.size_c).collect()
        } else {
            sel.c.clone()
        };
        if all.len() > MAX_COMPOSITE_CHANNELS {
            out.notes.push(format!(
                "composite limited to the first {MAX_COMPOSITE_CHANNELS} of {} channels",
                all.len()
            ));
            all.truncate(MAX_COMPOSITE_CHANNELS);
        }
        all
    } else {
        axis_indices("c", &sel.c, im.size_c, 0, false)?
    };
    let z_list = axis_indices(
        "z",
        &sel.z,
        im.size_z,
        im.size_z / 2,
        projection == Some(Axis::Z),
    )?;
    let t_list = axis_indices("t", &sel.t, im.size_t, 0, projection == Some(Axis::T))?;

    // The frame: `max_size` bounds the whole picture, so the data gets what the margins leave.
    let has_bar = im.physical_size.x.is_some_and(|v| v.is_finite() && v > 0.0);
    let titled = req.title.is_some() || req.caption.is_some();
    let mut layout = if req.axes && !req.figure {
        Some(Framing::Rulers(Layout::new(
            req.max_size,
            im.size_x,
            im.size_y,
        )))
    } else if (req.axes && req.figure) || titled {
        // without axes, a title or caption still gets its frame, with no scale bar
        Some(Framing::Figure(FigureLayout::new(
            req.max_size,
            has_bar && req.axes,
            req.title.as_deref(),
            req.caption.as_deref(),
        )))
    } else {
        None
    };
    if let Some(l) = &layout {
        let room = req.max_size.saturating_sub(l.h().max(l.v()));
        if room < 16 || room < req.max_size / 2 {
            out.notes.push(format!(
                "max size {} is too small for the frame; drawn without it",
                req.max_size
            ));
            layout = None;
        }
    }
    if req.grid && !matches!(layout, Some(Framing::Rulers(_))) {
        out.notes
            .push("grid lines are drawn only with the rulers (axes)".into());
    }
    if titled && !matches!(layout, Some(Framing::Figure(_))) {
        out.notes.push(
            "title and caption are drawn with axes scale-bar or none, not with rulers".into(),
        );
    }
    if req.axes && layout.is_some() && !has_bar {
        out.notes.push(
            "the file records no physical pixel size: no scale bar, and sizes are in pixels".into(),
        );
    }
    // The level is chosen for `max_size` as without rulers; the plane is then resampled so its
    // longer side fills what the margins leave (a bare plane is only ever made smaller).
    let fit = layout
        .as_ref()
        .map_or(req.max_size, |l| req.max_size - l.h().max(l.v()));
    let planes = (c_list.len() * z_list.len() * t_list.len()) as u64;
    let budget = req.max_read_bytes.map(|b| Budget {
        im: &im,
        per_plane: b / planes.max(1),
        planes,
    });

    let auto_level = req.level.is_none();
    // A region is in level-0 coordinates unless a level is given (then in that level's).
    let (mut level, mut region) = match (req.level, req.region) {
        (Some(l), r) => (l, r),
        (None, Some(r)) => {
            r.check_within(im.size_x, im.size_y, &format!("image {image} (level 0)"))?;
            let (l, rl) = choose_region_level(&im, r, req.max_size);
            (l, Some(rl))
        }
        (None, None) => (choose_level(&im, req.max_size), None),
    };
    let region0 = if auto_level { req.region } else { None };
    let spp = im.samples_per_pixel.max(1) as usize;
    let mut first_dims: Option<(u32, u32)> = None;
    let mut out_dims = (1usize, 1usize);
    let contrast = match (req.contrast, &geo) {
        (Contrast::Auto, Some(_)) => Contrast::Log(dif::AUTO_LOG.0, dif::AUTO_LOG.1),
        (c, _) => resolve_contrast(c, &im, rgb, &mut out.notes)?,
    };
    // MONOCHROME1: low values are drawn bright
    let display_inverted = im
        .extra
        .get("display_inverted")
        .and_then(serde_json::Value::as_bool)
        == Some(true);
    // Auto contrast (not what it resolved to for RGB) may leave fill and clipping out.
    let auto_contrast = req.contrast == Contrast::Auto && contrast != Contrast::Raw;
    let mut per_channel: Vec<(u32, Vec<Band>, Screened)> = Vec::new();
    // The power-spectrum inset, from the first channel's plane as read.
    let mut spectrum: Option<(usize, Vec<f32>)> = None;
    let mut found: Vec<(u32, Finding)> = Vec::new();
    for &c in &c_list {
        let mut acc: Option<Vec<f32>> = None;
        let mut dims = (0u32, 0u32);
        // A sum over time of a whole full-resolution plane: the reader adds the frames
        // (electron-event movies add their events without decoding each frame).
        let reader_sum = req.sum == Some(Axis::T)
            && t_list.len() > 1
            && region.is_none()
            && level == 0
            && spp == 1
            && budget.is_none();
        let t_groups: Vec<Vec<u32>> = if reader_sum {
            vec![t_list.clone()]
        } else {
            t_list.iter().map(|&t| vec![t]).collect()
        };
        for &z in &z_list {
            for group in &t_groups {
                let t = group[0];
                let p = if group.len() > 1 {
                    ds.sum_planes(image, c, z, group)?
                } else {
                    read_plane(
                        ds,
                        image,
                        PlaneIndex { c, z, t },
                        &mut level,
                        &mut region,
                        region0,
                        auto_level,
                        budget,
                        &mut out.notes,
                    )?
                };
                let mut s = samples(&p)?;
                if let Some(g) = &geo {
                    g.mask(&mut s);
                }
                // Areas of a mosaic with no stored tiles read as 0; draw them as background.
                if let Some(areas) =
                    ds.stored_areas(image, PlaneIndex { c, z, t }, level, region)?
                {
                    blank_unstored(
                        &mut s,
                        p.width as usize,
                        p.height as usize,
                        p.samples_per_pixel.max(1) as usize,
                        &areas,
                    );
                }
                dims = (p.width, p.height);
                if p.samples_per_pixel as usize != spp {
                    return Err(Error::Other(format!(
                        "plane has {} samples per pixel, image declares {spp}",
                        p.samples_per_pixel
                    )));
                }
                acc = Some(match acc {
                    None => s,
                    Some(mut a) => {
                        if a.len() != s.len() {
                            return Err(Error::Other(
                                "planes of one image differ in size; cannot project".into(),
                            ));
                        }
                        if req.sum.is_some() {
                            for (x, y) in a.iter_mut().zip(s) {
                                *x += y;
                            }
                        } else {
                            for (x, y) in a.iter_mut().zip(s) {
                                // NaN-aware maximum (f32::max ignores a NaN operand)
                                *x = x.max(y);
                            }
                        }
                        a
                    }
                });
            }
        }
        let mut acc = acc.unwrap_or_default();
        if req.fft && spectrum.is_none() && spp == 1 && !composite {
            // pixel size at the level read, in ångström
            let k = level_dims(&im, level)
                .map_or(1.0, |(lw, _)| f64::from(im.size_x) / f64::from(lw.max(1)));
            let pixel_a = im.physical_size.x.map(|um| um * 1e4 * k);
            let bin = crate::fft_inset::bin_for(dims.0.min(dims.1) as usize, pixel_a);
            spectrum =
                crate::fft_inset::power_spectrum(&acc, dims.0 as usize, dims.1 as usize, bin);
            if spectrum.is_none() {
                out.notes.push(format!(
                    "no power-spectrum inset: the plane read is smaller than {} px",
                    crate::fft_inset::MIN_SIDE
                ));
            }
        }
        let (screened, finding) = screen_samples(&mut acc, &im, auto_contrast);
        found.extend(finding.map(|f| (c, f)));
        match first_dims {
            None => {
                first_dims = Some(dims);
                // pixels that are not square (MRI, reformatted CT) are drawn to scale: rows
                // are stretched by the ratio of the pixel height to its width
                let shown = (dims.0, aspect_height(&im, dims.1));
                let fit = if let Some(Framing::Figure(f)) = &layout {
                    f.fit(req.max_size, shown.0, shown.1)
                } else if layout.is_some() {
                    fit
                } else {
                    fit.min(shown.0.max(shown.1))
                };
                out_dims = fitted(shown.0, shown.1, fit);
            }
            Some(d) if d != dims => {
                return Err(Error::Other(format!(
                    "channels of image {image} differ in size ({}x{} vs {}x{})",
                    d.0, d.1, dims.0, dims.1
                )));
            }
            Some(_) => {}
        }
        let (w, h) = (dims.0 as usize, dims.1 as usize);
        let bands = (0..spp)
            .map(|s| {
                if geo.is_some() {
                    let (w2, h2, v) = dif::resample_max(&acc, w, h, out_dims.0, out_dims.1);
                    Band { w: w2, h: h2, v }
                } else {
                    resample(&acc, w, h, spp, s, out_dims.0, out_dims.1)
                }
            })
            .collect();
        per_channel.push((c, bands, screened));
    }
    out.notes.extend(finding_notes(&im, &found));
    let (sw, sh) = match region {
        // The plane size at the level read (the region is part of it).
        Some(_) => level_dims(&im, level).unwrap_or((0, 0)),
        None => first_dims.unwrap_or((0, 0)),
    };
    let (ow, oh) = per_channel
        .first()
        .and_then(|(_, b, _)| b.first())
        .map_or((0, 0), |b| (b.w, b.h));
    let mut canvas = Raster::new(ow as u32, oh as u32, [0, 0, 0]);
    let mut channels = Vec::new();
    let mut acc = vec![0f32; ow * oh * 3];
    for (pos, (c, bands, screened)) in per_channel.iter().enumerate() {
        let ch = im.channels.iter().find(|x| x.index == *c);
        let refs: Vec<&Band> = bands.iter().collect();
        let (lo, hi) = display_range(&refs, contrast, im.pixel_type, *screened);
        let (col, source): (Rgb, &str) = if rgb {
            ([255, 255, 255], "rgb")
        } else if matches!(lut, Lut::Gray | Lut::Inverted) {
            ([255, 255, 255], "lut")
        } else {
            let (c, s) = color::channel_color(ch, pos);
            (c, s.as_str())
        };
        if rgb {
            for i in 0..ow * oh {
                // No data (unscanned slide areas, fill) is white, the colour of a blank slide.
                let blank = bands.iter().take(3).any(|b| !b.v[i].is_finite());
                for (k, band) in bands.iter().take(3).enumerate() {
                    acc[i * 3 + k] = if blank {
                        255.0
                    } else {
                        255.0 * level_of(band.v[i], lo, hi)
                    };
                }
            }
        } else {
            let band = &bands[0];
            let log = matches!(contrast, Contrast::Log(..));
            let inverted = lut == Lut::Inverted;
            for i in 0..ow * oh {
                let v = band.v[i];
                let mut l = if log {
                    log_level_of(v, lo, hi)
                } else {
                    level_of(v, lo, hi)
                };
                if inverted {
                    l = 1.0 - l;
                }
                if display_inverted && v.is_finite() {
                    l = 1.0 - l;
                }
                let fixed = match &geo {
                    Some(_) if !v.is_finite() => Some(dif::NO_DATA),
                    Some(g) if g.overloaded(v) => Some(dif::OVERLOAD),
                    _ => None,
                };
                for k in 0..3 {
                    acc[i * 3 + k] += fixed.map_or(f32::from(col[k]) * l, |c| f32::from(c[k]));
                }
            }
        }
        channels.push(PreviewChannel {
            index: *c,
            name: ch.and_then(|x| x.name.clone()),
            color: color::to_hex(col),
            color_source: source.into(),
            display_min: lo,
            display_max: hi,
        });
    }
    for (o, a) in canvas.rgb.iter_mut().zip(&acc) {
        *o = a.round().clamp(0.0, 255.0) as u8;
    }
    if req.fft && (rgb || composite) {
        out.notes
            .push("the power-spectrum inset is drawn on single-channel images".into());
    }
    let inset = spectrum.and_then(|(side, ps)| paint_inset(&mut canvas, side, &ps));
    if let Some(r) = inset {
        out.notes.push(format!(
            "power-spectrum inset (top right, {}×{} px): the averaged log power spectrum of tiles from the middle of the plane read, zero frequency in its middle; it covers part of the picture",
            r.width, r.height
        ));
    }
    // Map drawn pixels back to full-resolution pixels: level scale × resampling step.
    let level_size = if level == 0 {
        Some((im.size_x, im.size_y))
    } else {
        level_dims(&im, level).or(if region.is_none() { first_dims } else { None })
    };
    let (kx, ky) = match level_size {
        Some((w, h)) if w > 0 && h > 0 => (
            f64::from(im.size_x) / f64::from(w),
            f64::from(im.size_y) / f64::from(h),
        ),
        _ => {
            out.notes.push(format!(
                "the size of level {level} is not known: rulers and source_* fields count level-{level} pixels"
            ));
            (1.0, 1.0)
        }
    };
    // source pixels (at the level read) per drawn pixel, exact for the drawn size
    let step = first_dims.map_or((1.0, 1.0), |(w, h)| {
        (
            f64::from(w) / out_dims.0.max(1) as f64,
            f64::from(h) / out_dims.1.max(1) as f64,
        )
    });
    let map = Mapping {
        origin: region.map_or((0.0, 0.0), |r| (f64::from(r.x) * kx, f64::from(r.y) * ky)),
        per_pixel: (step.0 * kx, step.1 * ky),
    };
    let read_end = match (region, level_size) {
        (Some(r), Some(ls)) => {
            let r0 = r.rescale(ls, (im.size_x, im.size_y));
            (r0.x + r0.width, r0.y + r0.height)
        }
        _ => (im.size_x, im.size_y),
    };
    let full_res_region = map.covered(ow as u32, oh as u32, read_end);
    let rulers_drawn = matches!(layout, Some(Framing::Rulers(_)));
    let (mut figure, plot_area, scale_bar) = if let Some(l) = &layout {
        let theme = crate::theme(req);
        let d = match l {
            Framing::Rulers(l) => {
                rulers::decorate(canvas, *l, map, im.physical_size.x, req.grid, &theme)
            }
            Framing::Figure(f) => {
                figure_frame::decorate(canvas, f, map, im.physical_size.x, &theme)
            }
        };
        (d.figure, d.plot_area, d.scale_bar)
    } else {
        let (w, h) = (ow as f32, oh as f32);
        let mut f = Figure::new(w, h, None);
        f.image(
            Rect::new(0.0, 0.0, w, h),
            std::sync::Arc::new(canvas),
            false,
        );
        (f, Region::new(0, 0, ow as u32, oh as u32), None)
    };
    if let Some(g) = &geo {
        out.notes.push(dif_note(g, contrast, lut));
        if matches!(req.marks, crate::Marks::Auto | crate::Marks::Rings) {
            let shown = full_res_region;
            let marks = dif::draw_rings(
                &mut figure,
                plot_area,
                map,
                shown,
                &g.geometry,
                &crate::theme(req),
            );
            if marks.iter().all(|m| m.kind != "resolution_ring") && req.marks == crate::Marks::Rings
            {
                out.notes.push("no resolution rings: they need the wavelength, the detector distance, the beam centre and square pixels, on a detector normal to the beam".into());
            }
            out.marks.extend(marks);
        }
    } else if req.marks == crate::Marks::Rings {
        out.notes
            .push("resolution rings are drawn on diffraction images (extra.diffraction)".into());
    }
    let fft_inset = inset.map(|r| {
        let r = Region::new(plot_area.x + r.x, plot_area.y + r.y, r.width, r.height);
        let theme = crate::theme(req);
        let st = openreadout_figure::TextStyle::new(
            theme.small_size(),
            openreadout_figure::Color::rgb(255, 255, 255),
        )
        .face(openreadout_figure::Face::SansMedium)
        .halo(openreadout_figure::Color::rgb(29, 31, 36), 2.0)
        .align(
            openreadout_figure::Anchor::Start,
            openreadout_figure::Baseline::Top,
        );
        figure.text(r.x as f32 + 4.0, r.y as f32 + 3.0, "FFT", &st);
        r
    });
    let frame = crate::Frame::Image { plot_area, map };
    out.image = Some(ImagePreview {
        image,
        level,
        source_width: sw,
        source_height: sh,
        region,
        downsample: step.0,
        c: c_list,
        z: z_list,
        t: t_list,
        projection: projection.map(|a| {
            let op = if req.sum.is_some() { "sum" } else { "max" };
            match a {
                Axis::Z => format!("{op}-z"),
                Axis::T => format!("{op}-t"),
            }
        }),
        composite,
        rgb,
        contrast: contrast.to_string(),
        lut: if rgb {
            "rgb".into()
        } else if lut == Lut::Gray {
            "gray".into()
        } else if lut == Lut::Inverted {
            "inverted".into()
        } else {
            "channel-color".into()
        },
        channels,
        axes: rulers_drawn,
        grid: rulers_drawn && req.grid,
        plot_area,
        source_origin: SourcePoint {
            x: map.origin.0,
            y: map.origin.1,
        },
        source_per_pixel: map.per_pixel.0,
        source_per_pixel_y: map.per_pixel.1,
        full_res_region,
        scale_bar,
        view: None,
        crosshair: None,
        view_slices: None,
        fft_inset,
    });
    Ok((figure, frame))
}

/// Paint the power spectrum (`side`² values in 0..=1) into the top-right corner of `canvas`
/// with a light border; returns where, in canvas pixels.
fn paint_inset(canvas: &mut Raster, side: usize, ps: &[f32]) -> Option<Region> {
    let (cw, ch) = (canvas.width as usize, canvas.height as usize);
    let s = ((cw.min(ch) as f32 * 0.3) as usize).clamp(48, 360);
    let m = (cw.min(ch) / 80).max(3);
    if s + 2 * m + 2 > cw.min(ch) {
        return None;
    }
    let band = resample(ps, side, side, 1, 0, s, s);
    let (x0, y0) = (cw - m - s, m);
    // a 1-pixel light frame around it
    for y in y0.saturating_sub(1)..(y0 + s + 1).min(ch) {
        for x in x0.saturating_sub(1)..(x0 + s + 1).min(cw) {
            let i = (y * cw + x) * 3;
            canvas.rgb[i..i + 3].copy_from_slice(&[247, 245, 240]);
        }
    }
    for y in 0..s {
        for x in 0..s {
            let v = band.v[y * s + x];
            let g = if v.is_finite() {
                (v * 255.0).round().clamp(0.0, 255.0) as u8
            } else {
                0
            };
            let i = ((y0 + y) * cw + x0 + x) * 3;
            canvas.rgb[i..i + 3].copy_from_slice(&[g, g, g]);
        }
    }
    Some(Region::new(x0 as u32, y0 as u32, s as u32, s as u32))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resampling_averages_areas_and_skips_nan() {
        // 4x2 → 2x1: the mean of each 2x2 block
        let src = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
        let b = resample(&src, 4, 2, 1, 0, 2, 1);
        assert_eq!((b.w, b.h), (2, 1));
        assert_eq!(b.v, vec![3.5, 5.5]);
        // 3 → 2: the middle source pixel is shared half and half
        let b = resample(&[0.0, 3.0, 6.0], 3, 1, 1, 0, 2, 1);
        assert_eq!(b.v, vec![1.0, 5.0]);
        let b = resample(&[f32::NAN, 2.0], 2, 1, 1, 0, 1, 1);
        assert_eq!(b.v, vec![2.0]);
        // enlarging repeats pixels
        let b = resample(&[1.0, 2.0], 2, 1, 1, 0, 4, 2);
        assert_eq!(b.v, vec![1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 2.0, 2.0]);
        assert_eq!(fitted(4000, 3000, 768), (768, 576));
    }

    #[test]
    fn percentiles_and_ranges() {
        let s: Vec<f64> = (0..=100).map(f64::from).collect();
        assert!((percentile(&s, 1.0) - 1.0).abs() < 1e-12);
        assert!((percentile(&s, 99.5) - 99.5).abs() < 1e-12);
        let b = Band {
            w: 2,
            h: 1,
            v: vec![5.0, 5.0],
        };
        assert_eq!(
            display_range(
                &[&b],
                Contrast::MinMax,
                PixelType::Uint16,
                Screened::default()
            ),
            (5.0, 6.0)
        );
        assert_eq!(
            display_range(&[&b], Contrast::Raw, PixelType::Uint8, Screened::default()),
            (0.0, 255.0)
        );
    }

    fn twelve_bit() -> ImageInfo {
        let mut im = ImageInfo::new(0, 10, 10, PixelType::Uint16);
        im.extra
            .insert("component_bit_count".into(), serde_json::json!(12));
        im
    }

    #[test]
    fn fill_above_the_recorded_depth_becomes_no_data() {
        // 60 data samples, 30 at the fill 65535, 2 blends of fill and data, 8 uncovered zeros.
        let mut acc: Vec<f32> = (0..60).map(|i| 100.0 + i as f32).collect();
        acc.extend([65535.0; 30]);
        acc.extend([30_000.0, 9_000.0]);
        acc.extend([0.0; 8]);
        let (s, f) = screen_samples(&mut acc, &twelve_bit(), true);
        assert_eq!(s, Screened::default());
        let f = f.unwrap();
        assert_eq!(f.kind, FindingKind::Fill);
        assert!((f.share - 32.0).abs() < 1e-9 && (f.at_top - 93.75).abs() < 1e-9);
        assert_eq!(acc.iter().filter(|v| v.is_nan()).count(), 32);
        assert!(acc.iter().all(|v| v.is_nan() || *v <= 4095.0));
        // Also without auto contrast: fill is not data whatever the contrast rule.
        let mut acc2 = vec![100.0, 65535.0];
        let (_, f) = screen_samples(&mut acc2, &twelve_bit(), false);
        assert!(acc2[1].is_nan() && f.is_some());
    }

    #[test]
    fn blended_edges_leave_the_contrast_only() {
        // 1000 samples, 5 blends above 4095 and none at 65535: drawn, not counted.
        let mut acc: Vec<f32> = (0..995).map(|i| 1000.0 + (i % 100) as f32).collect();
        acc.extend([20_000.0, 18_000.0, 9_000.0, 5_000.0, 30_000.0]);
        let before = acc.clone();
        let (s, f) = screen_samples(&mut acc, &twelve_bit(), true);
        assert_eq!(acc, before, "blends stay drawn");
        assert_eq!(s.ceiling, Some(4095.0));
        assert_eq!(f.map(|f| f.kind), Some(FindingKind::Blended));
        let band = Band {
            w: 1000,
            h: 1,
            v: acc,
        };
        let p = Contrast::Percentile(0.1, 99.9);
        let (_, hi) = display_range(&[&band], p, PixelType::Uint16, s);
        assert!(
            hi <= 1099.0,
            "white point {hi} from the data, not the blends"
        );
        let (_, hi) = display_range(&[&band], p, PixelType::Uint16, Screened::default());
        assert!(hi > 4095.0, "unscreened, the blends set the white point");
        // Not in auto contrast: nothing is left out.
        let (s, f) = screen_samples(&mut before.clone(), &twelve_bit(), false);
        assert_eq!((s, f), (Screened::default(), None));
    }

    #[test]
    fn a_wrong_recorded_depth_screens_nothing() {
        // Most samples above 4095, spread out (14-bit data recorded as 12-bit).
        let mut acc: Vec<f32> = (0..100).map(|i| (i * 160) as f32).collect();
        let before = acc.clone();
        let (s, f) = screen_samples(&mut acc, &twelve_bit(), true);
        assert_eq!((acc, s, f), (before, Screened::default(), None));
    }

    #[test]
    fn dominant_type_maximum_is_left_out_of_auto_contrast() {
        // No recorded depth; 20% of the samples at 65535.
        let im = ImageInfo::new(0, 10, 10, PixelType::Uint16);
        let mut acc: Vec<f32> = (0..80).map(|i| 200.0 + i as f32).collect();
        acc.extend([65535.0; 20]);
        let (s, f) = screen_samples(&mut acc, &im, true);
        assert_eq!(s.skip, Some(65535.0));
        assert_eq!(f.map(|f| f.kind), Some(FindingKind::AtMaximum));
        let band = Band {
            w: 100,
            h: 1,
            v: acc.clone(),
        };
        let p = Contrast::Percentile(0.1, 99.9);
        let (lo, hi) = display_range(&[&band], p, PixelType::Uint16, s);
        assert!(lo >= 200.0 && hi < 280.0, "{lo}..{hi}");
        // A handful at the maximum (under 0.1%) or only the maximum: nothing changes.
        let mut few: Vec<f32> = (0..10_000).map(|i| (i % 500) as f32).collect();
        few[0] = 65535.0;
        assert_eq!(screen_samples(&mut few, &im, true).1, None);
        let mut all = vec![65535.0f32; 10];
        assert_eq!(screen_samples(&mut all, &im, true).1, None);
        // Only everything left out: the range falls back to all samples.
        let only = Band {
            w: 2,
            h: 1,
            v: vec![65535.0, 65535.0],
        };
        assert_eq!(
            display_range(&[&only], p, PixelType::Uint16, s),
            (65535.0, 65536.0)
        );
        // Floats have no fill value.
        let fim = ImageInfo::new(0, 10, 10, PixelType::Float);
        assert_eq!(screen_samples(&mut acc, &fim, true).1, None);
    }

    #[test]
    fn findings_make_one_note_per_kind() {
        let fill = |share, at_top| Finding {
            kind: FindingKind::Fill,
            share,
            at_top,
        };
        let blended = Finding {
            kind: FindingKind::Blended,
            share: 0.29,
            at_top: 0.0,
        };
        let found = [
            (0, fill(13.27, 97.23)),
            (1, blended),
            (3, fill(13.29, 97.07)),
        ];
        let notes = finding_notes(&twelve_bit(), &found);
        assert_eq!(notes.len(), 2, "{notes:?}");
        assert!(
            notes[0].starts_with("c=0, c=3: 13.27-13.29% of the samples lie above the 12-bit range the file records (images[].extra.component_bit_count), 97.07-97.23% of those at 65535"),
            "{}",
            notes[0]
        );
        assert!(notes[1].starts_with("c=1: 0.29% "), "{}", notes[1]);
    }

    #[test]
    fn level_choice_prefers_smallest_sufficient() {
        let mut im = ImageInfo::new(0, 8000, 6000, PixelType::Uint8);
        im.pyramid_levels = 3;
        im.extra.insert(
            "pyramid".into(),
            serde_json::json!([
                {"level": 1, "size_x": 2000, "size_y": 1500},
                {"level": 2, "size_x": 500, "size_y": 375}
            ]),
        );
        assert_eq!(choose_level(&im, 1024), 1);
        assert_eq!(choose_level(&im, 256), 2);
        assert_eq!(choose_level(&im, 9000), 0);
        // A 2000 px wide region renders from level 1 (4x smaller) at 500 px, from level 0
        // at 1024 px.
        let r = Region::new(4000, 3000, 2000, 1000);
        assert_eq!(
            choose_region_level(&im, r, 500),
            (1, Region::new(1000, 750, 500, 250))
        );
        assert_eq!(choose_region_level(&im, r, 1024), (0, r));
        // resolution_levels, when filled, take precedence over extra.pyramid.
        im.resolution_levels = vec![
            openreadout_core::ResolutionLevel::new(0, 8000, 6000, 8000, 6000),
            openreadout_core::ResolutionLevel::new(1, 4000, 3000, 8000, 6000),
            openreadout_core::ResolutionLevel::new(2, 2000, 1500, 8000, 6000),
        ];
        assert_eq!(choose_level(&im, 1024), 2);
        assert_eq!(level_dims(&im, 1), Some((4000, 3000)));
        // A level with fewer z planes (Imaris) is not chosen: the middle z of level 0 may not
        // exist there (zenodo4433202-ovule-732).
        im.size_z = 219;
        im.resolution_levels[2].size_z = Some(109);
        assert_eq!(choose_level(&im, 1024), 1);
    }
}