dcmnorm 0.23.0

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
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
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
//! Packs a `Volume` (see `super::volume`) or a single decoded 2D frame into a lossless,
//! GPU-upload-ready texture payload: a small metadata object (dimensions, physical geometry, a
//! rescale slope/intercept pair for reconstructing physical values from quantized samples) plus a
//! raw row-major `int16`/`uint16` byte buffer, optionally gzip-compressed for the wire.
//!
//! Deliberately NOT the same thing as `super::volume::reformat_plane`/`super::volume_export`:
//! those resample an arbitrary oblique plane or stack (windowed 8-bit render, or a full-precision
//! NIfTI/NRRD export respectively). This module ships the volume's own NATIVE voxel lattice (or a
//! single frame's native pixel grid) once, unwindowed, so a client can do arbitrary oblique
//! reslicing/window-level itself in a GPU shader instead of round-tripping to the server per
//! interaction.

use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};

use flate2::write::GzEncoder;
use flate2::Compression;
use rayon::prelude::*;
use serde_json::json;

use super::render::{
    decode_frame_grayscale_values, decode_frame_texture_rgb_values, resolve_default_window,
    resolve_grayscale_invert,
};
use super::types::RenderError;
use super::volume::{resample_volume, Interpolation, Volume};

#[derive(Debug)]
pub enum TextureExportError {
    Io(io::Error),
    Render(RenderError),
    /// `values.len()` didn't match the declared `width * height` (or `width * height * depth`).
    SampleCountMismatch {
        expected: usize,
        found: usize,
    },
    InvalidDimensions,
    /// A frame stack's frames didn't all share the same width/height - unlike `Volume`'s slices
    /// (guaranteed consistent Rows/Columns within a series by `build_volume`), frame-stack
    /// sources may come from independently-selected instances, so this is checked explicitly
    /// rather than assumed.
    FrameDimensionMismatch {
        expected: (u32, u32),
        found: (u32, u32),
    },
}

impl fmt::Display for TextureExportError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(error) => write!(formatter, "failed to pack texture export: {error}"),
            Self::Render(error) => write!(formatter, "failed to decode frame for texture export: {error}"),
            Self::SampleCountMismatch { expected, found } => write!(
                formatter,
                "texture export sample count ({found}) does not match its declared dimensions ({expected} expected)"
            ),
            Self::InvalidDimensions => write!(formatter, "texture export dimensions must all be non-zero"),
            Self::FrameDimensionMismatch { expected, found } => write!(
                formatter,
                "frame stack texture export requires every frame to share the same dimensions \
                 ({}x{} expected, found {}x{})",
                expected.0, expected.1, found.0, found.1
            ),
        }
    }
}

impl Error for TextureExportError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            Self::Render(error) => Some(error),
            _ => None,
        }
    }
}

impl From<io::Error> for TextureExportError {
    fn from(value: io::Error) -> Self {
        Self::Io(value)
    }
}

impl From<RenderError> for TextureExportError {
    fn from(value: RenderError) -> Self {
        Self::Render(value)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SampleFormat {
    Uint16,
    Int16,
    /// Interleaved 8-bit-per-channel RGB, 3 bytes/pixel - never quantized (see
    /// `pack_rgb_frame_texture`'s own doc), used for every color texture (grayscale textures are
    /// always `Uint16`/`Int16`).
    Rgb8,
}

impl SampleFormat {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Uint16 => "uint16",
            Self::Int16 => "int16",
            Self::Rgb8 => "rgb8",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContentKind {
    Volume,
    Image2D,
    /// Layers of independent original frames (a non-MPR-eligible multi-image series, or a
    /// multi-frame cine instance), uploaded once as a texture array. Distinct from `Volume` on
    /// purpose: `origin`/`row_dir`/`col_dir`/spacing carry no meaning for this kind (see
    /// `pack_frame_stack_texture`) - there is no physical/spatial claim being made, only "many
    /// frames, picked by index."
    FrameStack,
}

impl ContentKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Volume => "volume",
            Self::Image2D => "image2d",
            Self::FrameStack => "framestack",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextureCompression {
    None,
    Gzip,
}

impl TextureCompression {
    fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Gzip => "gzip",
        }
    }
}

/// Mirrors a cross-repo `TextureMeta` JSON contract shared with this library's downstream
/// consumers - see the embedding application's own docs for the full pipeline-stage/field
/// list this spans across dcmnorm, its Node/Python bindings, and downstream render/display
/// consumers.
/// `to_json` is the single source of truth for field names/casing consumed by the CLI sidecar,
/// the Node/Python bindings, and the render-server's WS response.
#[derive(Clone, Debug)]
pub struct TextureMeta {
    pub content_kind: ContentKind,
    pub sample_format: SampleFormat,
    pub compression: TextureCompression,
    pub lossless: bool,
    /// Columns - fastest-varying axis in the payload.
    pub width: u32,
    /// Rows.
    pub height: u32,
    /// Slices - always 1 for `ContentKind::Image2D`.
    pub depth: u32,
    /// `texel * rescale_slope + rescale_intercept` recovers the physical value (e.g. HU).
    pub rescale_slope: f64,
    pub rescale_intercept: f64,
    /// mm per row step (along `col_dir`) - matches `Volume::row_spacing_mm`'s convention exactly.
    pub row_spacing_mm: f64,
    /// mm per column step (along `row_dir`).
    pub col_spacing_mm: f64,
    /// mm per slice step (along `normal_dir`) - `0.0` for `ContentKind::Image2D`.
    pub slice_spacing_mm: f64,
    /// LPS mm, center of voxel (0,0,0).
    pub origin: [f64; 3],
    pub row_dir: [f64; 3],
    pub col_dir: [f64; 3],
    pub normal_dir: [f64; 3],
    pub default_window_center: Option<f64>,
    pub default_window_width: Option<f64>,
    /// Whether the client shader should display `1.0 - windowed_intensity` rather than
    /// `windowed_intensity` - the same single invert decision `render::resolve_grayscale_invert`
    /// makes for the classic JPEG/PNG path (PresentationLUTShape overriding PhotometricInterpretation's
    /// MONOCHROME1/2-derived default). Always `false` for `ContentKind::Volume`: `pack_volume_texture`
    /// only has voxel samples, not a source DICOM object, to resolve this from - see its own doc.
    pub invert: bool,
    /// `ContentKind::FrameStack` only (empty otherwise): each layer's OWN default window and
    /// invert decision, index-aligned with the layers. A multi-image series can mix instances with
    /// different value ranges/photometrics (e.g. 16-bit fluoro frames plus an 8-bit secondary
    /// capture dose sheet) - the stack-wide `default_window_*`/`invert` above come from one
    /// representative layer and would render every other kind of layer unreadable. Clients should
    /// prefer these over the stack-wide fields whenever they're present.
    pub layer_default_windows: Vec<(f64, f64)>,
    pub layer_invert: Vec<bool>,
    /// `(width, height, depth)` before any capability/progressive-driven downsampling.
    pub native_dims: (u32, u32, u32),
    pub downsampled: bool,
    pub payload_bytes_raw: u64,
    pub payload_bytes_stored: u64,
}

impl TextureMeta {
    pub fn to_json(&self) -> serde_json::Value {
        json!({
            "formatVersion": 1,
            "contentKind": self.content_kind.as_str(),
            "sampleFormat": self.sample_format.as_str(),
            "compression": self.compression.as_str(),
            "lossless": self.lossless,
            "width": self.width,
            "height": self.height,
            "depth": self.depth,
            "rescaleSlope": self.rescale_slope,
            "rescaleIntercept": self.rescale_intercept,
            "rowSpacingMm": self.row_spacing_mm,
            "colSpacingMm": self.col_spacing_mm,
            "sliceSpacingMm": self.slice_spacing_mm,
            "origin": self.origin,
            "rowDir": self.row_dir,
            "colDir": self.col_dir,
            "normalDir": self.normal_dir,
            "defaultWindowCenter": self.default_window_center,
            "defaultWindowWidth": self.default_window_width,
            "invert": self.invert,
            "layerWindowCenters": self.layer_default_windows.iter().map(|(center, _)| *center).collect::<Vec<_>>(),
            "layerWindowWidths": self.layer_default_windows.iter().map(|(_, width)| *width).collect::<Vec<_>>(),
            "layerInvert": self.layer_invert,
            "nativeDims": [self.native_dims.0, self.native_dims.1, self.native_dims.2],
            "downsampled": self.downsampled,
            "payloadBytesRaw": self.payload_bytes_raw,
            "payloadBytesStored": self.payload_bytes_stored,
        })
    }
}

pub struct PackedTexture {
    pub meta: TextureMeta,
    pub payload: Vec<u8>,
}

impl fmt::Debug for PackedTexture {
    // Manual impl (mirroring `Volume`'s) so a large `payload` (up to hundreds of MB) never floods
    // `{:?}`/`assert!` failure output.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PackedTexture")
            .field("meta", &self.meta)
            .field("payload_len", &self.payload.len())
            .finish()
    }
}

