ferrisma-libwebp 0.1.0

A mechanical Rust port of libwebp, the WebP reference implementation
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
// libwebp v1.6.0, src/dsp/lossless.c:
//
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Image transforms and color space conversion methods for lossless decoder.
//
// Authors: Vikas Arora (vikaas.arora@gmail.com)
//          Jyrki Alakuijala (jyrki@google.com)
//          Urvang Joshi (urvang@google.com)

// libwebp v1.6.0, src/dsp/lossless.h:
//
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Image transforms and color space conversion methods for lossless decoder.
//
// Authors: Vikas Arora (vikaas.arora@gmail.com)
//          Jyrki Alakuijala (jyrki@google.com)

//! Translation of `src/dsp/lossless.c` and `src/dsp/lossless.h` from libwebp v1.6.0.
//!
//! Work package: WP3 (lossless shared).
//!
//! Representation (ADR 0003, Pointers): the inverse transforms of the decoder
//! read and write one pixel buffer. Their input and output may be the same
//! rows (the transforms run in place), and the predictors read the row above
//! the output and the output pixel to the left. Each such function takes the
//! buffer once, as `data`, with the C pointers as positions in it, so every
//! read and write happens at the index and in the order of the C code,
//! whatever the overlap. The 8-bit alpha path and the color-space converters
//! take distinct buffers, as their callers have them.
//!
//! Not translated here, with the reason:
//! - `VP8LDspInit` only assigns the portable functions (ADR 0003); its calls are
//!   omitted. The SIMD pointers and initializers are wave 4.
//! - The encoder functions that `lossless.h` declares (`VP8LTransformColor_C`,
//!   `VP8LSubtractGreenFromBlueAndRed_C`, the collectors, the entropy and cost
//!   functions, `VP8LBundleColorMap_C`, `VP8LPredictorsSub`, `VP8LEncDspInit`
//!   and their pointers) are defined in `src/dsp/lossless_enc.c` (WP11).
//!
//! # Deviations from upstream
//!
//! Changes of representation that the ADRs allow, or behavior that the Rust
//! side cannot reproduce exactly. Each records the reason.
//!
//! 1. **One buffer for the decoder transforms.** The inverse transforms read
//!    and write one pixel buffer: input and output may be the same rows, and
//!    the predictors read the row above and the pixel to the left of the
//!    output. `VP8LInverseTransform`, the batch predictors,
//!    `VP8LAddGreenToBlueAndRed`, `VP8LTransformColorInverse` and
//!    `VP8LMapColor32b` therefore take the buffer once (`data`) with the C
//!    pointers as positions (ADR 0003, pointers), so every access happens at
//!    the C index and in the C order whatever the overlap. The unfilters of
//!    `src/dsp/filters.rs` copy the input instead (see the deviations of that
//!    module); here the predictors read output written by the same call (the
//!    top-right pixel of the last column is the first pixel of the current
//!    row), which a copy would not reproduce. The decoder
//!    (`src/dec/vp8l_dec.rs`) keeps `pixels` and `argb_cache` in one buffer, as
//!    the C allocation does, or passes the buffer that holds both. The 8-bit
//!    alpha path and the converters take distinct slices, as their callers have
//!    distinct buffers.
//! 2. **Predictor signatures.** A one-pixel predictor takes
//!    `(left, left_pos, top, top_pos)`, where `left[left_pos]` is `*left` and
//!    `top[top_pos + k]` is `top[k]` for `k` in -1 to 1.
//!    `VP8LPredictorAddSubFunc` is the decoder's form,
//!    `(data, in, upper, num_pixels, out)`. `VP8LPredictorsSub`
//!    (`src/dsp/lossless_enc.rs`) reads its input and the row above from one
//!    buffer and writes residuals into another, so its dispatch function has
//!    its own signature, as the function-pointer deviation of `src/dsp/dsp.rs`
//!    allows.
//! 3. **Converters keep their element types.** `VP8LConvertFromBGRA` and the
//!    converters take `&[u32]` and write `&mut [u8]`, as the C pointers are
//!    typed (the untyped-sample-buffer rule of ADR 0003 covers only `void*`),
//!    as `WebPMultARGBRows` (`src/dsp/alpha_processing.rs`) keeps `&mut [u32]`.
//!    `src/enc/picture_csp_enc.c` casts an RGBA byte buffer to `uint32_t*` for
//!    `VP8LConvertBGRAToRGBA`; `src/enc/picture_csp_enc.rs` builds the `u32`
//!    samples from the RGBA bytes in native byte order, which is what the C
//!    cast reads. A mode without a conversion debug-asserts and writes nothing,
//!    where C asserts.
//!
//! # Excluded undefined behavior
//!
//! Inputs that are undefined behavior (or assertion failures) in C and are
//! therefore excluded from the oracle comparison (PORTING rule 8):
//!
//! 1. `VP8LInverseTransform` with `row_start >= row_end` or `row_end > ysize`
//!    (C asserts), and with input and output rows that overlap without being
//!    equal. The batch predictors take a `WEBP_RESTRICT` output, so only the
//!    two layouts the decoder uses, equal or disjoint, have a defined result;
//!    both are tested.
//! 2. `VP8LConvertFromBGRA` with `MODE_YUV`, `MODE_YUVA` or `MODE_LAST` (C
//!    asserts).
//!
//! # Checks not applicable
//!
//! These checks do not apply, or cannot be made, with the reason:
//!
//! 1. **Big-endian hosts.** `is_big_endian` is the target's byte order, and
//!    `CopyOrSwap` keeps both branches. The host is little-endian, so the tests
//!    compare the little-endian branches only.
//! 2. **Compiler plumbing.** `WEBP_INLINE`, `LOCAL_INLINE` (a workaround for
//!    GCC 4.9 on ARM), `WEBP_RESTRICT`, `WEBP_NODISCARD` (`#[must_use]`) and
//!    `WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW` (the wrapping operations) have no
//!    other counterpart.

use crate::dec::vp8li_dec::VP8LTransform;
use crate::dsp::alpha_processing::{webp_apply_alpha_multiply, webp_apply_alpha_multiply4444};
use crate::dsp::lossless_common::{
    generate_predictor_add, vp8_get_alpha_index, vp8_get_alpha_value, vp8_get_argb_index,
    vp8_get_argb_value, vp8l_add_pixels, vp8l_sub_sample_size,
};
use crate::utils::endian_inl_utils::b_swap32;
use crate::utils::utils::webp_uint32_to_mem;
use crate::webp::decode::WEBP_CSP_MODE;
use crate::webp::format_constants::{ARGB_BLACK, VP8LImageTransformType};

//------------------------------------------------------------------------------
// Decoding

// upstream: src/dsp/lossless.h VP8LPredictorFunc
/// A one-pixel predictor: `left[left_pos]` is the C `*left`, and
/// `top[top_pos + k]` is the C `top[k]` for `k` in -1..=1.
pub type VP8LPredictorFunc = fn(&[u32], usize, &[u32], usize) -> u32;

