rust-j2k 0.3.0

Pure-Rust JPEG 2000 (ISO/IEC 15444) codec, built GRIB2-decode-first toward OpenJPEG-level coverage.
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
//! The three EBCOT coding passes and their context formation
//! (ISO/IEC 15444-1 Annex D).
//!
//! A code-block is decoded bit-plane by bit-plane, MSB→LSB. Each plane runs, in
//! order, the passes that apply: significance propagation (D.3.1), magnitude
//! refinement (D.3.2), and cleanup (D.3.3) with its run-length mode. Contexts
//! come from the significance state of the 3×3 neighbourhood (D.3.* tables),
//! and sign coding uses the neighbour-sign context (D.3.4). The cleanup pass
//! of the top plane runs first.
//!
//! The optional code-block style flags act at three points. `segmentation
//! symbols` appends a four-symbol marker to every cleanup pass (D.5).
//! `vertically causal context` narrows the significance context so a stripe's
//! bottom row ignores the row below it, and `reset context probabilities`
//! reinitialises the MQ context model after every pass — both change which
//! context a decision is coded under, threaded through [`BlockState`] and
//! [`decode_block`]. `restart` and `predictable termination` modulate
//! termination. `bypass` (lazy) codes the significance and refinement passes of
//! the low bit-planes as raw bits rather than MQ decisions (D.5); the raw reader
//! and the per-segment coder choice live in [`decode_block`].

use crate::tier1::mq::{Context, MqDecoder, RawDecoder};
use crate::{Error, Result};

#[cfg(test)]
#[path = "golden_vectors.rs"]
mod golden_vectors;

/// MQ context indices, laid out as ISO/IEC 15444-1 Table D-7 allocates them and
/// OpenJPEG's `T1_CTXNO_*` constants order them. A code-block's decoder owns one
/// [`Context`](crate::tier1::mq::Context) per index (`NUM_CONTEXTS` total); the
/// context-formation routines below return an index into that array.
///
/// - `0..=8`   zero coding (the nine significance contexts, [`zc_context`](BlockState::zc_context))
/// - `9..=13`  sign coding ([`sc_context`](BlockState::sc_context))
/// - `14..=16` magnitude refinement ([`mr_context`](BlockState::mr_context))
/// - `17`      run-length (the cleanup pass's aggregation context)
/// - `18`      uniform (equiprobable; raw bits in the cleanup run mode)
pub const CTX_ZC: u8 = 0;
pub const CTX_SC: u8 = 9;
pub const CTX_MR: u8 = 14;
pub const CTX_RUN: u8 = 17;
pub const CTX_UNI: u8 = 18;
/// Number of MQ contexts a code-block tracks (ISO Table D-7).
pub const NUM_CONTEXTS: usize = 19;

/// Largest coded bit-plane the double-scale reconstruction can hold: decoding
/// carries each magnitude at twice its weight (the mid-point half), so the top
/// plane's `1 << top` and the accumulated value must stay inside `i32`. At
/// `top == 30` the maximum magnitude `2^31 − 1` just fits; `top == 31` overflows
/// (this mirrors OpenJPEG rejecting `bpno_plus_one >= 31`). Callers reject any
/// subband whose `Mb − zero_bit_planes` exceeds this.
pub const MAX_BIT_PLANES: u32 = 30;

/// Subband orientation, which selects the zero-coding context table (D.3.1).
/// Per Table D-1, `LL` and `LH` share one table, `HL` swaps the horizontal and
/// vertical neighbour roles, and `HH` keys off the diagonal count instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
    Ll,
    Lh,
    Hl,
    Hh,
}

/// A code-block's decode state: the coefficient magnitudes plus the per-sample
/// flag planes the passes consult and update. Each flag vector is parallel to
/// `coeffs` (row-major, `width × height`).
#[derive(Debug)]
pub struct BlockState {
    pub width: u32,
    pub height: u32,
    pub coeffs: Vec<i32>,
    /// σ: the coefficient has become significant (a 1 bit has been coded).
    significant: Vec<bool>,
    /// The coefficient was coded in the current bit-plane's significance
    /// propagation pass, so the cleanup pass skips it.
    visited: Vec<bool>,
    /// Sign bit: `true` is negative. Meaningful only once significant.
    negative: Vec<bool>,
    /// The coefficient has been through at least one magnitude-refinement pass,
    /// which selects magnitude-refinement context 16 over 14/15 (D.3.2).
    refined: Vec<bool>,
    /// Vertically causal context (the `VCAUSAL` style): the context of a sample
    /// on a stripe's bottom row (`y % 4 == 3`) excludes the row below it, which
    /// belongs to the next stripe. `false` for the default style, where the full
    /// 3×3 neighbourhood is used. Set by [`decode_block`] from the style byte.
    vcausal: bool,
}

impl BlockState {
    pub fn new(width: u32, height: u32) -> Self {
        let n = (width * height) as usize;
        BlockState {
            width,
            height,
            coeffs: vec![0; n],
            significant: vec![false; n],
            visited: vec![false; n],
            negative: vec![false; n],
            refined: vec![false; n],
            vcausal: false,
        }
    }

    /// Flat row-major index of an in-bounds coefficient.
    fn idx(&self, x: u32, y: u32) -> usize {
        (y * self.width + x) as usize
    }

    /// Whether `(x, y)` lies inside the block.
    fn in_bounds(&self, x: i64, y: i64) -> bool {
        x >= 0 && y >= 0 && x < self.width as i64 && y < self.height as i64
    }

    /// Significance at a possibly out-of-range position; positions outside the
    /// block read as insignificant, which clamps the 3×3 neighbourhood at the
    /// block edges (D.3: out-of-block samples contribute 0).
    fn sig_at(&self, x: i64, y: i64) -> bool {
        self.in_bounds(x, y) && self.significant[self.idx(x as u32, y as u32)]
    }

    /// A single neighbour's signed contribution to the sign context (Table D-2):
    /// `0` if insignificant, `+1` if significant and positive, `-1` if negative.
    fn contrib_at(&self, x: i64, y: i64) -> i32 {
        if !self.sig_at(x, y) {
            0
        } else if self.negative[self.idx(x as u32, y as u32)] {
            -1
        } else {
            1
        }
    }

    pub fn is_significant(&self, x: u32, y: u32) -> bool {
        self.significant[self.idx(x, y)]
    }

    pub fn set_significant(&mut self, x: u32, y: u32) {
        let i = self.idx(x, y);
        self.significant[i] = true;
    }

    pub fn is_visited(&self, x: u32, y: u32) -> bool {
        self.visited[self.idx(x, y)]
    }

    pub fn set_visited(&mut self, x: u32, y: u32, value: bool) {
        let i = self.idx(x, y);
        self.visited[i] = value;
    }

    /// Set a coefficient's magnitude when it first becomes significant at plane
    /// `bpno`, to the mid-point reconstruction value `2^bpno + 2^(bpno−1)`
    /// (ISO E.1.1.2 / OpenJPEG `oneplushalf`): the significant bit plus half the
    /// next plane's weight, placing it at the centre of its interval.
    fn set_significant_magnitude(&mut self, x: u32, y: u32, bpno: u32) {
        let one = 1i32 << bpno;
        let i = self.idx(x, y);
        self.coeffs[i] = one | (one >> 1);
    }