fn gzip_bytes(bytes: &[u8]) -> Result<Vec<u8>, TextureExportError> {
    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
    encoder.write_all(bytes)?;
    Ok(encoder.finish()?)
}

/// Quantizes `raw` physical-value samples into a lossless little-endian byte buffer, picking
/// whichever of two encodings applies:
///
/// - **Exact, unsigned** (MG/DX/CR/DBT and most unsigned MR): integer samples in `0..=65535` are
///   stored as `uint16` with an identity slope/intercept (`1.0`/`0.0`). Preferred over `int16` even
///   when the values would also fit in `i16` (12-bit data does), because a client uploads `uint16`
///   samples as they are, while `int16` needs a rebias pass over every sample first.
/// - **Exact, signed** (CT and anything else negative): if every sample round-trips through an
///   `i16` lattice with zero error, store `int16` with an identity slope/intercept (`1.0`/`0.0`) -
///   genuinely lossless, no requantization at all.
/// - **Exact, offset `uint16`**: integer samples outside `i16` but whose span `max - min` still
///   fits in 16 bits (e.g. 16-bit unsigned DX/MG/CR with values above 32767) - store
///   `value - min` as `uint16` with slope `1.0` and intercept `min`. Still genuinely lossless.
/// - **Bounded-error fallback** (fractional-valued modalities, or an integer span wider than
///   16 bits): quantize to `uint16` via a slope/intercept spanning `[min, max]`; error is bounded by
///   `±0.5 * slope` and `lossless` is reported as `false` - callers must not claim losslessness
///   this path took.
///
/// Returns `(bytes, format, rescale_slope, rescale_intercept, lossless)`.
pub fn quantize_samples(raw: &[f32]) -> (Vec<u8>, SampleFormat, f64, f64, bool) {
    quantize_with_stats(raw, &sample_stats(raw))
}

/// Min/max and integrality of a sample buffer. One parallel pass, shared by `quantize_with_stats`
/// and `window_from_stats` - previously two separate serial passes plus a serial per-sample
/// `extend_from_slice` encode made this the bulk of a large volume's export time (a 1,200-slice
/// 512x512 CT, 315M samples: ~2.4 s single-threaded).
#[derive(Clone, Copy, Debug)]
struct SampleStats {
    min: f64,
    max: f64,
    all_integral: bool,
}

const PAR_CHUNK_SAMPLES: usize = 1 << 16;

fn sample_stats(raw: &[f32]) -> SampleStats {
    sample_stats_parts(&[raw])
}

/// `sample_stats` over several buffers taken as one (the frames of a stack), without
/// concatenating them first.
fn sample_stats_parts(parts: &[&[f32]]) -> SampleStats {
    let identity = || SampleStats {
        min: f64::INFINITY,
        max: f64::NEG_INFINITY,
        all_integral: true,
    };
    parts
        .par_iter()
        .flat_map(|part| part.par_chunks(PAR_CHUNK_SAMPLES))
        .map(|chunk| {
            let mut stats = identity();
            for &sample in chunk {
                let value = sample as f64;
                stats.min = stats.min.min(value);
                stats.max = stats.max.max(value);
                if stats.all_integral && (value - value.round()).abs() > 1e-4 {
                    stats.all_integral = false;
                }
            }
            stats
        })
        .reduce(identity, |a, b| SampleStats {
            min: a.min.min(b.min),
            max: a.max.max(b.max),
            all_integral: a.all_integral && b.all_integral,
        })
}

/// Encodes every sample of `parts` (in order) to 2 little-endian bytes, in parallel chunks, into
/// one preallocated buffer.
fn encode_u16_le_parts(parts: &[&[f32]], encode: impl Fn(f32) -> [u8; 2] + Sync) -> Vec<u8> {
    let total: usize = parts.iter().map(|part| part.len()).sum();
    let mut bytes = vec![0u8; total * 2];
    let mut rest: &mut [u8] = &mut bytes;
    for part in parts {
        let (out, tail) = rest.split_at_mut(part.len() * 2);
        rest = tail;
        out.par_chunks_mut(PAR_CHUNK_SAMPLES * 2)
            .zip(part.par_chunks(PAR_CHUNK_SAMPLES))
            .for_each(|(out, samples)| {
                for (dst, &sample) in out.chunks_exact_mut(2).zip(samples) {
                    dst.copy_from_slice(&encode(sample));
                }
            });
    }
    bytes
}

/// `quantize_samples` with its min/max/integrality pass already done (see `sample_stats`).
fn quantize_with_stats(
    raw: &[f32],
    stats: &SampleStats,
) -> (Vec<u8>, SampleFormat, f64, f64, bool) {
    quantize_parts_with_stats(&[raw], stats)
}

/// `quantize_with_stats` over several buffers taken as one (see `sample_stats_parts`).
fn quantize_parts_with_stats(
    parts: &[&[f32]],
    stats: &SampleStats,
) -> (Vec<u8>, SampleFormat, f64, f64, bool) {
    if parts.iter().all(|part| part.is_empty()) {
        return (Vec::new(), SampleFormat::Int16, 1.0, 0.0, true);
    }
    let SampleStats {
        min,
        max,
        all_integral,
    } = *stats;

    if all_integral && min >= 0.0 && max <= u16::MAX as f64 {
        let bytes = encode_u16_le_parts(parts, |sample| (sample.round() as u16).to_le_bytes());
        return (bytes, SampleFormat::Uint16, 1.0, 0.0, true);
    }

    if all_integral && min >= i16::MIN as f64 && max <= i16::MAX as f64 {
        let bytes = encode_u16_le_parts(parts, |sample| (sample.round() as i16).to_le_bytes());
        return (bytes, SampleFormat::Int16, 1.0, 0.0, true);
    }

    if all_integral && max - min <= u16::MAX as f64 {
        let intercept = min.round();
        let bytes = encode_u16_le_parts(parts, |sample| {
            ((sample as f64 - intercept).round() as u16).to_le_bytes()
        });
        return (bytes, SampleFormat::Uint16, 1.0, intercept, true);
    }

    let range = (max - min).max(1e-6);
    let slope = range / 65535.0;
    let intercept = min;
    let bytes = encode_u16_le_parts(parts, |sample| {
        let scaled = ((sample as f64 - intercept) / slope)
            .round()
            .clamp(0.0, 65535.0);
        (scaled as u16).to_le_bytes()
    });
    (bytes, SampleFormat::Uint16, slope, intercept, false)
}

/// Falls back to a min/max-spanning window (`center = (min+max)/2`, `width = max(max-min, 1)`)
/// when the caller didn't supply an explicit default window - the exact same span
/// `normalize_to_u8` (`super::render`) uses for the old JPEG path's own last-resort fallback when
/// an instance has neither a caller override nor its own `WindowCenter`/`WindowWidth` tags.
/// Without this, `default_window_center`/`width` stay `None` and the GPU shader's own hardcoded
/// default (`center=0, width=1`) clips nearly all real (non-zero-centered) pixel data to white.
fn window_from_stats(stats: &SampleStats) -> (f64, f64) {
    let SampleStats { min, max, .. } = *stats;
    if !min.is_finite() || !max.is_finite() {
        return (0.0, 1.0);
    }
    ((min + max) / 2.0, (max - min).max(1.0))
}

fn apply_compression(
    quantized: Vec<u8>,
    compression: TextureCompression,
) -> Result<(Vec<u8>, u64), TextureExportError> {
    let payload_bytes_raw = quantized.len() as u64;
    let payload = match compression {
        TextureCompression::None => quantized,
        TextureCompression::Gzip => gzip_bytes(&quantized)?,
    };
    Ok((payload, payload_bytes_raw))
}