// upstream: src/dsp/lossless.h VP8LPredictorAddSubFunc
/// The decoder form of a batch predictor: `(data, in, upper, num_pixels, out)`,
/// with `in`, `upper` and `out` as positions in `data`. Expects `upper - 1` and
/// `out - 1` to be readable, as the C functions expect `upper[-1]` and
/// `out[-1]`.
pub type VP8LPredictorAddSubFunc = fn(&mut [u32], usize, usize, i32, usize);

// upstream: src/dsp/lossless.h VP8LMultipliers
/// Note: the members are `uint8_t`, so that any negative values are
/// automatically converted to "mod 256" values.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct VP8LMultipliers {
    pub green_to_red: u8,
    pub green_to_blue: u8,
    pub red_to_blue: u8,
}

// upstream: src/dsp/lossless.h VP8LStreaks
/// Small struct to hold counters.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct VP8LStreaks {
    /// Index: 0=zero streak, 1=non-zero streak.
    pub counts: [i32; 2],
    /// [zero/non-zero][streak<3 / streak>=3].
    pub streaks: [[i32; 2]; 2],
}

// upstream: src/dsp/lossless.h VP8LBitEntropy
/// Small struct to hold bit entropy results.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct VP8LBitEntropy {
    /// Entropy.
    pub entropy: u64,
    /// Sum of the population.
    pub sum: u32,
    /// Number of non-zero elements in the population.
    pub nonzeros: i32,
    /// Maximum value in the population.
    pub max_val: u32,
    /// Index of the last non-zero in the population.
    pub nonzero_code: u32,
}

/// The pixel count of a C loop `for (i = 0; i < num_pixels; ++i)`, which runs
/// no iteration for a negative count.
#[inline]
fn pixel_count(num_pixels: i32) -> usize {
    usize::try_from(num_pixels).unwrap_or(0)
}

/// Converts a position or a size of the transforms, which is never negative,
/// to a slice index.
#[inline]
fn position(value: i32) -> usize {
    usize::try_from(value).expect("a transform position is not negative")
}

//------------------------------------------------------------------------------
// Image transforms.

// upstream: src/dsp/lossless.c Average2
#[must_use]
#[inline]
fn average2(a0: u32, a1: u32) -> u32 {
    (((a0 ^ a1) & 0xfefe_fefe) >> 1) + (a0 & a1)
}

// upstream: src/dsp/lossless.c Average3
#[must_use]
#[inline]
fn average3(a0: u32, a1: u32, a2: u32) -> u32 {
    average2(average2(a0, a2), a1)
}

// upstream: src/dsp/lossless.c Average4
#[must_use]
#[inline]
fn average4(a0: u32, a1: u32, a2: u32, a3: u32) -> u32 {
    average2(average2(a0, a1), average2(a2, a3))
}

// upstream: src/dsp/lossless.c Clip255
#[must_use]
#[inline]
fn clip255(a: u32) -> u32 {
    if a < 256 {
        return a;
    }
    // return 0, when a is a negative integer.
    // return 255, when a is positive.
    !a >> 24
}

// upstream: src/dsp/lossless.c AddSubtractComponentFull
#[must_use]
#[inline]
fn add_subtract_component_full(a: i32, b: i32, c: i32) -> i32 {
    clip255((a + b - c).cast_unsigned()).cast_signed()
}

/// The C conversion of a `uint32_t` channel to the `int` parameters of the
/// component helpers; a channel is at most 255.
#[inline]
fn channel(value: u32) -> i32 {
    value.cast_signed()
}

// upstream: src/dsp/lossless.c ClampedAddSubtractFull
#[must_use]
#[inline]
fn clamped_add_subtract_full(c0: u32, c1: u32, c2: u32) -> u32 {
    let a = add_subtract_component_full(channel(c0 >> 24), channel(c1 >> 24), channel(c2 >> 24));
    let r = add_subtract_component_full(
        channel((c0 >> 16) & 0xff),
        channel((c1 >> 16) & 0xff),
        channel((c2 >> 16) & 0xff),
    );
    let g = add_subtract_component_full(
        channel((c0 >> 8) & 0xff),
        channel((c1 >> 8) & 0xff),
        channel((c2 >> 8) & 0xff),
    );
    let b = add_subtract_component_full(channel(c0 & 0xff), channel(c1 & 0xff), channel(c2 & 0xff));
    (a.cast_unsigned() << 24) | ((r << 16) | (g << 8) | b).cast_unsigned()
}

// upstream: src/dsp/lossless.c AddSubtractComponentHalf
#[must_use]
#[inline]
fn add_subtract_component_half(a: i32, b: i32) -> i32 {
    clip255((a + (a - b) / 2).cast_unsigned()).cast_signed()
}

// upstream: src/dsp/lossless.c ClampedAddSubtractHalf
#[must_use]
#[inline]
fn clamped_add_subtract_half(c0: u32, c1: u32, c2: u32) -> u32 {
    let ave = average2(c0, c1);
    let a = add_subtract_component_half(channel(ave >> 24), channel(c2 >> 24));
    let r = add_subtract_component_half(channel((ave >> 16) & 0xff), channel((c2 >> 16) & 0xff));
    let g = add_subtract_component_half(channel((ave >> 8) & 0xff), channel((c2 >> 8) & 0xff));
    let b = add_subtract_component_half(channel(ave & 0xff), channel(c2 & 0xff));
    (a.cast_unsigned() << 24) | ((r << 16) | (g << 8) | b).cast_unsigned()
}

// upstream: src/dsp/lossless.c Sub3
#[must_use]
#[inline]
fn sub3(a: i32, b: i32, c: i32) -> i32 {
    let pb = b - c;
    let pa = a - c;
    pb.abs() - pa.abs()
}

// upstream: src/dsp/lossless.c Select
#[must_use]
#[inline]
fn select(a: u32, b: u32, c: u32) -> u32 {
    let pa_minus_pb = sub3(channel(a >> 24), channel(b >> 24), channel(c >> 24))
        + sub3(
            channel((a >> 16) & 0xff),
            channel((b >> 16) & 0xff),
            channel((c >> 16) & 0xff),
        )
        + sub3(
            channel((a >> 8) & 0xff),
            channel((b >> 8) & 0xff),
            channel((c >> 8) & 0xff),
        )
        + sub3(channel(a & 0xff), channel(b & 0xff), channel(c & 0xff));
    if pa_minus_pb <= 0 { a } else { b }
}

//------------------------------------------------------------------------------
// Predictors

// upstream: src/dsp/lossless.c VP8LPredictor0_C
fn vp8l_predictor0_c(_left: &[u32], _left_pos: usize, _top: &[u32], _top_pos: usize) -> u32 {
    ARGB_BLACK
}

