j2k-metal 0.6.1

Apple Metal GPU adapter for Rust JPEG 2000 and HTJ2K decode/encode paths
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
// SPDX-License-Identifier: Apache-2.0

use super::{
    classic_batch_uses_plain_fast_path, classic_repeated_uses_plain_fast_path,
    crop_prepared_direct_grayscale_plan_to_output_region, decode_prepared_classic_sub_band_on_cpu,
    decode_scaled_to_surface, direct_tier1_input_buffer_prepares_for_test,
    execute_flattened_hybrid_cpu_tier1_direct_color_plan_batch_for_test,
    execute_hybrid_cpu_tier1_direct_color_plan_batch, flattened_hybrid_cpu_decode_batches_for_test,
    hybrid_cpu_decode_inputs_for_test, hybrid_cpu_decode_worker_count,
    hybrid_cpu_decode_worker_inits_for_test, hybrid_repeated_output_blits_for_test,
    hybrid_stacked_component_batches_for_test, j2k_pack_kernel_name_for, j2k_pack_scale_arrays,
    output_shape_for, prepare_direct_color_plan, prepare_direct_color_plan_for_cpu_upload,
    prepare_direct_grayscale_plan, prepared_direct_color_tier1_input_count,
    prepared_direct_grayscale_plan_compute_encoder_count, prepared_idwt_output_len,
    prepared_repeated_direct_ht_cleanup_dispatch_count,
    repeated_gray_store_is_contiguous_full_surface,
    reset_direct_tier1_input_buffer_prepares_for_test,
    reset_flattened_hybrid_cpu_decode_batches_for_test, reset_hybrid_cpu_decode_inputs_for_test,
    reset_hybrid_cpu_decode_worker_inits_for_test, reset_hybrid_repeated_output_blits_for_test,
    reset_hybrid_stacked_component_batches_for_test, reset_shared_buffer_pool_misses_for_test,
    runtime_initialization_error, shared_buffer_pool_misses_for_test,
    should_flatten_hybrid_cpu_tier1_color_batch, supports_stacked_direct_component_plane_batch,
    with_runtime_for_device, J2kClassicCleanupBatchJob, J2kClassicSegment,
    J2kRepeatedGrayStoreParams, MetalRuntime, MetalSupportError, PreparedClassicSubBand,
    PreparedDirectColorPlan, PreparedDirectGrayscaleStep,
};
use j2k_core::PixelFormat;
use j2k_native::{
    decode_j2k_sub_band_scalar, encode, encode_htj2k, ColorSpace as NativeColorSpace,
    DecodeSettings, DecoderContext, EncodeOptions, Image, J2kCodeBlockBatchJob,
    J2kCodeBlockDecodeJob, J2kDirectGrayscaleStep as NativeDirectGrayscaleStep,
    J2kOwnedCodeBlockBatchJob, J2kOwnedSubBandPlan, J2kSubBandDecodeJob, J2kWaveletTransform,
};
use metal::foreign_types::ForeignType;
use metal::Device;
use std::sync::{Arc, Mutex};

static HYBRID_COUNTER_TEST_LOCK: Mutex<()> = Mutex::new(());

#[test]
fn rgb16_with_alpha_is_rejected() {
    let runtime = MetalRuntime::new().expect("Metal runtime");
    let result = output_shape_for(
        &NativeColorSpace::RGB,
        true,
        4,
        PixelFormat::Rgb16,
        &runtime,
    );
    assert!(result.is_err(), "RGBA input must not silently map to Rgb16");
}

#[test]
fn runtime_initialization_error_classifies_null_queue_as_unavailable() {
    assert!(matches!(
        runtime_initialization_error(&MetalSupportError::CommandQueueUnavailable),
        crate::Error::MetalUnavailable
    ));
}

#[test]
fn classic_encode_output_capacity_keeps_conservative_default() {
    let capacity =
        super::classic_encode_output_capacity(64, 64, 11).expect("classic output capacity");

    assert_eq!(capacity, 64 * 64 * 11 * 8 + 4097);
}

#[test]
fn classic_encode_segment_capacity_uses_coding_style_bound() {
    assert_eq!(super::classic_encode_segment_capacity(0, 16), 1);
    assert_eq!(
        super::classic_encode_segment_capacity(
            super::J2K_CLASSIC_STYLE_SELECTIVE_ARITHMETIC_CODING_BYPASS,
            9,
        ),
        11
    );
    assert_eq!(
        super::classic_encode_segment_capacity(
            super::J2K_CLASSIC_STYLE_SELECTIVE_ARITHMETIC_CODING_BYPASS,
            16,
        ),
        25
    );
    assert_eq!(
        super::classic_encode_segment_capacity(
            super::J2K_CLASSIC_STYLE_TERMINATION_ON_EACH_PASS,
            16,
        ),
        46
    );
}

#[test]
fn two_d_threads_per_group_clamps_empty_pipeline_limits() {
    let threads = j2k_metal_support::two_d_threads_per_group(0, 0);

    assert_eq!((threads.width, threads.height, threads.depth), (1, 1, 1));
}

#[test]
fn one_d_threads_per_group_clamps_empty_pipeline_width() {
    let threads = j2k_metal_support::one_d_threads_per_group(0);

    assert_eq!((threads.width, threads.height, threads.depth), (1, 1, 1));
}

#[test]
fn two_d_threads_per_group_preserves_simd_width_and_derives_height() {
    let threads = j2k_metal_support::two_d_threads_per_group(32, 1024);

    assert_eq!((threads.width, threads.height, threads.depth), (32, 32, 1));
}

#[test]
fn classic_tier1_pass_class_counts_split_bypass_pass_types() {
    let counts = super::classic_tier1_pass_class_counts(
        23,
        super::J2K_CLASSIC_STYLE_SELECTIVE_ARITHMETIC_CODING_BYPASS,
    );

    assert_eq!(counts.arithmetic, 14);
    assert_eq!(counts.raw, 9);
    assert_eq!(counts.cleanup, 8);
    assert_eq!(counts.sigprop, 8);
    assert_eq!(counts.magref, 7);
    assert_eq!(counts.arithmetic_cleanup, 8);
    assert_eq!(counts.arithmetic_sigprop, 3);
    assert_eq!(counts.arithmetic_magref, 3);
    assert_eq!(counts.raw_sigprop, 5);
    assert_eq!(counts.raw_magref, 4);
}

