pixo 0.4.1

A minimal-dependency, high-performance image compression library
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
//! PNG filtering implementation.
//!
//! PNG uses filtering to improve compression by exploiting correlations
//! between adjacent pixels.

use super::{FilterStrategy, PngOptions};
#[cfg(feature = "parallel")]
use rayon::prelude::*;

#[cfg(feature = "simd")]
use crate::simd;

/// Scratch buffers reused for adaptive filtering to reduce per-row allocations.
struct AdaptiveScratch {
    none: Vec<u8>,
    sub: Vec<u8>,
    up: Vec<u8>,
    avg: Vec<u8>,
    paeth: Vec<u8>,
}

impl AdaptiveScratch {
    fn new(row_len: usize) -> Self {
        Self {
            none: Vec::with_capacity(row_len),
            sub: Vec::with_capacity(row_len),
            up: Vec::with_capacity(row_len),
            avg: Vec::with_capacity(row_len),
            paeth: Vec::with_capacity(row_len),
        }
    }

    fn clear(&mut self) {
        self.none.clear();
        self.sub.clear();
        self.up.clear();
        self.avg.clear();
        self.paeth.clear();
    }
}

/// Filter type bytes as defined by PNG specification.
const FILTER_NONE: u8 = 0;
const FILTER_SUB: u8 = 1;
const FILTER_UP: u8 = 2;
const FILTER_AVERAGE: u8 = 3;
const FILTER_PAETH: u8 = 4;

/// Apply PNG filtering to raw image data.
///
/// Returns filtered data with a filter type byte prepended to each row.
pub fn apply_filters(
    data: &[u8],
    width: u32,
    height: u32,
    bytes_per_pixel: usize,
    options: &PngOptions,
) -> Vec<u8> {
    let row_bytes = width as usize * bytes_per_pixel;
    apply_filters_with_row_bytes(data, width, height, row_bytes, bytes_per_pixel, options)
}

/// Apply PNG filtering with a precomputed row byte length.
pub fn apply_filters_with_row_bytes(
    data: &[u8],
    width: u32,
    height: u32,
    row_bytes: usize,
    bytes_per_pixel: usize,
    options: &PngOptions,
) -> Vec<u8> {
    let filtered_row_size = row_bytes + 1; // +1 for filter type byte
    let zero_row = vec![0u8; row_bytes];

    // Height-aware strategy tweaks.
    let mut strategy = options.filter_strategy;
    let area = (width as usize).saturating_mul(height as usize);
    // For very small images, prefer Sub filter to minimize CPU overhead.
    if area <= 4096
        && matches!(
            strategy,
            FilterStrategy::Adaptive | FilterStrategy::AdaptiveFast | FilterStrategy::Bigrams
        )
    {
        strategy = FilterStrategy::Sub;
    }

    // Note: High-entropy row detection was previously here to skip adaptive
    // filtering for noisy data. However, checking only the first row is not
    // sufficient to determine the optimal strategy for the entire image.
    // For now, we rely on per-row adaptive decisions instead.

    // Parallel path (only for adaptive; other strategies are trivial)
    #[cfg(feature = "parallel")]
    {
        // Parallel gains when rows are numerous; avoid overhead on tiny images.
        if height > 32
            && matches!(
                strategy,
                FilterStrategy::Adaptive | FilterStrategy::AdaptiveFast | FilterStrategy::Bigrams
            )
        {
            return apply_filters_parallel(
                data,
                height as usize,
                row_bytes,
                bytes_per_pixel,
                filtered_row_size,
                strategy,
            );
        }
    }

    // Sequential path
    let height = height as usize;
    debug_assert_eq!(
        data.len(),
        row_bytes.saturating_mul(height),
        "filtered rows expect {} bytes, got {}",
        row_bytes.saturating_mul(height),
        data.len()
    );
    let mut output = Vec::with_capacity(filtered_row_size * height);
    let mut prev_row: &[u8] = &zero_row;
    let mut adaptive_scratch = AdaptiveScratch::new(row_bytes);
    let mut last_filter: u8 = FILTER_PAETH; // default guess for sampled reuse
                                            // Track last used filter to bias adaptive_fast toward recent winner.
    let mut last_adaptive_filter: Option<u8> = None;
    let mut filter_counts = [0usize; 5];

    for y in 0..height {
        let row_start = y * row_bytes;
        let row = &data[row_start..row_start + row_bytes];
        match strategy {
            FilterStrategy::MinSum => {
                minsum_filter(
                    row,
                    if y == 0 { &zero_row[..] } else { prev_row },
                    bytes_per_pixel,
                    &mut output,
                    &mut adaptive_scratch,
                );
                if let Some(&f) = output.last() {
                    last_filter = f;
                }
            }
            FilterStrategy::AdaptiveFast => {
                let base = output.len();
                filter_row(
                    row,
                    if y == 0 { &zero_row[..] } else { prev_row },
                    bytes_per_pixel,
                    // Bias adaptive fast toward the previous winning filter.
                    match last_adaptive_filter {
                        Some(FILTER_SUB) => FilterStrategy::Sub,
                        Some(FILTER_UP) => FilterStrategy::Up,
                        Some(FILTER_PAETH) => FilterStrategy::Paeth,
                        _ => FilterStrategy::AdaptiveFast,
                    },
                    &mut output,
                    &mut adaptive_scratch,
                );
                if let Some(&f) = output.get(base) {
                    last_filter = f;
                    last_adaptive_filter = Some(f);
                }
            }
            _ => {
                let base = output.len();
                filter_row(
                    row,
                    if y == 0 { &zero_row[..] } else { prev_row },
                    bytes_per_pixel,
                    strategy,
                    &mut output,
                    &mut adaptive_scratch,
                );
                if let Some(&f) = output.get(base) {
                    last_filter = f;
                }
            }
        }

        // Update previous row reference
        prev_row = row;

        if options.verbose_filter_log && last_filter <= FILTER_PAETH {
            filter_counts[last_filter as usize] += 1;
        }
    }

    if options.verbose_filter_log {
        eprintln!(
            "PNG filters: strategy={:?}, rows={} counts={{None:{}, Sub:{}, Up:{}, Avg:{}, Paeth:{}}}",
            strategy,
            height as u32,
            filter_counts[0],
            filter_counts[1],
            filter_counts[2],
            filter_counts[3],
            filter_counts[4]
        );
    }

    output
}