// upstream: src/dsp/lossless.c VP8LPredictor1_C
fn vp8l_predictor1_c(left: &[u32], left_pos: usize, _top: &[u32], _top_pos: usize) -> u32 {
    left[left_pos]
}

// upstream: src/dsp/lossless.c VP8LPredictor2_C
#[must_use]
pub fn vp8l_predictor2_c(_left: &[u32], _left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    top[top_pos]
}

// upstream: src/dsp/lossless.c VP8LPredictor3_C
#[must_use]
pub fn vp8l_predictor3_c(_left: &[u32], _left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    top[top_pos + 1]
}

// upstream: src/dsp/lossless.c VP8LPredictor4_C
#[must_use]
pub fn vp8l_predictor4_c(_left: &[u32], _left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    top[top_pos - 1]
}

// upstream: src/dsp/lossless.c VP8LPredictor5_C
#[must_use]
pub fn vp8l_predictor5_c(left: &[u32], left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    average3(left[left_pos], top[top_pos], top[top_pos + 1])
}

// upstream: src/dsp/lossless.c VP8LPredictor6_C
#[must_use]
pub fn vp8l_predictor6_c(left: &[u32], left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    average2(left[left_pos], top[top_pos - 1])
}

// upstream: src/dsp/lossless.c VP8LPredictor7_C
#[must_use]
pub fn vp8l_predictor7_c(left: &[u32], left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    average2(left[left_pos], top[top_pos])
}

// upstream: src/dsp/lossless.c VP8LPredictor8_C
#[must_use]
pub fn vp8l_predictor8_c(_left: &[u32], _left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    average2(top[top_pos - 1], top[top_pos])
}

// upstream: src/dsp/lossless.c VP8LPredictor9_C
#[must_use]
pub fn vp8l_predictor9_c(_left: &[u32], _left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    average2(top[top_pos], top[top_pos + 1])
}

// upstream: src/dsp/lossless.c VP8LPredictor10_C
#[must_use]
pub fn vp8l_predictor10_c(left: &[u32], left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    average4(
        left[left_pos],
        top[top_pos - 1],
        top[top_pos],
        top[top_pos + 1],
    )
}

// upstream: src/dsp/lossless.c VP8LPredictor11_C
#[must_use]
pub fn vp8l_predictor11_c(left: &[u32], left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    select(top[top_pos], left[left_pos], top[top_pos - 1])
}

// upstream: src/dsp/lossless.c VP8LPredictor12_C
#[must_use]
pub fn vp8l_predictor12_c(left: &[u32], left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    clamped_add_subtract_full(left[left_pos], top[top_pos], top[top_pos - 1])
}

// upstream: src/dsp/lossless.c VP8LPredictor13_C
#[must_use]
pub fn vp8l_predictor13_c(left: &[u32], left_pos: usize, top: &[u32], top_pos: usize) -> u32 {
    clamped_add_subtract_half(left[left_pos], top[top_pos], top[top_pos - 1])
}

// upstream: src/dsp/lossless.c PredictorAdd0_C
fn predictor_add0_c(
    data: &mut [u32],
    in_pos: usize,
    _upper_pos: usize,
    num_pixels: i32,
    out_pos: usize,
) {
    for x in 0..pixel_count(num_pixels) {
        data[out_pos + x] = vp8l_add_pixels(data[in_pos + x], ARGB_BLACK);
    }
}

// upstream: src/dsp/lossless.c PredictorAdd1_C
fn predictor_add1_c(
    data: &mut [u32],
    in_pos: usize,
    _upper_pos: usize,
    num_pixels: i32,
    out_pos: usize,
) {
    let mut left = data[out_pos - 1];
    for i in 0..pixel_count(num_pixels) {
        left = vp8l_add_pixels(data[in_pos + i], left);
        data[out_pos + i] = left;
    }
}

// upstream: src/dsp/lossless.c PredictorAdd2_C
generate_predictor_add!(vp8l_predictor2_c, predictor_add2_c);
// upstream: src/dsp/lossless.c PredictorAdd3_C
generate_predictor_add!(vp8l_predictor3_c, predictor_add3_c);
// upstream: src/dsp/lossless.c PredictorAdd4_C
generate_predictor_add!(vp8l_predictor4_c, predictor_add4_c);
// upstream: src/dsp/lossless.c PredictorAdd5_C
generate_predictor_add!(vp8l_predictor5_c, predictor_add5_c);
// upstream: src/dsp/lossless.c PredictorAdd6_C
generate_predictor_add!(vp8l_predictor6_c, predictor_add6_c);
// upstream: src/dsp/lossless.c PredictorAdd7_C
generate_predictor_add!(vp8l_predictor7_c, predictor_add7_c);
// upstream: src/dsp/lossless.c PredictorAdd8_C
generate_predictor_add!(vp8l_predictor8_c, predictor_add8_c);
// upstream: src/dsp/lossless.c PredictorAdd9_C
generate_predictor_add!(vp8l_predictor9_c, predictor_add9_c);
// upstream: src/dsp/lossless.c PredictorAdd10_C
generate_predictor_add!(vp8l_predictor10_c, predictor_add10_c);
// upstream: src/dsp/lossless.c PredictorAdd11_C
generate_predictor_add!(vp8l_predictor11_c, predictor_add11_c);
// upstream: src/dsp/lossless.c PredictorAdd12_C
generate_predictor_add!(vp8l_predictor12_c, predictor_add12_c);
// upstream: src/dsp/lossless.c PredictorAdd13_C
generate_predictor_add!(vp8l_predictor13_c, predictor_add13_c);

// upstream: src/dsp/lossless.c VP8LPredictors
/// The table that `VP8LDspInit` fills with `COPY_PREDICTOR_ARRAY`; entries 14
/// and 15 are padding security sentinels.
static VP8L_PREDICTORS: [VP8LPredictorFunc; 16] = [
    vp8l_predictor0_c,
    vp8l_predictor1_c,
    vp8l_predictor2_c,
    vp8l_predictor3_c,
    vp8l_predictor4_c,
    vp8l_predictor5_c,
    vp8l_predictor6_c,
    vp8l_predictor7_c,
    vp8l_predictor8_c,
    vp8l_predictor9_c,
    vp8l_predictor10_c,
    vp8l_predictor11_c,
    vp8l_predictor12_c,
    vp8l_predictor13_c,
    vp8l_predictor0_c, // <- padding security sentinels
    vp8l_predictor0_c,
];

// upstream: src/dsp/lossless.c VP8LPredictorsAdd
/// The table that `VP8LDspInit` fills with `COPY_PREDICTOR_ARRAY`.
static VP8L_PREDICTORS_ADD: [VP8LPredictorAddSubFunc; 16] = [
    predictor_add0_c,
    predictor_add1_c,
    predictor_add2_c,
    predictor_add3_c,
    predictor_add4_c,
    predictor_add5_c,
    predictor_add6_c,
    predictor_add7_c,
    predictor_add8_c,
    predictor_add9_c,
    predictor_add10_c,
    predictor_add11_c,
    predictor_add12_c,
    predictor_add13_c,
    predictor_add0_c, // <- padding security sentinels
    predictor_add0_c,
];