#[test]
fn classic_tier1_pass_class_counts_style0_stays_arithmetic() {
    let counts = super::classic_tier1_pass_class_counts(5, 0);

    assert_eq!(counts.arithmetic, 5);
    assert_eq!(counts.raw, 0);
    assert_eq!(counts.cleanup, 2);
    assert_eq!(counts.sigprop, 2);
    assert_eq!(counts.magref, 1);
    assert_eq!(counts.arithmetic_cleanup, 2);
    assert_eq!(counts.arithmetic_sigprop, 2);
    assert_eq!(counts.arithmetic_magref, 1);
    assert_eq!(counts.raw_sigprop, 0);
    assert_eq!(counts.raw_magref, 0);
}

#[test]
fn classic_tier1_scan_estimates_multiply_passes_by_block_area() {
    let pass_counts = super::classic_tier1_pass_class_counts(
        23,
        super::J2K_CLASSIC_STYLE_SELECTIVE_ARITHMETIC_CODING_BYPASS,
    );
    let mut stats = super::J2kResidentEncodeStageStats::default();

    super::accumulate_classic_tier1_scan_estimates(&mut stats, pass_counts, 32 * 32);

    assert_eq!(stats.tier1_full_scan_coeff_visit_count_total, 23 * 1024);
    assert_eq!(
        stats.tier1_arithmetic_scan_coeff_visit_count_total,
        14 * 1024
    );
    assert_eq!(stats.tier1_raw_scan_coeff_visit_count_total, 9 * 1024);
    assert_eq!(stats.tier1_cleanup_scan_coeff_visit_count_total, 8 * 1024);
    assert_eq!(stats.tier1_sigprop_scan_coeff_visit_count_total, 8 * 1024);
    assert_eq!(stats.tier1_magref_scan_coeff_visit_count_total, 7 * 1024);
    assert_eq!(stats.max_tier1_full_scan_coeff_visits_per_block, 23 * 1024);
}

#[test]
fn classic_packet_output_capacity_uses_raw_sample_bound_when_smaller() {
    let codestream = super::J2kLosslessCodestreamAssemblyJob {
        width: 512,
        height: 512,
        num_components: 3,
        bit_depth: 8,
        signed: false,
        num_decomposition_levels: 3,
        use_mct: true,
        guard_bits: 2,
        code_block_width_exp: 4,
        code_block_height_exp: 4,
        progression_order: j2k_native::EncodeProgressionOrder::Lrcp,
        write_tlm: false,
        block_coding_mode: super::J2kLosslessCodestreamBlockCodingMode::Classic,
    };
    let header_capacity = 1024 * 256 + 4096;
    let conservative_capacity = 12 * 1024 * 1024;
    let packet_descriptor_count = 3;

    let capacity = super::classic_packet_output_capacity(
        conservative_capacity,
        header_capacity,
        packet_descriptor_count,
        codestream,
    )
    .expect("classic packet capacity");

    let raw_bytes = 512 * 512 * 3;
    let descriptor_slack = packet_descriptor_count * 256;
    assert_eq!(
        capacity,
        raw_bytes + header_capacity + descriptor_slack + 64 * 1024
    );

    let tiny_tier1_capacity = 4096;
    let clamped = super::classic_packet_output_capacity(
        tiny_tier1_capacity,
        header_capacity,
        packet_descriptor_count,
        codestream,
    )
    .expect("classic packet capacity");
    let conservative_packet_capacity =
        tiny_tier1_capacity + header_capacity * packet_descriptor_count + 1024;
    assert_eq!(clamped, conservative_packet_capacity);
}

#[test]
fn ht_encode_output_capacity_scales_with_code_block_area() {
    let max_block = super::ht_encode_output_capacity(128, 128).expect("max HT output capacity");
    assert_eq!(max_block, super::J2K_HT_ENCODE_BASE_OUTPUT_SIZE);

    let smaller_block =
        super::ht_encode_output_capacity(32, 32).expect("scaled HT output capacity");
    assert!(smaller_block < max_block / 2);
    assert!(smaller_block >= 8192);
}

#[test]
fn classic_encode_pipeline_kind_prefers_style0_32_for_resident_jobs() {
    let jobs = [super::J2kClassicEncodeBatchJob {
        width: 32,
        height: 32,
        style_flags: 0,
        ..super::J2kClassicEncodeBatchJob::default()
    }];

    assert_eq!(
        super::classic_encode_code_blocks_pipeline_kind(&jobs),
        super::J2kClassicEncodePipelineKind::Style0_32
    );
}

#[test]
fn classic_encode_pipeline_kind_prefers_bypass_32_for_resident_jobs() {
    let jobs = [super::J2kClassicEncodeBatchJob {
        width: 32,
        height: 32,
        style_flags: super::J2K_CLASSIC_STYLE_SELECTIVE_ARITHMETIC_CODING_BYPASS,
        total_bitplanes: 31,
        ..super::J2kClassicEncodeBatchJob::default()
    }];

    assert_eq!(
        super::classic_encode_code_blocks_pipeline_kind(&jobs),
        super::J2kClassicEncodePipelineKind::Bypass32
    );
}

#[test]
fn classic_encode_pipeline_kind_prefers_bypass_u16_32_for_low_bitplane_resident_jobs() {
    let jobs = [super::J2kClassicEncodeBatchJob {
        width: 32,
        height: 32,
        style_flags: super::J2K_CLASSIC_STYLE_SELECTIVE_ARITHMETIC_CODING_BYPASS,
        total_bitplanes: 16,
        ..super::J2kClassicEncodeBatchJob::default()
    }];

    assert_eq!(
        super::classic_encode_code_blocks_pipeline_kind(&jobs),
        super::J2kClassicEncodePipelineKind::BypassU16_32
    );
}

#[test]
fn with_runtime_for_device_scopes_runtime_to_requested_device() {
    let Some(device) = Device::system_default() else {
        return;
    };

    let runtime_device =
        with_runtime_for_device(&device, |runtime| Ok(runtime.device.as_ptr() as usize))
            .expect("Metal runtime");

    assert_eq!(runtime_device, device.as_ptr() as usize);
}