/// Sub filter: difference from left pixel.
fn filter_sub(row: &[u8], bpp: usize, output: &mut Vec<u8>) {
    #[cfg(feature = "simd")]
    {
        simd::filter_sub(row, bpp, output);
    }

    #[cfg(not(feature = "simd"))]
    {
        for (i, &byte) in row.iter().enumerate() {
            let left = if i >= bpp { row[i - bpp] } else { 0 };
            output.push(byte.wrapping_sub(left));
        }
    }
}

/// Up filter: difference from above pixel.
fn filter_up(row: &[u8], prev_row: &[u8], output: &mut Vec<u8>) {
    #[cfg(feature = "simd")]
    {
        simd::filter_up(row, prev_row, output);
    }

    #[cfg(not(feature = "simd"))]
    {
        for (i, &byte) in row.iter().enumerate() {
            output.push(byte.wrapping_sub(prev_row[i]));
        }
    }
}

/// Average filter: difference from average of left and above.
fn filter_average(row: &[u8], prev_row: &[u8], bpp: usize, output: &mut Vec<u8>) {
    #[cfg(feature = "simd")]
    {
        simd::filter_average(row, prev_row, bpp, output);
    }

    #[cfg(not(feature = "simd"))]
    {
        for (i, &byte) in row.iter().enumerate() {
            let left = if i >= bpp { row[i - bpp] as u16 } else { 0 };
            let above = prev_row[i] as u16;
            let avg = ((left + above) / 2) as u8;
            output.push(byte.wrapping_sub(avg));
        }
    }
}

/// Paeth filter: difference from Paeth predictor.
fn filter_paeth(row: &[u8], prev_row: &[u8], bpp: usize, output: &mut Vec<u8>) {
    #[cfg(feature = "simd")]
    {
        simd::filter_paeth(row, prev_row, bpp, output);
    }

    #[cfg(not(feature = "simd"))]
    {
        for (i, &byte) in row.iter().enumerate() {
            let left = if i >= bpp { row[i - bpp] } else { 0 };
            let above = prev_row[i];
            let upper_left = if i >= bpp { prev_row[i - bpp] } else { 0 };
            let predicted = paeth_predictor(left, above, upper_left);
            output.push(byte.wrapping_sub(predicted));
        }
    }
}

/// Paeth predictor function.
///
/// Selects the value (a, b, or c) closest to p = a + b - c.
#[allow(dead_code)]
#[inline]
fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
    let a_i = a as i16;
    let b_i = b as i16;
    let c_i = c as i16;

    let p = a_i + b_i - c_i;
    let pa = (p - a_i).abs();
    let pb = (p - b_i).abs();
    let pc = (p - c_i).abs();

    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

/// Adaptive filter selection: try all filters and pick the best.
/// Optimized to track best score incrementally and potentially short-circuit.
fn adaptive_filter(
    row: &[u8],
    prev_row: &[u8],
    bpp: usize,
    output: &mut Vec<u8>,
    scratch: &mut AdaptiveScratch,
) {
    scratch.clear();

    let mut best_filter = FILTER_NONE;
    let mut best_score = u64::MAX;
    // Early-stop threshold: if a candidate beats this, skip remaining filters.
    // Bias toward speed: allow earlier exit.
    let early_stop = (row.len() as u64 / 4).saturating_add(1);

    // Try None filter first
    scratch.none.extend_from_slice(row);
    let score = score_filter(&scratch.none);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_NONE;
        if best_score <= early_stop {
            output.push(best_filter);
            output.extend_from_slice(&scratch.none);
            return;
        }
    }

    // A score of 0 means all zeros - can't do better
    if best_score == 0 {
        output.push(best_filter);
        output.extend_from_slice(&scratch.none);
        return;
    }

    // Try Sub filter
    filter_sub(row, bpp, &mut scratch.sub);
    let score = score_filter(&scratch.sub);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_SUB;
        if best_score == 0 || best_score <= early_stop {
            output.push(best_filter);
            output.extend_from_slice(&scratch.sub);
            return;
        }
    }

    // Try Up filter
    filter_up(row, prev_row, &mut scratch.up);
    let score = score_filter(&scratch.up);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_UP;
        if best_score == 0 || best_score <= early_stop {
            output.push(best_filter);
            output.extend_from_slice(&scratch.up);
            return;
        }
    }

    // Try Average filter
    filter_average(row, prev_row, bpp, &mut scratch.avg);
    let score = score_filter(&scratch.avg);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_AVERAGE;
        if best_score == 0 || best_score <= early_stop {
            output.push(best_filter);
            output.extend_from_slice(&scratch.avg);
            return;
        }
    }

    // Try Paeth filter
    filter_paeth(row, prev_row, bpp, &mut scratch.paeth);
    let score = score_filter(&scratch.paeth);
    if score < best_score {
        best_filter = FILTER_PAETH;
    }

    // Output the best filter result
    output.push(best_filter);
    match best_filter {
        FILTER_NONE => output.extend_from_slice(&scratch.none),
        FILTER_SUB => output.extend_from_slice(&scratch.sub),
        FILTER_UP => output.extend_from_slice(&scratch.up),
        FILTER_AVERAGE => output.extend_from_slice(&scratch.avg),
        FILTER_PAETH => output.extend_from_slice(&scratch.paeth),
        _ => unreachable!(),
    }
}