// upstream: src/dsp/lossless.c VP8LPredictorsAdd_C
/// The exposed plain-C implementations, which `VP8LDspInit` fills with
/// `COPY_PREDICTOR_ARRAY` as well.
static VP8L_PREDICTORS_ADD_C: [VP8LPredictorAddSubFunc; 16] = VP8L_PREDICTORS_ADD;

// upstream: src/dsp/lossless.c VP8LPredictors
/// Calls the predictor `VP8LPredictors[mode]`.
///
/// # Panics
///
/// Panics for a mode outside 0..16.
#[must_use]
#[inline]
pub fn vp8l_predictors(
    mode: usize,
    left: &[u32],
    left_pos: usize,
    top: &[u32],
    top_pos: usize,
) -> u32 {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 {
            match mode {
                5 => return crate::dsp::lossless_sse2::predictor5(left, left_pos, top, top_pos),
                6 => return crate::dsp::lossless_sse2::predictor6(left, left_pos, top, top_pos),
                7 => return crate::dsp::lossless_sse2::predictor7(left, left_pos, top, top_pos),
                8 => return crate::dsp::lossless_sse2::predictor8(left, left_pos, top, top_pos),
                9 => return crate::dsp::lossless_sse2::predictor9(left, left_pos, top, top_pos),
                10 => return crate::dsp::lossless_sse2::predictor10(left, left_pos, top, top_pos),
                11 => return crate::dsp::lossless_sse2::predictor11(left, left_pos, top, top_pos),
                12 => return crate::dsp::lossless_sse2::predictor12(left, left_pos, top, top_pos),
                13 => return crate::dsp::lossless_sse2::predictor13(left, left_pos, top, top_pos),
                _ => {}
            }
        }
    }
    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
    {
        // `VP8LDspInitNEON` assigns the entries 5, 6, 7 and 13.
        let neon: Option<VP8LPredictorFunc> = match mode {
            5 => Some(crate::dsp::lossless_neon::predictor5),
            6 => Some(crate::dsp::lossless_neon::predictor6),
            7 => Some(crate::dsp::lossless_neon::predictor7),
            13 => Some(crate::dsp::lossless_neon::predictor13),
            _ => None,
        };
        if let Some(predictor) = neon {
            return predictor(left, left_pos, top, top_pos);
        }
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    VP8L_PREDICTORS[mode](left, left_pos, top, top_pos)
}

// upstream: src/dsp/lossless.c VP8LPredictorsAdd
/// Calls the batch predictor `VP8LPredictorsAdd[mode]`.
///
/// # Panics
///
/// Panics for a mode outside 0..16.
#[inline]
pub fn vp8l_predictors_add(
    mode: usize,
    data: &mut [u32],
    in_pos: usize,
    upper_pos: usize,
    num_pixels: i32,
    out_pos: usize,
) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        use crate::dsp::lossless_avx2 as avx2;
        use crate::dsp::lossless_sse2 as sse2;
        let features = crate::dsp::cpu::features();
        if features.sse2 && features.sse4_1 && features.avx2 {
            let add: Option<VP8LPredictorAddSubFunc> = match mode {
                0 => Some(avx2::predictor_add0),
                1 => Some(avx2::predictor_add1),
                2 => Some(avx2::predictor_add2),
                3 => Some(avx2::predictor_add3),
                4 => Some(avx2::predictor_add4),
                8 => Some(avx2::predictor_add8),
                9 => Some(avx2::predictor_add9),
                10 => Some(avx2::predictor_add10),
                11 => Some(avx2::predictor_add11),
                12 => Some(avx2::predictor_add12),
                _ => None,
            };
            if let Some(add) = add {
                return add(data, in_pos, upper_pos, num_pixels, out_pos);
            }
        }
        if features.sse2 {
            let add: Option<VP8LPredictorAddSubFunc> = match mode {
                0 => Some(sse2::predictor_add0),
                1 => Some(sse2::predictor_add1),
                2 => Some(sse2::predictor_add2),
                3 => Some(sse2::predictor_add3),
                4 => Some(sse2::predictor_add4),
                5 => Some(sse2::predictor_add5),
                6 => Some(sse2::predictor_add6),
                7 => Some(sse2::predictor_add7),
                8 => Some(sse2::predictor_add8),
                9 => Some(sse2::predictor_add9),
                10 => Some(sse2::predictor_add10),
                11 => Some(sse2::predictor_add11),
                12 => Some(sse2::predictor_add12),
                13 => Some(sse2::predictor_add13),
                _ => None,
            };
            if let Some(add) = add {
                return add(data, in_pos, upper_pos, num_pixels, out_pos);
            }
        }
    }
    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
    {
        // `VP8LDspInitNEON` assigns the entries 0 to 13; 14 and 15 keep the
        // C padding sentinels.
        let neon: Option<VP8LPredictorAddSubFunc> = match mode {
            0 => Some(crate::dsp::lossless_neon::predictor_add0),
            1 => Some(crate::dsp::lossless_neon::predictor_add1),
            2 => Some(crate::dsp::lossless_neon::predictor_add2),
            3 => Some(crate::dsp::lossless_neon::predictor_add3),
            4 => Some(crate::dsp::lossless_neon::predictor_add4),
            5 => Some(crate::dsp::lossless_neon::predictor_add5),
            6 => Some(crate::dsp::lossless_neon::predictor_add6),
            7 => Some(crate::dsp::lossless_neon::predictor_add7),
            8 => Some(crate::dsp::lossless_neon::predictor_add8),
            9 => Some(crate::dsp::lossless_neon::predictor_add9),
            10 => Some(crate::dsp::lossless_neon::predictor_add10),
            11 => Some(crate::dsp::lossless_neon::predictor_add11),
            12 => Some(crate::dsp::lossless_neon::predictor_add12),
            13 => Some(crate::dsp::lossless_neon::predictor_add13),
            _ => None,
        };
        if let Some(predictor_add) = neon {
            return predictor_add(data, in_pos, upper_pos, num_pixels, out_pos);
        }
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    VP8L_PREDICTORS_ADD[mode](data, in_pos, upper_pos, num_pixels, out_pos);
}

// upstream: src/dsp/lossless.c VP8LPredictorsAdd_C
/// Calls the plain-C batch predictor `VP8LPredictorsAdd_C[mode]`.
///
/// # Panics
///
/// Panics for a mode outside 0..16.
#[inline]
pub fn vp8l_predictors_add_c(
    mode: usize,
    data: &mut [u32],
    in_pos: usize,
    upper_pos: usize,
    num_pixels: i32,
    out_pos: usize,
) {
    VP8L_PREDICTORS_ADD_C[mode](data, in_pos, upper_pos, num_pixels, out_pos);
}