    /// Refine a significant coefficient's magnitude at plane `bpno`: a `1` bit
    /// pushes it up by half the plane weight, a `0` bit down (OpenJPEG `poshalf`,
    /// the running mid-point update). Decoding runs at double scale and stops at
    /// `bpno == 1`, so `poshalf` is always ≥ 1; the carried half is dropped by
    /// the final halving in [`decode_block`].
    fn refine_magnitude(&mut self, x: u32, y: u32, bpno: u32, bit: u8) {
        let poshalf = (1i32 << bpno) >> 1;
        let i = self.idx(x, y);
        self.coeffs[i] += if bit == 1 { poshalf } else { -poshalf };
    }

    /// Clear every per-sample `visited` flag. The flag marks samples coded in
    /// the current bit-plane's significance-propagation pass; it is local to one
    /// plane, so the cleanup pass clears it before the next plane begins.
    fn clear_visited(&mut self) {
        self.visited.iter_mut().for_each(|v| *v = false);
    }

    pub fn is_negative(&self, x: u32, y: u32) -> bool {
        self.negative[self.idx(x, y)]
    }

    pub fn set_negative(&mut self, x: u32, y: u32, value: bool) {
        let i = self.idx(x, y);
        self.negative[i] = value;
    }

    pub fn is_refined(&self, x: u32, y: u32) -> bool {
        self.refined[self.idx(x, y)]
    }

    pub fn set_refined(&mut self, x: u32, y: u32) {
        let i = self.idx(x, y);
        self.refined[i] = true;
    }

    /// Whether the row below `(·, y)` lies in the next stripe and so is excluded
    /// from the context under vertically causal coding: it is the stripe's bottom
    /// row (`y % 4 == 3`) and the flag is set. Off, or on an interior row, the
    /// full neighbourhood is used (D.3).
    fn excludes_south(&self, y: u32) -> bool {
        self.vcausal && y % 4 == 3
    }

    /// (ΣH, ΣV, ΣD): the significance sums of the two horizontal, two vertical,
    /// and four diagonal neighbours of `(x, y)` — the inputs to every D.3 table.
    /// Under vertically causal coding the south neighbours of a stripe's bottom
    /// row read as insignificant.
    fn neighbour_sums(&self, x: u32, y: u32) -> (u8, u8, u8) {
        let south = !self.excludes_south(y);
        let (x, y) = (x as i64, y as i64);
        let sig_south = |dx: i64| (south && self.sig_at(x + dx, y + 1)) as u8;
        let h = self.sig_at(x - 1, y) as u8 + self.sig_at(x + 1, y) as u8;
        let v = self.sig_at(x, y - 1) as u8 + sig_south(0);
        let d = self.sig_at(x - 1, y - 1) as u8
            + self.sig_at(x + 1, y - 1) as u8
            + sig_south(-1)
            + sig_south(1);
        (h, v, d)
    }

    /// Zero-coding context label (`CTX_ZC..CTX_SC`) for `(x, y)` in a subband of
    /// the given orientation (ISO Table D-1). `LL`/`LH` use the base assignment,
    /// `HL` swaps the horizontal and vertical sums, and `HH` keys off the
    /// diagonal count.
    pub fn zc_context(&self, x: u32, y: u32, orient: Orientation) -> u8 {
        let (h, v, d) = self.neighbour_sums(x, y);
        let label = match orient {
            Orientation::Ll | Orientation::Lh => zc_label_lh(h, v, d),
            Orientation::Hl => zc_label_lh(v, h, d),
            Orientation::Hh => zc_label_hh(h + v, d),
        };
        CTX_ZC + label
    }

    /// Sign-coding context (`CTX_SC..CTX_MR`) and the XOR bit (ISO Tables D-2,
    /// D-3). The MQ decision is XORed with the returned bit to recover the sign
    /// (`0` positive, `1` negative).
    pub fn sc_context(&self, x: u32, y: u32) -> (u8, u8) {
        let south_contrib = if self.excludes_south(y) {
            0
        } else {
            self.contrib_at(x as i64, y as i64 + 1)
        };
        let (x, y) = (x as i64, y as i64);
        let h = (self.contrib_at(x - 1, y) + self.contrib_at(x + 1, y)).clamp(-1, 1);
        let v = (self.contrib_at(x, y - 1) + south_contrib).clamp(-1, 1);
        let (label, xor) = match (h, v) {
            (1, 1) => (4, 0),
            (1, 0) => (3, 0),
            (1, -1) => (2, 0),
            (0, 1) => (1, 0),
            (0, 0) => (0, 0),
            (0, -1) => (1, 1),
            (-1, 1) => (2, 1),
            (-1, 0) => (3, 1),
            (-1, -1) => (4, 1),
            _ => unreachable!("clamped contributions are in -1..=1"),
        };
        (CTX_SC + label, xor)
    }

    /// Magnitude-refinement context (`CTX_MR..CTX_RUN`) for `(x, y)` (ISO
    /// Table D-4 / D.3.2). After the first refinement the context is always 16;
    /// on the first refinement it is 15 if any neighbour is significant, else 14.
    pub fn mr_context(&self, x: u32, y: u32) -> u8 {
        if self.is_refined(x, y) {
            CTX_MR + 2
        } else {
            let (h, v, d) = self.neighbour_sums(x, y);
            let label = if h + v + d > 0 { 1 } else { 0 };
            CTX_MR + label
        }
    }
}

/// Zero-coding label for the `LL`/`LH` table (ISO Table D-1). `HL` reuses this
/// with `h` and `v` exchanged by the caller.
fn zc_label_lh(h: u8, v: u8, d: u8) -> u8 {
    match (h, v, d) {
        (2, _, _) => 8,
        (1, v, _) if v >= 1 => 7,
        (1, 0, d) if d >= 1 => 6,
        (1, 0, 0) => 5,
        (0, 2, _) => 4,
        (0, 1, _) => 3,
        (0, 0, d) if d >= 2 => 2,
        (0, 0, 1) => 1,
        _ => 0,
    }
}

/// Zero-coding label for the `HH` table (ISO Table D-1), keyed by the diagonal
/// count `d` and the combined horizontal+vertical count `hv`.
fn zc_label_hh(hv: u8, d: u8) -> u8 {
    match (d, hv) {
        (d, _) if d >= 3 => 8,
        (2, hv) if hv >= 1 => 7,
        (2, _) => 6,
        (1, hv) if hv >= 2 => 5,
        (1, 1) => 4,
        (1, _) => 3,
        (0, hv) if hv >= 2 => 2,
        (0, 1) => 1,
        _ => 0,
    }
}

/// Initial MQ states for a fresh code-block (ISO Table D-7 / Annex D.3): the
/// uniform context starts at state 46, the run-length context at 3, and the
/// all-insignificant zero-coding context at 4; every other context at 0. Using
/// the default zero state for these three would desynchronize the decoder.
pub(crate) fn init_contexts() -> [Context; NUM_CONTEXTS] {
    let mut cx = [Context::default(); NUM_CONTEXTS];
    cx[CTX_ZC as usize].index = 4;
    cx[CTX_RUN as usize].index = 3;
    cx[CTX_UNI as usize].index = 46;
    cx
}

/// Decode the sign of a coefficient that has just become significant (D.3.4):
/// the MQ decision under the neighbour-sign context is XORed with the context's
/// predicted sign. Records the sign in `state` (`true` = negative).
fn decode_sign(mq: &mut MqDecoder<'_>, state: &mut BlockState, cx: &mut [Context], x: u32, y: u32) {
    let (ctx, xor) = state.sc_context(x, y);
    let bit = mq.decode(&mut cx[ctx as usize]);
    state.set_negative(x, y, bit ^ xor == 1);
}