#[test]
fn runtime_reuses_recycled_shared_buffers() -> Result<(), crate::Error> {
    let Some(device) = Device::system_default() else {
        return Ok(());
    };
    let runtime = MetalRuntime::new_with_device(&device).expect("Metal runtime");

    reset_shared_buffer_pool_misses_for_test();
    let first = runtime.take_shared_buffer(64)?;
    runtime.recycle_shared_buffer(64, first)?;
    let _second = runtime.take_shared_buffer(64)?;

    assert_eq!(
        shared_buffer_pool_misses_for_test(),
        1,
        "recycled shared metadata buffers should be reused instead of allocating again"
    );
    Ok(())
}

#[test]
fn j2k_pack_selects_specialized_kernels_for_wsi_formats() {
    assert_eq!(
        j2k_pack_kernel_name_for(&NativeColorSpace::Gray, false, 1, PixelFormat::Gray8),
        Some("j2k_pack_gray8")
    );
    assert_eq!(
        j2k_pack_kernel_name_for(&NativeColorSpace::RGB, false, 3, PixelFormat::Rgb8),
        Some("j2k_pack_rgb8")
    );
    assert_eq!(
        j2k_pack_kernel_name_for(&NativeColorSpace::RGB, false, 3, PixelFormat::Rgba8),
        Some("j2k_pack_rgb_opaque_rgba8")
    );
    assert_eq!(
        j2k_pack_kernel_name_for(&NativeColorSpace::RGB, true, 4, PixelFormat::Rgba8),
        Some("j2k_pack_rgba8")
    );
    assert_eq!(
        j2k_pack_kernel_name_for(&NativeColorSpace::Gray, false, 1, PixelFormat::Gray16),
        Some("j2k_pack_gray16")
    );
    assert_eq!(
        j2k_pack_kernel_name_for(&NativeColorSpace::RGB, false, 3, PixelFormat::Rgb16),
        Some("j2k_pack_rgb16")
    );
    assert_eq!(
        j2k_pack_kernel_name_for(&NativeColorSpace::RGB, true, 4, PixelFormat::Rgb16),
        None,
        "RGBA input must not silently drop alpha when packing RGB16"
    );
}

#[test]
fn j2k_pack_precomputes_scale_factors_on_cpu() {
    let (max_values, u8_scales, u16_scales) = j2k_pack_scale_arrays([8, 12, 16, 0]);

    assert_f32_near(max_values[0], 255.0);
    assert_f32_near(max_values[1], 4095.0);
    assert_f32_near(max_values[2], 65_535.0);
    assert_f32_near(max_values[3], 1.0);
    assert_f32_near(u8_scales[0], 1.0);
    assert_f32_near(u8_scales[1], 255.0 / 4095.0);
    assert_f32_near(u16_scales[0], 257.0);
    assert_f32_near(u16_scales[1], 1.0);
    assert_f32_near(u16_scales[2], 1.0);
    assert_f32_near(u16_scales[3], 65_535.0);
}

fn assert_f32_near(actual: f32, expected: f32) {
    assert!(
        (actual - expected).abs() <= f32::EPSILON,
        "expected {actual} to be within f32 epsilon of {expected}"
    );
}

#[test]
fn scaled_htj2k_decode_runs_through_metal_compute_path() {
    let pixels: Vec<u8> = (0..16).collect();
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 4, 4, 1, 8, false, &options).expect("encode ht gray8");

    let image = Image::new(
        &bytes,
        &DecodeSettings {
            target_resolution: Some((2, 2)),
            ..DecodeSettings::default()
        },
    )
    .expect("image");
    let host = image.decode().expect("host scaled decode");

    let surface = decode_scaled_to_surface(
        &bytes,
        (4, 4),
        PixelFormat::Gray8,
        j2k_core::Downscale::Half,
    )
    .expect("metal scaled decode");
    assert_eq!(surface.as_bytes(), host.as_slice());
}

#[test]
fn prepared_ht_direct_plan_groups_cleanup_subbands_before_idwt() {
    let pixels: Vec<u8> = (0..64).collect();
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 8, 8, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let ht_subband_steps = plan
        .steps
        .iter()
        .filter(|step| matches!(step, j2k_native::J2kDirectGrayscaleStep::HtSubBand(_)))
        .count();
    assert!(
        ht_subband_steps > 1,
        "fixture must exercise multiple HT sub-band cleanup steps"
    );

    let prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    assert_eq!(
        prepared.ht_groups.len(),
        1,
        "single-tile HTJ2K direct decode should group adjacent HT sub-bands into one cleanup dispatch"
    );
    assert_eq!(prepared.ht_groups[0].members.len(), ht_subband_steps);
    assert!(matches!(
        prepared.steps[prepared.ht_groups[0].start_step],
        PreparedDirectGrayscaleStep::HtSubBand(_)
    ));
}

#[test]
fn grouped_ht_direct_plan_uses_one_group_coded_arena() {
    let pixels: Vec<u8> = (0..64).collect();
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 8, 8, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");

    reset_direct_tier1_input_buffer_prepares_for_test();
    let prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    assert_eq!(
        prepared.ht_groups.len(),
        1,
        "fixture must exercise one grouped HT dispatch"
    );
    let group = &prepared.ht_groups[0];
    assert!(!group.coded_arena.data.is_empty());
    assert_eq!(
        direct_tier1_input_buffer_prepares_for_test(),
        2,
        "grouped HT dispatch should prepare one coded arena buffer and one job buffer"
    );

    for step in &prepared.steps[group.start_step..group.end_step] {
        let PreparedDirectGrayscaleStep::HtSubBand(sub_band) = step else {
            panic!("HT group should only span HT sub-band steps");
        };
        assert!(sub_band.coded_buffer.is_none());
        assert!(sub_band.jobs_buffer.is_none());
    }
}