/// Min-sum filter selection (alias of adaptive using sum of absolute values).
fn minsum_filter(
    row: &[u8],
    prev_row: &[u8],
    bpp: usize,
    output: &mut Vec<u8>,
    scratch: &mut AdaptiveScratch,
) {
    adaptive_filter(row, prev_row, bpp, output, scratch);
}

/// Bigrams filter selection: try all filters and pick the one with fewest distinct bigrams.
///
/// This correlates better with DEFLATE compression than min-sum because DEFLATE's
/// LZ77 algorithm benefits from repeated byte sequences (fewer distinct bigrams).
fn bigrams_filter(
    row: &[u8],
    prev_row: &[u8],
    bpp: usize,
    output: &mut Vec<u8>,
    scratch: &mut AdaptiveScratch,
) {
    scratch.clear();

    let mut best_filter = FILTER_NONE;
    let mut best_score = usize::MAX;

    // Try None filter first
    scratch.none.extend_from_slice(row);
    let score = score_bigrams(&scratch.none);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_NONE;
    }

    // Try Sub filter
    filter_sub(row, bpp, &mut scratch.sub);
    let score = score_bigrams(&scratch.sub);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_SUB;
    }

    // Try Up filter
    filter_up(row, prev_row, &mut scratch.up);
    let score = score_bigrams(&scratch.up);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_UP;
    }

    // Try Average filter
    filter_average(row, prev_row, bpp, &mut scratch.avg);
    let score = score_bigrams(&scratch.avg);
    if score < best_score {
        best_score = score;
        best_filter = FILTER_AVERAGE;
    }

    // Try Paeth filter
    filter_paeth(row, prev_row, bpp, &mut scratch.paeth);
    let score = score_bigrams(&scratch.paeth);
    if score < best_score {
        best_filter = FILTER_PAETH;
    }

    // Output the best filter result
    output.push(best_filter);
    match best_filter {
        FILTER_NONE => output.extend_from_slice(&scratch.none),
        FILTER_SUB => output.extend_from_slice(&scratch.sub),
        FILTER_UP => output.extend_from_slice(&scratch.up),
        FILTER_AVERAGE => output.extend_from_slice(&scratch.avg),
        FILTER_PAETH => output.extend_from_slice(&scratch.paeth),
        _ => unreachable!(),
    }
}

/// Adaptive filtering with a faster heuristic and early cutoffs.
fn adaptive_filter_fast(
    row: &[u8],
    prev_row: &[u8],
    bpp: usize,
    output: &mut Vec<u8>,
    scratch: &mut AdaptiveScratch,
) {
    scratch.clear();

    // Try Sub first (good for high-frequency data)
    filter_sub(row, bpp, &mut scratch.sub);
    let mut best_filter = FILTER_SUB;
    let mut best_score = score_filter(&scratch.sub);

    // Early stop threshold: very low score, stop immediately. Bias toward speed.
    let early_stop = (row.len() as u64 / 8).saturating_add(1);
    if best_score <= early_stop {
        output.push(best_filter);
        output.extend_from_slice(&scratch.sub);
        return;
    }

    // Try Up (good for smooth gradients)
    filter_up(row, prev_row, &mut scratch.up);
    let up_score = score_filter(&scratch.up);
    if up_score < best_score {
        best_score = up_score;
        best_filter = FILTER_UP;
    }
    if best_score <= early_stop {
        output.push(best_filter);
        match best_filter {
            FILTER_SUB => output.extend_from_slice(&scratch.sub),
            FILTER_UP => output.extend_from_slice(&scratch.up),
            _ => {}
        }
        return;
    }

    // Try Paeth last (more expensive)
    filter_paeth(row, prev_row, bpp, &mut scratch.paeth);
    let paeth_score = score_filter(&scratch.paeth);
    if paeth_score < best_score {
        best_filter = FILTER_PAETH;
    }

    output.push(best_filter);
    match best_filter {
        FILTER_SUB => output.extend_from_slice(&scratch.sub),
        FILTER_UP => output.extend_from_slice(&scratch.up),
        FILTER_PAETH => output.extend_from_slice(&scratch.paeth),
        _ => unreachable!(),
    }
}