/// Packs `volume`'s own native voxel lattice (NOT a resampled oblique plane - see the module doc)
/// into a lossless texture payload. If `target_max_dim` is set and any of the volume's own
/// `cols`/`rows`/`num_slices` exceeds it, the whole grid is first proportionally downsampled (via
/// `super::volume::resample_volume`) to fit, preserving physical extent.
pub fn pack_volume_texture(
    volume: &Volume,
    target_max_dim: Option<u32>,
    default_window: Option<(f64, f64)>,
    compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
    let native_dims = (volume.cols, volume.rows, volume.num_slices);
    if native_dims.0 == 0 || native_dims.1 == 0 || native_dims.2 == 0 {
        return Err(TextureExportError::InvalidDimensions);
    }

    let native_max = native_dims.0.max(native_dims.1).max(native_dims.2);
    // Borrowed unless downsampled - cloning a native-size volume here was a full extra copy of
    // every sample (1.26 GB for a 1,200-slice 512x512 CT) just to read it.
    let (raw, dims, downsampled): (Cow<[f32]>, (u32, u32, u32), bool) = match target_max_dim {
        Some(max_dim) if native_max > max_dim.max(1) => {
            let scale = max_dim.max(1) as f64 / native_max as f64;
            let target_cols = ((native_dims.0 as f64 * scale).round() as u32).max(1);
            let target_rows = ((native_dims.1 as f64 * scale).round() as u32).max(1);
            let target_slices = ((native_dims.2 as f64 * scale).round() as u32).max(1);
            let resampled = resample_volume(
                volume,
                target_cols,
                target_rows,
                target_slices,
                Interpolation::Trilinear,
            );
            (
                Cow::Owned(resampled),
                (target_cols, target_rows, target_slices),
                true,
            )
        }
        // An irregularly spaced stack has no uniform slice spacing to report, so it's resampled
        // by position onto a uniform lattice with the same slice count (the texture's
        // `slice_spacing_mm` is then exact instead of an average that stretches part of it).
        _ if volume.has_irregular_spacing() => {
            let resampled = resample_volume(
                volume,
                native_dims.0,
                native_dims.1,
                native_dims.2,
                Interpolation::Trilinear,
            );
            (Cow::Owned(resampled), native_dims, false)
        }
        _ => (Cow::Borrowed(volume.samples.as_slice()), native_dims, false),
    };

    let expected = dims.0 as usize * dims.1 as usize * dims.2 as usize;
    if raw.len() != expected {
        return Err(TextureExportError::SampleCountMismatch {
            expected,
            found: raw.len(),
        });
    }

    let stats = sample_stats(&raw);
    let (quantized, sample_format, rescale_slope, rescale_intercept, lossless) =
        quantize_with_stats(&raw, &stats);
    let default_window = default_window.or_else(|| Some(window_from_stats(&stats)));
    let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
    let payload_bytes_stored = payload.len() as u64;

    // Downsampling shrinks voxel COUNT while covering the same physical extent, so per-axis
    // spacing grows by the inverse of that axis's shrink ratio.
    // `resample_volume` places the first and last target voxel exactly on the first and last
    // native voxel, so an axis of n native voxels exported as d covers the same centre-to-centre
    // extent: its spacing grows by (n - 1) / (d - 1), not n / d (which left the far end of a
    // 512 -> 256 axis half a voxel short).
    let axis_scale = |native: u32, exported: u32| -> f64 {
        if exported > 1 && native > 1 {
            (native - 1) as f64 / (exported - 1) as f64
        } else {
            native as f64 / exported as f64
        }
    };
    let col_scale = axis_scale(native_dims.0, dims.0);
    let row_scale = axis_scale(native_dims.1, dims.1);
    let slice_nominal_spacing = volume.nominal_slice_spacing_mm();
    let slice_scale = axis_scale(native_dims.2, dims.2);

    let meta = TextureMeta {
        content_kind: ContentKind::Volume,
        sample_format,
        compression,
        lossless,
        width: dims.0,
        height: dims.1,
        depth: dims.2,
        rescale_slope,
        rescale_intercept,
        row_spacing_mm: volume.row_spacing_mm * row_scale,
        col_spacing_mm: volume.col_spacing_mm * col_scale,
        slice_spacing_mm: slice_nominal_spacing * slice_scale,
        origin: volume.origin,
        row_dir: volume.row_vector,
        col_dir: volume.col_vector,
        normal_dir: volume.slice_normal,
        default_window_center: default_window.map(|(center, _)| center),
        default_window_width: default_window.map(|(_, width)| width),
        // See TextureMeta::invert's own doc: no source DICOM object is available here to resolve
        // PresentationLUTShape/PhotometricInterpretation from (deliberately - same reasoning as
        // the per-frame VOI/rescale fix that left this MPR volume path alone).
        invert: false,
        layer_default_windows: Vec::new(),
        layer_invert: Vec::new(),
        native_dims,
        downsampled,
        payload_bytes_raw,
        payload_bytes_stored,
    };

    Ok(PackedTexture { meta, payload })
}

/// 2D bilinear box-downsample of a single frame's raw values to fit within `target_max_dim` on
/// its longest axis, preserving aspect ratio. Deliberately independent of `super::render`'s
/// existing (lossy, 8-bit-targeted) resize path used for `--scale-max-size` - this operates on
/// raw physical values, before any windowing/quantization. Returns `(values, width, height)`;
/// a no-op (clone) if the frame already fits.
pub fn resample_frame_2d(
    values: &[f32],
    width: u32,
    height: u32,
    target_max_dim: u32,
) -> (Vec<f32>, u32, u32) {
    let native_max = width.max(height);
    if native_max == 0 || native_max <= target_max_dim.max(1) {
        return (values.to_vec(), width, height);
    }

    let scale = target_max_dim.max(1) as f64 / native_max as f64;
    let target_width = ((width as f64 * scale).round() as u32).max(1);
    let target_height = ((height as f64 * scale).round() as u32).max(1);

    let col_scale = if target_width > 1 {
        (width as f64 - 1.0) / (target_width as f64 - 1.0)
    } else {
        0.0
    };
    let row_scale = if target_height > 1 {
        (height as f64 - 1.0) / (target_height as f64 - 1.0)
    } else {
        0.0
    };

    let sample_at = |x_f: f64, y_f: f64| -> f32 {
        let x0 = x_f.floor().clamp(0.0, (width - 1) as f64) as usize;
        let y0 = y_f.floor().clamp(0.0, (height - 1) as f64) as usize;
        let x1 = (x0 + 1).min(width as usize - 1);
        let y1 = (y0 + 1).min(height as usize - 1);
        let tx = x_f - x0 as f64;
        let ty = y_f - y0 as f64;
        let get = |x: usize, y: usize| values[y * width as usize + x] as f64;
        let top = get(x0, y0) * (1.0 - tx) + get(x1, y0) * tx;
        let bottom = get(x0, y1) * (1.0 - tx) + get(x1, y1) * tx;
        (top * (1.0 - ty) + bottom * ty) as f32
    };

    let mut out = vec![0f32; target_width as usize * target_height as usize];
    for target_row in 0..target_height {
        let y_f = if target_height > 1 {
            target_row as f64 * row_scale
        } else {
            (height as f64 - 1.0) / 2.0
        };
        for target_col in 0..target_width {
            let x_f = if target_width > 1 {
                target_col as f64 * col_scale
            } else {
                (width as f64 - 1.0) / 2.0
            };
            out[target_row as usize * target_width as usize + target_col as usize] =
                sample_at(x_f, y_f);
        }
    }
    (out, target_width, target_height)
}

