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
// libwebp v1.6.0, src/enc/cost_enc.c:
//
// Copyright 2011 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.
// -----------------------------------------------------------------------------
//
// Cost tables for level and modes
//
// Author: Skal (pascal.massimino@gmail.com)

// libwebp v1.6.0, src/enc/cost_enc.h:
//
// Copyright 2011 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.
// -----------------------------------------------------------------------------
//
// Cost tables for level and modes.
//
// Author: Skal (pascal.massimino@gmail.com)

//! Translation of `src/enc/cost_enc.c` and `src/enc/cost_enc.h` from libwebp v1.6.0.
//!
//! Work package: WP10 (VP8 encoder core).

use crate::dec::common_dec::{NUM_BANDS, NUM_BMODES};
use crate::dsp::cost::{
    VP8_ENC_BANDS, VP8_ENTROPY_COST, VP8_LEVEL_FIXED_COSTS, vp8_get_residual_cost,
    vp8_set_residual_coeffs,
};
use crate::enc::iterator_enc::vp8_iterator_nz_to_bytes;
use crate::enc::vp8i_enc::{
    CostArrayPtr, MAX_VARIABLE_LEVEL, ProbaArray, StatsArray, VP8EncIterator, VP8EncProba,
    VP8Encoder, VP8ModeScore, proba_t,
};

// upstream: src/enc/cost_enc.h VP8Residual
/// On-the-fly info about the current set of residuals. Handy to avoid passing
/// zillions of params. C points `prob`, `stats` and `costs` into the encoder's
/// probabilities; here they are borrows of the three arrays of one coefficient
/// type, and `stats` is the only mutable one.
#[derive(Debug)]
pub struct VP8Residual<'a> {
    pub first: i32,
    pub last: i32,
    /// The 16 levels of the current block.
    pub coeffs: &'a [i16],

    pub coeff_type: i32,
    pub prob: &'a [ProbaArray; NUM_BANDS as usize],
    pub stats: &'a mut [StatsArray; NUM_BANDS as usize],
    pub costs: CostArrayPtr<'a>,
}

// upstream: src/enc/cost_enc.h VP8RecordStats
/// Record proba context used.
pub fn vp8_record_stats(bit: i32, stats: &mut proba_t) -> i32 {
    let mut p = *stats;
    // An overflow is inbound. Note we handle this at 0xfffe0000u instead of
    // 0xffff0000u to make sure p + 1u does not overflow.
    if p >= 0xfffe_0000 {
        p = ((p + 1) >> 1) & 0x7fff_7fff; // -> divide the stats by 2.
    }
    // record bit count (lower 16 bits) and increment total count (upper 16 bits).
    #[expect(clippy::cast_sign_loss, reason = "bit is 0 or 1")]
    {
        p += 0x0001_0000 + bit as u32;
    }
    *stats = p;
    bit
}

// upstream: src/enc/cost_enc.h VP8BitCost
/// Cost of coding one event with probability 'proba'.
#[must_use]
pub fn vp8_bit_cost(bit: bool, proba: u8) -> i32 {
    if bit {
        i32::from(VP8_ENTROPY_COST[255 - usize::from(proba)])
    } else {
        i32::from(VP8_ENTROPY_COST[usize::from(proba)])
    }
}

// upstream: src/enc/cost_enc.h VP8LevelCost
/// The cost of `level` with the variable part from `table`.
#[must_use]
#[expect(clippy::cast_sign_loss, reason = "levels are non-negative")]
pub fn vp8_level_cost(table: &[u16; MAX_VARIABLE_LEVEL as usize + 1], level: i32) -> i32 {
    i32::from(VP8_LEVEL_FIXED_COSTS[level as usize])
        + i32::from(
            table[if level > MAX_VARIABLE_LEVEL {
                MAX_VARIABLE_LEVEL
            } else {
                level
            } as usize],
        )
}

//------------------------------------------------------------------------------
// Level cost tables