#[test]
fn prepared_classic_sub_band_decodes_on_cpu_for_hybrid_upload() {
    let pixels: Vec<u8> = (0..64).collect();
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes = encode(&pixels, 8, 8, 1, 8, false, &options).expect("encode classic gray8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    let native_sub_band = first_native_classic_sub_band(&plan);
    let prepared_sub_band = first_prepared_classic_sub_band(&prepared);

    let expected = decode_native_classic_sub_band(native_sub_band);
    let actual =
        decode_prepared_classic_sub_band_on_cpu(prepared_sub_band).expect("prepared CPU decode");

    assert_eq!(actual, expected);
}

#[test]
fn cpu_upload_color_prepare_skips_tier1_metal_input_buffers() {
    if Device::system_default().is_none() {
        eprintln!("skipping CPUUpload prepare test: no Metal device");
        return;
    }

    let pixels = j2k_test_support::gradient_u8(32, 32, 3);
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 2,
        ..EncodeOptions::default()
    };
    let bytes = encode(&pixels, 32, 32, 3, 8, false, &options).expect("encode rgb8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_color_plan_with_context(&mut context)
        .expect("direct color plan");

    reset_direct_tier1_input_buffer_prepares_for_test();
    let metal_prepared = prepare_direct_color_plan(&plan).expect("Metal prepared color plan");
    assert_eq!(metal_prepared.component_plans.len(), 3);
    assert!(
        direct_tier1_input_buffer_prepares_for_test() > 0,
        "normal Metal preparation should build Tier-1 input buffers"
    );

    reset_direct_tier1_input_buffer_prepares_for_test();
    let cpu_upload_prepared =
        prepare_direct_color_plan_for_cpu_upload(&plan).expect("CPUUpload prepared color plan");
    assert_eq!(cpu_upload_prepared.component_plans.len(), 3);
    assert_eq!(
        direct_tier1_input_buffer_prepares_for_test(),
        0,
        "CPUUpload preparation should keep coded Tier-1 payloads on CPU and skip Metal input buffers"
    );
}

fn first_native_classic_sub_band(
    plan: &j2k_native::J2kDirectGrayscalePlan,
) -> &J2kOwnedSubBandPlan {
    plan.steps
        .iter()
        .find_map(|step| match step {
            NativeDirectGrayscaleStep::ClassicSubBand(sub_band) => Some(sub_band),
            _ => None,
        })
        .expect("classic sub-band step")
}

fn first_prepared_classic_sub_band(
    plan: &super::PreparedDirectGrayscalePlan,
) -> &PreparedClassicSubBand {
    plan.steps
        .iter()
        .find_map(|step| match step {
            PreparedDirectGrayscaleStep::ClassicSubBand(sub_band) => Some(sub_band),
            _ => None,
        })
        .expect("prepared classic sub-band step")
}

fn decode_native_classic_sub_band(plan: &J2kOwnedSubBandPlan) -> Vec<f32> {
    let mut output = vec![0.0_f32; plan.width as usize * plan.height as usize];
    let jobs = plan
        .jobs
        .iter()
        .map(|job| J2kCodeBlockBatchJob {
            output_x: job.output_x,
            output_y: job.output_y,
            code_block: native_classic_job(job),
        })
        .collect::<Vec<_>>();
    decode_j2k_sub_band_scalar(
        J2kSubBandDecodeJob {
            width: plan.width,
            height: plan.height,
            jobs: &jobs,
        },
        &mut output,
    )
    .expect("native scalar classic sub-band decode");
    output
}

fn native_classic_job(job: &J2kOwnedCodeBlockBatchJob) -> J2kCodeBlockDecodeJob<'_> {
    J2kCodeBlockDecodeJob {
        data: &job.data,
        segments: &job.segments,
        width: job.width,
        height: job.height,
        output_stride: job.output_stride,
        missing_bit_planes: job.missing_bit_planes,
        number_of_coding_passes: job.number_of_coding_passes,
        total_bitplanes: job.total_bitplanes,
        roi_shift: job.roi_shift,
        sub_band_type: job.sub_band_type,
        style: job.style,
        strict: job.strict,
        dequantization_step: job.dequantization_step,
    }
}

#[test]
fn prepared_ht_direct_plan_encodes_full_decode_in_one_compute_encoder() {
    let pixels: Vec<u8> = (0..64).collect();
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 8, 8, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");

    assert_eq!(
        prepared_direct_grayscale_plan_compute_encoder_count(&prepared, PixelFormat::Gray8),
        1,
        "prepared single-tile direct decode should keep cleanup, IDWT, and grayscale store in one compute encoder"
    );
}

#[test]
fn repeated_prepared_ht_direct_plan_groups_cleanup_subbands_before_idwt() {
    let pixels: Vec<u8> = (0..64).collect();
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 8, 8, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let ht_subband_steps = plan
        .steps
        .iter()
        .filter(|step| matches!(step, j2k_native::J2kDirectGrayscaleStep::HtSubBand(_)))
        .count();
    assert!(
        ht_subband_steps > 1,
        "fixture must exercise multiple HT sub-band cleanup steps"
    );

    let prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    assert_eq!(
        prepared_repeated_direct_ht_cleanup_dispatch_count(&prepared),
        1,
        "repeated HTJ2K WSI tile batches should group adjacent sub-band cleanups like the single-tile path"
    );
}

#[test]
fn distinct_prepared_ht_direct_plans_support_stacked_component_batch() {
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes_a = encode_htj2k(&(0..64).collect::<Vec<u8>>(), 8, 8, 1, 8, false, &options)
        .expect("encode first ht gray8");
    let bytes_b = encode_htj2k(
        &(0..64).rev().collect::<Vec<u8>>(),
        8,
        8,
        1,
        8,
        false,
        &options,
    )
    .expect("encode second ht gray8");
    let image_a = Image::new(&bytes_a, &DecodeSettings::default()).expect("first image");
    let image_b = Image::new(&bytes_b, &DecodeSettings::default()).expect("second image");
    let mut context_a = DecoderContext::default();
    let mut context_b = DecoderContext::default();
    let plan_a = image_a
        .build_direct_grayscale_plan_with_context(&mut context_a)
        .expect("first direct plan");
    let plan_b = image_b
        .build_direct_grayscale_plan_with_context(&mut context_b)
        .expect("second direct plan");
    let prepared_a = prepare_direct_grayscale_plan(&plan_a).expect("first prepared plan");
    let prepared_b = prepare_direct_grayscale_plan(&plan_b).expect("second prepared plan");

    assert!(
        supports_stacked_direct_component_plane_batch(&[&prepared_a, &prepared_b]),
        "distinct same-shape HTJ2K grayscale plans should be eligible for one stacked batch graph"
    );
}