fn filter_row(
    row: &[u8],
    prev_row: &[u8],
    bpp: usize,
    strategy: FilterStrategy,
    output: &mut Vec<u8>,
    scratch: &mut AdaptiveScratch,
) {
    match strategy {
        FilterStrategy::None => {
            output.push(FILTER_NONE);
            output.extend_from_slice(row);
        }
        FilterStrategy::Sub => {
            output.push(FILTER_SUB);
            filter_sub(row, bpp, output);
        }
        FilterStrategy::Up => {
            output.push(FILTER_UP);
            filter_up(row, prev_row, output);
        }
        FilterStrategy::Average => {
            output.push(FILTER_AVERAGE);
            filter_average(row, prev_row, bpp, output);
        }
        FilterStrategy::Paeth => {
            output.push(FILTER_PAETH);
            filter_paeth(row, prev_row, bpp, output);
        }
        FilterStrategy::MinSum => {
            minsum_filter(row, prev_row, bpp, output, scratch);
        }
        FilterStrategy::Adaptive => {
            adaptive_filter(row, prev_row, bpp, output, scratch);
        }
        FilterStrategy::AdaptiveFast => {
            adaptive_filter_fast(row, prev_row, bpp, output, scratch);
        }
        FilterStrategy::Bigrams => {
            bigrams_filter(row, prev_row, bpp, output, scratch);
        }
    }
}

#[cfg(feature = "parallel")]
fn apply_filters_parallel(
    data: &[u8],
    height: usize,
    row_bytes: usize,
    bpp: usize,
    filtered_row_size: usize,
    strategy: FilterStrategy,
) -> Vec<u8> {
    let zero_row = vec![0u8; row_bytes];
    let mut output = vec![0u8; filtered_row_size * height];

    output
        .par_chunks_mut(filtered_row_size)
        .enumerate()
        .for_each(|(y, out_row)| {
            let row_start = y * row_bytes;
            let row = &data[row_start..row_start + row_bytes];
            let prev = if y == 0 {
                &zero_row[..]
            } else {
                &data[(y - 1) * row_bytes..y * row_bytes]
            };
            let mut scratch = AdaptiveScratch::new(row_bytes);
            let mut row_buf = Vec::with_capacity(filtered_row_size);
            filter_row(row, prev, bpp, strategy, &mut row_buf, &mut scratch);
            debug_assert_eq!(
                row_buf.len(),
                filtered_row_size,
                "filtered row size mismatch"
            );
            out_row.copy_from_slice(&row_buf);
        });

    output
}

/// Score a filtered row using sum of absolute values.
///
/// Lower scores typically result in better compression.
#[inline]
fn score_filter(filtered: &[u8]) -> u64 {
    #[cfg(feature = "simd")]
    {
        simd::score_filter(filtered)
    }

    #[cfg(not(feature = "simd"))]
    {
        filtered
            .iter()
            .map(|&b| (b as i8).unsigned_abs() as u64)
            .sum()
    }
}

/// Score a filtered row by counting distinct byte pairs (bigrams).
///
/// Lower scores (fewer distinct bigrams) correlate better with DEFLATE
/// compression than sum-of-absolute-values, as DEFLATE's LZ77 benefits
/// from repeated byte sequences.
#[inline]
fn score_bigrams(filtered: &[u8]) -> usize {
    let mut seen = [false; 65536];
    filtered
        .windows(2)
        .filter(|w| {
            let key = (w[0] as usize) << 8 | w[1] as usize;
            if seen[key] {
                false
            } else {
                seen[key] = true;
                true
            }
        })
        .count()
}