// upstream: src/enc/cost_enc.c VP8LevelCodes
/// For each given level, the following table gives the pattern of contexts to
/// use for coding it (in [][0]) as well as the bit value to use for each
/// context (in [][1]).
pub static VP8_LEVEL_CODES: [[u16; 2]; MAX_VARIABLE_LEVEL as usize] = [
    [0x001, 0x000],
    [0x007, 0x001],
    [0x00f, 0x005],
    [0x00f, 0x00d],
    [0x033, 0x003],
    [0x033, 0x003],
    [0x033, 0x023],
    [0x033, 0x023],
    [0x033, 0x023],
    [0x033, 0x023],
    [0x0d3, 0x013],
    [0x0d3, 0x013],
    [0x0d3, 0x013],
    [0x0d3, 0x013],
    [0x0d3, 0x013],
    [0x0d3, 0x013],
    [0x0d3, 0x013],
    [0x0d3, 0x013],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x0d3, 0x093],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x053],
    [0x153, 0x153],
];

// upstream: src/enc/cost_enc.c VariableLevelCost
#[expect(clippy::cast_sign_loss, reason = "level is in 1..=MAX_VARIABLE_LEVEL")]
fn variable_level_cost(level: i32, probas: &[u8; 11]) -> i32 {
    let mut pattern = i32::from(VP8_LEVEL_CODES[(level - 1) as usize][0]);
    let mut bits = i32::from(VP8_LEVEL_CODES[(level - 1) as usize][1]);
    let mut cost = 0;
    let mut i = 2;
    while pattern != 0 {
        if pattern & 1 != 0 {
            cost += vp8_bit_cost(bits & 1 != 0, probas[i]);
        }
        bits >>= 1;
        pattern >>= 1;
        i += 1;
    }
    cost
}

//------------------------------------------------------------------------------
// Pre-calc level costs once for all

// upstream: src/enc/cost_enc.c VP8CalculateLevelCosts
/// Fills the level cost tables and their remapping from the probabilities,
/// when they are dirty.
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "the costs fit uint16_t, as in C, and the loop indexes are non-negative"
)]
#[expect(clippy::needless_range_loop, reason = "the C index loops")]
pub fn vp8_calculate_level_costs(proba: &mut VP8EncProba) {
    if !proba.dirty {
        return; // nothing to do.
    }

    for ctype in 0..crate::dec::common_dec::NUM_TYPES as usize {
        for band in 0..NUM_BANDS as usize {
            for ctx in 0..crate::dec::common_dec::NUM_CTX as usize {
                let p = &proba.coeffs[ctype][band][ctx];
                let table = &mut proba.level_cost[ctype][band][ctx];
                let cost0 = if ctx > 0 { vp8_bit_cost(true, p[0]) } else { 0 };
                let cost_base = vp8_bit_cost(true, p[1]) + cost0;
                table[0] = (vp8_bit_cost(false, p[1]) + cost0) as u16;
                for v in 1..=MAX_VARIABLE_LEVEL {
                    table[v as usize] = (cost_base + variable_level_cost(v, p)) as u16;
                }
                // Starting at level 67 and up, the variable part of the cost is
                // actually constant.
            }
        }
        for n in 0..16 {
            // replicate bands. We don't need to sentinel.
            for ctx in 0..crate::dec::common_dec::NUM_CTX as usize {
                proba.remapped_costs[ctype][n][ctx] = VP8_ENC_BANDS[n];
            }
        }
    }
    proba.dirty = false;
}

//------------------------------------------------------------------------------
// Mode cost tables.