//------------------------------------------------------------------------------

// upstream: src/dsp/lossless.c PredictorInverseTransform_C
/// Inverse prediction of rows `y_start..y_end` from `data[in_pos..]` into
/// `data[out_pos..]`; for `y_start > 0` the row above `out_pos` holds the last
/// row of the previous call.
fn predictor_inverse_transform_c(
    transform: &VP8LTransform,
    mut y_start: i32,
    y_end: i32,
    data: &mut [u32],
    mut in_pos: usize,
    mut out_pos: usize,
) {
    let width = transform.xsize;
    let row = position(width);
    if y_start == 0 {
        // First Row follows the L (mode=1) mode.
        predictor_add0_c(data, in_pos, 0, 1, out_pos);
        predictor_add1_c(data, in_pos + 1, 0, width - 1, out_pos + 1);
        in_pos += row;
        out_pos += row;
        y_start += 1;
    }

    {
        let mut y = y_start;
        let tile_width: i32 = 1 << transform.bits;
        let mask = tile_width - 1;
        let tiles_per_row =
            vp8l_sub_sample_size(width.cast_unsigned(), transform.bits.cast_unsigned());
        let mut pred_mode_base =
            (y >> transform.bits).cast_unsigned() as usize * tiles_per_row as usize;

        while y < y_end {
            let mut pred_mode_src = pred_mode_base;
            let mut x: i32 = 1;
            // First pixel follows the T (mode=2) mode.
            predictor_add2_c(data, in_pos, out_pos - row, 1, out_pos);
            // .. the rest:
            while x < width {
                let mode = ((transform.data[pred_mode_src] >> 8) & 0xf) as usize;
                pred_mode_src += 1;
                let mut x_end = (x & !mask) + tile_width;
                if x_end > width {
                    x_end = width;
                }
                let at = position(x);
                vp8l_predictors_add(
                    mode,
                    data,
                    in_pos + at,
                    out_pos + at - row,
                    x_end - x,
                    out_pos + at,
                );
                x = x_end;
            }
            in_pos += row;
            out_pos += row;
            y += 1;
            if (y & mask) == 0 {
                // Use the same mask, since tiles are squares.
                pred_mode_base += tiles_per_row as usize;
            }
        }
    }
}

// upstream: src/dsp/lossless.c VP8LAddGreenToBlueAndRed_C
/// Add green to blue and red channels (i.e. perform the inverse transform of
/// 'subtract green'), from `data[src_pos..]` into `data[dst_pos..]`.
pub fn vp8l_add_green_to_blue_and_red_c(
    data: &mut [u32],
    src_pos: usize,
    num_pixels: i32,
    dst_pos: usize,
) {
    for i in 0..pixel_count(num_pixels) {
        let argb = data[src_pos + i];
        let green = (argb >> 8) & 0xff;
        let mut red_blue = argb & 0x00ff_00ff;
        red_blue = red_blue.wrapping_add((green << 16) | green);
        red_blue &= 0x00ff_00ff;
        data[dst_pos + i] = (argb & 0xff00_ff00) | red_blue;
    }
}

// upstream: src/dsp/lossless.c VP8LAddGreenToBlueAndRed
/// Calls the SIMD variant that `VP8LDspInit` selects (ADR 0008), or the
/// portable [`vp8l_add_green_to_blue_and_red_c`].
#[inline]
pub fn vp8l_add_green_to_blue_and_red(
    data: &mut [u32],
    src_pos: usize,
    num_pixels: i32,
    dst_pos: usize,
) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 && features.sse4_1 && features.avx2 {
            return crate::dsp::lossless_avx2::add_green_to_blue_and_red(
                data, src_pos, num_pixels, dst_pos,
            );
        }
        if features.sse2 {
            return crate::dsp::lossless_sse2::add_green_to_blue_and_red(
                data, src_pos, num_pixels, dst_pos,
            );
        }
    }
    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
    {
        return crate::dsp::lossless_neon::add_green_to_blue_and_red(
            data, src_pos, num_pixels, dst_pos,
        );
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    vp8l_add_green_to_blue_and_red_c(data, src_pos, num_pixels, dst_pos);
}

// upstream: src/dsp/lossless.c ColorTransformDelta
#[must_use]
#[inline]
fn color_transform_delta(color_pred: i8, color: i8) -> i32 {
    (i32::from(color_pred) * i32::from(color)) >> 5
}

// upstream: src/dsp/lossless.c ColorCodeToMultipliers
#[inline]
fn color_code_to_multipliers(color_code: u32, m: &mut VP8LMultipliers) {
    m.green_to_red = (color_code & 0xff) as u8;
    m.green_to_blue = ((color_code >> 8) & 0xff) as u8;
    m.red_to_blue = ((color_code >> 16) & 0xff) as u8;
}

/// The C `(int8_t)` cast of the low byte of a value.
#[inline]
#[expect(
    clippy::cast_possible_truncation,
    reason = "the C (int8_t) cast keeps the low byte"
)]
fn low_int8(value: u32) -> i8 {
    (value as u8).cast_signed()
}

// upstream: src/dsp/lossless.c VP8LTransformColorInverse_C
/// The inverse color transform of `num_pixels` pixels, from `data[src_pos..]`
/// into `data[dst_pos..]`.
pub fn vp8l_transform_color_inverse_c(
    m: &VP8LMultipliers,
    data: &mut [u32],
    src_pos: usize,
    num_pixels: i32,
    dst_pos: usize,
) {
    for i in 0..pixel_count(num_pixels) {
        let argb = data[src_pos + i];
        let green = low_int8(argb >> 8);
        let red = argb >> 16;
        let mut new_red: i32 = channel(red & 0xff);
        let mut new_blue: i32 = channel(argb & 0xff);
        new_red += color_transform_delta(m.green_to_red.cast_signed(), green);
        new_red &= 0xff;
        new_blue += color_transform_delta(m.green_to_blue.cast_signed(), green);
        new_blue += color_transform_delta(
            m.red_to_blue.cast_signed(),
            low_int8(new_red.cast_unsigned()),
        );
        new_blue &= 0xff;
        data[dst_pos + i] = (argb & 0xff00_ff00) | ((new_red << 16) | new_blue).cast_unsigned();
    }
}