/// Simple high-entropy detector:
/// - Fewer than 1% of neighboring bytes are equal (no runs)
/// - The most common delta between neighbors accounts for <10% of positions
///
/// This avoids misclassifying smooth gradients (constant delta).
/// Guarded to rows >= 1024 bytes to avoid noise.
#[allow(dead_code)]
fn is_high_entropy_row(row: &[u8]) -> bool {
    if row.len() < 1024 {
        return false;
    }
    let mut equal_neighbors = 0usize;
    let mut delta_hist = [0u32; 256];
    let mut total_deltas = 0usize;
    for w in row.windows(2) {
        if w[0] == w[1] {
            equal_neighbors += 1;
        }
        let delta = w[1].wrapping_sub(w[0]);
        delta_hist[delta as usize] += 1;
        total_deltas += 1;
    }
    let ratio = equal_neighbors as f32 / (row.len().saturating_sub(1) as f32);
    let max_delta = delta_hist.iter().copied().max().unwrap_or(0);
    let max_delta_ratio = if total_deltas == 0 {
        1.0
    } else {
        max_delta as f32 / total_deltas as f32
    };
    ratio < 0.01 && max_delta_ratio < 0.10
}

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

    #[test]
    fn test_paeth_predictor() {
        // When all are equal, should return that value
        assert_eq!(paeth_predictor(100, 100, 100), 100);

        // When a=0, b=0, c=0, should return 0
        assert_eq!(paeth_predictor(0, 0, 0), 0);

        // Test typical case: a=10, b=20, c=15
        // p = a + b - c = 10 + 20 - 15 = 15
        // pa = |p - a| = |15 - 10| = 5
        // pb = |p - b| = |15 - 20| = 5
        // pc = |p - c| = |15 - 15| = 0
        // pc is smallest, so return c (15)
        assert_eq!(paeth_predictor(10, 20, 15), 15);
    }

    #[test]
    fn test_filter_sub() {
        let row = vec![10, 20, 30, 40, 50, 60];
        let mut output = Vec::new();
        filter_sub(&row, 3, &mut output);

        // First 3 bytes: no left pixel, so unchanged
        assert_eq!(output[0], 10);
        assert_eq!(output[1], 20);
        assert_eq!(output[2], 30);

        // Next 3 bytes: difference from 3 bytes back
        assert_eq!(output[3], 40u8.wrapping_sub(10)); // 30
        assert_eq!(output[4], 50u8.wrapping_sub(20)); // 30
        assert_eq!(output[5], 60u8.wrapping_sub(30)); // 30
    }

    #[test]
    fn test_filter_up() {
        let row = vec![50, 60, 70];
        let prev = vec![10, 20, 30];
        let mut output = Vec::new();
        filter_up(&row, &prev, &mut output);

        assert_eq!(output[0], 40); // 50 - 10
        assert_eq!(output[1], 40); // 60 - 20
        assert_eq!(output[2], 40); // 70 - 30
    }

    #[test]
    fn test_apply_filters_none() {
        let data = vec![100, 150, 200, 50, 100, 150];
        let options = PngOptions {
            filter_strategy: FilterStrategy::None,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 2, 1, 3, &options);

        // Should be filter byte (0) + original data
        assert_eq!(filtered[0], FILTER_NONE);
        assert_eq!(&filtered[1..], &data[..]);
    }

    #[test]
    fn test_apply_filters_multiple_rows() {
        let data = vec![
            10, 20, 30, 40, 50, 60, // Row 1
            70, 80, 90, 100, 110, 120, // Row 2
        ];
        let options = PngOptions {
            filter_strategy: FilterStrategy::None,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 2, 2, 3, &options);

        // Should have 2 rows, each with filter byte
        assert_eq!(filtered.len(), 2 * (1 + 6)); // 2 rows * (1 filter + 6 data)
        assert_eq!(filtered[0], FILTER_NONE);
        assert_eq!(filtered[7], FILTER_NONE);
    }

    #[test]
    fn test_apply_filters_adaptive_fast() {
        let data = vec![
            10, 20, 30, 40, 50, 60, // Row 1
            70, 80, 90, 100, 110, 120, // Row 2
        ];
        let options = PngOptions {
            filter_strategy: FilterStrategy::AdaptiveFast,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 2, 2, 3, &options);

        // Two rows, each 1 filter byte + 6 bytes
        assert_eq!(filtered.len(), 2 * (1 + 6));
        // Filter bytes should be one of the defined filters
        assert!(matches!(filtered[0], FILTER_SUB | FILTER_UP | FILTER_PAETH));
        assert!(matches!(filtered[7], FILTER_SUB | FILTER_UP | FILTER_PAETH));
    }

    #[test]
    fn test_filter_average() {
        let row = vec![100, 100, 100];
        let prev = vec![50, 50, 50];
        let mut output = Vec::new();
        filter_average(&row, &prev, 1, &mut output);

        // First byte: left=0, above=50, avg=25
        assert_eq!(output[0], 100u8.wrapping_sub(25)); // 75
                                                       // Second byte: left=100, above=50, avg=75
        assert_eq!(output[1], 100u8.wrapping_sub(75)); // 25
                                                       // Third byte: left=100, above=50, avg=75
        assert_eq!(output[2], 100u8.wrapping_sub(75)); // 25
    }

    #[test]
    fn test_filter_paeth() {
        let row = vec![100, 100, 100];
        let prev = vec![50, 50, 50];
        let mut output = Vec::new();
        filter_paeth(&row, &prev, 1, &mut output);

        // First byte: left=0, above=50, upper_left=0
        // p = 0 + 50 - 0 = 50
        // pa = |50-0| = 50, pb = |50-50| = 0, pc = |50-0| = 50
        // pb is smallest, return b=50
        assert_eq!(output[0], 100u8.wrapping_sub(50)); // 50

        // All output should be valid filtered values
        assert_eq!(output.len(), 3);
    }

    #[test]
    fn test_score_filter_all_zeros() {
        let data = vec![0u8; 100];
        let score = score_filter(&data);
        assert_eq!(score, 0);
    }

    #[test]
    fn test_score_filter_high_values() {
        // 0x80 as i8 is -128, abs = 128
        let data = vec![0x80u8; 10];
        let score = score_filter(&data);
        assert_eq!(score, 128 * 10);
    }

    #[test]
    fn test_score_filter_mixed() {
        // Mix of positive and negative values (as i8)
        let data = vec![1, 0xFF, 2, 0xFE]; // 1, -1, 2, -2 as i8
        let score = score_filter(&data);
        // abs values: 1, 1, 2, 2 = 6
        assert_eq!(score, 6);
    }

    #[test]
    fn test_score_bigrams_all_same() {
        // All same bytes = only 1 distinct bigram
        let data = vec![42u8; 100];
        let score = score_bigrams(&data);
        assert_eq!(score, 1); // (42, 42) is the only bigram
    }

    #[test]
    fn test_score_bigrams_all_unique() {
        // Sequential bytes = many distinct bigrams
        let data: Vec<u8> = (0..10).collect();
        let score = score_bigrams(&data);
        // Bigrams: (0,1), (1,2), (2,3), ..., (8,9) = 9 distinct bigrams
        assert_eq!(score, 9);
    }

    #[test]
    fn test_score_bigrams_repeating_pattern() {
        // Repeating pattern should have fewer distinct bigrams
        let data = vec![1, 2, 1, 2, 1, 2, 1, 2];
        let score = score_bigrams(&data);
        // Bigrams: (1,2), (2,1) = 2 distinct bigrams
        assert_eq!(score, 2);
    }

    #[test]
    fn test_score_bigrams_single_byte() {
        // Single byte = no bigrams
        let data = vec![42u8];
        let score = score_bigrams(&data);
        assert_eq!(score, 0);
    }

    #[test]
    fn test_score_bigrams_empty() {
        // Empty = no bigrams
        let data: Vec<u8> = vec![];
        let score = score_bigrams(&data);
        assert_eq!(score, 0);
    }

    #[test]
    fn test_is_high_entropy_row_short() {
        // Short rows should not be considered high entropy
        let row = vec![0u8; 100];
        assert!(!is_high_entropy_row(&row));
    }

    #[test]
    fn test_is_high_entropy_row_uniform() {
        // Uniform data has many equal neighbors - not high entropy
        let row = vec![42u8; 2000];
        assert!(!is_high_entropy_row(&row));
    }

    #[test]
    fn test_is_high_entropy_row_gradient() {
        // Gradient has constant delta - not high entropy
        let row: Vec<u8> = (0..2000).map(|i| (i % 256) as u8).collect();
        assert!(!is_high_entropy_row(&row));
    }

    #[test]
    fn test_paeth_predictor_edge_cases() {
        // Edge case: a closest to p
        assert_eq!(paeth_predictor(100, 0, 0), 100);
        // Edge case: b closest to p
        assert_eq!(paeth_predictor(0, 100, 0), 100);
        // Edge case: c closest to p
        assert_eq!(paeth_predictor(100, 100, 100), 100);
        // Edge case: boundary values
        assert_eq!(paeth_predictor(255, 0, 0), 255);
        assert_eq!(paeth_predictor(0, 255, 0), 255);
    }

    #[test]
    fn test_paeth_predictor_tie_breaking() {
        // When pa == pb, a should be chosen
        // p = a + b - c, if pa <= pb and pa <= pc, return a
        // a=100, b=100, c=100: p=100, pa=0, pb=0, pc=0
        // pa <= pb is true, pa <= pc is true, return a
        assert_eq!(paeth_predictor(100, 100, 100), 100);

        // a=50, b=100, c=75: p = 50+100-75 = 75
        // pa = |75-50| = 25, pb = |75-100| = 25, pc = |75-75| = 0
        // pc is smallest, return c
        assert_eq!(paeth_predictor(50, 100, 75), 75);
    }

    #[test]
    fn test_adaptive_scratch_reuse() {
        let mut scratch = AdaptiveScratch::new(100);
        scratch.none.extend_from_slice(&[1, 2, 3]);
        scratch.sub.extend_from_slice(&[4, 5, 6]);

        assert_eq!(scratch.none.len(), 3);
        assert_eq!(scratch.sub.len(), 3);

        scratch.clear();

        assert_eq!(scratch.none.len(), 0);
        assert_eq!(scratch.sub.len(), 0);
    }

    #[test]
    fn test_filter_sub_bpp_variations() {
        // Test with different bytes per pixel values
        for bpp in 1..=4 {
            let row: Vec<u8> = (0..20).collect();
            let mut output = Vec::new();
            filter_sub(&row, bpp, &mut output);
            assert_eq!(output.len(), row.len());

            // First bpp bytes should equal original (no left reference)
            for i in 0..bpp {
                assert_eq!(output[i], row[i]);
            }
        }
    }

    #[test]
    fn test_filter_up_first_row() {
        // First row uses zero as previous row
        let row = vec![10, 20, 30, 40];
        let zero_row = vec![0u8; 4];
        let mut output = Vec::new();
        filter_up(&row, &zero_row, &mut output);

        // Should just be the original row values (minus zero)
        assert_eq!(output, row);
    }

    #[test]
    fn test_apply_filters_sub_strategy() {
        let data = vec![10, 20, 30, 40, 50, 60]; // Single row
        let options = PngOptions {
            filter_strategy: FilterStrategy::Sub,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 2, 1, 3, &options);

        assert_eq!(filtered[0], FILTER_SUB);
        // Check the filtered values
        assert_eq!(filtered.len(), 1 + 6); // 1 filter byte + 6 data bytes
    }

    #[test]
    fn test_apply_filters_up_strategy() {
        let data = vec![
            10, 20, 30, // Row 1
            50, 60, 70, // Row 2
        ];
        let options = PngOptions {
            filter_strategy: FilterStrategy::Up,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 1, 2, 3, &options);

        // Both rows should use Up filter
        assert_eq!(filtered[0], FILTER_UP);
        assert_eq!(filtered[4], FILTER_UP);
    }

    #[test]
    fn test_apply_filters_average_strategy() {
        let data = vec![100, 100, 100];
        let options = PngOptions {
            filter_strategy: FilterStrategy::Average,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 1, 1, 3, &options);

        assert_eq!(filtered[0], FILTER_AVERAGE);
    }

    #[test]
    fn test_apply_filters_paeth_strategy() {
        let data = vec![100, 100, 100];
        let options = PngOptions {
            filter_strategy: FilterStrategy::Paeth,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 1, 1, 3, &options);

        assert_eq!(filtered[0], FILTER_PAETH);
    }

    #[test]
    fn test_apply_filters_minsum_strategy() {
        let data = vec![0u8; 100]; // All zeros should favor None filter
        let options = PngOptions {
            filter_strategy: FilterStrategy::MinSum,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 10, 1, 10, &options);

        // Should produce valid output
        assert_eq!(filtered.len(), 1 + 100); // 1 row: 1 filter byte + 100 data bytes
    }

    #[test]
    fn test_apply_filters_bigrams_strategy() {
        // Use a larger image to avoid small-image optimization (area > 4096)
        let width = 100;
        let height = 50;
        let bytes_per_pixel = 3;
        let row_bytes = width * bytes_per_pixel;
        let data: Vec<u8> = (0..(width * height * bytes_per_pixel))
            .map(|i| (i % 256) as u8)
            .collect();
        let options = PngOptions {
            filter_strategy: FilterStrategy::Bigrams,
            ..Default::default()
        };

        let filtered = apply_filters(
            &data,
            width as u32,
            height as u32,
            bytes_per_pixel,
            &options,
        );

        // Should produce valid output (height rows, each with filter byte + row_bytes)
        assert_eq!(filtered.len(), height * (1 + row_bytes));
        // Filter bytes should be valid filter types
        assert!(filtered[0] <= 4); // FILTER_NONE through FILTER_PAETH
    }

    #[test]
    fn test_apply_filters_adaptive_strategy() {
        let data: Vec<u8> = (0..200).map(|i| (i % 256) as u8).collect();
        let options = PngOptions {
            filter_strategy: FilterStrategy::Adaptive,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 10, 2, 10, &options);

        // Should produce valid output with filter bytes
        assert_eq!(filtered.len(), 2 * (1 + 100)); // 2 rows
    }

    #[test]
    fn test_filter_wrapping() {
        // Test that filters handle wrapping correctly
        let row = vec![5, 10, 15];
        let prev = vec![10, 20, 30];
        let mut output = Vec::new();

        filter_up(&row, &prev, &mut output);

        // 5 - 10 = -5, wraps to 251
        assert_eq!(output[0], 5u8.wrapping_sub(10));
        // 10 - 20 = -10, wraps to 246
        assert_eq!(output[1], 10u8.wrapping_sub(20));
    }

    #[test]
    fn test_small_image_uses_sub() {
        // Small images (area <= 4096) should use Sub instead of Adaptive
        let data = vec![0u8; 64 * 3]; // 64 pixels = area < 4096
        let options = PngOptions {
            filter_strategy: FilterStrategy::Adaptive,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 8, 8, 3, &options);

        // Should use Sub filter for small images
        // (Filter byte is the first byte)
        assert_eq!(filtered[0], FILTER_SUB);
    }

    #[test]
    fn test_verbose_filter_log_does_not_panic() {
        // Test that verbose_filter_log option works without errors
        let data: Vec<u8> = (0..100).map(|i| (i % 256) as u8).collect();
        let options = PngOptions {
            filter_strategy: FilterStrategy::Adaptive,
            verbose_filter_log: true,
            ..Default::default()
        };

        // This will write to stderr but should not panic
        let filtered = apply_filters(&data, 10, 1, 10, &options);

        // Should produce valid output
        assert_eq!(filtered.len(), 1 + 100);
    }

    #[test]
    fn test_verbose_filter_log_with_multiple_rows() {
        // Test verbose logging with multiple rows
        let data: Vec<u8> = (0..500).map(|i| (i % 256) as u8).collect();
        let options = PngOptions {
            filter_strategy: FilterStrategy::MinSum,
            verbose_filter_log: true,
            ..Default::default()
        };

        let filtered = apply_filters(&data, 10, 5, 10, &options);

        // Should produce valid output (5 rows, each with filter byte + 100 bytes)
        assert_eq!(filtered.len(), 5 * (1 + 100));
    }

    // Additional Filter Tests

    #[test]
    fn test_apply_filters_parallel_large_image() {
        // Large image (height > 32) to trigger parallel filtering path
        let width = 100;
        let height = 64; // > 32 to trigger parallel
        let bytes_per_pixel = 3;
        let data: Vec<u8> = (0..(width * height * bytes_per_pixel))
            .map(|i| (i % 256) as u8)
            .collect();

        let options = PngOptions {
            filter_strategy: FilterStrategy::Adaptive,
            ..Default::default()
        };

        let filtered = apply_filters(
            &data,
            width as u32,
            height as u32,
            bytes_per_pixel,
            &options,
        );

        // Should produce valid output
        let row_bytes = width * bytes_per_pixel;
        assert_eq!(filtered.len(), height * (1 + row_bytes));
    }

    #[test]
    fn test_apply_filters_parallel_bigrams() {
        // Large image with Bigrams strategy for parallel path
        let width = 100;
        let height = 64;
        let bytes_per_pixel = 4; // RGBA
        let data: Vec<u8> = (0..(width * height * bytes_per_pixel))
            .map(|i| (i % 256) as u8)
            .collect();

        let options = PngOptions {
            filter_strategy: FilterStrategy::Bigrams,
            ..Default::default()
        };

        let filtered = apply_filters(
            &data,
            width as u32,
            height as u32,
            bytes_per_pixel,
            &options,
        );

        let row_bytes = width * bytes_per_pixel;
        assert_eq!(filtered.len(), height * (1 + row_bytes));
    }

    #[test]
    fn test_apply_filters_parallel_adaptive_fast() {
        // Large image with AdaptiveFast strategy
        let width = 100;
        let height = 64;
        let bytes_per_pixel = 3;
        let data: Vec<u8> = (0..(width * height * bytes_per_pixel))
            .map(|i| (i % 256) as u8)
            .collect();

        let options = PngOptions {
            filter_strategy: FilterStrategy::AdaptiveFast,
            ..Default::default()
        };

        let filtered = apply_filters(
            &data,
            width as u32,
            height as u32,
            bytes_per_pixel,
            &options,
        );

        let row_bytes = width * bytes_per_pixel;
        assert_eq!(filtered.len(), height * (1 + row_bytes));
    }

    #[test]
    fn test_filter_paeth_predictor_edge_cases() {
        // Test Paeth filter with specific edge cases
        let row = vec![100, 50, 25, 75];
        let prev = vec![50, 100, 75, 25];
        let mut output = Vec::new();

        filter_paeth(&row, &prev, 1, &mut output);

        // Just verify it produces output without panicking
        assert_eq!(output.len(), 4);
    }

    #[test]
    fn test_filter_average_multi_bpp() {
        // Average filter with bpp > 1
        let row = vec![10, 20, 30, 40, 50, 60]; // 2 RGB pixels
        let prev = vec![20, 40, 60, 80, 100, 120];
        let mut output = Vec::new();

        filter_average(&row, &prev, 3, &mut output);

        assert_eq!(output.len(), 6);
        // First 3 bytes only use prev (no left neighbor)
        // Remaining use avg(left, prev)
    }

    #[test]
    fn test_score_filter_all_types() {
        let row = vec![100, 110, 120, 130, 140];
        let prev = vec![50, 60, 70, 80, 90];

        // Test all filter types produce valid scores
        let score_none = score_filter(&row);
        let score_sub = {
            let mut out = Vec::new();
            filter_sub(&row, 1, &mut out);
            score_filter(&out)
        };
        let score_up = {
            let mut out = Vec::new();
            filter_up(&row, &prev, &mut out);
            score_filter(&out)
        };
        let score_avg = {
            let mut out = Vec::new();
            filter_average(&row, &prev, 1, &mut out);
            score_filter(&out)
        };
        let score_paeth = {
            let mut out = Vec::new();
            filter_paeth(&row, &prev, 1, &mut out);
            score_filter(&out)
        };

        // Scores are usize, so they're inherently non-negative.
        // Just verify they were computed (non-zero for non-trivial input).
        assert!(
            score_none > 0 || score_sub > 0 || score_up > 0 || score_avg > 0 || score_paeth > 0
        );
    }

    #[test]
    fn test_filter_strategies_produce_different_results() {
        // Same data with different strategies may produce different outputs
        let width = 50;
        let height = 50;
        let bpp = 3;
        let data: Vec<u8> = (0..(width * height * bpp))
            .map(|i| ((i * 7) % 256) as u8)
            .collect();

        let none_opts = PngOptions {
            filter_strategy: FilterStrategy::None,
            ..Default::default()
        };
        let sub_opts = PngOptions {
            filter_strategy: FilterStrategy::Sub,
            ..Default::default()
        };

        let filtered_none = apply_filters(&data, width as u32, height as u32, bpp, &none_opts);
        let filtered_sub = apply_filters(&data, width as u32, height as u32, bpp, &sub_opts);

        // Both should be valid but may differ
        assert_eq!(filtered_none.len(), filtered_sub.len());
        // Filter bytes should differ
        assert_eq!(filtered_none[0], FILTER_NONE);
        assert_eq!(filtered_sub[0], FILTER_SUB);
    }

    #[test]
    fn test_adaptive_scratch_clear_and_reuse() {
        // Test that AdaptiveScratch can be cleared and reused
        let row_len = 100;
        let mut scratch = AdaptiveScratch::new(row_len);

        // First use
        scratch.none.extend_from_slice(&[0u8; 50]);
        scratch.sub.extend_from_slice(&[1u8; 50]);
        scratch.avg.extend_from_slice(&[3u8; 25]);
        scratch.paeth.extend_from_slice(&[4u8; 25]);

        // Clear and reuse
        scratch.clear();
        assert!(scratch.none.is_empty());
        assert!(scratch.sub.is_empty());
        assert!(scratch.up.is_empty());
        assert!(scratch.avg.is_empty());
        assert!(scratch.paeth.is_empty());

        // Can use again after clear
        scratch.up.extend_from_slice(&[2u8; 100]);
        assert_eq!(scratch.up.len(), 100);
    }
}