// upstream: src/enc/cost_enc.c VP8FixedCostsUV
/// These are the fixed probabilities (in the coding trees) turned into bit-cost
/// by calling `VP8BitCost()`.
pub static VP8_FIXED_COSTS_UV: [u16; 4] = [302, 984, 439, 642];
// upstream: src/enc/cost_enc.c VP8FixedCostsI16
/// Note: these values include the fixed `VP8BitCost(1, 145)` mode selection cost.
pub static VP8_FIXED_COSTS_I16: [u16; 4] = [663, 919, 872, 919];
// upstream: src/enc/cost_enc.c VP8FixedCostsI4
pub static VP8_FIXED_COSTS_I4: [[[u16; NUM_BMODES as usize]; NUM_BMODES as usize];
    NUM_BMODES as usize] = [
    [
        [40, 1151, 1723, 1874, 2103, 2019, 1628, 1777, 2226, 2137],
        [192, 469, 1296, 1308, 1849, 1794, 1781, 1703, 1713, 1522],
        [142, 910, 762, 1684, 1849, 1576, 1460, 1305, 1801, 1657],
        [559, 641, 1370, 421, 1182, 1569, 1612, 1725, 863, 1007],
        [299, 1059, 1256, 1108, 636, 1068, 1581, 1883, 869, 1142],
        [277, 1111, 707, 1362, 1089, 672, 1603, 1541, 1545, 1291],
        [214, 781, 1609, 1303, 1632, 2229, 726, 1560, 1713, 918],
        [152, 1037, 1046, 1759, 1983, 2174, 1358, 742, 1740, 1390],
        [512, 1046, 1420, 753, 752, 1297, 1486, 1613, 460, 1207],
        [424, 827, 1362, 719, 1462, 1202, 1199, 1476, 1199, 538],
    ],
    [
        [240, 402, 1134, 1491, 1659, 1505, 1517, 1555, 1979, 2099],
        [467, 242, 960, 1232, 1714, 1620, 1834, 1570, 1676, 1391],
        [500, 455, 463, 1507, 1699, 1282, 1564, 982, 2114, 2114],
        [672, 643, 1372, 331, 1589, 1667, 1453, 1938, 996, 876],
        [458, 783, 1037, 911, 738, 968, 1165, 1518, 859, 1033],
        [504, 815, 504, 1139, 1219, 719, 1506, 1085, 1268, 1268],
        [333, 630, 1445, 1239, 1883, 3672, 799, 1548, 1865, 598],
        [399, 644, 746, 1342, 1856, 1350, 1493, 613, 1855, 1015],
        [622, 749, 1205, 608, 1066, 1408, 1290, 1406, 546, 971],
        [500, 753, 1041, 668, 1230, 1617, 1297, 1425, 1383, 523],
    ],
    [
        [394, 553, 523, 1502, 1536, 981, 1608, 1142, 1666, 2181],
        [655, 430, 375, 1411, 1861, 1220, 1677, 1135, 1978, 1553],
        [690, 640, 245, 1954, 2070, 1194, 1528, 982, 1972, 2232],
        [559, 834, 741, 867, 1131, 980, 1225, 852, 1092, 784],
        [690, 875, 516, 959, 673, 894, 1056, 1190, 1528, 1126],
        [740, 951, 384, 1277, 1177, 492, 1579, 1155, 1846, 1513],
        [323, 775, 1062, 1776, 3062, 1274, 813, 1188, 1372, 655],
        [488, 971, 484, 1767, 1515, 1775, 1115, 503, 1539, 1461],
        [740, 1006, 998, 709, 851, 1230, 1337, 788, 741, 721],
        [522, 1073, 573, 1045, 1346, 887, 1046, 1146, 1203, 697],
    ],
    [
        [105, 864, 1442, 1009, 1934, 1840, 1519, 1920, 1673, 1579],
        [534, 305, 1193, 683, 1388, 2164, 1802, 1894, 1264, 1170],
        [305, 518, 877, 1108, 1426, 3215, 1425, 1064, 1320, 1242],
        [683, 732, 1927, 257, 1493, 2048, 1858, 1552, 1055, 947],
        [394, 814, 1024, 660, 959, 1556, 1282, 1289, 893, 1047],
        [528, 615, 996, 940, 1201, 635, 1094, 2515, 803, 1358],
        [347, 614, 1609, 1187, 3133, 1345, 1007, 1339, 1017, 667],
        [218, 740, 878, 1605, 3650, 3650, 1345, 758, 1357, 1617],
        [672, 750, 1541, 558, 1257, 1599, 1870, 2135, 402, 1087],
        [592, 684, 1161, 430, 1092, 1497, 1475, 1489, 1095, 822],
    ],
    [
        [228, 1056, 1059, 1368, 752, 982, 1512, 1518, 987, 1782],
        [494, 514, 818, 942, 965, 892, 1610, 1356, 1048, 1363],
        [512, 648, 591, 1042, 761, 991, 1196, 1454, 1309, 1463],
        [683, 749, 1043, 676, 841, 1396, 1133, 1138, 654, 939],
        [622, 1101, 1126, 994, 361, 1077, 1203, 1318, 877, 1219],
        [631, 1068, 857, 1650, 651, 477, 1650, 1419, 828, 1170],
        [555, 727, 1068, 1335, 3127, 1339, 820, 1331, 1077, 429],
        [504, 879, 624, 1398, 889, 889, 1392, 808, 891, 1406],
        [683, 1602, 1289, 977, 578, 983, 1280, 1708, 406, 1122],
        [399, 865, 1433, 1070, 1072, 764, 968, 1477, 1223, 678],
    ],
    [
        [333, 760, 935, 1638, 1010, 529, 1646, 1410, 1472, 2219],
        [512, 494, 750, 1160, 1215, 610, 1870, 1868, 1628, 1169],
        [572, 646, 492, 1934, 1208, 603, 1580, 1099, 1398, 1995],
        [786, 789, 942, 581, 1018, 951, 1599, 1207, 731, 768],
        [690, 1015, 672, 1078, 582, 504, 1693, 1438, 1108, 2897],
        [768, 1267, 571, 2005, 1243, 244, 2881, 1380, 1786, 1453],
        [452, 899, 1293, 903, 1311, 3100, 465, 1311, 1319, 813],
        [394, 927, 942, 1103, 1358, 1104, 946, 593, 1363, 1109],
        [559, 1005, 1007, 1016, 658, 1173, 1021, 1164, 623, 1028],
        [564, 796, 632, 1005, 1014, 863, 2316, 1268, 938, 764],
    ],
    [
        [266, 606, 1098, 1228, 1497, 1243, 948, 1030, 1734, 1461],
        [366, 585, 901, 1060, 1407, 1247, 876, 1134, 1620, 1054],
        [452, 565, 542, 1729, 1479, 1479, 1016, 886, 2938, 1150],
        [555, 1088, 1533, 950, 1354, 895, 834, 1019, 1021, 496],
        [704, 815, 1193, 971, 973, 640, 1217, 2214, 832, 578],
        [672, 1245, 579, 871, 875, 774, 872, 1273, 1027, 949],
        [296, 1134, 2050, 1784, 1636, 3425, 442, 1550, 2076, 722],
        [342, 982, 1259, 1846, 1848, 1848, 622, 568, 1847, 1052],
        [555, 1064, 1304, 828, 746, 1343, 1075, 1329, 1078, 494],
        [288, 1167, 1285, 1174, 1639, 1639, 833, 2254, 1304, 509],
    ],
    [
        [342, 719, 767, 1866, 1757, 1270, 1246, 550, 1746, 2151],
        [483, 653, 694, 1509, 1459, 1410, 1218, 507, 1914, 1266],
        [488, 757, 447, 2979, 1813, 1268, 1654, 539, 1849, 2109],
        [522, 1097, 1085, 851, 1365, 1111, 851, 901, 961, 605],
        [709, 716, 841, 728, 736, 945, 941, 862, 2845, 1057],
        [512, 1323, 500, 1336, 1083, 681, 1342, 717, 1604, 1350],
        [452, 1155, 1372, 1900, 1501, 3290, 311, 944, 1919, 922],
        [403, 1520, 977, 2132, 1733, 3522, 1076, 276, 3335, 1547],
        [559, 1374, 1101, 615, 673, 2462, 974, 795, 984, 984],
        [547, 1122, 1062, 812, 1410, 951, 1140, 622, 1268, 651],
    ],
    [
        [165, 982, 1235, 938, 1334, 1366, 1659, 1578, 964, 1612],
        [592, 422, 925, 847, 1139, 1112, 1387, 2036, 861, 1041],
        [403, 837, 732, 770, 941, 1658, 1250, 809, 1407, 1407],
        [896, 874, 1071, 381, 1568, 1722, 1437, 2192, 480, 1035],
        [640, 1098, 1012, 1032, 684, 1382, 1581, 2106, 416, 865],
        [559, 1005, 819, 914, 710, 770, 1418, 920, 838, 1435],
        [415, 1258, 1245, 870, 1278, 3067, 770, 1021, 1287, 522],
        [406, 990, 601, 1009, 1265, 1265, 1267, 759, 1017, 1277],
        [968, 1182, 1329, 788, 1032, 1292, 1705, 1714, 203, 1403],
        [732, 877, 1279, 471, 901, 1161, 1545, 1294, 755, 755],
    ],
    [
        [111, 931, 1378, 1185, 1933, 1648, 1148, 1714, 1873, 1307],
        [406, 414, 1030, 1023, 1910, 1404, 1313, 1647, 1509, 793],
        [342, 640, 575, 1088, 1241, 1349, 1161, 1350, 1756, 1502],
        [559, 766, 1185, 357, 1682, 1428, 1329, 1897, 1219, 802],
        [473, 909, 1164, 771, 719, 2508, 1427, 1432, 722, 782],
        [342, 892, 785, 1145, 1150, 794, 1296, 1550, 973, 1057],
        [208, 1036, 1326, 1343, 1606, 3395, 815, 1455, 1618, 712],
        [228, 928, 890, 1046, 3499, 1711, 994, 829, 1720, 1318],
        [768, 724, 1058, 636, 991, 1075, 1319, 1324, 616, 825],
        [305, 1167, 1358, 899, 1587, 1587, 987, 1988, 1332, 501],
    ],
];