#[test]
fn hybrid_rgb8_batch_uses_stacked_component_graph() {
    let pixels = j2k_test_support::gradient_u8(32, 32, 3);
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 2,
        ..EncodeOptions::default()
    };
    let bytes = encode(&pixels, 32, 32, 3, 8, false, &options).expect("encode rgb8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_color_plan_with_context(&mut context)
        .expect("direct color plan");
    let prepared = Arc::new(prepare_direct_color_plan(&plan).expect("prepared color plan"));
    let _guard = HYBRID_COUNTER_TEST_LOCK
        .lock()
        .expect("hybrid counter lock");
    reset_hybrid_stacked_component_batches_for_test();
    reset_hybrid_cpu_decode_worker_inits_for_test();

    let surfaces = execute_hybrid_cpu_tier1_direct_color_plan_batch(
        &[prepared.clone(), prepared],
        PixelFormat::Rgb8,
    )
    .expect("hybrid RGB8 batch");

    assert_eq!(surfaces.len(), 2);
    assert!(
        hybrid_stacked_component_batches_for_test() >= 3,
        "hybrid RGB batch should stack each component plane instead of encoding each tile/component serially"
    );
    assert!(
        hybrid_cpu_decode_worker_inits_for_test() > 0,
        "hybrid RGB batch should use worker-local CPU decode scratch instead of per-input decode/flatten"
    );
}

#[test]
fn hybrid_rgb8_repeated_batch_decodes_shared_tier1_inputs_once() {
    let pixels = j2k_test_support::gradient_u8(32, 32, 3);
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 2,
        ..EncodeOptions::default()
    };
    let bytes = encode(&pixels, 32, 32, 3, 8, false, &options).expect("encode rgb8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_color_plan_with_context(&mut context)
        .expect("direct color plan");
    let prepared = Arc::new(prepare_direct_color_plan(&plan).expect("prepared color plan"));
    let unique_tier1_inputs = prepared_direct_color_tier1_input_count(&prepared);
    assert!(
        unique_tier1_inputs > 0,
        "fixture should have Tier-1 inputs to decode"
    );
    let _guard = HYBRID_COUNTER_TEST_LOCK
        .lock()
        .expect("hybrid counter lock");
    reset_hybrid_cpu_decode_inputs_for_test();

    let surfaces = execute_hybrid_cpu_tier1_direct_color_plan_batch(
        &[prepared.clone(), prepared.clone(), prepared],
        PixelFormat::Rgb8,
    )
    .expect("hybrid repeated RGB8 batch");

    assert_eq!(surfaces.len(), 3);
    assert_eq!(
        hybrid_cpu_decode_inputs_for_test(),
        unique_tier1_inputs,
        "repeated RGB hybrid batches should decode each shared coefficient input once, not once per output surface"
    );
}

#[test]
fn hybrid_rgb8_reused_plan_caches_cpu_tier1_inputs_across_calls() {
    let pixels = j2k_test_support::gradient_u8(32, 32, 3);
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 2,
        ..EncodeOptions::default()
    };
    let bytes = encode(&pixels, 32, 32, 3, 8, false, &options).expect("encode rgb8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_color_plan_with_context(&mut context)
        .expect("direct color plan");
    let prepared = Arc::new(prepare_direct_color_plan(&plan).expect("prepared color plan"));
    let unique_tier1_inputs = prepared_direct_color_tier1_input_count(&prepared);
    assert!(
        unique_tier1_inputs > 0,
        "fixture should have Tier-1 inputs to decode"
    );
    let _guard = HYBRID_COUNTER_TEST_LOCK
        .lock()
        .expect("hybrid counter lock");
    reset_hybrid_cpu_decode_inputs_for_test();

    for _ in 0..2 {
        let surfaces = execute_hybrid_cpu_tier1_direct_color_plan_batch(
            &[prepared.clone(), prepared.clone()],
            PixelFormat::Rgb8,
        )
        .expect("hybrid repeated RGB8 batch");
        assert_eq!(surfaces.len(), 2);
    }

    assert_eq!(
        hybrid_cpu_decode_inputs_for_test(),
        unique_tier1_inputs,
        "reusing the same RGB hybrid plan across calls should reuse decoded CPU Tier-1 coefficients"
    );
}

#[test]
fn hybrid_rgb8_repeated_batch_decodes_once_and_blits_distinct_outputs() {
    let pixels = j2k_test_support::gradient_u8(32, 32, 3);
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 2,
        ..EncodeOptions::default()
    };
    let bytes = encode(&pixels, 32, 32, 3, 8, false, &options).expect("encode rgb8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_color_plan_with_context(&mut context)
        .expect("direct color plan");
    let prepared = Arc::new(prepare_direct_color_plan(&plan).expect("prepared color plan"));
    let _guard = HYBRID_COUNTER_TEST_LOCK
        .lock()
        .expect("hybrid counter lock");
    reset_hybrid_repeated_output_blits_for_test();

    let surfaces = execute_hybrid_cpu_tier1_direct_color_plan_batch(
        &[
            prepared.clone(),
            prepared.clone(),
            prepared.clone(),
            prepared,
        ],
        PixelFormat::Rgb8,
    )
    .expect("hybrid repeated RGB8 batch");

    assert_eq!(surfaces.len(), 4);
    let surface_bytes = surfaces[0].as_bytes().len();
    let offsets = surfaces
        .iter()
        .map(|surface| surface.metal_buffer().expect("resident Metal surface").1)
        .collect::<Vec<_>>();
    assert_eq!(
        offsets,
        (0..surfaces.len())
            .map(|index| index * surface_bytes)
            .collect::<Vec<_>>(),
        "repeated outputs must retain distinct Metal buffer offsets"
    );
    for surface in &surfaces[1..] {
        assert_eq!(
            surface.as_bytes(),
            surfaces[0].as_bytes(),
            "repeated outputs should remain byte-identical"
        );
    }
    assert_eq!(
        hybrid_repeated_output_blits_for_test(),
        2,
        "repeated RGB hybrid batches should duplicate packed output surfaces with logarithmic Metal blit ranges"
    );
}