/// Iterate a code-block in EBCOT scan order: stripes of four rows top to bottom,
/// each stripe scanned column by column. The bottom stripe may be shorter.
fn stripes(width: u32, height: u32) -> impl Iterator<Item = (u32, u32)> {
    (0..height)
        .step_by(4)
        .flat_map(move |y0| (0..width).map(move |x| (x, y0)))
}

/// Significance-propagation pass (D.3.1): visit each still-insignificant sample
/// that has at least one significant neighbour, zero-code it, and on a 1 decode
/// its sign. `bpno` is the current bit-plane; `1 << bpno` is its weight.
fn sig_prop_pass(
    mq: &mut MqDecoder<'_>,
    state: &mut BlockState,
    cx: &mut [Context],
    orient: Orientation,
    bpno: u32,
) {
    let (w, h) = (state.width, state.height);
    for (x, y0) in stripes(w, h) {
        for y in y0..(y0 + 4).min(h) {
            if state.is_significant(x, y) {
                continue;
            }
            let ctx = state.zc_context(x, y, orient);
            if ctx == CTX_ZC {
                continue; // no significant neighbour: deferred to cleanup
            }
            if mq.decode(&mut cx[ctx as usize]) == 1 {
                state.set_significant_magnitude(x, y, bpno);
                state.set_significant(x, y);
                decode_sign(mq, state, cx, x, y);
            }
            state.set_visited(x, y, true);
        }
    }
}

/// Magnitude-refinement pass (D.3.2): refine every sample that was already
/// significant before this plane (so not coded in this plane's significance
/// pass) by decoding one more magnitude bit under the refinement context.
fn mag_ref_pass(mq: &mut MqDecoder<'_>, state: &mut BlockState, cx: &mut [Context], bpno: u32) {
    let (w, h) = (state.width, state.height);
    for (x, y0) in stripes(w, h) {
        for y in y0..(y0 + 4).min(h) {
            if !state.is_significant(x, y) || state.is_visited(x, y) {
                continue;
            }
            let ctx = state.mr_context(x, y);
            let bit = mq.decode(&mut cx[ctx as usize]);
            state.refine_magnitude(x, y, bpno, bit);
            state.set_refined(x, y);
        }
    }
}

/// Significance-propagation pass under `bypass` (ISO D.5): the same scan and the
/// same sample selection as [`sig_prop_pass`], but the significance decision and
/// the sign are read as raw bits instead of MQ-coded ones. The zero-coding
/// context still decides *which* samples are visited (a non-zero context means a
/// significant neighbour), it just no longer codes the bit — so the sign is the
/// raw bit itself, without the neighbour-sign context or its XOR.
fn sig_prop_pass_raw(
    raw: &mut RawDecoder<'_>,
    state: &mut BlockState,
    orient: Orientation,
    bpno: u32,
) {
    let (w, h) = (state.width, state.height);
    for (x, y0) in stripes(w, h) {
        for y in y0..(y0 + 4).min(h) {
            if state.is_significant(x, y) {
                continue;
            }
            if state.zc_context(x, y, orient) == CTX_ZC {
                continue; // no significant neighbour: deferred to cleanup
            }
            if raw.decode() == 1 {
                state.set_significant_magnitude(x, y, bpno);
                state.set_significant(x, y);
                state.set_negative(x, y, raw.decode() == 1);
            }
            state.set_visited(x, y, true);
        }
    }
}

/// Magnitude-refinement pass under `bypass` (ISO D.5): identical to
/// [`mag_ref_pass`] except the refinement bit is a raw bit rather than an
/// MQ-coded decision under the refinement context.
fn mag_ref_pass_raw(raw: &mut RawDecoder<'_>, state: &mut BlockState, bpno: u32) {
    let (w, h) = (state.width, state.height);
    for (x, y0) in stripes(w, h) {
        for y in y0..(y0 + 4).min(h) {
            if !state.is_significant(x, y) || state.is_visited(x, y) {
                continue;
            }
            let bit = raw.decode();
            state.refine_magnitude(x, y, bpno, bit);
            state.set_refined(x, y);
        }
    }
}

/// Cleanup pass (D.3.3): code every sample not yet handled this plane. A full
/// column of four insignificant samples with no significant neighbours is
/// aggregated through the run-length context — a 0 leaves all four
/// insignificant, a 1 reads the first significant sample's position as two
/// uniform bits — after which the column finishes with ordinary zero coding.
///
/// Under `segmentation symbols` the pass ends by reading the `1010` symbol
/// (D.5); see [`read_segmentation_symbol`].
fn cleanup_pass(
    mq: &mut MqDecoder<'_>,
    state: &mut BlockState,
    cx: &mut [Context],
    orient: Orientation,
    bpno: u32,
    style: u8,
) -> Result<()> {
    let (w, h) = (state.width, state.height);
    for (x, y0) in stripes(w, h) {
        let rows = (y0 + 4).min(h) - y0;
        let mut first = 0;
        if rows == 4 {
            let aggregate = (0..4).all(|dy| {
                let y = y0 + dy;
                !state.is_significant(x, y)
                    && !state.is_visited(x, y)
                    && state.zc_context(x, y, orient) == CTX_ZC
            });
            if aggregate {
                if mq.decode(&mut cx[CTX_RUN as usize]) == 0 {
                    continue; // run of four insignificant samples
                }
                let hi = mq.decode(&mut cx[CTX_UNI as usize]);
                let lo = mq.decode(&mut cx[CTX_UNI as usize]);
                let run = (hi << 1) | lo; // position of the first significant
                let y = y0 + run as u32;
                state.set_significant_magnitude(x, y, bpno);
                state.set_significant(x, y);
                decode_sign(mq, state, cx, x, y);
                first = run as u32 + 1;
            }
        }
        for dy in first..rows {
            let y = y0 + dy;
            if state.is_significant(x, y) || state.is_visited(x, y) {
                continue;
            }
            let ctx = state.zc_context(x, y, orient);
            if mq.decode(&mut cx[ctx as usize]) == 1 {
                state.set_significant_magnitude(x, y, bpno);
                state.set_significant(x, y);
                decode_sign(mq, state, cx, x, y);
            }
        }
    }
    state.clear_visited();
    if style & crate::codestream::markers::code_block_style::SEGSYM != 0 {
        read_segmentation_symbol(mq, cx)?;
    }
    Ok(())
}

/// Read the segmentation symbol that closes a cleanup pass under `segmentation
/// symbols` (ISO D.5): four decisions in the uniform context, most significant
/// first, spelling `1010`.
///
/// The four decisions are part of the codeword whether or not anyone looks at
/// the value, so a decoder that skips them desynchronises the MQ coder for every
/// later pass. That is why this runs before the value is judged.
///
/// A wrong value means the coded data is corrupt. OpenJPEG decodes the symbol
/// and leaves the comparison commented out, so it decodes the rest of the block
/// from data it has already established is damaged; this returns an error
/// instead, which is what the symbol exists to let a decoder do.
fn read_segmentation_symbol(mq: &mut MqDecoder<'_>, cx: &mut [Context]) -> Result<()> {
    let mut symbol = 0u8;
    for _ in 0..4 {
        symbol = (symbol << 1) | mq.decode(&mut cx[CTX_UNI as usize]);
    }
    if symbol != 0b1010 {
        return Err(Error::Codestream(format!(
            "segmentation symbol at the end of a cleanup pass is {symbol:#06b}, expected 0b1010; \
             the coded data is corrupt"
        )));
    }
    Ok(())
}