//------------------------------------------------------------------------------
// helper functions for residuals struct VP8Residual.

// upstream: src/enc/cost_enc.c VP8InitResidual
/// A residual of `coeff_type` from position `first`, over the probabilities of
/// that type. C fills the caller's `res` and leaves `last` and `coeffs` to
/// `VP8SetResidualCoeffs`; the returned residual has no levels yet. C reads
/// only `enc->proba`, which is what the residual borrows.
#[expect(clippy::cast_sign_loss, reason = "coeff_type is in 0..NUM_TYPES")]
pub fn vp8_init_residual(first: i32, coeff_type: i32, proba: &mut VP8EncProba) -> VP8Residual<'_> {
    let VP8EncProba {
        coeffs,
        stats,
        level_cost,
        remapped_costs,
        ..
    } = proba;
    let t = coeff_type as usize;
    VP8Residual {
        first,
        last: -1,
        coeffs: &[],
        coeff_type,
        prob: &coeffs[t],
        stats: &mut stats[t],
        costs: CostArrayPtr {
            level_cost: &level_cost[t],
            remapped: &remapped_costs[t],
        },
    }
}

//------------------------------------------------------------------------------
// Mode costs

// upstream: src/enc/cost_enc.c VP8GetCostLuma4
/// The rate of the intra4 block `it->i4` with the levels `levels`.
#[must_use]
#[expect(clippy::cast_sign_loss, reason = "i4 is in 0..16")]
pub fn vp8_get_cost_luma4(it: &VP8EncIterator, enc: &mut VP8Encoder, levels: &[i16; 16]) -> i32 {
    let x = (it.i4 & 3) as usize;
    let y = (it.i4 >> 2) as usize;
    let mut r = 0;

    let mut res = vp8_init_residual(0, 3, &mut enc.proba);
    let ctx = it.top_nz[x] + it.left_nz[y];
    vp8_set_residual_coeffs(levels, &mut res);
    r += vp8_get_residual_cost(ctx, &res);
    r
}