/// Packs a single 2D frame's already-decoded raw physical values (e.g. from
/// `super::render::decode_frame_grayscale_values`) as a depth-1 "1-slice volume" texture -
/// letting a large diagnostic 2D image reuse the exact same client GPU texture/shader machinery
/// as an MPR volume instead of a separate implementation.
pub fn pack_frame_texture(
    values: &[f32],
    width: u32,
    height: u32,
    default_window: Option<(f64, f64)>,
    target_max_dim: Option<u32>,
    compression: TextureCompression,
    invert: bool,
) -> Result<PackedTexture, TextureExportError> {
    if width == 0 || height == 0 {
        return Err(TextureExportError::InvalidDimensions);
    }
    let expected = width as usize * height as usize;
    if values.len() != expected {
        return Err(TextureExportError::SampleCountMismatch {
            expected,
            found: values.len(),
        });
    }
    let native_dims = (width, height, 1);

    let (raw, out_width, out_height, downsampled) = match target_max_dim {
        Some(max_dim) if width.max(height) > max_dim.max(1) => {
            let (resampled, w, h) = resample_frame_2d(values, width, height, max_dim);
            (Cow::Owned(resampled), w, h, true)
        }
        _ => (Cow::Borrowed(values), width, height, false),
    };

    let stats = sample_stats(&raw);
    let (quantized, sample_format, rescale_slope, rescale_intercept, lossless) =
        quantize_with_stats(&raw, &stats);
    let default_window = default_window.or_else(|| Some(window_from_stats(&stats)));
    let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
    let payload_bytes_stored = payload.len() as u64;

    let meta = TextureMeta {
        content_kind: ContentKind::Image2D,
        sample_format,
        compression,
        lossless,
        width: out_width,
        height: out_height,
        depth: 1,
        rescale_slope,
        rescale_intercept,
        // A single decoded frame carries no volume-level geometry here - callers with real
        // PixelSpacing available (the CLI/Node bindings, from the source DICOM object) can layer
        // physical spacing on top later; pan/zoom/W-L don't require it.
        row_spacing_mm: 1.0,
        col_spacing_mm: 1.0,
        slice_spacing_mm: 0.0,
        origin: [0.0, 0.0, 0.0],
        row_dir: [1.0, 0.0, 0.0],
        col_dir: [0.0, 1.0, 0.0],
        normal_dir: [0.0, 0.0, 1.0],
        default_window_center: default_window.map(|(center, _)| center),
        default_window_width: default_window.map(|(_, width)| width),
        invert,
        layer_default_windows: Vec::new(),
        layer_invert: Vec::new(),
        native_dims,
        downsampled,
        payload_bytes_raw,
        payload_bytes_stored,
    };

    Ok(PackedTexture { meta, payload })
}

/// Convenience wrapper: decodes frame `frame_index` of `object` (modality-LUT-applied, raw
/// physical values - the same primitive `super::volume::build_volume` uses per-slice) and packs
/// it, so callers (the CLI, and eventually the Node bindings) don't need to touch
/// `decode_frame_grayscale_values` directly.
///
/// If the caller didn't supply an explicit `default_window`, resolves the object's OWN VOI window
/// (top-level WindowCenter/Width, or the per-frame functional group fallback for Enhanced
/// Multi-frame objects - see `render::resolve_default_window`) before falling further back to
/// `pack_frame_texture`'s own min/max span. Without this, the GPU texture pipeline's initial
/// window/level would silently disagree with the classic JPEG/PNG pipeline's `resolve_window` for
/// any file whose caller (e.g. render-server) didn't already resolve and pass one itself.
pub fn pack_dicom_frame_texture(
    object: &dcmnorm_object::DefaultDicomObject,
    frame_index: usize,
    target_max_dim: Option<u32>,
    default_window: Option<(f64, f64)>,
    compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
    let default_window = default_window.or_else(|| {
        let (center, width) = resolve_default_window(object, frame_index);
        center.zip(width)
    });
    let (metadata, values) = decode_frame_grayscale_values(object, frame_index)?;
    let invert = resolve_grayscale_invert(object, &metadata.photometric_interpretation);
    let raw: Vec<f32> = values.into_iter().map(|value| value as f32).collect();
    pack_frame_texture(
        &raw,
        metadata.cols as u32,
        metadata.rows as u32,
        default_window,
        target_max_dim,
        compression,
        invert,
    )
}

/// One already-decoded 2D frame, as input to `pack_frame_stack_texture` - the frame-stack analog
/// of `pack_frame_texture`'s bare `values`/`width`/`height` triple, bundled into a struct since a
/// stack takes many of them at once.
#[derive(Clone, Debug)]
pub struct DecodedFrame {
    pub values: Vec<f32>,
    pub width: u32,
    pub height: u32,
}

/// Packs `frames` - independent original frames, in caller-supplied order (this order becomes
/// the texture array's own layer order, and must match the client's own frame-index ordering, so
/// scrolling/cine playback picks the right layer) - as one texture array upload: no cross-layer
/// interpolation, no physical geometry, just "many same-sized frames, picked by index."
///
/// Deliberately DOES NOT resample/downsample: unlike `pack_volume_texture`'s `target_max_dim`,
/// there is no size-reduction path here at all. A stack that would be too large to upload is the
/// caller's job to reject BEFORE calling this (see the render-server's size-ceiling guard) - once
/// a frame is in the stack, it is exactly the source frame, which matters for cine playback where
/// a resampled frame could visibly differ from what per-tick server JPEG rendering already showed
/// during the mid-playback swap.
///
/// All frames must share the same width/height (`FrameDimensionMismatch` otherwise) - DICOM
/// guarantees this within a series' Rows/Columns in practice, but frame-stack sources aren't
/// necessarily from a single geometrically-consistent series (that's exactly the case real MPR
/// volumes reject and this tier exists to still serve), so it's checked explicitly rather than
/// assumed.
pub fn pack_frame_stack_texture(
    frames: &[DecodedFrame],
    default_window: Option<(f64, f64)>,
    compression: TextureCompression,
    invert: bool,
) -> Result<PackedTexture, TextureExportError> {
    let Some(first) = frames.first() else {
        return Err(TextureExportError::InvalidDimensions);
    };
    let (width, height) = (first.width, first.height);
    if width == 0 || height == 0 {
        return Err(TextureExportError::InvalidDimensions);
    }
    let expected_per_frame = width as usize * height as usize;

    // Validated and quantized as one sequence of parts - never concatenated into a second full
    // copy of every sample first.
    let mut parts: Vec<&[f32]> = Vec::with_capacity(frames.len());
    for frame in frames {
        if frame.width != width || frame.height != height {
            return Err(TextureExportError::FrameDimensionMismatch {
                expected: (width, height),
                found: (frame.width, frame.height),
            });
        }
        if frame.values.len() != expected_per_frame {
            return Err(TextureExportError::SampleCountMismatch {
                expected: expected_per_frame,
                found: frame.values.len(),
            });
        }
        parts.push(&frame.values);
    }

    let depth = frames.len() as u32;
    let native_dims = (width, height, depth);

    let stats = sample_stats_parts(&parts);
    let (quantized, sample_format, rescale_slope, rescale_intercept, lossless) =
        quantize_parts_with_stats(&parts, &stats);
    let default_window = default_window.or_else(|| Some(window_from_stats(&stats)));
    let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
    let payload_bytes_stored = payload.len() as u64;

    let meta = TextureMeta {
        content_kind: ContentKind::FrameStack,
        sample_format,
        compression,
        lossless,
        width,
        height,
        depth,
        rescale_slope,
        rescale_intercept,
        // No physical geometry, ever - see the module doc and ContentKind::FrameStack. Kept at
        // the same identity/zero values pack_frame_texture uses for its own non-volume case.
        row_spacing_mm: 1.0,
        col_spacing_mm: 1.0,
        slice_spacing_mm: 0.0,
        origin: [0.0, 0.0, 0.0],
        row_dir: [1.0, 0.0, 0.0],
        col_dir: [0.0, 1.0, 0.0],
        normal_dir: [0.0, 0.0, 1.0],
        default_window_center: default_window.map(|(center, _)| center),
        default_window_width: default_window.map(|(_, width)| width),
        invert,
        layer_default_windows: Vec::new(),
        layer_invert: Vec::new(),
        native_dims,
        downsampled: false,
        payload_bytes_raw,
        payload_bytes_stored,
    };

    Ok(PackedTexture { meta, payload })
}

