dcmnorm 0.23.1

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
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
//! VL Whole Slide Microscopy Image rendering (SOP class 1.2.840.10008.5.1.4.1.1.77.1.6):
//! stitch the tiles (frames) of one pyramid level into the requested region of the total pixel
//! matrix (`TotalPixelMatrixColumns` x `TotalPixelMatrixRows`), optionally downsampled, picking
//! the pyramid level that best matches the requested output size when several are given.
//!
//! Tile placement (PS3.3 C.8.12.4.1.5 / C.7.6.17.3):
//! - `TILED_FULL`: positions are implied by frame order - column position increases fastest,
//!   then row, then focal plane (`TotalPixelMatrixFocalPlanes`), then optical path.
//! - `TILED_SPARSE`: each frame's position is its per-frame `PlanePositionSlideSequence`
//!   `ColumnPositionInTotalImagePixelMatrix`/`RowPositionInTotalImagePixelMatrix` (1-based).
//!   Focal planes are the distinct `ZOffsetInSlideCoordinateSystem` values (ascending); optical
//!   paths are matched through `OpticalPathIdentificationSequence`. Positions with no tile are
//!   filled with `background_color`; overlapping tiles are allowed (with no downsampling the
//!   later frame wins, when downsampling their samples are averaged).
//!
//! Edge tiles that extend past the matrix are clipped. Only the tiles that intersect the region
//! are decoded (each through the ordinary single-frame decode path, so every transfer syntax and
//! photometric interpretation 2D rendering supports works here too).
//!
//! Coordinates: `RenderPipelineOptions::region` is in BASE level (largest `TotalPixelMatrix
//! Columns`) pixels whichever level renders it; it is mapped to a coarser level by the ratio of
//! the levels' `TotalPixelMatrixColumns`/`Rows`. A region partly outside the matrix is clamped
//! to it; one entirely outside is an error.

use dcmnorm_dictionary::{tags, uids};
use dcmnorm_object::{DefaultDicomObject, InMemDicomObject};
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;

use super::region::Region;
use super::render::{
    draw_bounding_boxes, encode_rendered_frame, icc_profile_to_srgb_transform, maybe_pad_frame,
    maybe_resize_frame, render_dicom_frame, render_dicom_frame_pixels, resolve_grayscale_invert,
    rgb_to_luma, scale_by_ratio, scale_to_max_dimension, IccTransform, RenderFrameOutput,
    RenderOutputFormat, RenderPipelineOptions, RenderedFramePixels,
};
use super::types::RenderError;

/// Default cap on a stitched output's pixel count (width x height): 100 megapixels.
pub const DEFAULT_WSI_MAX_OUTPUT_PIXELS: u64 = 100_000_000;

/// How a level's frames map onto its total pixel matrix (`DimensionOrganizationType`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WsiDimensionOrganization {
    TiledFull,
    TiledSparse,
}

impl WsiDimensionOrganization {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::TiledFull => "TILED_FULL",
            Self::TiledSparse => "TILED_SPARSE",
        }
    }
}

/// One pyramid level (one WSI instance), described from its header alone.
#[derive(Clone, Debug, PartialEq)]
pub struct WsiLevelInfo {
    /// Position in the pyramid: 0 is the base (largest `TotalPixelMatrixColumns`) level.
    pub index: usize,
    /// Position of this instance in the caller's input list.
    pub input_index: usize,
    pub total_columns: u32,
    pub total_rows: u32,
    /// Tile size: the instance's `Columns` x `Rows`.
    pub tile_columns: u32,
    pub tile_rows: u32,
    pub number_of_frames: usize,
    pub dimension_organization: WsiDimensionOrganization,
    /// `TotalPixelMatrixFocalPlanes` for TILED_FULL; distinct per-frame Z offsets for
    /// TILED_SPARSE.
    pub focal_planes: usize,
    pub optical_paths: usize,
    pub samples_per_pixel: u16,
    pub photometric_interpretation: String,
    pub transfer_syntax_uid: String,
    pub image_type: Vec<String>,
    pub sop_instance_uid: Option<String>,
    pub series_instance_uid: Option<String>,
    /// `PixelSpacing` (row spacing, column spacing) in mm from the shared functional groups.
    pub pixel_spacing_mm: Option<[f64; 2]>,
    /// Base level columns / this level's columns (1.0 for the base level).
    pub downsample: f64,
}

/// Options for [`render_wsi`]. `render` carries the ordinary 2D options that apply to the
/// stitched image: `region` (base level pixels), `output_width`/`output_height`/
/// `scale_max_size`, `pad`/`pad_color`, `bounding_boxes`, `jpeg_quality`, `apply_icc_profile`
/// and, for monochrome slides, `window_center`/`window_width`. `frame_index` and the overlay
/// options are ignored.
#[derive(Clone, Debug)]
pub struct WsiRenderOptions {
    pub render: RenderPipelineOptions,
    /// Fill for positions no tile covers (TILED_SPARSE). Defaults to white.
    pub background_color: [u8; 3],
    /// Force a pyramid level (by [`WsiLevelInfo::index`]) instead of choosing one from the
    /// requested output size.
    pub level: Option<usize>,
    /// 0-based focal plane to render (see [`WsiLevelInfo::focal_planes`]).
    pub focal_plane_index: usize,
    /// 0-based optical path to render, in `OpticalPathSequence` order.
    pub optical_path_index: usize,
    /// Refuse outputs larger than this many pixels (width x height). Defaults to
    /// [`DEFAULT_WSI_MAX_OUTPUT_PIXELS`].
    pub max_output_pixels: u64,
}