/// Undo the maxshift on one coefficient magnitude (ISO/IEC 15444-1 H.2).
///
/// `mag` is the double-scale magnitude Tier-1 reconstructed, the value OpenJPEG
/// holds in `datap` before `opj_t1_clbl_decode_processor` halves it. A magnitude
/// **at or above** `2^roi_shift` was lifted there by the encoder and belongs to
/// the region; everything strictly below is background, already on the common
/// scale. Nothing else identifies the region — the shift is the label, which is
/// why the boundary is `>=` and not `>`: a coefficient of exactly `2^roi_shift`
/// is the smallest the encoder can have lifted.
///
/// Transliterated from `t1.c`:
///
/// ```text
/// if (roishift >= 31) { datap[...] = 0; }
/// else { thresh = 1 << roishift; if (mag >= thresh) { mag >>= roishift; } }
/// ```
///
/// The `>= 31` arm is OpenJPEG's guard for a shift `1i32` cannot express, and
/// it is reachable: `SPrgn` is a free byte, and a block whose zero bit-planes
/// exceed `Mb` keeps [`top_coded_plane`] under the [`MAX_BIT_PLANES`] check
/// however large the shift is. Zeroing the block is the *oracle's* reading,
/// not H.2's: a threshold of `2^31` or more is above every `i32` magnitude,
/// so the rule below, taken literally, would keep every coefficient as
/// background. `t1.c` zeroes `datap` wholesale instead, and this follows it —
/// changing the arm to keep the coefficients would diverge from OpenJPEG on
/// every such stream (see `docs/correctness.md` on deviations).
fn undo_maxshift(mag: i32, roi_shift: u8) -> i32 {
    if roi_shift == 0 {
        return mag;
    }
    if roi_shift >= 31 {
        return 0;
    }
    let threshold = 1i32 << roi_shift;
    if mag >= threshold {
        mag >> roi_shift
    } else {
        mag
    }
}

/// The most significant coded bit-plane of a code-block, one-based: OpenJPEG's
/// `bpno_plus_one = roishift + cblk->numbps`, zero when nothing is coded.
///
/// The zero bit-planes signalled in the packet header count against the
/// *raised* plane count `Mb + roi_shift` (ISO H.2 sets Kmax = Mb + s), so under
/// a maxshift a background-only block can carry more of them than the band has
/// magnitude planes — the shift must be added before the subtraction, or such
/// a block starts too high and decodes its coefficients too large. OpenJPEG's
/// arithmetic is signed; exceeding even the raised count saturates to zero
/// coded planes here, which is also the oracle's outcome — its negative
/// `bpno_plus_one` fails the pass loop's `>= 1` guard, running zero passes,
/// and the block decodes to all zeros without an error.
pub fn top_coded_plane(numbps: u32, zero_bit_planes: u32, roi_shift: u8) -> u32 {
    (numbps + u32::from(roi_shift)).saturating_sub(zero_bit_planes)
}

/// The per-component parameters a code-block decode needs beyond its own
/// subband: the code-block style flags (`SPcod`/`SPcoc`) and the
/// region-of-interest maxshift (`SPrgn`).
#[derive(Debug, Clone, Copy, Default)]
pub struct BlockParams {
    pub style: u8,
    pub roi_shift: u8,
}

/// Which of the three coding passes runs next within a bit-plane (ISO D.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PassType {
    SigProp,
    MagRef,
    Cleanup,
}