// upstream: src/dsp/lossless.c VP8LTransformColorInverse
/// Calls the SIMD variant that `VP8LDspInit` selects (ADR 0008), or the
/// portable [`vp8l_transform_color_inverse_c`].
#[inline]
pub fn vp8l_transform_color_inverse(
    m: &VP8LMultipliers,
    data: &mut [u32],
    src_pos: usize,
    num_pixels: i32,
    dst_pos: usize,
) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 && features.sse4_1 && features.avx2 {
            return crate::dsp::lossless_avx2::transform_color_inverse(
                m, data, src_pos, num_pixels, dst_pos,
            );
        }
        if features.sse2 && features.sse4_1 {
            return crate::dsp::lossless_sse41::transform_color_inverse(
                m, data, src_pos, num_pixels, dst_pos,
            );
        }
        if features.sse2 {
            return crate::dsp::lossless_sse2::transform_color_inverse(
                m, data, src_pos, num_pixels, dst_pos,
            );
        }
    }
    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
    {
        return crate::dsp::lossless_neon::transform_color_inverse(
            m, data, src_pos, num_pixels, dst_pos,
        );
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    vp8l_transform_color_inverse_c(m, data, src_pos, num_pixels, dst_pos);
}

// upstream: src/dsp/lossless.c ColorSpaceInverseTransform_C
/// Color space inverse transform of rows `y_start..y_end`, from
/// `data[src_pos..]` into `data[dst_pos..]`.
fn color_space_inverse_transform_c(
    transform: &VP8LTransform,
    y_start: i32,
    y_end: i32,
    data: &mut [u32],
    mut src: usize,
    mut dst: usize,
) {
    let width = transform.xsize;
    let tile_width: i32 = 1 << transform.bits;
    let mask = tile_width - 1;
    let safe_width = width & !mask;
    let remaining_width = width - safe_width;
    let tiles_per_row =
        vp8l_sub_sample_size(width.cast_unsigned(), transform.bits.cast_unsigned()) as usize;
    let mut y = y_start;
    let mut pred_row = (y >> transform.bits).cast_unsigned() as usize * tiles_per_row;

    while y < y_end {
        let mut pred = pred_row;
        let mut m = VP8LMultipliers::default();
        let src_safe_end = src + position(safe_width);
        let src_end = src + position(width);
        while src < src_safe_end {
            color_code_to_multipliers(transform.data[pred], &mut m);
            pred += 1;
            vp8l_transform_color_inverse(&m, data, src, tile_width, dst);
            src += position(tile_width);
            dst += position(tile_width);
        }
        if src < src_end {
            // Left-overs using C-version.
            color_code_to_multipliers(transform.data[pred], &mut m);
            vp8l_transform_color_inverse(&m, data, src, remaining_width, dst);
            src += position(remaining_width);
            dst += position(remaining_width);
        }
        y += 1;
        if (y & mask) == 0 {
            pred_row += tiles_per_row;
        }
    }
}

// Separate out pixels packed together using pixel-bundling.
// We define two methods for ARGB data (uint32_t) and alpha-only data (uint8_t).

// upstream: src/dsp/lossless.c MapARGB_C
/// Maps `width` pixels of each row `y_start..y_end` through `color_map`, from
/// `data[src..]` into `data[dst..]`.
fn map_argb_c(
    data: &mut [u32],
    mut src: usize,
    color_map: &[u32],
    mut dst: usize,
    y_start: i32,
    y_end: i32,
    width: i32,
) {
    for _ in y_start..y_end {
        for _ in 0..pixel_count(width) {
            data[dst] = vp8_get_argb_value(color_map[vp8_get_argb_index(data[src]) as usize]);
            dst += 1;
            src += 1;
        }
    }
}

// upstream: src/dsp/lossless.c MapAlpha_C
/// Maps `width` pixels of each row `y_start..y_end` through `color_map`, from
/// `src` into `dst`.
fn map_alpha_c(
    src: &[u8],
    color_map: &[u32],
    dst: &mut [u8],
    y_start: i32,
    y_end: i32,
    width: i32,
) {
    let mut s = 0;
    let mut d = 0;
    for _ in y_start..y_end {
        for _ in 0..pixel_count(width) {
            dst[d] = vp8_get_alpha_value(color_map[usize::from(vp8_get_alpha_index(src[s]))]);
            d += 1;
            s += 1;
        }
    }
}

// upstream: src/dsp/lossless.c VP8LMapColor32b
/// Calls the portable `MapARGB_C`.
#[inline]
pub fn vp8l_map_color32b(
    data: &mut [u32],
    src: usize,
    color_map: &[u32],
    dst: usize,
    y_start: i32,
    y_end: i32,
    width: i32,
) {
    map_argb_c(data, src, color_map, dst, y_start, y_end, width);
}

// upstream: src/dsp/lossless.c VP8LMapColor8b
/// Calls the portable `MapAlpha_C`.
#[inline]
pub fn vp8l_map_color8b(
    src: &[u8],
    color_map: &[u32],
    dst: &mut [u8],
    y_start: i32,
    y_end: i32,
    width: i32,
) {
    map_alpha_c(src, color_map, dst, y_start, y_end, width);
}

// upstream: src/dsp/lossless.c ColorIndexInverseTransform_C
/// The color-indexing inverse transform of rows `y_start..y_end` for ARGB
/// data, from `data[src..]` into `data[dst..]` (the `COLOR_INDEX_INVERSE`
/// macro with `uint32_t`).
fn color_index_inverse_transform_c(
    transform: &VP8LTransform,
    y_start: i32,
    y_end: i32,
    data: &mut [u32],
    mut src: usize,
    mut dst: usize,
) {
    let bits_per_pixel = 8 >> transform.bits;
    let width = transform.xsize;
    let color_map = &transform.data[..];
    if bits_per_pixel < 8 {
        let pixels_per_byte = 1 << transform.bits;
        let count_mask = pixels_per_byte - 1;
        let bit_mask: u32 = ((1_i32 << bits_per_pixel) - 1).cast_unsigned();
        for _ in y_start..y_end {
            let mut packed_pixels: u32 = 0;
            for x in 0..width {
                // We need to load fresh 'packed_pixels' once every
                // 'pixels_per_byte' increments of x. Fortunately, pixels_per_byte
                // is a power of 2, so can just use a mask for that, instead of
                // decrementing a counter.
                if (x & count_mask) == 0 {
                    packed_pixels = vp8_get_argb_index(data[src]);
                    src += 1;
                }
                data[dst] = vp8_get_argb_value(color_map[(packed_pixels & bit_mask) as usize]);
                dst += 1;
                packed_pixels >>= bits_per_pixel;
            }
        }
    } else {
        vp8l_map_color32b(data, src, color_map, dst, y_start, y_end, width);
    }
}