impl Default for WsiRenderOptions {
    fn default() -> Self {
        Self {
            render: RenderPipelineOptions::default(),
            background_color: [255, 255, 255],
            level: None,
            focal_plane_index: 0,
            optical_path_index: 0,
            max_output_pixels: DEFAULT_WSI_MAX_OUTPUT_PIXELS,
        }
    }
}

/// The stitched image plus what was rendered.
#[derive(Clone, Debug)]
pub struct WsiRenderOutput {
    pub frame: RenderFrameOutput,
    /// The level the stitched pixels came from.
    pub level: WsiLevelInfo,
    /// The rendered region in base level pixels, after clamping to the matrix.
    pub region: Region,
    /// The same region in the chosen level's pixels.
    pub level_region: Region,
    /// How many tiles (frames) were decoded.
    pub tiles_decoded: usize,
}

/// Whether `object` is a VL Whole Slide Microscopy Image.
pub fn is_whole_slide_object(object: &DefaultDicomObject) -> bool {
    let sop_class = object
        .get(tags::SOP_CLASS_UID)
        .and_then(|element| element.to_str().ok())
        .map(|value| value.trim_end_matches(['\0', ' ']).to_owned())
        .unwrap_or_else(|| {
            object
                .meta()
                .media_storage_sop_class_uid()
                .trim_end_matches(['\0', ' '])
                .to_owned()
        });
    sop_class == uids::VL_WHOLE_SLIDE_MICROSCOPY_IMAGE_STORAGE
}

/// Describes the pyramid formed by `objects` (one per level; headers are enough - pixel data
/// isn't read): the levels sorted base first. Non-pyramid instances (ImageType value 3 LABEL or
/// OVERVIEW) are skipped when there is more than one input; same-size duplicates keep the
/// first. All inputs must share one SeriesInstanceUID.
pub fn describe_wsi(objects: &[&DefaultDicomObject]) -> Result<Vec<WsiLevelInfo>, RenderError> {
    build_pyramid(objects)
}

/// Stitches the requested region (default: the whole slide) of the pyramid `objects` into one
/// image. See the module docs and [`WsiRenderOptions`].
pub fn render_wsi(
    objects: &[&DefaultDicomObject],
    output_format: RenderOutputFormat,
    options: &WsiRenderOptions,
) -> Result<WsiRenderOutput, RenderError> {
    let levels = build_pyramid(objects)?;
    let plan = plan_render(&levels, options)?;
    let object = objects[plan.level.input_index];
    render_planned(object, plan, output_format, options)
}

/// [`describe_wsi`] for files, reading only each file's header (up to PixelData).
#[cfg(not(target_arch = "wasm32"))]
pub fn describe_wsi_files<P: AsRef<std::path::Path>>(
    paths: &[P],
) -> Result<Vec<WsiLevelInfo>, RenderError> {
    let headers = read_headers(paths)?;
    let refs: Vec<&DefaultDicomObject> = headers.iter().collect();
    build_pyramid(&refs)
}

/// [`render_wsi`] for files: reads every file's header to choose the level, then reads only the
/// chosen level's file in full.
#[cfg(not(target_arch = "wasm32"))]
pub fn render_wsi_files<P: AsRef<std::path::Path>>(
    paths: &[P],
    output_format: RenderOutputFormat,
    options: &WsiRenderOptions,
) -> Result<WsiRenderOutput, RenderError> {
    let headers = read_headers(paths)?;
    let refs: Vec<&DefaultDicomObject> = headers.iter().collect();
    let levels = build_pyramid(&refs)?;
    let plan = plan_render(&levels, options)?;
    let path = paths[plan.level.input_index].as_ref();
    let object = super::io::read_dicom_file(path)
        .map_err(|error| RenderError::WholeSlide(format!("reading {}: {error}", path.display())))?;
    render_planned(&object, plan, output_format, options)
}

/// Whether the file at `path` is a VL Whole Slide Microscopy Image, from its header alone.
#[cfg(not(target_arch = "wasm32"))]
pub fn is_whole_slide_file(path: impl AsRef<std::path::Path>) -> bool {
    read_header(path.as_ref())
        .map(|object| is_whole_slide_object(&object))
        .unwrap_or(false)
}

#[cfg(not(target_arch = "wasm32"))]
fn read_header(path: &std::path::Path) -> Result<DefaultDicomObject, RenderError> {
    // Everything before PixelData: (7FDF,FFFF) is the last tag read, so the read stops at the
    // PixelData element header instead of loading tiles.
    dcmnorm_object::OpenFileOptions::new()
        .read_preamble(dcmnorm_object::ReadPreamble::Always)
        .read_until(dcmnorm_core::Tag(0x7FDF, 0xFFFF))
        .open_file(path)
        .map_err(|error| RenderError::WholeSlide(format!("reading {}: {error}", path.display())))
}