/// Convenience wrapper mirroring `pack_dicom_frame_texture`: decodes `(object, frame_index)` for
/// each entry of `sources` and packs the result as a frame stack. A source repeated with
/// different frame indices (same multi-frame object, decoded once per index by the caller) is
/// exactly how a cine instance's own frames become a stack; one entry per distinct object (each
/// at frame_index 0) is exactly how a multi-image series' instances become a stack - this
/// function doesn't need to know which case it's in, since both reduce to the same flat list.
///
/// If the caller didn't supply an explicit `default_window`, resolves it from the FIRST source
/// (same "one representative instance speaks for the whole stack" convention the render-server's
/// own volume/stack export handlers already use) via `render::resolve_default_window` - see
/// `pack_dicom_frame_texture`'s own doc for why this matters for Enhanced Multi-frame objects.
pub fn pack_dicom_frame_stack_texture(
    sources: &[(&dcmnorm_object::DefaultDicomObject, usize)],
    default_window: Option<(f64, f64)>,
    compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
    let default_window = default_window.or_else(|| {
        let (object, frame_index) = sources.first()?;
        let (center, width) = resolve_default_window(object, *frame_index);
        center.zip(width)
    });
    // Same "first source speaks for the whole stack" convention as default_window above: a
    // frame stack is either one multi-frame instance's own frames (one object, uniform
    // PhotometricInterpretation/PresentationLUTShape by definition) or a multi-image series
    // (independently-selected instances, but in practice never mixing MONOCHROME1 and
    // MONOCHROME2 members within one series).
    let mut invert = false;
    let mut layer_invert = Vec::with_capacity(sources.len());
    let mut decoded = Vec::with_capacity(sources.len());
    for (index, (object, frame_index)) in sources.iter().enumerate() {
        let (metadata, values) = decode_frame_grayscale_values(object, *frame_index)?;
        if index == 0 {
            invert = resolve_grayscale_invert(object, &metadata.photometric_interpretation);
        }
        let raw: Vec<f32> = values.into_iter().map(|value| value as f32).collect();
        decoded.push(DecodedFrame {
            values: raw,
            width: metadata.cols as u32,
            height: metadata.rows as u32,
        });
        layer_invert.push(resolve_grayscale_invert(
            object,
            &metadata.photometric_interpretation,
        ));
    }

    // Per-layer defaults (see `TextureMeta::layer_default_windows`): a layer's own
    // WindowCenter/Width (per-frame for Enhanced Multi-frame, via resolve_default_window), else a
    // min/max span over ALL of its source object's frames in the stack - per object rather than
    // per frame, so an untagged cine loop keeps one stable window instead of flickering
    // frame-to-frame.
    let mut object_min_max: Vec<(*const dcmnorm_object::DefaultDicomObject, (f64, f64))> =
        Vec::new();
    let mut layer_default_windows = Vec::with_capacity(sources.len());
    for (object, frame_index) in sources {
        let (center, width) = resolve_default_window(object, *frame_index);
        let window = match center.zip(width) {
            Some(window) => window,
            None => {
                let key: *const dcmnorm_object::DefaultDicomObject = *object;
                match object_min_max.iter().find(|(cached, _)| *cached == key) {
                    Some((_, window)) => *window,
                    None => {
                        let object_frames: Vec<&[f32]> = sources
                            .iter()
                            .zip(decoded.iter())
                            .filter(|((other, _), _)| std::ptr::eq(*other, *object))
                            .map(|(_, frame)| frame.values.as_slice())
                            .collect();
                        let window = window_from_stats(&sample_stats_parts(&object_frames));
                        object_min_max.push((key, window));
                        window
                    }
                }
            }
        };
        layer_default_windows.push(window);
    }

    let mut packed = pack_frame_stack_texture(&decoded, default_window, compression, invert)?;
    packed.meta.layer_default_windows = layer_default_windows;
    packed.meta.layer_invert = layer_invert;
    Ok(packed)
}

/// RGB analog of `resample_frame_2d` - independent per-channel bilinear box-downsample of an
/// interleaved RGB8 frame. `u8` in/out (round + clamp to 0-255) rather than a raw `f32`
/// passthrough - RGB8 has no "physical value" concept beyond the display range, unlike the
/// grayscale path's physical samples.
pub fn resample_rgb_frame_2d(
    rgb: &[u8],
    width: u32,
    height: u32,
    target_max_dim: u32,
) -> (Vec<u8>, u32, u32) {
    let native_max = width.max(height);
    if native_max == 0 || native_max <= target_max_dim.max(1) {
        return (rgb.to_vec(), width, height);
    }

    let scale = target_max_dim.max(1) as f64 / native_max as f64;
    let target_width = ((width as f64 * scale).round() as u32).max(1);
    let target_height = ((height as f64 * scale).round() as u32).max(1);

    let col_scale = if target_width > 1 {
        (width as f64 - 1.0) / (target_width as f64 - 1.0)
    } else {
        0.0
    };
    let row_scale = if target_height > 1 {
        (height as f64 - 1.0) / (target_height as f64 - 1.0)
    } else {
        0.0
    };

    let sample_at = |channel: usize, x_f: f64, y_f: f64| -> f64 {
        let x0 = x_f.floor().clamp(0.0, (width - 1) as f64) as usize;
        let y0 = y_f.floor().clamp(0.0, (height - 1) as f64) as usize;
        let x1 = (x0 + 1).min(width as usize - 1);
        let y1 = (y0 + 1).min(height as usize - 1);
        let tx = x_f - x0 as f64;
        let ty = y_f - y0 as f64;
        let get = |x: usize, y: usize| rgb[(y * width as usize + x) * 3 + channel] as f64;
        let top = get(x0, y0) * (1.0 - tx) + get(x1, y0) * tx;
        let bottom = get(x0, y1) * (1.0 - tx) + get(x1, y1) * tx;
        top * (1.0 - ty) + bottom * ty
    };

    let mut out = vec![0u8; target_width as usize * target_height as usize * 3];
    for target_row in 0..target_height {
        let y_f = if target_height > 1 {
            target_row as f64 * row_scale
        } else {
            (height as f64 - 1.0) / 2.0
        };
        for target_col in 0..target_width {
            let x_f = if target_width > 1 {
                target_col as f64 * col_scale
            } else {
                (width as f64 - 1.0) / 2.0
            };
            let out_index = (target_row as usize * target_width as usize + target_col as usize) * 3;
            for channel in 0..3 {
                out[out_index + channel] =
                    sample_at(channel, x_f, y_f).round().clamp(0.0, 255.0) as u8;
            }
        }
    }
    (out, target_width, target_height)
}

/// Packs a single 2D frame's already-decoded interleaved RGB8 bytes (e.g. from
/// `super::render::decode_frame_texture_rgb_values`) as a depth-1 texture - the color counterpart
/// to `pack_frame_texture`. Never quantized: RGB8 IS the wire format, so `lossless` is
/// unconditionally `true` in the quantization-fidelity sense this flag tracks (see
/// `TextureMeta::lossless`'s own doc) - whether the SOURCE transfer syntax was itself
/// lossy-compressed is an entirely orthogonal, client-side concern (see js/utils.js's
/// `sourceIsLossy`), same as it already is for a lossy-source grayscale texture. No window/invert
/// concept for color - both are grayscale-only ideas (color is never windowed, and MONOCHROME1
/// inversion has no color analog).
pub fn pack_rgb_frame_texture(
    rgb: &[u8],
    width: u32,
    height: u32,
    target_max_dim: Option<u32>,
    compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
    if width == 0 || height == 0 {
        return Err(TextureExportError::InvalidDimensions);
    }
    let expected = width as usize * height as usize * 3;
    if rgb.len() != expected {
        return Err(TextureExportError::SampleCountMismatch {
            expected,
            found: rgb.len(),
        });
    }
    let native_dims = (width, height, 1);

    let (quantized, out_width, out_height, downsampled) = match target_max_dim {
        Some(max_dim) if width.max(height) > max_dim.max(1) => {
            let (resampled, w, h) = resample_rgb_frame_2d(rgb, width, height, max_dim);
            (resampled, w, h, true)
        }
        _ => (rgb.to_vec(), width, height, false),
    };

    let (payload, payload_bytes_raw) = apply_compression(quantized, compression)?;
    let payload_bytes_stored = payload.len() as u64;

    let meta = TextureMeta {
        content_kind: ContentKind::Image2D,
        sample_format: SampleFormat::Rgb8,
        compression,
        lossless: true,
        width: out_width,
        height: out_height,
        depth: 1,
        rescale_slope: 1.0,
        rescale_intercept: 0.0,
        row_spacing_mm: 1.0,
        col_spacing_mm: 1.0,
        slice_spacing_mm: 0.0,
        origin: [0.0, 0.0, 0.0],
        row_dir: [1.0, 0.0, 0.0],
        col_dir: [0.0, 1.0, 0.0],
        normal_dir: [0.0, 0.0, 1.0],
        default_window_center: None,
        default_window_width: None,
        invert: false,
        layer_default_windows: Vec::new(),
        layer_invert: Vec::new(),
        native_dims,
        downsampled,
        payload_bytes_raw,
        payload_bytes_stored,
    };

    Ok(PackedTexture { meta, payload })
}

/// Convenience wrapper: decodes frame `frame_index` of `object` to RGB8 (via
/// `decode_frame_texture_rgb_values` - PALETTE COLOR-aware, ICC-corrected, matching the classic
/// JPEG/PNG render exactly) and packs it - the color counterpart to `pack_dicom_frame_texture`.
pub fn pack_dicom_rgb_frame_texture(
    object: &dcmnorm_object::DefaultDicomObject,
    frame_index: usize,
    target_max_dim: Option<u32>,
    compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
    let (metadata, rgb) = decode_frame_texture_rgb_values(object, frame_index)?;
    pack_rgb_frame_texture(
        &rgb,
        metadata.cols as u32,
        metadata.rows as u32,
        target_max_dim,
        compression,
    )
}