// upstream: src/dsp/lossless.c VP8LColorIndexInverseTransformAlpha
/// Similar to the static method `ColorIndexInverseTransform()` that is part of
/// lossless.c, but used only for alpha decoding. It takes `uint8_t` (rather
/// than `uint32_t`) arguments for `src` and `dst` (the `COLOR_INDEX_INVERSE`
/// macro with `uint8_t`).
pub fn vp8l_color_index_inverse_transform_alpha(
    transform: &VP8LTransform,
    y_start: i32,
    y_end: i32,
    src: &[u8],
    dst: &mut [u8],
) {
    let bits_per_pixel = 8 >> transform.bits;
    let width = transform.xsize;
    let color_map = &transform.data[..];
    if bits_per_pixel < 8 {
        let pixels_per_byte = 1 << transform.bits;
        let count_mask = pixels_per_byte - 1;
        let bit_mask: u32 = ((1_i32 << bits_per_pixel) - 1).cast_unsigned();
        let mut s = 0;
        let mut d = 0;
        for _ in y_start..y_end {
            let mut packed_pixels: u32 = 0;
            for x in 0..width {
                // We need to load fresh 'packed_pixels' once every
                // 'pixels_per_byte' increments of x. Fortunately, pixels_per_byte
                // is a power of 2, so can just use a mask for that, instead of
                // decrementing a counter.
                if (x & count_mask) == 0 {
                    packed_pixels = u32::from(vp8_get_alpha_index(src[s]));
                    s += 1;
                }
                dst[d] = vp8_get_alpha_value(color_map[(packed_pixels & bit_mask) as usize]);
                d += 1;
                packed_pixels >>= bits_per_pixel;
            }
        }
    } else {
        vp8l_map_color8b(src, color_map, dst, y_start, y_end, width);
    }
}

// upstream: src/dsp/lossless.c VP8LInverseTransform
/// Performs inverse transform of data given transform information, start and
/// end rows. Transform will be applied to rows [`row_start`, `row_end`[.
/// The `in_pos` and `out_pos` positions refer to source and destination data
/// in `data`, corresponding to the intermediate row (`row_start`). They may be
/// equal; the predictor reads the row above `out_pos` when `row_start > 0`.
///
/// # Panics
///
/// Panics when a row lies outside `data` or a transform reads outside its
/// `data`, where C reads or writes outside the buffers.
pub fn vp8l_inverse_transform(
    transform: &VP8LTransform,
    row_start: i32,
    row_end: i32,
    data: &mut [u32],
    in_pos: usize,
    out_pos: usize,
) {
    let width = transform.xsize;
    debug_assert!(row_start < row_end);
    debug_assert!(row_end <= transform.ysize);
    match transform.r#type {
        VP8LImageTransformType::SUBTRACT_GREEN_TRANSFORM => {
            vp8l_add_green_to_blue_and_red(data, in_pos, (row_end - row_start) * width, out_pos);
        }
        VP8LImageTransformType::PREDICTOR_TRANSFORM => {
            predictor_inverse_transform_c(transform, row_start, row_end, data, in_pos, out_pos);
            if row_end != transform.ysize {
                // The last predicted row in this iteration will be the top-pred row
                // for the first row in next iteration.
                let row = position(width);
                let last = out_pos + position((row_end - row_start - 1) * width);
                data.copy_within(last..last + row, out_pos - row);
            }
        }
        VP8LImageTransformType::CROSS_COLOR_TRANSFORM => {
            color_space_inverse_transform_c(transform, row_start, row_end, data, in_pos, out_pos);
        }
        VP8LImageTransformType::COLOR_INDEXING_TRANSFORM => {
            if in_pos == out_pos && transform.bits > 0 {
                // Move packed pixels to the end of unpacked region, so that unpacking
                // can occur seamlessly.
                // Also, note that this is the only transform that applies on
                // the effective width of VP8LSubSampleSize(xsize, bits). All other
                // transforms work on effective width of 'xsize'.
                let out_stride = position((row_end - row_start) * width);
                let in_stride = position(row_end - row_start)
                    * vp8l_sub_sample_size(
                        transform.xsize.cast_unsigned(),
                        transform.bits.cast_unsigned(),
                    ) as usize;
                let src = out_pos + out_stride - in_stride;
                data.copy_within(out_pos..out_pos + in_stride, src);
                color_index_inverse_transform_c(transform, row_start, row_end, data, src, out_pos);
            } else {
                color_index_inverse_transform_c(
                    transform, row_start, row_end, data, in_pos, out_pos,
                );
            }
        }
        _ => {}
    }
}

//------------------------------------------------------------------------------
// Color space conversion.

// upstream: src/dsp/lossless.c is_big_endian
#[must_use]
#[inline]
fn is_big_endian() -> bool {
    cfg!(target_endian = "big")
}