#[test]
fn hybrid_rgb8_distinct_batch_keeps_tier1_inputs_separate() {
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 2,
        ..EncodeOptions::default()
    };
    let bytes_a = encode(
        &j2k_test_support::gradient_variant_u8(32, 32, 3, 0),
        32,
        32,
        3,
        8,
        false,
        &options,
    )
    .expect("encode first rgb8");
    let bytes_b = encode(
        &j2k_test_support::gradient_variant_u8(32, 32, 3, 7),
        32,
        32,
        3,
        8,
        false,
        &options,
    )
    .expect("encode second rgb8");
    let image_a = Image::new(&bytes_a, &DecodeSettings::default()).expect("first image");
    let image_b = Image::new(&bytes_b, &DecodeSettings::default()).expect("second image");
    let mut context_a = DecoderContext::default();
    let mut context_b = DecoderContext::default();
    let plan_a = image_a
        .build_direct_color_plan_with_context(&mut context_a)
        .expect("first direct color plan");
    let plan_b = image_b
        .build_direct_color_plan_with_context(&mut context_b)
        .expect("second direct color plan");
    let prepared_a = Arc::new(prepare_direct_color_plan(&plan_a).expect("first prepared"));
    let prepared_b = Arc::new(prepare_direct_color_plan(&plan_b).expect("second prepared"));
    let expected_inputs = prepared_direct_color_tier1_input_count(&prepared_a)
        + prepared_direct_color_tier1_input_count(&prepared_b);
    let _guard = HYBRID_COUNTER_TEST_LOCK
        .lock()
        .expect("hybrid counter lock");
    reset_hybrid_cpu_decode_inputs_for_test();

    let surfaces = execute_hybrid_cpu_tier1_direct_color_plan_batch(
        &[prepared_a, prepared_b],
        PixelFormat::Rgb8,
    )
    .expect("hybrid distinct RGB8 batch");

    assert_eq!(surfaces.len(), 2);
    assert_ne!(
        surfaces[0].as_bytes(),
        surfaces[1].as_bytes(),
        "distinct RGB inputs must not reuse the first tile's decoded coefficients"
    );
    assert_eq!(
        hybrid_cpu_decode_inputs_for_test(),
        expected_inputs,
        "distinct RGB hybrid batches should decode each tile's own Tier-1 inputs"
    );
}

#[test]
fn hybrid_rgb8_flattened_cpu_tier1_batch_uses_one_decode_queue() {
    let pixels_a = j2k_test_support::gradient_variant_u8(32, 32, 3, 0);
    let pixels_b = j2k_test_support::gradient_variant_u8(32, 32, 3, 11);
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 2,
        ..EncodeOptions::default()
    };
    let bytes_a = encode(&pixels_a, 32, 32, 3, 8, false, &options).expect("encode first rgb8");
    let bytes_b = encode(&pixels_b, 32, 32, 3, 8, false, &options).expect("encode second rgb8");
    let image_a = Image::new(&bytes_a, &DecodeSettings::default()).expect("first image");
    let image_b = Image::new(&bytes_b, &DecodeSettings::default()).expect("second image");
    let mut context_a = DecoderContext::default();
    let mut context_b = DecoderContext::default();
    let plan_a = image_a
        .build_direct_color_plan_with_context(&mut context_a)
        .expect("first direct color plan");
    let plan_b = image_b
        .build_direct_color_plan_with_context(&mut context_b)
        .expect("second direct color plan");
    let prepared_a = Arc::new(prepare_direct_color_plan(&plan_a).expect("first prepared"));
    let prepared_b = Arc::new(prepare_direct_color_plan(&plan_b).expect("second prepared"));
    let expected_inputs = prepared_direct_color_tier1_input_count(&prepared_a)
        + prepared_direct_color_tier1_input_count(&prepared_b);
    let _guard = HYBRID_COUNTER_TEST_LOCK
        .lock()
        .expect("hybrid counter lock");
    reset_hybrid_cpu_decode_inputs_for_test();
    reset_flattened_hybrid_cpu_decode_batches_for_test();

    let surfaces = execute_flattened_hybrid_cpu_tier1_direct_color_plan_batch_for_test(
        &[prepared_a, prepared_b],
        PixelFormat::Rgb8,
    )
    .expect("flattened hybrid distinct RGB8 batch");

    assert_eq!(surfaces.len(), 2);
    assert_ne!(
        surfaces[0].as_bytes(),
        surfaces[1].as_bytes(),
        "flattened distinct RGB hybrid batches must keep each tile's coefficients separate"
    );
    assert_eq!(
        hybrid_cpu_decode_inputs_for_test(),
        expected_inputs,
        "flattened RGB hybrid batches should still decode every distinct Tier-1 input"
    );
    assert_eq!(
        flattened_hybrid_cpu_decode_batches_for_test(),
        1,
        "flattened RGB hybrid should collect Tier-1 work into one CPU decode queue"
    );
}

#[test]
fn flattened_cpu_tier1_default_gate_targets_large_distinct_batches_only() {
    fn color_plan(width: u32, height: u32) -> Arc<PreparedDirectColorPlan> {
        Arc::new(PreparedDirectColorPlan {
            dimensions: (width, height),
            bit_depths: [8, 8, 8],
            mct: true,
            transform: J2kWaveletTransform::Reversible53,
            component_plans: Vec::new(),
        })
    }

    let repeated = vec![color_plan(1024, 1024); 16];
    assert!(
        !should_flatten_hybrid_cpu_tier1_color_batch(&repeated),
        "repeated RGB batches already win through shared Tier-1 decode and should not use the flattened distinct scheduler"
    );

    let small_distinct = (0..16).map(|_| color_plan(256, 256)).collect::<Vec<_>>();
    assert!(
        !should_flatten_hybrid_cpu_tier1_color_batch(&small_distinct),
        "small RGB batches measured slower with flattened Tier-1 and should stay on the grouped path"
    );

    let large_distinct = (0..16).map(|_| color_plan(1024, 1024)).collect::<Vec<_>>();
    assert!(
        should_flatten_hybrid_cpu_tier1_color_batch(&large_distinct),
        "large distinct RGB explicit hybrid batches measured faster with flattened Tier-1"
    );
}