/// How a codeword segment is decoded: the MQ arithmetic decoder for the
/// context-coded passes, or a raw bit reader for the `bypass` (lazy) passes of
/// the low bit-planes (D.5). One codeword segment uses exactly one of them.
enum PassCoder<'a> {
    Mq(MqDecoder<'a>),
    Raw(RawDecoder<'a>),
}

/// Decode one code-block: run the bit-plane passes over its codeword segments
/// into `state`.
///
/// `numbps` is the subband's magnitude bit-plane count `Mb` (guard bits +
/// quantization exponent − 1); `num_passes` and `zero_bit_planes` come from the
/// Tier-2 packet headers; `orient` is the subband's orientation (it selects the
/// zero-coding table); and `style` is the COD/COC code-block style flags. On
/// On return `state.coeffs` holds the signed quantized coefficients at **twice**
/// their weight — OpenJPEG's `datap` as `opj_t1_clbl_decode_processor` receives
/// it. Halving them is the caller's job because the two arms do it differently:
///
/// - reversible (5/3): an integer `datap[i] /= 2`, truncating toward zero;
/// - irreversible (9/7): folded into the float dequantization, which multiplies
///   by `0.5f * band->stepsize` rather than by `band->stepsize`. The half bit
///   survives into the float, and truncating it first loses up to half a
///   quantization step per coefficient.
///
/// Halving here would force the integer form on both.
///
/// Following OpenJPEG, decoding runs at double scale: it begins at the most
/// significant coded plane `Mb − zero_bit_planes` with a cleanup pass and walks
/// down three passes per plane to plane 1 (never plane 0), carrying each
/// magnitude in mid-point form, then halves toward zero. A stream that stops
/// early (the lossy/rate-truncated case) simply leaves the un-coded low planes
/// zero. Quality layers are handled in Tier-2, which concatenates a block's
/// per-layer contributions into the single MQ codeword decoded here.
///
/// `segments` carries the block's codeword segments in order, each with the
/// coding passes it codes. The MQ decoder is re-initialised at every segment —
/// under `restart` that is once per pass — while the context states, the
/// significance map, and the bit-plane counter carry straight through, exactly
/// as `opj_t1_decode_cblk` does. Without termination there is one segment and
/// the codeword runs unbroken.
///
/// `decode_cod` admits every Part 1 style flag and rejects only the two HTJ2K
/// bits. Most act at the segment split or the context, which Tier-2 and
/// [`BlockState`] have already applied, so the pass cycle below is unchanged.
/// Two reach into the passes themselves: `segmentation symbols` appends four
/// decisions to every cleanup pass, and `bypass` (lazy) switches the
/// significance and refinement passes of the low bit-planes from MQ-coded to raw
/// (D.5) — see the per-segment coder choice below.
pub fn decode_block(
    segments: &[(Vec<u8>, u32)],
    state: &mut BlockState,
    orient: Orientation,
    numbps: u32,
    num_passes: u32,
    zero_bit_planes: u32,
    params: BlockParams,
) -> Result<()> {
    let BlockParams { style, roi_shift } = params;
    use crate::codestream::markers::code_block_style::{
        LAZY, PTERM, RESET, SEGSYM, TERMALL, VCAUSAL,
    };
    debug_assert_eq!(
        style & !(LAZY | TERMALL | PTERM | SEGSYM | VCAUSAL | RESET),
        0,
        "decode_cod rejects every style flag but bypass, restart, pterm, segsym, vcausal and reset",
    );
    // Vertically causal context changes how every significance/sign context is
    // formed; the pass functions read it off the state.
    state.vcausal = style & VCAUSAL != 0;
    if num_passes == 0 {
        return Ok(());
    }

    // Decode at twice the final scale, matching OpenJPEG: the most significant
    // coded plane is `cblk.numbps = Mb − zero_bit_planes` (`numbps = Mb`, the
    // subband's guard + exponent − 1), and decoding walks down to plane 1, never
    // plane 0. Carrying the extra low bit lets the mid-point reconstruction stay
    // integral (the half is ≥ 1 at every coded plane); the final halving below
    // drops it. A truncated (lossy) stream simply stops higher, leaving the
    // un-coded low planes zero. For a fully coded block
    // `Mb − zero_bit_planes == num_passes.div_ceil(3)`.
    // Maxshift starts the block `roi_shift` planes higher, so that every
    // region-of-interest coefficient outranks every background one; see
    // `top_coded_plane` for the interplay with the zero bit-planes.
    let top = top_coded_plane(numbps, zero_bit_planes, roi_shift);
    // The double scale means `1 << top` must stay inside `i32`. `decode_subband`
    // rejects this too, before allocating; checking again here is where OpenJPEG
    // puts it (`opj_t1_decode_cblk`'s `bpno_plus_one >= 31`), so a caller that
    // reaches `decode_block` by another route cannot overflow
    // `set_significant_magnitude`. It does *not* bound the maxshift: enough
    // zero bit-planes keep `top` small under any `SPrgn`, which is why
    // `undo_maxshift` carries its own `roi_shift >= 31` arm.
    if top > MAX_BIT_PLANES {
        return Err(Error::Unsupported(format!(
            "code-block needs {top} bit-planes, over the {MAX_BIT_PLANES}-plane limit"
        )));
    }
    if top < 1 {
        return Ok(()); // no coded magnitude planes: the block stays zero
    }

    let mut cx = init_contexts();
    let mut bpno = top;
    // The most significant plane runs the cleanup pass only (D.4), so the pass
    // cycle starts at cleanup and wraps to the next plane after it.
    let mut pass_type = PassType::Cleanup;

    let bypass = style & LAZY != 0;
    // OpenJPEG's `cblk->numbps`, the coded plane count without the maxshift: our
    // `top` is `bpno_plus_one` (`roishift + cblk->numbps`), so subtracting the
    // shift recovers it. Under `bypass` a significance or refinement pass turns
    // raw once the four most significant bit-planes are behind it, i.e. once
    // `bpno <= cblk->numbps - 4` (t1.c). Signed, because that difference is
    // negative on a shallow block that never reaches the raw region.
    let cblk_numbps = top as i32 - i32::from(roi_shift);

    'segments: for (bytes, passes) in segments {
        // A codeword segment is a single terminated stream — MQ for the
        // context-coded passes, raw for the `bypass` ones. Context states and
        // `bpno` carry across segments; only the arithmetic decoder restarts.
        //
        // The coder is fixed by the pass the segment opens on, matching t1.c's
        // per-segment `type`: the lazy split (Tier-2) keeps each segment
        // homogeneous — a two-pass raw run (significance + refinement) or a
        // one-pass MQ cleanup — so this one decision holds for every pass in it.
        let raw = bypass && pass_type != PassType::Cleanup && (bpno as i32) <= cblk_numbps - 4;
        let mut coder = if raw {
            PassCoder::Raw(RawDecoder::new(bytes))
        } else {
            PassCoder::Mq(MqDecoder::new(bytes))
        };
        for _ in 0..*passes {
            if bpno < 1 {
                // The plane counter is exhausted, so this segment stops mid-way
                // and every later one goes unread. None of them is the
                // terminated whole `predictable termination` promises about, and
                // their bytes are never consumed — checking them would reject a
                // sound codestream for leaving a buffer it never had to read.
                break 'segments;
            }
            match (&mut coder, pass_type) {
                (PassCoder::Mq(mq), PassType::SigProp) => {
                    sig_prop_pass(mq, state, &mut cx, orient, bpno)
                }
                (PassCoder::Mq(mq), PassType::MagRef) => mag_ref_pass(mq, state, &mut cx, bpno),
                (PassCoder::Mq(mq), PassType::Cleanup) => {
                    cleanup_pass(mq, state, &mut cx, orient, bpno, style)?
                }
                (PassCoder::Raw(rd), PassType::SigProp) => {
                    sig_prop_pass_raw(rd, state, orient, bpno)
                }
                (PassCoder::Raw(rd), PassType::MagRef) => mag_ref_pass_raw(rd, state, bpno),
                // The lazy split routes every cleanup to its own MQ segment, so a
                // raw segment never carries one.
                (PassCoder::Raw(_), PassType::Cleanup) => {
                    unreachable!("a bypass cleanup pass is MQ-coded, never raw")
                }
            }
            // Under `reset context probabilities` the MQ context states return to
            // their initial estimates after every pass (D.3, OpenJPEG's
            // `opj_mqc_resetstates` + the three seeded contexts). The default
            // style carries the states across passes. OpenJPEG guards this with
            // `type == T1_TYPE_MQ`: the raw passes of `bypass` carry no context,
            // so they never reset it.
            if style & RESET != 0 && !raw {
                cx = init_contexts();
            }
            pass_type = match pass_type {
                PassType::SigProp => PassType::MagRef,
                PassType::MagRef => PassType::Cleanup,
                // A cleanup pass closes the plane; the next one starts below it.
                // `bpno >= 1` here, guaranteed by the guard above, so this
                // cannot underflow — and a `bpno` of 0 stops the next pass.
                PassType::Cleanup => {
                    bpno -= 1;
                    PassType::SigProp
                }
            };
        }
        // Every codeword segment is separately terminated, so under `predictable
        // termination` each one must account for its own bytes. OpenJPEG checks
        // only the last segment of a block and warns; checking each one costs
        // nothing and localises the damage. The check is the MQ flush's, so it
        // applies to MQ segments only — a raw `bypass` segment ends on a byte
        // boundary with no such guarantee.
        if let PassCoder::Mq(mq) = &coder {
            if style & PTERM != 0 && !mq.ends_predictably() {
                return Err(Error::Codestream(format!(
                    "code-block style declares predictable termination, but a codeword segment \
                     leaves {} of its {} byte(s) unconsumed; the coded data is corrupt",
                    mq.unconsumed(),
                    bytes.len(),
                )));
            }
        }
    }

    // Undo the maxshift (Annex H.2), then apply the decoded signs.
    //
    // The passes carried each magnitude in the mid-point reconstruction form at
    // double scale (ISO E.1.1.2, r = ½): becoming significant set
    // `2^bpno + 2^(bpno−1)` and each refinement nudged it by ±2^(bpno−1). The
    // coefficients are left at that scale; the caller halves them, because how
    // the half bit is dropped depends on the arm it lands in (see this
    // function's contract).
    //
    // The maxshift is undone here, before that halving, as
    // `opj_t1_clbl_decode_processor` does it: its threshold is stated in the
    // coefficients' own scale, and halving first would drop a region coefficient
    // below it.
    for y in 0..state.height {
        for x in 0..state.width {
            let i = state.idx(x, y);
            let mag = undo_maxshift(state.coeffs[i], roi_shift);
            state.coeffs[i] = if state.is_negative(x, y) { -mag } else { mag };
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::golden_vectors::GOLDEN_BLOCKS;
    use super::*;
    /// Decode one golden block from its committed segment into a fresh state.
    fn decode_golden(g: &super::golden_vectors::GoldenBlock) -> Vec<i32> {
        // The golden vectors carry no termination, so one segment holds them all.
        let segments = [(g.segment.to_vec(), g.num_passes)];
        let mut state = BlockState::new(g.width, g.height);
        // The golden vectors are fully coded (lossless, every plane to plane 0),
        // so Mb = decoded-plane count + skipped MSB planes.
        let numbps = g.num_passes.div_ceil(3) + g.zero_bit_planes;
        decode_block(
            &segments,
            &mut state,
            g.orient,
            numbps,
            g.num_passes,
            g.zero_bit_planes,
            BlockParams::default(),
        )
        .expect("the default style decodes without a style check");
        // `decode_block` leaves the coefficients at double scale; the golden
        // vectors are the halved, integer values the reversible arm produces.
        state.coeffs.iter().map(|&c| c / 2).collect()
    }

    /// Each committed code-block segment decodes bit-exactly to its oracle
    /// coefficient grid (decoded sample − DC shift, from `opj_decompress`). The
    /// three blocks carry different pass counts (19, 16, 10), so a bit-exact
    /// match also proves the bit-plane loop runs *exactly* `num_passes` passes:
    /// stopping early or late would scale or corrupt the magnitudes.
    #[test]
    fn golden_blocks_decode_to_expected_coefficients() {
        for g in GOLDEN_BLOCKS {
            assert_eq!(decode_golden(g), g.coeffs, "block {}", g.name);
        }
    }

    /// Vertically causal context excludes the next stripe from the 3×3
    /// neighbourhood of a stripe's bottom row (`y % 4 == 3`), and only there. The
    /// three context types must all see the reduction — significance
    /// (`neighbour_sums`/`zc_context`), sign (`sc_context`), and refinement
    /// (`mr_context`) — because OpenJPEG forms them from the same flags.
    #[test]
    fn vertically_causal_context_excludes_the_next_stripe() {
        // Two stripes of a 3-wide block. Make the whole row below (1, 3) — the
        // top of the second stripe — significant and negative, so the vertical
        // and both diagonal south neighbours of (1, 3) are set.
        let mut state = BlockState::new(3, 8);
        for x in 0..3 {
            state.set_significant(x, 4);
            state.set_negative(x, 4, true);
        }

        // Default: (1, 3) sees one vertical and two diagonal south neighbours.
        let (h, v, d) = state.neighbour_sums(1, 3);
        assert_eq!((h, v, d), (0, 1, 2), "default neighbourhood");
        assert_ne!(state.zc_context(1, 3, Orientation::Ll), CTX_ZC);
        // Sign: the south neighbours are negative, so v < 0.
        let (_, xor_default) = state.sc_context(1, 3);
        assert_eq!(xor_default, 1, "negative south neighbours flip the sign");
        // First refinement: a significant neighbour selects context 15, not 14.
        assert_eq!(state.mr_context(1, 3), CTX_MR + 1);

        // Vertically causal: the next stripe vanishes from (1, 3)'s context.
        state.vcausal = true;
        assert_eq!(
            state.neighbour_sums(1, 3),
            (0, 0, 0),
            "south excluded at ci==3"
        );
        assert_eq!(state.zc_context(1, 3, Orientation::Ll), CTX_ZC);
        let (sc, xor_causal) = state.sc_context(1, 3);
        assert_eq!((sc, xor_causal), (CTX_SC, 0), "no neighbour, neutral sign");
        assert_eq!(state.mr_context(1, 3), CTX_MR, "no significant neighbour");

        // An interior row (ci == 2) keeps its south neighbour even under vcausal:
        // (1, 2)'s south row (y = 3) is inside the same stripe.
        for x in 0..3 {
            state.set_significant(x, 3);
        }
        let (_, v_interior, _) = state.neighbour_sums(1, 2);
        assert_eq!(v_interior, 1, "an interior row is unaffected by vcausal");
    }

    /// A code-block with no coding passes contributes nothing.
    #[test]
    fn zero_passes_yields_all_zero_coefficients() {
        let mut state = BlockState::new(4, 4);
        decode_block(
            &[(vec![0x80], 0)],
            &mut state,
            Orientation::Ll,
            8,
            0,
            0,
            BlockParams::default(),
        )
        .expect("zero passes decode to nothing");
        assert!(state.coeffs.iter().all(|&c| c == 0));
    }

    /// `predictable termination` promises each terminated segment accounts for
    /// its own bytes, so a segment padded with bytes the codeword never reaches
    /// is corrupt. Without the flag the same segment decodes without complaint,
    /// which is what makes this a check and not a new parse rule.
    #[test]
    fn predictable_termination_catches_a_segment_the_codeword_does_not_consume() {
        use crate::codestream::markers::code_block_style::PTERM;
        let padded = vec![0x80, 0, 0, 0, 0, 0, 0, 0];

        let mut state = BlockState::new(4, 4);
        let err = decode_block(
            &[(padded.clone(), 1)],
            &mut state,
            Orientation::Ll,
            8,
            1,
            0,
            BlockParams {
                style: PTERM,
                roi_shift: 0,
            },
        )
        .expect_err("eight bytes for one cleanup pass leaves more than two unconsumed");
        assert!(matches!(err, Error::Codestream(_)), "{err:?}");

        let mut state = BlockState::new(4, 4);
        decode_block(
            &[(padded, 1)],
            &mut state,
            Orientation::Ll,
            8,
            1,
            0,
            BlockParams::default(),
        )
        .expect("the same segment is fine without the flag");
    }

    /// A segment cut short because the bit-planes ran out is not a terminated
    /// whole, so the predictable-termination promise does not apply to it.
    #[test]
    fn predictable_termination_ignores_a_segment_stopped_by_the_bit_plane_floor() {
        use crate::codestream::markers::code_block_style::PTERM;
        let mut state = BlockState::new(4, 4);
        // `top` is 1, so the first cleanup pass drops `bpno` to 0 and the second
        // pass never runs; the segment's bytes stay unconsumed.
        decode_block(
            &[(vec![0x80, 0, 0, 0, 0, 0, 0, 0], 4)],
            &mut state,
            Orientation::Ll,
            8,
            4,
            7,
            BlockParams {
                style: PTERM,
                roi_shift: 0,
            },
        )
        .expect("a segment the decoder stops early in is not checked");
    }

    /// The segmentation symbol is verified, not just consumed. Flipping a bit of
    /// a cleanup pass's trailing symbol has to surface as a typed error rather
    /// than as silently wrong coefficients.
    #[test]
    fn a_corrupt_segmentation_symbol_is_a_codestream_error() {
        use crate::codestream::markers::code_block_style::SEGSYM;
        // An all-zero codeword decodes the uniform context to a value that is
        // not `1010`, which is exactly the corruption the symbol exists to find.
        let mut state = BlockState::new(4, 4);
        let err = decode_block(
            &[(vec![0x00; 8], 1)],
            &mut state,
            Orientation::Ll,
            8,
            1,
            0,
            BlockParams {
                style: SEGSYM,
                roi_shift: 0,
            },
        )
        .expect_err("the trailing symbol is not 1010");
        let Error::Codestream(message) = &err else {
            panic!("{err:?}")
        };
        assert!(message.contains("segmentation symbol"), "{message}");
    }

    /// The maxshift boundary, against the reference formula. `t1.c` reads
    ///
    /// ```text
    /// thresh = 1 << roishift;
    /// if (mag >= thresh) { mag >>= roishift; }
    /// ```
    ///
    /// so a magnitude of exactly `2^roi_shift` is the *smallest* the encoder can
    /// have lifted, and it must come down. `>` for `>=` leaves it up by
    /// `roi_shift` planes; the whole-component ROI fixture cannot see that,
    /// because it has no background coefficient below the threshold at all.
    #[test]
    fn undo_maxshift_matches_the_reference_formula_across_the_boundary() {
        /// `t1.c`'s roishift block, transliterated.
        fn reference(mag: i32, roishift: u8) -> i32 {
            if roishift == 0 {
                return mag;
            }
            let thresh = 1i32 << roishift;
            if mag >= thresh { mag >> roishift } else { mag }
        }

        for roi_shift in 0..=12u8 {
            let threshold = 1i32 << roi_shift;
            // Straddle the boundary, and cover zero and the far tails.
            let cases = [
                0,
                1,
                threshold - 2,
                threshold - 1,
                threshold,
                threshold + 1,
                threshold * 2,
                threshold * 1234 + 7,
                i32::MAX,
            ];
            for mag in cases.into_iter().filter(|&m| m >= 0) {
                assert_eq!(
                    undo_maxshift(mag, roi_shift),
                    reference(mag, roi_shift),
                    "mag {mag}, roi_shift {roi_shift}"
                );
            }
        }
    }

    /// A magnitude one below the threshold is background and stays where it is;
    /// one at the threshold is the region and comes down. This is the single
    /// discriminating pair, spelled out so a boundary regression names itself.
    #[test]
    fn the_maxshift_threshold_separates_background_from_region() {
        let roi_shift = 6;
        let threshold = 1i32 << roi_shift; // 64
        assert_eq!(undo_maxshift(threshold - 1, roi_shift), 63, "background");
        assert_eq!(undo_maxshift(threshold, roi_shift), 1, "region");
        assert_eq!(undo_maxshift(0, roi_shift), 0, "zero is neither");
        // Without a shift nothing moves, whatever the magnitude.
        assert_eq!(undo_maxshift(threshold, 0), threshold);
    }

    /// The zero bit-planes count against the raised `Mb + roi_shift` (Kmax of
    /// ISO H.2), so under a maxshift they may exceed `Mb` alone — a
    /// background-only block in `p0_06` does exactly that. Subtracting them
    /// from `Mb` first (saturating) and adding the shift after would start
    /// such a block `zero_bit_planes − Mb` planes too high and decode its
    /// coefficients that many planes too large.
    #[test]
    fn zero_bit_planes_count_against_the_maxshift_raised_planes() {
        // OpenJPEG: bpno_plus_one = roishift + (numbps − P), signed.
        assert_eq!(top_coded_plane(10, 3, 0), 7, "no ROI");
        assert_eq!(top_coded_plane(10, 3, 9), 16, "ROI block, few zero planes");
        assert_eq!(top_coded_plane(10, 13, 9), 6, "background block, P > Mb");
        assert_eq!(top_coded_plane(10, 19, 9), 0, "all planes zero");
        assert_eq!(top_coded_plane(10, 25, 9), 0, "past Kmax saturates");
    }

    /// A hostile `SPrgn` whose raised `top` overflows the bit-plane budget is
    /// rejected. Rejection is only this arm's outcome: with enough zero
    /// bit-planes the same shifts are *accepted* and the block zeroed — the
    /// companion test below.
    #[test]
    fn an_out_of_range_maxshift_is_rejected_rather_than_overflowing() {
        for roi_shift in [31u8, 32, 64, 255] {
            let mut state = BlockState::new(4, 4);
            let err = decode_block(
                &[(vec![0x80], 1)],
                &mut state,
                Orientation::Ll,
                8,
                1,
                0,
                BlockParams {
                    style: 0,
                    roi_shift,
                },
            )
            .expect_err(&format!("maxshift {roi_shift} passes the bit-plane limit"));
            assert!(matches!(err, Error::Unsupported(_)), "{err:?}");
        }
    }

    /// The bit-plane limit alone does not bound `SPrgn`: enough zero bit-planes
    /// pull `top` back under it whatever the shift, so an inexpressible shift
    /// reaches `undo_maxshift`. OpenJPEG's `roishift >= 31` arm zeroes such a
    /// block — this must do the same, not overflow `1i32 << roi_shift`.
    #[test]
    fn an_inexpressible_maxshift_on_a_decodable_block_zeroes_it() {
        for roi_shift in [31u8, 64, 255] {
            let mut state = BlockState::new(4, 4);
            // numbps 8, zero planes 8 + roi_shift − 5: top decodes 5 planes.
            let zero_bit_planes = 8 + u32::from(roi_shift) - 5;
            decode_block(
                &[(vec![0x80, 0x27], 3)],
                &mut state,
                Orientation::Ll,
                8,
                3,
                zero_bit_planes,
                BlockParams {
                    style: 0,
                    roi_shift,
                },
            )
            .expect("a small top decodes whatever the maxshift");
            assert!(
                state.coeffs.iter().all(|&c| c == 0),
                "roi_shift {roi_shift}: every coefficient reads as region and shifts to nothing"
            );
        }
    }

    /// A codeword segment may carry coding passes and no bytes: under `restart`
    /// each pass is its own segment, and its length field may be zero. The MQ
    /// decoder reads `0xFF` past the end of its slice, the way OpenJPEG pads
    /// with `OPJ_COMMON_CBLK_DATA_EXTRA`, so this decodes rather than panicking.
    /// `build_subbands` still rejects a block with passes and no bytes anywhere.
    #[test]
    fn an_empty_codeword_segment_does_not_panic() {
        let mut state = BlockState::new(4, 4);
        decode_block(
            &[(Vec::new(), 1), (vec![0x80], 1)],
            &mut state,
            Orientation::Ll,
            8,
            2,
            0,
            BlockParams {
                style: crate::codestream::markers::code_block_style::TERMALL,
                roi_shift: 0,
            },
        )
        .expect("an empty segment decodes as 0xFF padding");
    }

    /// Signs are recovered, not just magnitudes: the sparse block has both
    /// positive and negative significant coefficients among its zeros.
    #[test]
    fn golden_block_recovers_signs() {
        let sparse = GOLDEN_BLOCKS
            .iter()
            .find(|g| g.name == "sparse_8x8")
            .unwrap();
        let out = decode_golden(sparse);
        assert!(
            out.iter().any(|&c| c > 0),
            "expected a positive coefficient"
        );
        assert!(
            out.iter().any(|&c| c < 0),
            "expected a negative coefficient"
        );
        assert_eq!(out, sparse.coeffs);
    }

    /// Build a block and mark the listed `(x, y)` offsets significant, optionally
    /// negative. Centre tests on `(2, 2)` of a 5×5 block so all eight neighbours
    /// are in range unless a test deliberately probes an edge.
    fn block_with(sig: &[(u32, u32)]) -> BlockState {
        let mut b = BlockState::new(5, 5);
        for &(x, y) in sig {
            b.set_significant(x, y);
        }
        b
    }

    #[test]
    fn state_round_trips() {
        let mut b = BlockState::new(4, 3);
        assert!(!b.is_significant(1, 2));
        b.set_significant(1, 2);
        assert!(b.is_significant(1, 2));

        assert!(!b.is_visited(1, 2));
        b.set_visited(1, 2, true);
        assert!(b.is_visited(1, 2));
        b.set_visited(1, 2, false);
        assert!(!b.is_visited(1, 2));

        b.set_negative(1, 2, true);
        assert!(b.is_negative(1, 2));

        assert!(!b.is_refined(1, 2));
        b.set_refined(1, 2);
        assert!(b.is_refined(1, 2));
    }

    // --- Zero coding (ISO Table D-1) -------------------------------------

    /// Each `LL`/`LH` context label, hit by a hand-built neighbourhood whose
    /// (ΣH, ΣV, ΣD) lands in that row of the table.
    #[test]
    fn zc_ll_lh_all_labels() {
        let cases: [(&[(u32, u32)], u8); 9] = [
            (&[], 0),               // h0 v0 d0
            (&[(1, 1)], 1),         // h0 v0 d1
            (&[(1, 1), (3, 3)], 2), // h0 v0 d2
            (&[(2, 1)], 3),         // h0 v1
            (&[(2, 1), (2, 3)], 4), // h0 v2
            (&[(1, 2)], 5),         // h1 v0 d0
            (&[(1, 2), (1, 1)], 6), // h1 v0 d1
            (&[(1, 2), (2, 1)], 7), // h1 v1
            (&[(1, 2), (3, 2)], 8), // h2
        ];
        for (sig, want) in cases {
            let b = block_with(sig);
            assert_eq!(
                b.zc_context(2, 2, Orientation::Ll),
                CTX_ZC + want,
                "LL {sig:?}"
            );
            assert_eq!(
                b.zc_context(2, 2, Orientation::Lh),
                CTX_ZC + want,
                "LH {sig:?}"
            );
        }
    }

    /// `HL` is the `LL`/`LH` table with horizontal and vertical roles swapped:
    /// a purely horizontal neighbourhood (ΣH=2) that scores 8 for LL must follow
    /// the ΣV=2 row for HL, and vice versa.
    #[test]
    fn zc_hl_swaps_h_and_v() {
        // Two horizontal neighbours: LL → 8 (h2), HL reads it as v2 → 4.
        let horiz = block_with(&[(1, 2), (3, 2)]);
        assert_eq!(horiz.zc_context(2, 2, Orientation::Ll), CTX_ZC + 8);
        assert_eq!(horiz.zc_context(2, 2, Orientation::Hl), CTX_ZC + 4);

        // Two vertical neighbours: LL → 4 (v2), HL reads it as h2 → 8.
        let vert = block_with(&[(2, 1), (2, 3)]);
        assert_eq!(vert.zc_context(2, 2, Orientation::Ll), CTX_ZC + 4);
        assert_eq!(vert.zc_context(2, 2, Orientation::Hl), CTX_ZC + 8);

        // One horizontal + one vertical is symmetric (label 7) either way.
        let mix = block_with(&[(1, 2), (2, 1)]);
        assert_eq!(mix.zc_context(2, 2, Orientation::Hl), CTX_ZC + 7);
    }

    /// Each `HH` context label, keyed by (ΣD, ΣH+ΣV).
    #[test]
    fn zc_hh_all_labels() {
        let cases: [(&[(u32, u32)], u8); 9] = [
            (&[], 0),                       // d0 hv0
            (&[(2, 1)], 1),                 // d0 hv1
            (&[(2, 1), (1, 2)], 2),         // d0 hv2
            (&[(1, 1)], 3),                 // d1 hv0
            (&[(1, 1), (2, 1)], 4),         // d1 hv1
            (&[(1, 1), (2, 1), (1, 2)], 5), // d1 hv2
            (&[(1, 1), (3, 3)], 6),         // d2 hv0
            (&[(1, 1), (3, 3), (2, 1)], 7), // d2 hv1
            (&[(1, 1), (3, 3), (3, 1)], 8), // d3
        ];
        for (sig, want) in cases {
            let b = block_with(sig);
            assert_eq!(
                b.zc_context(2, 2, Orientation::Hh),
                CTX_ZC + want,
                "HH {sig:?}"
            );
        }
    }

    // --- Sign coding (ISO Tables D-2, D-3) ------------------------------

    /// Build a block whose horizontal pair sums to `h` and vertical pair to `v`
    /// (each in -1..=1), by signing one neighbour per axis.
    fn block_for_sign(h: i32, v: i32) -> BlockState {
        let mut b = BlockState::new(5, 5);
        let mut sign = |x: u32, y: u32, neg: bool| {
            b.set_significant(x, y);
            b.set_negative(x, y, neg);
        };
        match h {
            1 => sign(1, 2, false),
            -1 => sign(1, 2, true),
            _ => {}
        }
        match v {
            1 => sign(2, 1, false),
            -1 => sign(2, 1, true),
            _ => {}
        }
        b
    }

    #[test]
    fn sc_all_nine_contexts_and_xorbit() {
        let cases: [(i32, i32, u8, u8); 9] = [
            (1, 1, 4, 0),
            (1, 0, 3, 0),
            (1, -1, 2, 0),
            (0, 1, 1, 0),
            (0, 0, 0, 0),
            (0, -1, 1, 1),
            (-1, 1, 2, 1),
            (-1, 0, 3, 1),
            (-1, -1, 4, 1),
        ];
        for (h, v, label, xor) in cases {
            let b = block_for_sign(h, v);
            assert_eq!(b.sc_context(2, 2), (CTX_SC + label, xor), "H={h} V={v}");
        }
    }

    /// Two like-signed neighbours on one axis clamp to a single contribution
    /// (ISO Table D-2: H, V are bounded to -1..=1).
    #[test]
    fn sc_contributions_clamp() {
        let mut b = BlockState::new(5, 5);
        for x in [1, 3] {
            b.set_significant(x, 2); // both horizontal neighbours positive
        }
        // H would be +2 unclamped; clamped to +1 → label 3, xorbit 0.
        assert_eq!(b.sc_context(2, 2), (CTX_SC + 3, 0));
    }

    // --- Magnitude refinement (ISO Table D-4) ---------------------------

    #[test]
    fn mr_first_refinement_with_no_significant_neighbours() {
        let b = BlockState::new(5, 5);
        assert_eq!(b.mr_context(2, 2), CTX_MR);
    }

    #[test]
    fn mr_first_refinement_with_a_significant_neighbour() {
        let b = block_with(&[(2, 1)]);
        assert_eq!(b.mr_context(2, 2), CTX_MR + 1);
    }

    #[test]
    fn mr_after_first_refinement_ignores_neighbours() {
        let mut b = block_with(&[(2, 1)]);
        b.set_refined(2, 2);
        assert_eq!(b.mr_context(2, 2), CTX_MR + 2);
    }

    // --- Edge clamping --------------------------------------------------

    /// At a corner the off-block neighbours read as insignificant, so a lone
    /// significant in-block neighbour is counted and nothing indexes out of
    /// bounds.
    #[test]
    fn neighbours_clamp_at_corners() {
        let mut b = BlockState::new(3, 3);
        // Corner (0,0): only (1,0), (0,1), (1,1) exist as neighbours.
        b.set_significant(1, 0); // horizontal neighbour of (0,0)
        assert_eq!(b.zc_context(0, 0, Orientation::Ll), CTX_ZC + 5); // h1 v0 d0

        // The opposite corner with a diagonal-only neighbour → label 1.
        let mut c = BlockState::new(3, 3);
        c.set_significant(1, 1); // diagonal neighbour of (2,2)
        assert_eq!(c.zc_context(2, 2, Orientation::Ll), CTX_ZC + 1);

        // Sign and MR at a corner must not panic and read clamped neighbours.
        let _ = b.sc_context(0, 0);
        let _ = b.mr_context(0, 0);
    }
}