/// One already-decoded RGB8 frame, as input to `pack_rgb_frame_stack_texture` - the color analog
/// of `DecodedFrame`.
#[derive(Clone, Debug)]
pub struct DecodedRgbFrame {
    pub bytes: Vec<u8>,
    pub width: u32,
    pub height: u32,
}

/// Packs `frames` as one RGB8 texture array - the color counterpart to `pack_frame_stack_texture`.
/// Same "no resampling, caller rejects an oversized stack before calling this" contract (see that
/// function's own doc) and the same `FrameDimensionMismatch` check.
pub fn pack_rgb_frame_stack_texture(
    frames: &[DecodedRgbFrame],
    compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
    let Some(first) = frames.first() else {
        return Err(TextureExportError::InvalidDimensions);
    };
    let (width, height) = (first.width, first.height);
    if width == 0 || height == 0 {
        return Err(TextureExportError::InvalidDimensions);
    }
    let expected_per_frame = width as usize * height as usize * 3;

    let mut concatenated = Vec::with_capacity(expected_per_frame * frames.len());
    for frame in frames {
        if frame.width != width || frame.height != height {
            return Err(TextureExportError::FrameDimensionMismatch {
                expected: (width, height),
                found: (frame.width, frame.height),
            });
        }
        if frame.bytes.len() != expected_per_frame {
            return Err(TextureExportError::SampleCountMismatch {
                expected: expected_per_frame,
                found: frame.bytes.len(),
            });
        }
        concatenated.extend_from_slice(&frame.bytes);
    }

    let depth = frames.len() as u32;
    let native_dims = (width, height, depth);
    let (payload, payload_bytes_raw) = apply_compression(concatenated, compression)?;
    let payload_bytes_stored = payload.len() as u64;

    let meta = TextureMeta {
        content_kind: ContentKind::FrameStack,
        sample_format: SampleFormat::Rgb8,
        compression,
        lossless: true,
        width,
        height,
        depth,
        rescale_slope: 1.0,
        rescale_intercept: 0.0,
        row_spacing_mm: 1.0,
        col_spacing_mm: 1.0,
        slice_spacing_mm: 0.0,
        origin: [0.0, 0.0, 0.0],
        row_dir: [1.0, 0.0, 0.0],
        col_dir: [0.0, 1.0, 0.0],
        normal_dir: [0.0, 0.0, 1.0],
        default_window_center: None,
        default_window_width: None,
        invert: false,
        layer_default_windows: Vec::new(),
        layer_invert: Vec::new(),
        native_dims,
        downsampled: false,
        payload_bytes_raw,
        payload_bytes_stored,
    };

    Ok(PackedTexture { meta, payload })
}