#[test]
fn hybrid_cpu_decode_worker_count_allows_two_way_small_batch_parallelism() {
    let available = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
    if available < 2 {
        return;
    }

    assert_eq!(
        hybrid_cpu_decode_worker_count(2),
        2,
        "two independent hybrid CPU Tier-1 inputs should be able to use two workers"
    );
}

#[test]
fn cropped_region_scaled_ht_direct_plan_prunes_codeblocks_outside_output_roi() {
    let mut pixels = Vec::with_capacity(256 * 256);
    for y in 0..256u32 {
        for x in 0..256u32 {
            pixels.push(((x * 3 + y * 5) & 0xff) as u8);
        }
    }
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 3,
        code_block_width_exp: 0,
        code_block_height_exp: 0,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 256, 256, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(
        &bytes,
        &DecodeSettings {
            target_resolution: Some((64, 64)),
            ..DecodeSettings::default()
        },
    )
    .expect("scaled image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let mut prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    let full_jobs = prepared_direct_grayscale_ht_job_count(&prepared);
    assert!(
        full_jobs > 8,
        "fixture should have multiple HT code-block jobs"
    );

    crop_prepared_direct_grayscale_plan_to_output_region(
        &mut prepared,
        j2k_core::Rect {
            x: 24,
            y: 24,
            w: 8,
            h: 8,
        },
    )
    .expect("crop direct plan");
    let cropped_jobs = prepared_direct_grayscale_ht_job_count(&prepared);

    assert!(
        cropped_jobs > 0 && cropped_jobs < full_jobs,
        "cropped ROI should prune HT code-block jobs; full={full_jobs}, cropped={cropped_jobs}"
    );
}

#[test]
fn cropped_region_scaled_ht_direct_plan_compacts_coded_payloads() {
    let mut pixels = Vec::with_capacity(256 * 256);
    for y in 0..256u32 {
        for x in 0..256u32 {
            pixels.push(((x * 3 + y * 5) & 0xff) as u8);
        }
    }
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 3,
        code_block_width_exp: 0,
        code_block_height_exp: 0,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 256, 256, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(
        &bytes,
        &DecodeSettings {
            target_resolution: Some((64, 64)),
            ..DecodeSettings::default()
        },
    )
    .expect("scaled image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let mut prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    let full_bytes = prepared_direct_grayscale_ht_coded_byte_count(&prepared);
    assert!(full_bytes > 0, "fixture should carry HT coded payloads");

    crop_prepared_direct_grayscale_plan_to_output_region(
        &mut prepared,
        j2k_core::Rect {
            x: 24,
            y: 24,
            w: 8,
            h: 8,
        },
    )
    .expect("crop direct plan");
    let cropped_bytes = prepared_direct_grayscale_ht_coded_byte_count(&prepared);

    assert!(
        cropped_bytes > 0 && cropped_bytes < full_bytes,
        "cropped ROI should compact HT coded bytes; full={full_bytes}, cropped={cropped_bytes}"
    );
}

#[test]
fn cropped_region_scaled_ht_direct_plan_reduces_idwt_output_work() {
    let mut pixels = Vec::with_capacity(128 * 128);
    for y in 0..128u32 {
        for x in 0..128u32 {
            pixels.push(((x * 3 + y * 5) & 0xff) as u8);
        }
    }
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 3,
        code_block_width_exp: 0,
        code_block_height_exp: 0,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 128, 128, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(
        &bytes,
        &DecodeSettings {
            target_resolution: Some((32, 32)),
            ..DecodeSettings::default()
        },
    )
    .expect("scaled image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let mut prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    let full_samples = prepared_direct_grayscale_idwt_output_sample_count(&prepared);

    crop_prepared_direct_grayscale_plan_to_output_region(
        &mut prepared,
        j2k_core::Rect {
            x: 10,
            y: 10,
            w: 4,
            h: 4,
        },
    )
    .expect("crop direct plan");
    let cropped_samples = prepared_direct_grayscale_idwt_output_sample_count(&prepared);

    assert!(
        cropped_samples > 0 && cropped_samples < full_samples,
        "cropped ROI should reduce IDWT output work; full={full_samples}, cropped={cropped_samples}"
    );
}

#[test]
fn cropped_region_ht_direct_plan_keeps_idwt_windows_bounded() {
    let mut pixels = Vec::with_capacity(256 * 256);
    for y in 0..256u32 {
        for x in 0..256u32 {
            pixels.push(((x * 3 + y * 5) & 0xff) as u8);
        }
    }
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 3,
        code_block_width_exp: 0,
        code_block_height_exp: 0,
        ..EncodeOptions::default()
    };
    let bytes = encode_htj2k(&pixels, 256, 256, 1, 8, false, &options).expect("encode ht gray8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let mut prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    let idwt_levels = prepared_direct_grayscale_idwt_full_and_prepared_lens(&prepared);
    assert!(
        idwt_levels.len() >= 3,
        "fixture should exercise a multi-level IDWT plan"
    );

    crop_prepared_direct_grayscale_plan_to_output_region(
        &mut prepared,
        j2k_core::Rect {
            x: 112,
            y: 112,
            w: 32,
            h: 32,
        },
    )
    .expect("crop direct plan");
    let cropped_idwt_levels = prepared_direct_grayscale_idwt_full_and_prepared_lens(&prepared);

    assert_eq!(cropped_idwt_levels.len(), idwt_levels.len());
    for (level_idx, (full_len, cropped_len)) in cropped_idwt_levels.iter().copied().enumerate() {
        assert!(
            cropped_len > 0 && cropped_len <= full_len,
            "cropped ROI should keep IDWT level {level_idx} bounded; full={full_len}, cropped={cropped_len}"
        );
    }
    assert!(
        cropped_idwt_levels
            .iter()
            .any(|(full_len, cropped_len)| cropped_len < full_len),
        "cropped ROI should reduce at least one IDWT level"
    );
}

fn prepared_direct_grayscale_ht_job_count(plan: &super::PreparedDirectGrayscalePlan) -> usize {
    plan.steps
        .iter()
        .map(|step| match step {
            PreparedDirectGrayscaleStep::HtSubBand(sub_band) => sub_band.jobs.len(),
            _ => 0,
        })
        .sum()
}

fn prepared_direct_grayscale_ht_coded_byte_count(
    plan: &super::PreparedDirectGrayscalePlan,
) -> usize {
    plan.steps
        .iter()
        .map(|step| match step {
            PreparedDirectGrayscaleStep::HtSubBand(sub_band) => sub_band.coded_data.len(),
            _ => 0,
        })
        .sum()
}

fn prepared_direct_grayscale_idwt_output_sample_count(
    plan: &super::PreparedDirectGrayscalePlan,
) -> usize {
    plan.steps
        .iter()
        .map(|step| match step {
            PreparedDirectGrayscaleStep::Idwt(idwt) => prepared_idwt_output_len(idwt),
            _ => 0,
        })
        .sum()
}

fn prepared_direct_grayscale_idwt_full_and_prepared_lens(
    plan: &super::PreparedDirectGrayscalePlan,
) -> Vec<(usize, usize)> {
    plan.steps
        .iter()
        .filter_map(|step| match step {
            PreparedDirectGrayscaleStep::Idwt(idwt) => Some((
                idwt.step.rect.width() as usize * idwt.step.rect.height() as usize,
                prepared_idwt_output_len(idwt),
            )),
            _ => None,
        })
        .collect()
}

#[test]
fn prepared_classic_direct_plan_groups_cleanup_subbands_before_idwt() {
    let pixels: Vec<u8> = (0..64).collect();
    let options = EncodeOptions {
        reversible: true,
        num_decomposition_levels: 1,
        ..EncodeOptions::default()
    };
    let bytes = encode(&pixels, 8, 8, 1, 8, false, &options).expect("encode j2k gray8");
    let image = Image::new(&bytes, &DecodeSettings::default()).expect("image");
    let mut context = DecoderContext::default();
    let plan = image
        .build_direct_grayscale_plan_with_context(&mut context)
        .expect("direct grayscale plan");
    let classic_subband_steps = plan
        .steps
        .iter()
        .filter(|step| matches!(step, j2k_native::J2kDirectGrayscaleStep::ClassicSubBand(_)))
        .count();
    assert!(
        classic_subband_steps > 1,
        "fixture must exercise multiple classic sub-band cleanup steps"
    );

    let prepared = prepare_direct_grayscale_plan(&plan).expect("prepared direct plan");
    assert_eq!(
        prepared.classic_groups.len(),
        1,
        "classic J2K direct decode should group adjacent sub-band cleanups before IDWT"
    );
    assert_eq!(
        prepared.classic_groups[0].members.len(),
        classic_subband_steps
    );
    assert!(matches!(
        prepared.steps[prepared.classic_groups[0].start_step],
        PreparedDirectGrayscaleStep::ClassicSubBand(_)
    ));
}

#[test]
fn classic_plain_fast_path_accepts_style_zero_arithmetic_jobs() {
    let jobs = [J2kClassicCleanupBatchJob {
        coded_offset: 0,
        coded_len: 1,
        segment_offset: 0,
        segment_count: 1,
        width: 64,
        height: 64,
        output_stride: 64,
        output_offset: 0,
        missing_msbs: 0,
        total_bitplanes: 8,
        roi_shift: 0,
        number_of_coding_passes: 1,
        sub_band_type: 0,
        style_flags: 0,
        strict: 1,
        dequantization_step: 1.0,
    }];
    let segments = [J2kClassicSegment {
        data_offset: 0,
        data_length: 1,
        start_coding_pass: 0,
        end_coding_pass: 1,
        use_arithmetic: 1,
    }];

    assert!(
        classic_batch_uses_plain_fast_path(&jobs, &segments),
        "style-0 arithmetic-only classic J2K jobs should use the fused plain cleanup/store kernel"
    );
}

#[test]
fn classic_repeated_plain_fast_path_stays_off_for_wsi_batch_size() {
    let jobs = [J2kClassicCleanupBatchJob {
        coded_offset: 0,
        coded_len: 1,
        segment_offset: 0,
        segment_count: 1,
        width: 64,
        height: 64,
        output_stride: 64,
        output_offset: 0,
        missing_msbs: 0,
        total_bitplanes: 8,
        roi_shift: 0,
        number_of_coding_passes: 1,
        sub_band_type: 0,
        style_flags: 0,
        strict: 1,
        dequantization_step: 1.0,
    }];
    let segments = [J2kClassicSegment {
        data_offset: 0,
        data_length: 1,
        start_coding_pass: 0,
        end_coding_pass: 1,
        use_arithmetic: 1,
    }];

    assert!(
        !classic_repeated_uses_plain_fast_path(16, &jobs, &segments),
        "batch-16 WSI classic J2K should keep the device-state cleanup plus separate store path"
    );
}

#[test]
fn repeated_gray_store_detects_contiguous_full_wsi_tiles() {
    let full_tile = J2kRepeatedGrayStoreParams {
        input_width: 1024,
        input_height: 1024,
        source_x: 0,
        source_y: 0,
        copy_width: 1024,
        copy_height: 1024,
        output_width: 1024,
        output_height: 1024,
        output_x: 0,
        output_y: 0,
        addend: 0.0,
        batch_count: 16,
        max_value: 255.0,
        u8_scale: 1.0,
        u16_scale: 257.0,
    };
    assert!(
        repeated_gray_store_is_contiguous_full_surface(full_tile),
        "full repeated grayscale WSI stores should use the contiguous store kernel"
    );

    let windowed = J2kRepeatedGrayStoreParams {
        source_x: 1,
        copy_width: 1023,
        ..full_tile
    };
    assert!(
        !repeated_gray_store_is_contiguous_full_surface(windowed),
        "ROI/windowed repeated grayscale stores must stay on the generic store kernel"
    );
}