// upstream: src/enc/cost_enc.c VP8GetCostLuma16
/// The rate of the intra16 levels of `rd`.
pub fn vp8_get_cost_luma16(
    it: &mut VP8EncIterator,
    enc: &mut VP8Encoder,
    rd: &VP8ModeScore,
) -> i32 {
    let mut r = 0;

    vp8_iterator_nz_to_bytes(it, enc); // re-import the non-zero context

    // DC
    let mut res = vp8_init_residual(0, 1, &mut enc.proba);
    vp8_set_residual_coeffs(&rd.y_dc_levels, &mut res);
    r += vp8_get_residual_cost(it.top_nz[8] + it.left_nz[8], &res);

    // AC
    let mut res = vp8_init_residual(1, 0, &mut enc.proba);
    for y in 0..4 {
        for x in 0..4 {
            let ctx = it.top_nz[x] + it.left_nz[y];
            vp8_set_residual_coeffs(&rd.y_ac_levels[x + y * 4], &mut res);
            r += vp8_get_residual_cost(ctx, &res);
            let nz = i32::from(res.last >= 0);
            it.top_nz[x] = nz;
            it.left_nz[y] = nz;
        }
    }
    r
}

// upstream: src/enc/cost_enc.c VP8GetCostUV
/// The rate of the chroma levels of `rd`.
pub fn vp8_get_cost_uv(it: &mut VP8EncIterator, enc: &mut VP8Encoder, rd: &VP8ModeScore) -> i32 {
    let mut r = 0;

    vp8_iterator_nz_to_bytes(it, enc); // re-import the non-zero context

    let mut res = vp8_init_residual(0, 2, &mut enc.proba);
    for ch in [0, 2] {
        for y in 0..2 {
            for x in 0..2 {
                let ctx = it.top_nz[4 + ch + x] + it.left_nz[4 + ch + y];
                vp8_set_residual_coeffs(&rd.uv_levels[ch * 2 + x + y * 2], &mut res);
                r += vp8_get_residual_cost(ctx, &res);
                let nz = i32::from(res.last >= 0);
                it.top_nz[4 + ch + x] = nz;
                it.left_nz[4 + ch + y] = nz;
            }
        }
    }
    r
}