/// Convenience wrapper mirroring `pack_dicom_frame_stack_texture`: decodes `(object, frame_index)`
/// for each entry of `sources` to RGB8 and packs the result as a frame stack.
pub fn pack_dicom_rgb_frame_stack_texture(
    sources: &[(&dcmnorm_object::DefaultDicomObject, usize)],
    compression: TextureCompression,
) -> Result<PackedTexture, TextureExportError> {
    let mut decoded = Vec::with_capacity(sources.len());
    for (object, frame_index) in sources.iter() {
        let (metadata, bytes) = decode_frame_texture_rgb_values(object, *frame_index)?;
        decoded.push(DecodedRgbFrame {
            bytes,
            width: metadata.cols as u32,
            height: metadata.rows as u32,
        });
    }
    pack_rgb_frame_stack_texture(&decoded, compression)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dicom_io::volume::Volume;

    fn axis_aligned_test_volume(cols: u32, rows: u32, num_slices: u32) -> Volume {
        let plane = (rows * cols) as usize;
        let mut samples = vec![0f32; plane * num_slices as usize];
        for (index, sample) in samples.iter_mut().enumerate() {
            *sample = index as f32 - 1024.0; // exercises negative HU-like values too
        }
        Volume {
            samples,
            rows,
            cols,
            num_slices,
            origin: [10.0, -20.0, 30.0],
            row_vector: [1.0, 0.0, 0.0],
            col_vector: [0.0, 1.0, 0.0],
            slice_normal: [0.0, 0.0, 1.0],
            col_spacing_mm: 0.5,
            row_spacing_mm: 0.6,
            slice_zs: (0..num_slices).map(|index| index as f64 * 2.0).collect(),
            modality: None,
            frame_of_reference_uid: None,
            series_instance_uid: None,
            study_instance_uid: None,
            gantry_tilt_deg: 0.0,
            desheared: false,
        }
    }

    #[test]
    fn quantize_samples_of_integer_values_is_exact_and_lossless() {
        let raw = vec![-1024.0f32, 0.0, 1500.0, 3071.0];
        let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
        assert_eq!(format, SampleFormat::Int16);
        assert_eq!(slope, 1.0);
        assert_eq!(intercept, 0.0);
        assert!(lossless);
        assert_eq!(bytes.len(), raw.len() * 2);
        for (index, &expected) in raw.iter().enumerate() {
            let value = i16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
            assert_eq!(value as f32, expected);
        }
    }

    #[test]
    fn quantize_samples_of_fractional_values_falls_back_to_bounded_error_uint16() {
        let raw = vec![0.0f32, 0.25, 0.5, 1.0];
        let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
        assert_eq!(format, SampleFormat::Uint16);
        assert!(!lossless);
        assert_eq!(bytes.len(), raw.len() * 2);
        for (index, &expected) in raw.iter().enumerate() {
            let quantized = u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
            let reconstructed = quantized as f64 * slope + intercept;
            assert!((reconstructed - expected as f64).abs() <= 0.5 * slope + 1e-9);
        }
    }

    #[test]
    fn quantize_samples_of_unsigned_16_bit_integer_values_is_exact_uint16() {
        // 16-bit unsigned DX/MG/CR: above i16::MAX, stored as they are.
        let raw = vec![1000.0f32, 28876.0, 56990.0, 65535.0];
        let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
        assert_eq!(format, SampleFormat::Uint16);
        assert_eq!(slope, 1.0);
        assert_eq!(intercept, 0.0);
        assert!(lossless);
        for (index, &expected) in raw.iter().enumerate() {
            let stored = u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
            assert_eq!(stored as f64 * slope + intercept, expected as f64);
        }
    }

    #[test]
    fn quantize_samples_of_unsigned_12_bit_values_is_uint16_not_int16() {
        // 12-bit MG/DBT fits i16 too, but uint16 needs no rebias on the client.
        let raw = vec![0.0f32, 1.0, 2048.0, 4095.0];
        let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
        assert_eq!(format, SampleFormat::Uint16);
        assert_eq!((slope, intercept, lossless), (1.0, 0.0, true));
        for (index, &expected) in raw.iter().enumerate() {
            assert_eq!(
                u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap()) as f32,
                expected
            );
        }
    }

    #[test]
    fn quantize_samples_of_signed_values_wider_than_i16_is_exact_offset_uint16() {
        // Negative, so not plain uint16; above i16::MAX, so not int16; the span fits uint16.
        let raw = vec![-1000.0f32, 0.0, 40000.0, 64535.0];
        let (bytes, format, slope, intercept, lossless) = quantize_samples(&raw);
        assert_eq!(format, SampleFormat::Uint16);
        assert_eq!(slope, 1.0);
        assert_eq!(intercept, -1000.0);
        assert!(lossless);
        for (index, &expected) in raw.iter().enumerate() {
            let stored = u16::from_le_bytes(bytes[index * 2..index * 2 + 2].try_into().unwrap());
            assert_eq!(stored as f64 * slope + intercept, expected as f64);
        }
    }

    #[test]
    fn quantize_samples_of_out_of_i16_range_values_falls_back_to_bounded_error_uint16() {
        // Integer, but the span (80000) is wider than uint16 can hold exactly.
        let raw = vec![-40000.0f32, 0.0, 40000.0];
        let (_, format, _, _, lossless) = quantize_samples(&raw);
        assert_eq!(format, SampleFormat::Uint16);
        assert!(!lossless);
    }

    #[test]
    fn pack_volume_texture_without_downsampling_round_trips_exactly() {
        let volume = axis_aligned_test_volume(4, 4, 4);
        let packed = pack_volume_texture(&volume, None, None, TextureCompression::None).unwrap();
        assert!(packed.meta.lossless);
        assert!(!packed.meta.downsampled);
        assert_eq!(
            (packed.meta.width, packed.meta.height, packed.meta.depth),
            (4, 4, 4)
        );
        assert_eq!(packed.meta.native_dims, (4, 4, 4));
        assert_eq!(packed.payload.len(), volume.samples.len() * 2);

        for (index, &expected) in volume.samples.iter().enumerate() {
            let value =
                i16::from_le_bytes(packed.payload[index * 2..index * 2 + 2].try_into().unwrap());
            assert_eq!(value as f32, expected);
        }
    }

    #[test]
    fn pack_volume_texture_downsamples_to_fit_target_max_dim() {
        let volume = axis_aligned_test_volume(8, 8, 8);
        let packed = pack_volume_texture(&volume, Some(4), None, TextureCompression::None).unwrap();
        assert!(packed.meta.downsampled);
        assert!(packed.meta.width <= 4 && packed.meta.height <= 4 && packed.meta.depth <= 4);
        assert_eq!(packed.meta.native_dims, (8, 8, 8));
        // Spacing must widen proportionally so physical extent is preserved.
        assert!(packed.meta.col_spacing_mm > volume.col_spacing_mm);
        assert!(packed.meta.row_spacing_mm > volume.row_spacing_mm);
    }

    #[test]
    fn pack_volume_texture_below_target_max_dim_is_a_no_op() {
        let volume = axis_aligned_test_volume(4, 4, 4);
        let packed =
            pack_volume_texture(&volume, Some(64), None, TextureCompression::None).unwrap();
        assert!(!packed.meta.downsampled);
        assert_eq!(
            (packed.meta.width, packed.meta.height, packed.meta.depth),
            (4, 4, 4)
        );
    }

    #[test]
    fn pack_volume_texture_gzip_round_trips_to_the_uncompressed_payload() {
        let volume = axis_aligned_test_volume(4, 4, 4);
        let plain = pack_volume_texture(&volume, None, None, TextureCompression::None).unwrap();
        let gzipped = pack_volume_texture(&volume, None, None, TextureCompression::Gzip).unwrap();

        assert_eq!(gzipped.meta.payload_bytes_raw, plain.payload.len() as u64);
        assert_eq!(
            gzipped.meta.payload_bytes_stored,
            gzipped.payload.len() as u64
        );

        let mut decoder = flate2::read::GzDecoder::new(&gzipped.payload[..]);
        let mut decompressed = Vec::new();
        std::io::Read::read_to_end(&mut decoder, &mut decompressed).unwrap();
        assert_eq!(decompressed, plain.payload);
    }

    #[test]
    fn pack_volume_texture_carries_default_window_through_to_meta() {
        let volume = axis_aligned_test_volume(2, 2, 2);
        let packed =
            pack_volume_texture(&volume, None, Some((40.0, 400.0)), TextureCompression::None)
                .unwrap();
        assert_eq!(packed.meta.default_window_center, Some(40.0));
        assert_eq!(packed.meta.default_window_width, Some(400.0));
    }

    #[test]
    fn resample_frame_2d_is_a_no_op_when_already_within_target() {
        let values: Vec<f32> = (0..16).map(|value| value as f32).collect();
        let (out, w, h) = resample_frame_2d(&values, 4, 4, 8);
        assert_eq!((w, h), (4, 4));
        assert_eq!(out, values);
    }

    #[test]
    fn resample_frame_2d_downsamples_a_linear_ramp_correctly() {
        // 8x8, values = col only (a ramp 0..7 repeated in every row) - halving to 4x4 should
        // sample columns 0,2.333,4.666,7 (bilinear on an exact linear ramp reproduces the ramp
        // value at any fractional position).
        let width = 8u32;
        let height = 8u32;
        let mut values = vec![0f32; (width * height) as usize];
        for row in 0..height {
            for col in 0..width {
                values[(row * width + col) as usize] = col as f32;
            }
        }
        let (out, out_w, out_h) = resample_frame_2d(&values, width, height, 4);
        assert_eq!((out_w, out_h), (4, 4));
        let expected_cols = [0.0f32, 7.0 / 3.0, 14.0 / 3.0, 7.0];
        for row in 0..out_h {
            for col in 0..out_w {
                let value = out[(row * out_w + col) as usize];
                assert!(
                    (value - expected_cols[col as usize]).abs() < 1e-4,
                    "row={row} col={col} value={value} expected={}",
                    expected_cols[col as usize]
                );
            }
        }
    }

    #[test]
    fn pack_frame_texture_rejects_a_sample_count_mismatch() {
        let error =
            pack_frame_texture(&[0.0; 3], 2, 2, None, None, TextureCompression::None, false)
                .unwrap_err();
        assert!(matches!(
            error,
            TextureExportError::SampleCountMismatch {
                expected: 4,
                found: 3
            }
        ));
    }

    #[test]
    fn pack_frame_texture_downsamples_and_round_trips_within_tolerance() {
        let width = 8u32;
        let height = 8u32;
        let values: Vec<f32> = (0..width * height).map(|index| index as f32).collect();
        let packed = pack_frame_texture(
            &values,
            width,
            height,
            None,
            Some(4),
            TextureCompression::None,
            false,
        )
        .unwrap();
        assert!(packed.meta.downsampled);
        assert_eq!(packed.meta.depth, 1);
        assert_eq!(packed.meta.native_dims, (8, 8, 1));
        assert!(packed.meta.width <= 4 && packed.meta.height <= 4);
    }

    #[test]
    fn pack_frame_texture_without_a_default_window_falls_back_to_min_max_span() {
        // Values 0..15 (min=0, max=15) with no caller-supplied window - must NOT leave
        // default_window_center/width as None (the GPU shader's own hardcoded center=0/width=1
        // fallback would clip nearly everything to white for real, non-zero-centered pixel data).
        let width = 4u32;
        let height = 4u32;
        let values: Vec<f32> = (0..width * height).map(|index| index as f32).collect();
        let packed = pack_frame_texture(
            &values,
            width,
            height,
            None,
            None,
            TextureCompression::None,
            true,
        )
        .unwrap();
        assert_eq!(packed.meta.default_window_center, Some(7.5));
        assert_eq!(packed.meta.default_window_width, Some(15.0));
    }

    #[test]
    fn pack_volume_texture_without_a_default_window_falls_back_to_min_max_span() {
        let volume = axis_aligned_test_volume(2, 2, 2);
        let packed = pack_volume_texture(&volume, None, None, TextureCompression::None).unwrap();
        // axis_aligned_test_volume fills samples as `index - 1024.0` over 2*2*2=8 voxels (indices
        // 0..7), so min=-1024.0, max=-1017.0.
        assert_eq!(
            packed.meta.default_window_center,
            Some((-1024.0 + -1017.0) / 2.0)
        );
        assert_eq!(packed.meta.default_window_width, Some(7.0));
    }

    #[test]
    fn texture_meta_to_json_round_trips_expected_fields() {
        let volume = axis_aligned_test_volume(2, 2, 2);
        let packed =
            pack_volume_texture(&volume, None, Some((40.0, 400.0)), TextureCompression::Gzip)
                .unwrap();
        let json = packed.meta.to_json();
        assert_eq!(json["formatVersion"], 1);
        assert_eq!(json["contentKind"], "volume");
        assert_eq!(json["compression"], "gzip");
        assert_eq!(json["width"], 2);
        assert_eq!(json["defaultWindowCenter"], 40.0);
        assert_eq!(json["defaultWindowWidth"], 400.0);
        assert_eq!(json["nativeDims"], serde_json::json!([2, 2, 2]));
    }

    fn ramp_frame(width: u32, height: u32, base: f32) -> DecodedFrame {
        let values = (0..width * height)
            .map(|index| base + index as f32)
            .collect();
        DecodedFrame {
            values,
            width,
            height,
        }
    }

    #[test]
    fn pack_frame_stack_texture_concatenates_layers_in_source_order() {
        let frames = vec![
            ramp_frame(2, 2, 0.0),
            ramp_frame(2, 2, 100.0),
            ramp_frame(2, 2, 200.0),
        ];
        let packed =
            pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
        assert_eq!(packed.meta.content_kind, ContentKind::FrameStack);
        assert_eq!(
            (packed.meta.width, packed.meta.height, packed.meta.depth),
            (2, 2, 3)
        );
        assert_eq!(packed.meta.native_dims, (2, 2, 3));
        assert!(!packed.meta.downsampled);
        // Each layer is exactly 2*2=4 int16 samples (values are all integral here, so this is the
        // exact/lossless quantize_samples path) - verify layer 1 (base=100) lands at the expected
        // byte offset, not interleaved or reordered relative to layer 0/2.
        assert!(packed.meta.lossless);
        let layer1_offset = 1 * 4 * 2; // layer index * samples-per-layer * bytes-per-sample
        let value = i16::from_le_bytes(
            packed.payload[layer1_offset..layer1_offset + 2]
                .try_into()
                .unwrap(),
        );
        assert_eq!(value, 100);
    }

    #[test]
    fn pack_frame_stack_texture_never_carries_physical_geometry() {
        let frames = vec![ramp_frame(2, 2, 0.0), ramp_frame(2, 2, 1.0)];
        let packed =
            pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
        assert_eq!(packed.meta.origin, [0.0, 0.0, 0.0]);
        assert_eq!(packed.meta.slice_spacing_mm, 0.0);
        assert_eq!(packed.meta.row_dir, [1.0, 0.0, 0.0]);
        assert_eq!(packed.meta.col_dir, [0.0, 1.0, 0.0]);
    }

    #[test]
    fn pack_frame_stack_texture_rejects_mismatched_frame_dimensions() {
        let frames = vec![ramp_frame(2, 2, 0.0), ramp_frame(3, 2, 0.0)];
        let error =
            pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap_err();
        assert!(matches!(
            error,
            TextureExportError::FrameDimensionMismatch {
                expected: (2, 2),
                found: (3, 2)
            }
        ));
    }

    #[test]
    fn pack_frame_stack_texture_rejects_an_empty_stack() {
        let error =
            pack_frame_stack_texture(&[], None, TextureCompression::None, false).unwrap_err();
        assert!(matches!(error, TextureExportError::InvalidDimensions));
    }

    #[test]
    fn pack_frame_stack_texture_never_downsamples_even_when_large() {
        // No target_max_dim parameter exists at all for this function (see its own doc) - a
        // frame larger than any volume/image2d target_max_dim ceiling used elsewhere in this
        // module must still come out at native resolution, unlike pack_volume_texture/
        // pack_frame_texture which would shrink it.
        let frames = vec![ramp_frame(16, 16, 0.0)];
        let packed =
            pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
        assert_eq!((packed.meta.width, packed.meta.height), (16, 16));
        assert!(!packed.meta.downsampled);
    }

    #[test]
    fn pack_frame_stack_texture_default_window_spans_the_whole_stack_not_just_one_layer() {
        // base offsets 0/100/200 over a 2x2 ramp (values 0..3, 100..103, 200..203) - the fallback
        // min/max window must reflect the FULL concatenated range (0..203), not get reset/
        // overwritten by whichever layer happens to be processed last.
        let frames = vec![
            ramp_frame(2, 2, 0.0),
            ramp_frame(2, 2, 100.0),
            ramp_frame(2, 2, 200.0),
        ];
        let packed =
            pack_frame_stack_texture(&frames, None, TextureCompression::None, false).unwrap();
        assert_eq!(packed.meta.default_window_center, Some((0.0 + 203.0) / 2.0));
        assert_eq!(packed.meta.default_window_width, Some(203.0));
    }

    fn fixture(name: &str) -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("test/files")
            .join(name)
    }

    fn rgb_ramp(width: u32, height: u32, base: u8) -> DecodedRgbFrame {
        let bytes = (0..width * height * 3)
            .map(|index| base.wrapping_add((index % 251) as u8))
            .collect();
        DecodedRgbFrame {
            bytes,
            width,
            height,
        }
    }

    #[test]
    fn pack_rgb_frame_texture_is_unconditionally_lossless_and_rgb8() {
        let rgb = vec![10u8, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; // 2x2 RGB8
        let packed = pack_rgb_frame_texture(&rgb, 2, 2, None, TextureCompression::None).unwrap();
        assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
        assert!(packed.meta.lossless);
        assert_eq!(
            (packed.meta.width, packed.meta.height, packed.meta.depth),
            (2, 2, 1)
        );
        assert_eq!(packed.payload, rgb);
        assert_eq!(
            packed.meta.default_window_center, None,
            "color has no window/level concept"
        );
        assert!(
            !packed.meta.invert,
            "color has no MONOCHROME1 invert concept"
        );
    }

    #[test]
    fn pack_rgb_frame_texture_rejects_wrong_byte_count() {
        let error =
            pack_rgb_frame_texture(&[1, 2, 3], 2, 2, None, TextureCompression::None).unwrap_err();
        assert!(matches!(
            error,
            TextureExportError::SampleCountMismatch {
                expected: 12,
                found: 3
            }
        ));
    }

    #[test]
    fn pack_rgb_frame_texture_rejects_zero_dimensions() {
        let error = pack_rgb_frame_texture(&[], 0, 4, None, TextureCompression::None).unwrap_err();
        assert!(matches!(error, TextureExportError::InvalidDimensions));
    }

    #[test]
    fn pack_rgb_frame_texture_downsamples_when_over_target_max_dim() {
        let rgb = vec![128u8; 16 * 16 * 3];
        let packed =
            pack_rgb_frame_texture(&rgb, 16, 16, Some(8), TextureCompression::None).unwrap();
        assert!(packed.meta.downsampled);
        assert_eq!((packed.meta.width, packed.meta.height), (8, 8));
        assert_eq!(packed.meta.native_dims, (16, 16, 1));
        assert_eq!(packed.payload.len(), 8 * 8 * 3);
    }

    #[test]
    fn pack_rgb_frame_stack_texture_concatenates_layers_in_source_order() {
        let frames = vec![rgb_ramp(2, 2, 0), rgb_ramp(2, 2, 100), rgb_ramp(2, 2, 200)];
        let packed = pack_rgb_frame_stack_texture(&frames, TextureCompression::None).unwrap();
        assert_eq!(packed.meta.content_kind, ContentKind::FrameStack);
        assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
        assert_eq!(
            (packed.meta.width, packed.meta.height, packed.meta.depth),
            (2, 2, 3)
        );
        assert!(packed.meta.lossless);
        let bytes_per_layer = 2 * 2 * 3;
        assert_eq!(&packed.payload[0..bytes_per_layer], &frames[0].bytes[..]);
        assert_eq!(
            &packed.payload[bytes_per_layer..bytes_per_layer * 2],
            &frames[1].bytes[..]
        );
    }

    #[test]
    fn pack_rgb_frame_stack_texture_rejects_mismatched_frame_dimensions() {
        let frames = vec![rgb_ramp(2, 2, 0), rgb_ramp(3, 2, 0)];
        let error = pack_rgb_frame_stack_texture(&frames, TextureCompression::None).unwrap_err();
        assert!(matches!(
            error,
            TextureExportError::FrameDimensionMismatch {
                expected: (2, 2),
                found: (3, 2)
            }
        ));
    }

    #[test]
    fn pack_rgb_frame_stack_texture_rejects_an_empty_stack() {
        let error = pack_rgb_frame_stack_texture(&[], TextureCompression::None).unwrap_err();
        assert!(matches!(error, TextureExportError::InvalidDimensions));
    }

    #[test]
    fn pack_dicom_rgb_frame_texture_packs_a_real_uncompressed_rgb_fixture() {
        let object = crate::dicom_io::read_dicom_file(fixture("rgb_interleaved.dcm"))
            .expect("fixture should be readable");
        let packed =
            pack_dicom_rgb_frame_texture(&object, 0, None, TextureCompression::None).unwrap();
        assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
        assert!(packed.meta.lossless);
        assert_eq!(
            packed.payload.len(),
            packed.meta.width as usize * packed.meta.height as usize * 3
        );
    }

    #[test]
    fn pack_dicom_rgb_frame_stack_texture_packs_two_real_instances() {
        let planar = crate::dicom_io::read_dicom_file(fixture("rgb_planar.dcm"))
            .expect("fixture should be readable");
        let interleaved = crate::dicom_io::read_dicom_file(fixture("rgb_interleaved.dcm"))
            .expect("fixture should be readable");
        // Same real instance re-encoded two ways (see render.rs's own
        // planar_and_interleaved_rgb_render_to_identical_png_bytes test) - same dimensions, so a
        // legitimate (if synthetic) 2-frame stack.
        let sources: Vec<(&dcmnorm_object::DefaultDicomObject, usize)> =
            vec![(&planar, 0), (&interleaved, 0)];
        let packed =
            pack_dicom_rgb_frame_stack_texture(&sources, TextureCompression::None).unwrap();
        assert_eq!(packed.meta.depth, 2);
        assert_eq!(packed.meta.sample_format, SampleFormat::Rgb8);
    }
}