#[cfg(not(target_arch = "wasm32"))]
fn read_headers<P: AsRef<std::path::Path>>(
    paths: &[P],
) -> Result<Vec<DefaultDicomObject>, RenderError> {
    paths
        .iter()
        .map(|path| read_header(path.as_ref()))
        .collect()
}

fn wsi_error(message: impl Into<String>) -> RenderError {
    RenderError::WholeSlide(message.into())
}

fn text(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<String> {
    object
        .get(tag)
        .and_then(|element| element.to_str().ok())
        .map(|value| value.trim_end_matches(['\0', ' ']).trim().to_owned())
        .filter(|value| !value.is_empty())
}

fn uint(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<u64> {
    object.get(tag).and_then(|element| {
        element.to_int::<u64>().ok().or_else(|| {
            element
                .to_str()
                .ok()
                .and_then(|value| value.split('\\').next()?.trim().parse::<u64>().ok())
        })
    })
}

fn float(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<f64> {
    object.get(tag).and_then(|element| {
        element.to_float64().ok().or_else(|| {
            element
                .to_str()
                .ok()
                .and_then(|value| value.split('\\').next()?.trim().parse::<f64>().ok())
        })
    })
}

fn first_item(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<&InMemDicomObject> {
    object.get(tag)?.value().items()?.first()
}

fn items(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> &[InMemDicomObject] {
    object
        .get(tag)
        .and_then(|element| element.value().items())
        .unwrap_or(&[])
}

fn optical_path_identifiers(object: &InMemDicomObject) -> Vec<String> {
    items(object, tags::OPTICAL_PATH_SEQUENCE)
        .iter()
        .map(|item| text(item, tags::OPTICAL_PATH_IDENTIFIER).unwrap_or_default())
        .collect()
}

/// A frame's optical path identifier: per-frame first, then shared.
fn frame_optical_path(object: &InMemDicomObject, frame_index: usize) -> Option<String> {
    let lookup = |group: &InMemDicomObject| {
        first_item(group, tags::OPTICAL_PATH_IDENTIFICATION_SEQUENCE)
            .and_then(|item| text(item, tags::OPTICAL_PATH_IDENTIFIER))
    };
    items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE)
        .get(frame_index)
        .and_then(lookup)
        .or_else(|| first_item(object, tags::SHARED_FUNCTIONAL_GROUPS_SEQUENCE).and_then(lookup))
}

/// One frame's 0-based (column, row) position and Z offset from its per-frame
/// PlanePositionSlideSequence.
fn sparse_position(item: &InMemDicomObject) -> Option<(i64, i64, Option<f64>)> {
    let position = first_item(item, tags::PLANE_POSITION_SLIDE_SEQUENCE)?;
    let column = position
        .get(tags::COLUMN_POSITION_IN_TOTAL_IMAGE_PIXEL_MATRIX)?
        .to_int::<i64>()
        .ok()?;
    let row = position
        .get(tags::ROW_POSITION_IN_TOTAL_IMAGE_PIXEL_MATRIX)?
        .to_int::<i64>()
        .ok()?;
    let z = float(position, tags::Z_OFFSET_IN_SLIDE_COORDINATE_SYSTEM);
    Some((column - 1, row - 1, z))
}

fn z_key(z: Option<f64>) -> i64 {
    // Group Z offsets (mm) at nanometer resolution so float noise doesn't split a focal plane.
    z.map(|value| (value * 1e6).round() as i64).unwrap_or(0)
}

fn sorted_focal_planes(object: &InMemDicomObject) -> Vec<i64> {
    let mut keys: Vec<i64> = items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE)
        .iter()
        .filter_map(sparse_position)
        .map(|(_, _, z)| z_key(z))
        .collect();
    keys.sort_unstable();
    keys.dedup();
    if keys.is_empty() {
        keys.push(0);
    }
    keys
}

fn dimension_organization(object: &InMemDicomObject) -> WsiDimensionOrganization {
    match text(object, tags::DIMENSION_ORGANIZATION_TYPE).as_deref() {
        Some("TILED_SPARSE") => WsiDimensionOrganization::TiledSparse,
        Some("TILED_FULL") => WsiDimensionOrganization::TiledFull,
        // Not declared: per-frame positions mean sparse, otherwise assume the implied layout.
        _ => {
            let has_positions = items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE)
                .first()
                .and_then(sparse_position)
                .is_some();
            if has_positions {
                WsiDimensionOrganization::TiledSparse
            } else {
                WsiDimensionOrganization::TiledFull
            }
        }
    }
}

fn level_info(
    object: &DefaultDicomObject,
    input_index: usize,
) -> Result<WsiLevelInfo, RenderError> {
    let sop_instance_uid = text(object, tags::SOP_INSTANCE_UID);
    let name = sop_instance_uid
        .clone()
        .unwrap_or_else(|| format!("input {input_index}"));
    let tile_columns = uint(object, tags::COLUMNS)
        .ok_or_else(|| wsi_error(format!("{name} has no Columns")))? as u32;
    let tile_rows =
        uint(object, tags::ROWS).ok_or_else(|| wsi_error(format!("{name} has no Rows")))? as u32;
    let number_of_frames = uint(object, tags::NUMBER_OF_FRAMES).unwrap_or(1) as usize;
    // A single-frame image without the tiled attributes is its own (one tile) total matrix.
    let total_columns = uint(object, tags::TOTAL_PIXEL_MATRIX_COLUMNS)
        .map(|value| value as u32)
        .unwrap_or(tile_columns);
    let total_rows = uint(object, tags::TOTAL_PIXEL_MATRIX_ROWS)
        .map(|value| value as u32)
        .unwrap_or(tile_rows);
    if tile_columns == 0 || tile_rows == 0 || total_columns == 0 || total_rows == 0 {
        return Err(wsi_error(format!(
            "{name} has an empty tile or total pixel matrix"
        )));
    }
    let organization = dimension_organization(object);
    let focal_planes = match organization {
        WsiDimensionOrganization::TiledFull => uint(object, tags::TOTAL_PIXEL_MATRIX_FOCAL_PLANES)
            .unwrap_or(1)
            .max(1) as usize,
        WsiDimensionOrganization::TiledSparse => sorted_focal_planes(object).len(),
    };
    let optical_paths = uint(object, tags::NUMBER_OF_OPTICAL_PATHS)
        .map(|value| value as usize)
        .unwrap_or_else(|| optical_path_identifiers(object).len())
        .max(1);
    let pixel_spacing_mm = first_item(object, tags::SHARED_FUNCTIONAL_GROUPS_SEQUENCE)
        .and_then(|group| first_item(group, tags::PIXEL_MEASURES_SEQUENCE))
        .and_then(|measures| text(measures, tags::PIXEL_SPACING))
        .and_then(|value| {
            let parts: Vec<f64> = value
                .split('\\')
                .filter_map(|part| part.trim().parse::<f64>().ok())
                .collect();
            (parts.len() == 2).then(|| [parts[0], parts[1]])
        });
    Ok(WsiLevelInfo {
        index: 0,
        input_index,
        total_columns,
        total_rows,
        tile_columns,
        tile_rows,
        number_of_frames,
        dimension_organization: organization,
        focal_planes,
        optical_paths,
        samples_per_pixel: uint(object, tags::SAMPLES_PER_PIXEL).unwrap_or(1) as u16,
        photometric_interpretation: text(object, tags::PHOTOMETRIC_INTERPRETATION)
            .unwrap_or_else(|| "MONOCHROME2".to_owned()),
        transfer_syntax_uid: object
            .meta()
            .transfer_syntax()
            .trim_end_matches(['\0', ' '])
            .to_owned(),
        image_type: text(object, tags::IMAGE_TYPE)
            .map(|value| value.split('\\').map(|v| v.trim().to_owned()).collect())
            .unwrap_or_default(),
        sop_instance_uid,
        series_instance_uid: text(object, tags::SERIES_INSTANCE_UID),
        pixel_spacing_mm,
        downsample: 1.0,
    })
}

fn build_pyramid(objects: &[&DefaultDicomObject]) -> Result<Vec<WsiLevelInfo>, RenderError> {
    if objects.is_empty() {
        return Err(wsi_error("no input instances"));
    }
    let mut levels = Vec::with_capacity(objects.len());
    for (input_index, object) in objects.iter().enumerate() {
        levels.push(level_info(object, input_index)?);
    }
    if levels.len() > 1 {
        let series = levels[0].series_instance_uid.clone();
        if levels
            .iter()
            .any(|level| level.series_instance_uid != series)
        {
            return Err(wsi_error(
                "the inputs belong to different series; pass the levels of one pyramid",
            ));
        }
        // LABEL / OVERVIEW images share the series but aren't pyramid levels.
        levels.retain(|level| {
            !matches!(
                level.image_type.get(2).map(String::as_str),
                Some("LABEL") | Some("OVERVIEW")
            )
        });
        if levels.is_empty() {
            return Err(wsi_error(
                "none of the inputs is a pyramid level (all are LABEL/OVERVIEW images)",
            ));
        }
    }
    // Base first; stable, so of two same-size instances the first given wins.
    levels.sort_by_key(|level| std::cmp::Reverse((level.total_columns, level.total_rows)));
    levels.dedup_by(|b, a| a.total_columns == b.total_columns && a.total_rows == b.total_rows);
    let base_columns = f64::from(levels[0].total_columns);
    for (index, level) in levels.iter_mut().enumerate() {
        level.index = index;
        level.downsample = base_columns / f64::from(level.total_columns);
    }
    Ok(levels)
}

struct RenderPlan {
    level: WsiLevelInfo,
    base_region: Region,
    level_region: Region,
    output: (u32, u32),
    decimation: u32,
}

/// `compute_output_dimensions` for u32 sizes.
fn requested_output(
    width: u32,
    height: u32,
    options: &RenderPipelineOptions,
) -> Result<Option<(u32, u32)>, RenderError> {
    match (
        options.output_width,
        options.output_height,
        options.scale_max_size,
    ) {
        (None, None, None) => Ok(None),
        (Some(w), Some(h), None) => Ok(Some((w, h))),
        (Some(w), None, None) => Ok(Some((w, scale_by_ratio(height, width, w)))),
        (None, Some(h), None) => Ok(Some((scale_by_ratio(width, height, h), h))),
        (None, None, Some(max)) => Ok(Some(scale_to_max_dimension(width, height, max))),
        _ => Err(wsi_error(
            "scale_max_size can't be combined with output_width/output_height",
        )),
    }
}

fn plan_render(
    levels: &[WsiLevelInfo],
    options: &WsiRenderOptions,
) -> Result<RenderPlan, RenderError> {
    let base = &levels[0];
    let full = Region::new(0, 0, base.total_columns, base.total_rows);
    let base_region = options
        .render
        .region
        .unwrap_or(full)
        .clamp_to(u64::from(base.total_columns), u64::from(base.total_rows))?;
    let target = requested_output(base_region.width, base_region.height, &options.render)?;
    if let Some((width, height)) = target {
        if width == 0 || height == 0 {
            return Err(wsi_error("output width/height must be greater than zero"));
        }
    }

    let level = match options.level {
        Some(index) => levels.get(index).ok_or_else(|| {
            wsi_error(format!(
                "level {index} is out of range; the pyramid has {} level(s)",
                levels.len()
            ))
        })?,
        None => match target {
            // The coarsest level that still has (to within a pixel of rounding) at least the
            // output's resolution across the region.
            Some((width, height)) => levels
                .iter()
                .rev()
                .find(|level| {
                    let columns = f64::from(base_region.width) * f64::from(level.total_columns)
                        / f64::from(base.total_columns);
                    let rows = f64::from(base_region.height) * f64::from(level.total_rows)
                        / f64::from(base.total_rows);
                    columns + 1.0 + 1e-9 >= f64::from(width)
                        && rows + 1.0 + 1e-9 >= f64::from(height)
                })
                .unwrap_or(base),
            None => base,
        },
    };

    // Map the base region onto the level, rounding outward so it is fully covered.
    let fx = f64::from(base.total_columns) / f64::from(level.total_columns);
    let fy = f64::from(base.total_rows) / f64::from(level.total_rows);
    let left = (base_region.x as f64 / fx).floor() as i64;
    let top = (base_region.y as f64 / fy).floor() as i64;
    let right = ((base_region.right() as f64 / fx).ceil() as i64)
        .clamp(left + 1, i64::from(level.total_columns));
    let bottom = ((base_region.bottom() as f64 / fy).ceil() as i64)
        .clamp(top + 1, i64::from(level.total_rows));
    let level_region = Region::new(left, top, (right - left) as u32, (bottom - top) as u32);

    let output = target.unwrap_or((level_region.width, level_region.height));
    let pixels = u64::from(output.0) * u64::from(output.1);
    if output.0 > u32::from(u16::MAX)
        || output.1 > u32::from(u16::MAX)
        || pixels > options.max_output_pixels
    {
        return Err(wsi_error(format!(
            "the stitched output would be {}x{} pixels, over the limit ({} pixels, 65535 per side); \
             request a smaller region or a downsampled output (output_width/output_height/scale_max_size)",
            output.0, output.1, options.max_output_pixels
        )));
    }

    // Box-average k x k source pixels into each canvas pixel while stitching, so a large
    // downsample never materializes the full-resolution region; the final resize to the exact
    // output size then works on a canvas at most ~2x the output per side.
    let mut decimation = if target.is_some() {
        (level_region.width / output.0)
            .min(level_region.height / output.1)
            .max(1)
    } else {
        1
    };
    let max_side = u32::from(u16::MAX);
    decimation = decimation
        .max(level_region.width.div_ceil(max_side))
        .max(level_region.height.div_ceil(max_side));

    Ok(RenderPlan {
        level: level.clone(),
        base_region,
        level_region,
        output,
        decimation,
    })
}

/// Tile positions (frame index, 0-based column, 0-based row) for the chosen focal plane and
/// optical path.
fn tile_positions(
    object: &DefaultDicomObject,
    level: &WsiLevelInfo,
    options: &WsiRenderOptions,
) -> Result<Vec<(usize, i64, i64)>, RenderError> {
    if options.focal_plane_index >= level.focal_planes {
        return Err(wsi_error(format!(
            "focal plane {} is out of range; the level has {} focal plane(s)",
            options.focal_plane_index, level.focal_planes
        )));
    }
    if options.optical_path_index >= level.optical_paths {
        return Err(wsi_error(format!(
            "optical path {} is out of range; the level has {} optical path(s)",
            options.optical_path_index, level.optical_paths
        )));
    }
    match level.dimension_organization {
        WsiDimensionOrganization::TiledFull => {
            let tiles_x = level.total_columns.div_ceil(level.tile_columns) as usize;
            let tiles_y = level.total_rows.div_ceil(level.tile_rows) as usize;
            let plane = options.optical_path_index * level.focal_planes + options.focal_plane_index;
            let first = plane * tiles_x * tiles_y;
            let last = first + tiles_x * tiles_y;
            if last > level.number_of_frames {
                return Err(wsi_error(format!(
                    "TILED_FULL level {}x{} with {}x{} tiles needs {} frames for focal plane {} / optical path {}, but NumberOfFrames is {}",
                    level.total_columns,
                    level.total_rows,
                    level.tile_columns,
                    level.tile_rows,
                    last,
                    options.focal_plane_index,
                    options.optical_path_index,
                    level.number_of_frames
                )));
            }
            let mut positions = Vec::with_capacity(tiles_x * tiles_y);
            for ty in 0..tiles_y {
                for tx in 0..tiles_x {
                    positions.push((
                        first + ty * tiles_x + tx,
                        (tx as u64 * u64::from(level.tile_columns)) as i64,
                        (ty as u64 * u64::from(level.tile_rows)) as i64,
                    ));
                }
            }
            Ok(positions)
        }
        WsiDimensionOrganization::TiledSparse => {
            let per_frame = items(object, tags::PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE);
            if per_frame.len() < level.number_of_frames {
                return Err(wsi_error(format!(
                    "TILED_SPARSE level has {} frames but only {} PerFrameFunctionalGroupsSequence items",
                    level.number_of_frames,
                    per_frame.len()
                )));
            }
            let planes = sorted_focal_planes(object);
            let plane_key = planes[options.focal_plane_index];
            let path_ids = optical_path_identifiers(object);
            let wanted_path = path_ids.get(options.optical_path_index).cloned();
            let mut positions = Vec::with_capacity(level.number_of_frames);
            for (frame_index, item) in per_frame.iter().take(level.number_of_frames).enumerate() {
                let (column, row, z) = sparse_position(item).ok_or_else(|| {
                    wsi_error(format!(
                        "TILED_SPARSE frame {frame_index} has no PlanePositionSlideSequence column/row position"
                    ))
                })?;
                if z_key(z) != plane_key {
                    continue;
                }
                if let (Some(wanted), Some(actual)) = (
                    wanted_path.as_deref(),
                    frame_optical_path(object, frame_index),
                ) {
                    if path_ids.len() > 1 && actual != wanted {
                        continue;
                    }
                }
                positions.push((frame_index, column, row));
            }
            Ok(positions)
        }
    }
}

/// Monochrome tiles are windowed with ONE mapping for the whole slide (explicit window, else
/// the full BitsStored range), not each tile's own data-driven default - a per-tile automatic
/// window would give every tile different contrast.
struct MonochromeMapping {
    center: Option<f64>,
    width: Option<f64>,
    bits_stored: u32,
    invert: bool,
}

impl MonochromeMapping {
    fn map(&self, value: f64) -> u8 {
        let mapped = match (self.center, self.width) {
            (Some(center), Some(width)) if width > 0.0 => {
                let lower = center - 0.5 - (width - 1.0) / 2.0;
                let upper = center - 0.5 + (width - 1.0) / 2.0;
                if value <= lower {
                    0.0
                } else if value > upper {
                    255.0
                } else {
                    ((value - (center - 0.5)) / (width - 1.0).max(1.0) + 0.5) * 255.0
                }
            }
            _ if self.bits_stored <= 8 => value,
            _ => value * 255.0 / ((1u64 << self.bits_stored.min(32)) - 1) as f64,
        };
        let byte = mapped.round().clamp(0.0, 255.0) as u8;
        if self.invert {
            255 - byte
        } else {
            byte
        }
    }
}

/// ICC color conversion for color tiles. A WSI keeps its ICCProfile in each
/// OpticalPathSequence item rather than at the top level, so the selected optical path's
/// profile is used when it has one (converted once for every tile); otherwise the frame
/// renderer applies a top-level ICCProfile as for any other image.
struct TileIcc {
    /// Let the frame renderer apply a top-level ICCProfile.
    frame_profile: bool,
    /// The selected optical path's profile (None when absent or unusable).
    path_transform: Option<IccTransform>,
}

impl TileIcc {
    fn new(object: &DefaultDicomObject, options: &WsiRenderOptions) -> Self {
        if !options.render.apply_icc_profile {
            return Self {
                frame_profile: false,
                path_transform: None,
            };
        }
        let path_profile = items(object, tags::OPTICAL_PATH_SEQUENCE)
            .get(options.optical_path_index)
            .and_then(|item| item.get(tags::ICC_PROFILE))
            .and_then(|element| element.to_bytes().ok())
            .filter(|bytes| !bytes.is_empty());
        match path_profile {
            Some(bytes) => Self {
                frame_profile: false,
                path_transform: icc_profile_to_srgb_transform(&bytes),
            },
            None => Self {
                frame_profile: true,
                path_transform: None,
            },
        }
    }
}

struct DecodedTile {
    column: i64,
    row: i64,
    width: u32,
    height: u32,
    samples_per_pixel: u16,
    bytes: Vec<u8>,
}

fn decode_tile(
    object: &DefaultDicomObject,
    frame_index: usize,
    column: i64,
    row: i64,
    mono: Option<&MonochromeMapping>,
    icc: &TileIcc,
) -> Result<DecodedTile, RenderError> {
    let tile_options = RenderPipelineOptions {
        frame_index,
        apply_icc_profile: icc.frame_profile,
        show_overlays: false,
        ..Default::default()
    };
    let Some(mapping) = mono else {
        let mut frame = render_dicom_frame_pixels(object, &tile_options)?;
        if let Some(transform) = &icc.path_transform {
            if frame.samples_per_pixel == 3 && frame.bytes.len().is_multiple_of(3) {
                let _ = transform.transform(&mut frame.bytes);
            }
        }
        return Ok(DecodedTile {
            column,
            row,
            width: u32::from(frame.width),
            height: u32::from(frame.height),
            samples_per_pixel: frame.samples_per_pixel,
            bytes: frame.bytes,
        });
    };
    let raw = render_dicom_frame(object, RenderOutputFormat::Raw, &tile_options)?;
    let signed = object
        .get(tags::PIXEL_REPRESENTATION)
        .and_then(|element| element.to_int::<u16>().ok())
        .unwrap_or(0)
        == 1;
    let bytes = match raw.bits_allocated {
        8 => raw
            .bytes
            .iter()
            .map(|&value| {
                let value = if signed {
                    f64::from(value as i8)
                } else {
                    f64::from(value)
                };
                mapping.map(value)
            })
            .collect(),
        16 => raw
            .bytes
            .chunks_exact(2)
            .map(|pair| {
                let word = u16::from_le_bytes([pair[0], pair[1]]);
                let value = if signed {
                    f64::from(word as i16)
                } else {
                    f64::from(word)
                };
                mapping.map(value)
            })
            .collect(),
        other => return Err(RenderError::UnsupportedBitsAllocated(other)),
    };
    Ok(DecodedTile {
        column,
        row,
        width: u32::from(raw.width),
        height: u32::from(raw.height),
        samples_per_pixel: 1,
        bytes,
    })
}

/// Stitching target: the level region at 1/`k` resolution.
struct Canvas {
    region: Region,
    k: u32,
    width: u32,
    height: u32,
    samples: usize,
    background: [u8; 3],
    /// k == 1: final pixels, background-filled, tiles copied in (later tiles win).
    direct: Vec<u8>,
    /// k > 1: per-sample sums and per-pixel contribution counts.
    sums: Vec<u64>,
    counts: Vec<u64>,
}

impl Canvas {
    fn new(region: Region, k: u32, samples: usize, background: [u8; 3]) -> Self {
        let width = region.width.div_ceil(k);
        let height = region.height.div_ceil(k);
        let pixels = width as usize * height as usize;
        let background = if samples == 1 {
            [rgb_to_luma(background); 3]
        } else {
            background
        };
        let (direct, sums, counts) = if k == 1 {
            let mut direct = Vec::with_capacity(pixels * samples);
            for _ in 0..pixels {
                direct.extend_from_slice(&background[..samples]);
            }
            (direct, Vec::new(), Vec::new())
        } else {
            (Vec::new(), vec![0u64; pixels * samples], vec![0u64; pixels])
        };
        Self {
            region,
            k,
            width,
            height,
            samples,
            background,
            direct,
            sums,
            counts,
        }
    }

    /// Adds the part of `tile` inside the region and inside the level's matrix (`matrix_w` x
    /// `matrix_h`, clipping edge tiles' padding).
    fn add(&mut self, tile: &DecodedTile, matrix_w: i64, matrix_h: i64) {
        let x0 = tile.column.max(self.region.x);
        let x1 = (tile.column + i64::from(tile.width))
            .min(self.region.right())
            .min(matrix_w);
        let y0 = tile.row.max(self.region.y);
        let y1 = (tile.row + i64::from(tile.height))
            .min(self.region.bottom())
            .min(matrix_h);
        if x1 <= x0 || y1 <= y0 {
            return;
        }
        let samples = self.samples;
        let tile_stride = tile.width as usize * samples;
        if self.k == 1 {
            let row_len = (x1 - x0) as usize * samples;
            for gy in y0..y1 {
                let src =
                    (gy - tile.row) as usize * tile_stride + (x0 - tile.column) as usize * samples;
                let dst = ((gy - self.region.y) as usize * self.width as usize
                    + (x0 - self.region.x) as usize)
                    * samples;
                self.direct[dst..dst + row_len].copy_from_slice(&tile.bytes[src..src + row_len]);
            }
            return;
        }
        let k = i64::from(self.k);
        for gy in y0..y1 {
            let dy = ((gy - self.region.y) / k) as usize;
            let src_row = (gy - tile.row) as usize * tile_stride;
            for gx in x0..x1 {
                let dx = ((gx - self.region.x) / k) as usize;
                let pixel = dy * self.width as usize + dx;
                let src = src_row + (gx - tile.column) as usize * samples;
                for sample in 0..samples {
                    self.sums[pixel * samples + sample] += u64::from(tile.bytes[src + sample]);
                }
                self.counts[pixel] += 1;
            }
        }
    }

    fn finish(self) -> RenderedFramePixels {
        let samples = self.samples;
        let bytes = if self.k == 1 {
            self.direct
        } else {
            let k = self.k;
            let mut bytes =
                Vec::with_capacity(self.width as usize * self.height as usize * samples);
            // A bin covers up to k x k source pixels (k is a u32, so that is up to ~2^64), so
            // the background term and rounding are done in u128.
            for dy in 0..self.height {
                let rows = k.min(self.region.height - dy * k);
                for dx in 0..self.width {
                    let columns = k.min(self.region.width - dx * k);
                    let expected = u128::from(rows) * u128::from(columns);
                    let pixel = dy as usize * self.width as usize + dx as usize;
                    let count = u128::from(self.counts[pixel]);
                    // Uncovered source pixels count as background.
                    let missing = expected.saturating_sub(count);
                    let total = count.max(expected).max(1);
                    for sample in 0..samples {
                        let sum = u128::from(self.sums[pixel * samples + sample])
                            + missing * u128::from(self.background[sample]);
                        bytes.push(((sum + total / 2) / total) as u8);
                    }
                }
            }
            bytes
        };
        RenderedFramePixels {
            width: self.width as u16,
            height: self.height as u16,
            samples_per_pixel: samples as u16,
            bytes,
        }
    }
}

fn render_planned(
    object: &DefaultDicomObject,
    plan: RenderPlan,
    output_format: RenderOutputFormat,
    options: &WsiRenderOptions,
) -> Result<WsiRenderOutput, RenderError> {
    let level = &plan.level;
    let positions = tile_positions(object, level, options)?;
    let region = plan.level_region;
    let matrix_w = i64::from(level.total_columns);
    let matrix_h = i64::from(level.total_rows);
    let tile_w = i64::from(level.tile_columns);
    let tile_h = i64::from(level.tile_rows);
    let wanted: Vec<(usize, i64, i64)> = positions
        .into_iter()
        .filter(|&(_, column, row)| {
            column < region.right().min(matrix_w)
                && column + tile_w > region.x
                && row < region.bottom().min(matrix_h)
                && row + tile_h > region.y
        })
        .collect();

    let mono = level
        .photometric_interpretation
        .starts_with("MONOCHROME")
        .then(|| {
            let bits_stored = uint(object, tags::BITS_STORED)
                .or_else(|| uint(object, tags::BITS_ALLOCATED))
                .unwrap_or(8) as u32;
            let (center, width) = match (options.render.window_center, options.render.window_width)
            {
                (Some(center), Some(width)) => (Some(center), Some(width)),
                _ => super::render::resolve_default_window(object, 0),
            };
            MonochromeMapping {
                center,
                width,
                bits_stored,
                invert: resolve_grayscale_invert(object, &level.photometric_interpretation),
            }
        });

    let icc = TileIcc::new(object, options);
    let decode = |&(frame_index, column, row): &(usize, i64, i64)| {
        decode_tile(object, frame_index, column, row, mono.as_ref(), &icc)
    };
    // Tiles are folded into the canvas as they decode, in frame order (so an overlapping later
    // frame still wins at decimation 1), and the canvas takes its sample count from the first
    // tile. Only one batch of decoded tiles is alive at a time, so peak memory is the canvas
    // plus a batch, not every decoded tile of the region.
    let mut canvas: Option<Canvas> = None;
    let mut fold = |tile: Result<DecodedTile, RenderError>| -> Result<(), RenderError> {
        let tile = tile?;
        let canvas = canvas.get_or_insert_with(|| {
            let samples = if mono.is_some() {
                1
            } else {
                usize::from(tile.samples_per_pixel)
            };
            Canvas::new(region, plan.decimation, samples, options.background_color)
        });
        if usize::from(tile.samples_per_pixel) != canvas.samples {
            return Err(wsi_error("tiles decode to different sample counts"));
        }
        canvas.add(&tile, matrix_w, matrix_h);
        Ok(())
    };
    #[cfg(not(target_arch = "wasm32"))]
    {
        let batch = rayon::current_num_threads().max(1) * 4;
        for chunk in wanted.chunks(batch) {
            let decoded: Vec<Result<DecodedTile, RenderError>> =
                chunk.par_iter().map(decode).collect();
            for tile in decoded {
                fold(tile)?;
            }
        }
    }
    #[cfg(target_arch = "wasm32")]
    for position in &wanted {
        fold(decode(position))?;
    }
    let tiles_decoded = wanted.len();
    let canvas = canvas.unwrap_or_else(|| {
        let samples = if mono.is_some() {
            1
        } else {
            usize::from(level.samples_per_pixel.max(1))
        };
        Canvas::new(region, plan.decimation, samples, options.background_color)
    });
    let stitched = canvas.finish();

    let resize_options = RenderPipelineOptions {
        output_width: Some(plan.output.0),
        output_height: Some(plan.output.1),
        ..Default::default()
    };
    let mut frame = maybe_resize_frame(stitched, &resize_options);
    draw_bounding_boxes(&mut frame, &options.render);
    let frame = maybe_pad_frame(frame, &options.render);
    let encoded = encode_rendered_frame(&frame, output_format, options.render.jpeg_quality)?;
    Ok(WsiRenderOutput {
        frame: encoded,
        level: plan.level,
        region: plan.base_region,
        level_region: plan.level_region,
        tiles_decoded,
    })
}