//------------------------------------------------------------------------------
// Recording of token probabilities.

// upstream: src/enc/cost_enc.c USE_LEVEL_CODE_TABLE
// We keep the table-free variant around for reference, in case. The reference
// configuration defines USE_LEVEL_CODE_TABLE, so only the table variant is
// translated.

// upstream: src/enc/cost_enc.c VP8RecordCoeffs
/// Simulate block coding, but only record statistics.
/// Note: no need to record the fixed probas.
#[expect(
    clippy::cast_sign_loss,
    reason = "positions, contexts and levels are non-negative indexes"
)]
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    reason = "the position is in 0..=16"
)]
pub fn vp8_record_coeffs(ctx: i32, res: &mut VP8Residual<'_>) -> i32 {
    let mut n = res.first as usize;
    // should be stats[VP8EncBands[n]], but it's equivalent for n=0 or 1
    let mut s: (usize, usize) = (n, ctx as usize);
    if res.last < 0 {
        vp8_record_stats(0, &mut res.stats[s.0][s.1][0]);
        return 0;
    }
    while n as i32 <= res.last {
        let mut v;
        vp8_record_stats(1, &mut res.stats[s.0][s.1][0]); // order of record doesn't matter
        loop {
            v = i32::from(res.coeffs[n]);
            n += 1;
            if v != 0 {
                break;
            }
            vp8_record_stats(0, &mut res.stats[s.0][s.1][1]);
            s = (usize::from(VP8_ENC_BANDS[n]), 0);
        }
        vp8_record_stats(1, &mut res.stats[s.0][s.1][1]);
        #[expect(clippy::cast_sign_loss, reason = "C compares (unsigned int)(v + 1)")]
        let big = i32::from(2u32 < (v + 1) as u32);
        if vp8_record_stats(big, &mut res.stats[s.0][s.1][2]) == 0 {
            // v = -1 or 1
            s = (usize::from(VP8_ENC_BANDS[n]), 1);
        } else {
            v = v.abs();
            if v > MAX_VARIABLE_LEVEL {
                v = MAX_VARIABLE_LEVEL;
            }

            {
                let bits = i32::from(VP8_LEVEL_CODES[(v - 1) as usize][1]);
                let mut pattern = i32::from(VP8_LEVEL_CODES[(v - 1) as usize][0]);
                let mut i = 0;
                loop {
                    pattern >>= 1;
                    if pattern == 0 {
                        break;
                    }
                    let mask = 2 << i;
                    if pattern & 1 != 0 {
                        vp8_record_stats(
                            i32::from(bits & mask != 0),
                            &mut res.stats[s.0][s.1][3 + i],
                        );
                    }
                    i += 1;
                }
            }
            s = (usize::from(VP8_ENC_BANDS[n]), 2);
        }
    }
    if n < 16 {
        vp8_record_stats(0, &mut res.stats[s.0][s.1][0]);
    }
    1
}