/// The byte `(argb >> shift) & 0xff`.
#[inline]
fn byte_at(argb: u32, shift: u32) -> u8 {
    ((argb >> shift) & 0xff) as u8
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGB_C
pub fn vp8l_convert_bgra_to_rgb_c(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    for (&argb, out) in src[..pixel_count(num_pixels)]
        .iter()
        .zip(dst.as_chunks_mut::<3>().0)
    {
        out[0] = byte_at(argb, 16);
        out[1] = byte_at(argb, 8);
        out[2] = byte_at(argb, 0);
    }
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGBA_C
pub fn vp8l_convert_bgra_to_rgba_c(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    for (&argb, out) in src[..pixel_count(num_pixels)]
        .iter()
        .zip(dst.as_chunks_mut::<4>().0)
    {
        out[0] = byte_at(argb, 16);
        out[1] = byte_at(argb, 8);
        out[2] = byte_at(argb, 0);
        out[3] = byte_at(argb, 24);
    }
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGBA4444_C
/// `WEBP_SWAP_16BIT_CSP` is 0 in the reference configuration, so the bytes are
/// stored as `rg`, `ba`.
pub fn vp8l_convert_bgra_to_rgba4444_c(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    for (&argb, out) in src[..pixel_count(num_pixels)]
        .iter()
        .zip(dst.as_chunks_mut::<2>().0)
    {
        let rg = byte_at(argb, 16) & 0xf0 | byte_at(argb, 12) & 0xf;
        let ba = byte_at(argb, 0) & 0xf0 | byte_at(argb, 28) & 0xf;
        out[0] = rg;
        out[1] = ba;
    }
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGB565_C
/// `WEBP_SWAP_16BIT_CSP` is 0 in the reference configuration, so the bytes are
/// stored as `rg`, `gb`.
pub fn vp8l_convert_bgra_to_rgb565_c(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    for (&argb, out) in src[..pixel_count(num_pixels)]
        .iter()
        .zip(dst.as_chunks_mut::<2>().0)
    {
        let rg = byte_at(argb, 16) & 0xf8 | byte_at(argb, 13) & 0x7;
        let gb = byte_at(argb, 5) & 0xe0 | byte_at(argb, 3) & 0x1f;
        out[0] = rg;
        out[1] = gb;
    }
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToBGR_C
pub fn vp8l_convert_bgra_to_bgr_c(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    for (&argb, out) in src[..pixel_count(num_pixels)]
        .iter()
        .zip(dst.as_chunks_mut::<3>().0)
    {
        out[0] = byte_at(argb, 0);
        out[1] = byte_at(argb, 8);
        out[2] = byte_at(argb, 16);
    }
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGB
/// Calls the SIMD variant that `VP8LDspInit` selects (ADR 0008), or the
/// portable [`vp8l_convert_bgra_to_rgb_c`].
#[inline]
pub fn vp8l_convert_bgra_to_rgb(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 && features.sse4_1 {
            return crate::dsp::lossless_sse41::convert_bgra_to_rgb(src, num_pixels, dst);
        }
        if features.sse2 {
            return crate::dsp::lossless_sse2::convert_bgra_to_rgb(src, num_pixels, dst);
        }
    }
    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
    {
        return crate::dsp::lossless_neon::convert_bgra_to_rgb(src, num_pixels, dst);
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    vp8l_convert_bgra_to_rgb_c(src, num_pixels, dst);
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGBA
/// Calls the SIMD variant that `VP8LDspInit` selects (ADR 0008), or the
/// portable [`vp8l_convert_bgra_to_rgba_c`].
#[inline]
pub fn vp8l_convert_bgra_to_rgba(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 && features.sse4_1 && features.avx2 {
            return crate::dsp::lossless_avx2::convert_bgra_to_rgba(src, num_pixels, dst);
        }
        if features.sse2 {
            return crate::dsp::lossless_sse2::convert_bgra_to_rgba(src, num_pixels, dst);
        }
    }
    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
    {
        return crate::dsp::lossless_neon::convert_bgra_to_rgba(src, num_pixels, dst);
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    vp8l_convert_bgra_to_rgba_c(src, num_pixels, dst);
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGBA4444
/// Calls the SIMD variant that `VP8LDspInit` selects (ADR 0008), or the
/// portable [`vp8l_convert_bgra_to_rgba4444_c`].
#[inline]
pub fn vp8l_convert_bgra_to_rgba4444(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 {
            return crate::dsp::lossless_sse2::convert_bgra_to_rgba4444(src, num_pixels, dst);
        }
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    vp8l_convert_bgra_to_rgba4444_c(src, num_pixels, dst);
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToRGB565
/// Calls the SIMD variant that `VP8LDspInit` selects (ADR 0008), or the
/// portable [`vp8l_convert_bgra_to_rgb565_c`].
#[inline]
pub fn vp8l_convert_bgra_to_rgb565(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 {
            return crate::dsp::lossless_sse2::convert_bgra_to_rgb565(src, num_pixels, dst);
        }
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    vp8l_convert_bgra_to_rgb565_c(src, num_pixels, dst);
}

// upstream: src/dsp/lossless.c VP8LConvertBGRAToBGR
/// Calls the SIMD variant that `VP8LDspInit` selects (ADR 0008), or the
/// portable [`vp8l_convert_bgra_to_bgr_c`].
#[inline]
pub fn vp8l_convert_bgra_to_bgr(src: &[u32], num_pixels: i32, dst: &mut [u8]) {
    #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        let features = crate::dsp::cpu::features();
        if features.sse2 && features.sse4_1 {
            return crate::dsp::lossless_sse41::convert_bgra_to_bgr(src, num_pixels, dst);
        }
        if features.sse2 {
            return crate::dsp::lossless_sse2::convert_bgra_to_bgr(src, num_pixels, dst);
        }
    }
    #[cfg(all(feature = "simd", target_arch = "aarch64"))]
    {
        return crate::dsp::lossless_neon::convert_bgra_to_bgr(src, num_pixels, dst);
    }
    #[allow(
        unreachable_code,
        reason = "the C path is reached only without a SIMD variant"
    )]
    vp8l_convert_bgra_to_bgr_c(src, num_pixels, dst);
}

// upstream: src/dsp/lossless.c CopyOrSwap
/// Stores each pixel in host byte order, byte-swapped when the host's byte
/// order is `swap_on_big_endian`.
fn copy_or_swap(src: &[u32], num_pixels: i32, dst: &mut [u8], swap_on_big_endian: bool) {
    let src = &src[..pixel_count(num_pixels)];
    if is_big_endian() == swap_on_big_endian {
        for (&argb, out) in src.iter().zip(dst.as_chunks_mut::<4>().0) {
            webp_uint32_to_mem(out, b_swap32(argb));
        }
    } else {
        for (&argb, out) in src.iter().zip(dst.as_chunks_mut::<4>().0) {
            out.copy_from_slice(&argb.to_ne_bytes());
        }
    }
}

// upstream: src/dsp/lossless.c VP8LConvertFromBGRA
/// Converts from BGRA to other color spaces.
///
/// C asserts for a mode without a conversion (`MODE_YUV` and above); this
/// debug-asserts and writes nothing.
pub fn vp8l_convert_from_bgra(
    in_data: &[u32],
    num_pixels: i32,
    out_colorspace: WEBP_CSP_MODE,
    rgba: &mut [u8],
) {
    match out_colorspace {
        WEBP_CSP_MODE::MODE_RGB => vp8l_convert_bgra_to_rgb(in_data, num_pixels, rgba),
        WEBP_CSP_MODE::MODE_RGBA => vp8l_convert_bgra_to_rgba(in_data, num_pixels, rgba),
        WEBP_CSP_MODE::MODE_rgbA => {
            vp8l_convert_bgra_to_rgba(in_data, num_pixels, rgba);
            webp_apply_alpha_multiply(rgba, false, num_pixels, 1, 0);
        }
        WEBP_CSP_MODE::MODE_BGR => vp8l_convert_bgra_to_bgr(in_data, num_pixels, rgba),
        WEBP_CSP_MODE::MODE_BGRA => copy_or_swap(in_data, num_pixels, rgba, true),
        WEBP_CSP_MODE::MODE_bgrA => {
            copy_or_swap(in_data, num_pixels, rgba, true);
            webp_apply_alpha_multiply(rgba, false, num_pixels, 1, 0);
        }
        WEBP_CSP_MODE::MODE_ARGB => copy_or_swap(in_data, num_pixels, rgba, false),
        WEBP_CSP_MODE::MODE_Argb => {
            copy_or_swap(in_data, num_pixels, rgba, false);
            webp_apply_alpha_multiply(rgba, true, num_pixels, 1, 0);
        }
        WEBP_CSP_MODE::MODE_RGBA_4444 => vp8l_convert_bgra_to_rgba4444(in_data, num_pixels, rgba),
        WEBP_CSP_MODE::MODE_rgbA_4444 => {
            vp8l_convert_bgra_to_rgba4444(in_data, num_pixels, rgba);
            webp_apply_alpha_multiply4444(rgba, num_pixels, 1, 0);
        }
        WEBP_CSP_MODE::MODE_RGB_565 => vp8l_convert_bgra_to_rgb565(in_data, num_pixels, rgba),
        _ => debug_assert!(false, "Code flow should not reach here."),
    }
}