maroontree 0.1.1

AV1 & AV2 tiny still-image (AVIF) encoder
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
/*
 * Copyright (c) Radzivon Bartoshyk 6/2026. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3.  Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

use super::*;
use crate::Speed;

#[allow(clippy::too_many_arguments)]
fn dispatch_intra_pred(
    m: usize,
    adelta: i32,
    ab: &[i32],
    lf: &[i32],
    corner: i32,
    have_top: bool,
    have_left: bool,
    max_w: i32,
    max_h: i32,
) -> Vec<f32> {
    use directional::Dir::*;
    let dir = match m {
        1 => return intrapred::smooth(32, ab, lf),
        2 => return intrapred::smooth_v(32, ab, lf),
        3 => return intrapred::smooth_h(32, ab, lf),
        4 => return intrapred::paeth(32, ab, lf, corner),
        5 => V,
        6 => H,
        7 => D45,
        8 => D135,
        9 => D113,
        10 => D157,
        11 => D203,
        _ => D67,
    };
    directional::directional(
        dir, adelta, 32, ab, lf, corner, true, have_top, have_left, false, max_w, max_h,
    )
}

/// Build the prediction block for luma candidate `m` (0=DC, 1=SMOOTH, 4=PAETH)
/// at TX index `i` (raster within the 64x64 SB) and pixel origin `(y0,x0)`.
#[allow(clippy::too_many_arguments)]
pub(super) fn predict_luma(
    recy: &[f32],
    pw: usize,
    width: usize,
    height: usize,
    i: usize,
    y0: usize,
    x0: usize,
    m: usize,
    adelta: i32,
    neutral: f32,
) -> Vec<f32> {
    if m == 0 {
        return vec![dc_pred(recy, pw, y0, x0, 32, neutral); 1024];
    }
    let have_above = y0 > 0;
    let have_left = x0 > 0;
    let mi_col_end = (((width + 63) & !63) >> 2) as i64;
    let mi_row_end = (((height + 63) & !63) >> 2) as i64;
    let sb_y0 = (y0 / 64) * 64;
    let sb_x0 = (x0 / 64) * 64;
    let mi_row = (sb_y0 >> 2) as i64;
    let mi_col = (sb_x0 >> 2) as i64;
    let (row_off, col_off) = ((y0 - sb_y0) as i64 / 4, (x0 - sb_x0) as i64 / 4);
    let (lx, ly) = ((x0 - sb_x0) as i64, (y0 - sb_y0) as i64); // TX offset px within SB
    let xr = ((mi_col_end - mi_col - 16) << 2) + 32 - lx;
    let yd = ((mi_row_end - mi_row - 16) << 2) + 32 - ly;
    let right_available = (mi_col + col_off + 8) < mi_col_end;
    let bottom_available = (yd > 0) && ((mi_row + row_off + 8) < mi_row_end);
    // top-right: needed by TX 0/1/2 (TX 3 has col_off+txw==block width -> none)
    let tr_ok = matches!(i, 0..=2) && have_above && right_available && xr > 0;
    let tr_px = if tr_ok { xr.min(32).max(0) as usize } else { 0 };
    // bottom-left: only TX 0 (others sit at/under the block's bottom-left edge)
    let bl_ok = i == 0 && have_left && bottom_available && yd > 0;
    let bl_px = if bl_ok {
        (yd.min(32)).max(0) as usize
    } else {
        0
    };
    let (ab, lf, corner) = intrapred::build_refs(
        recy, pw, y0, x0, 32, have_above, have_left, tr_px, bl_px, neutral,
    );
    dispatch_intra_pred(
        m,
        adelta,
        &ab,
        &lf,
        corner,
        have_above,
        have_left,
        32 + tr_px as i32,
        32 + bl_px as i32,
    )
}

pub(crate) fn part_lambda(qstep: i32, c: f64) -> f64 {
    c * (qstep as f64) * (qstep as f64)
}

fn project_luma_rdoq(
    luma: &Basis,
    resid: &[f32],
    scan: &[u16],
    qc: usize,
    cost: &mut f64,
    lambda: f64,
) -> Vec<f32> {
    if lambda > 0.0 {
        let (mut l, prm) = luma.project_scan_with_prm(resid, scan);
        *cost += coder::rdoq_luma(&prm, &mut l, qc, scan, 1024, lambda);
        l
    } else {
        let l = luma.project(resid, 0.0);
        *cost += l
            .iter()
            .filter(|&&v| v != 0.0)
            .map(|&v| 2.0 + 2.0 * ((v.abs() as f64) + 1.0).log2())
            .sum::<f64>();
        l
    }
}

#[allow(clippy::too_many_arguments)]
pub(super) fn encode_luma_sb(
    recy: &mut [f32],
    yp: &[f32],
    pw: usize,
    width: usize,
    height: usize,
    sb_y: usize,
    sb_x: usize,
    luma: &Basis,
    qstep: i32,
    resid_scale: f32,
    scan: &[u16],
    neutral: f32,
    qc: usize,
    rdoq_lambda: f64,
    speed: Speed,
    bd: i32,
    allow_dir: bool,
) -> ([Vec<Coeff>; 4], usize, i8) {
    const POS: [(usize, usize); 4] = [(0, 0), (0, 32), (32, 0), (32, 32)];
    let mut best_cost = f64::INFINITY;
    let mut best_mode = 0usize;
    let mut best_delta = 0i32;
    let mut best_tus: [Vec<Coeff>; 4] = [Vec::new(), Vec::new(), Vec::new(), Vec::new()];
    let mut best_region = vec![0f32; 64 * 64];
    // Fast reduces the intra candidate set; non-Full tiers rank candidates with a
    // cheap coeff cost (RDOQ disabled) and re-RDOQ the winner only.
    let base_modes: &[usize] = if speed.reduced_modes() {
        if allow_dir {
            &[0usize, 1, 2, 5, 6, 7, 8, 9, 10, 11, 12]
        } else {
            &[0usize, 1, 2]
        }
    } else if allow_dir {
        &[0usize, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    } else {
        &[0usize, 1, 2, 3, 4]
    };
    // Directional modes trial all angle deltas (Δ = -3..=3, ×3°) only on the
    // Slow tier; faster tiers use the nominal angle (Δ=0) to avoid 7× the
    // directional RD candidates. Non-directional modes are always Δ=0.
    let dir_deltas: &[i32] = if speed.try_angle_deltas() {
        &[0, -1, 1, -2, 2, -3, 3]
    } else {
        &[0]
    };
    let mut cands: Vec<(usize, i32)> = Vec::new();
    for &m in base_modes {
        if m >= 5 {
            for &d in dir_deltas {
                cands.push((m, d));
            }
        } else {
            cands.push((m, 0));
        }
    }
    let search_lambda = if speed.per_candidate_rdoq() {
        rdoq_lambda
    } else {
        0.0
    };
    // Residual scratch reused across every (mode, angle) candidate of this SB,
    // instead of allocating a fresh 1024-element buffer per candidate.
    let resid_buf = std::cell::RefCell::new(vec![0f32; 1024]);
    // Encode one (mode, angle_delta) into `recy`, returning its TU coeffs and RD cost.
    let encode_mode =
        |recy: &mut [f32], m: usize, adelta: i32, lambda: f64| -> ([Vec<Coeff>; 4], f64) {
            let mut resid = resid_buf.borrow_mut();
            let mut cost = 0f64;
            let mut tus: [Vec<Coeff>; 4] = [Vec::new(), Vec::new(), Vec::new(), Vec::new()];
            for (i, &(ty, tx)) in POS.iter().enumerate() {
                let (y0, x0) = (sb_y + ty, sb_x + tx);
                let pblk = predict_luma(recy, pw, width, height, i, y0, x0, m, adelta, neutral);
                for r in 0..32 {
                    let base = (y0 + r) * pw + x0;
                    let src = &yp[base..base + 32];
                    let pred = &pblk[r * 32..r * 32 + 32];
                    let dst = &mut resid[r * 32..r * 32 + 32];
                    for ((d, &s), &p) in dst.iter_mut().zip(src).zip(pred) {
                        *d = (s - p) * resid_scale;
                    }
                }
                let lev = if lambda > 0.0 {
                    // Trellis RDOQ: pick coefficient levels by real rate-distortion
                    // (rate = true coded bits), then RD-trim the EOB.
                    let (mut l, prm) = luma.project_with_prm(&resid[..]);
                    cost += coder::rdoq_luma(&prm, &mut l, qc, scan, 1024, lambda);
                    l
                } else {
                    let l = luma.project(&resid[..], 0.0);
                    cost += l
                        .iter()
                        .filter(|&&v| v != 0.0)
                        .map(|&v| 2.0 + 2.0 * ((v.abs() as f64) + 1.0).log2())
                        .sum::<f64>();
                    l
                };
                let rb = reconstruct_luma(&pblk, &lev, qstep, scan, bd);
                put_block(recy, pw, y0, x0, 32, &rb);
                tus[i] = levels_to_coeffs(&lev);
            }
            // Mode-signaling cost (once per 64x64 block). DC is cheapest; SMOOTH/PAETH
            // and directional cost a few extra bits (directional a bit more for the
            // set/idx symbols), so only win when they earn them.
            if m != 0 {
                cost += if m >= 5 { 9.0 } else { 6.0 };
            }
            (tus, cost)
        };
    for &(m, d) in &cands {
        let (tus, cost) = encode_mode(recy, m, d, search_lambda);
        if cost < best_cost {
            best_cost = cost;
            best_mode = m;
            best_delta = d;
            best_tus = tus;
            for ry in 0..64 {
                let dst = ry * 64;
                let src = (sb_y + ry) * pw + sb_x;
                best_region[dst..dst + 64].copy_from_slice(&recy[src..src + 64]);
            }
        }
    }
    if speed.per_candidate_rdoq() || rdoq_lambda <= 0.0 {
        // Winner already coded at the final RDOQ setting (or RDOQ is off):
        // restore the saved winning reconstruction.
        for ry in 0..64 {
            let src = ry * 64;
            let dst = (sb_y + ry) * pw + sb_x;
            recy[dst..dst + 64].copy_from_slice(&best_region[src..src + 64]);
        }
    } else {
        // Winner-only RDOQ: re-encode the chosen mode with real RDOQ.
        let (tus, _) = encode_mode(recy, best_mode, best_delta, rdoq_lambda);
        best_tus = tus;
    }
    (best_tus, best_mode, best_delta as i8)
}

#[allow(clippy::too_many_arguments)]
pub(super) fn predict_luma_leaf32(
    recy: &[f32],
    pw: usize,
    mi_cols: i64,
    _mi_rows: i64,
    sb_y: usize,
    sb_x: usize,
    ti: usize,
    m: usize,
    neutral: f32,
) -> Vec<f32> {
    let (y0, x0) = (sb_y, sb_x + ti * 32);
    if m == 0 {
        return vec![dc_pred(recy, pw, y0, x0, 32, neutral); 1024];
    }
    let have_above = y0 > 0;
    let have_left = x0 > 0;
    let mi_col = (sb_x >> 2) as i64;
    let lx = (ti * 32) as i64;
    let col_off = lx / 4;
    // top-right reference width (px), clamped to 32. Same geometry as predict_luma
    // but with the native column bound.
    let xr = ((mi_cols - mi_col - 16) << 2) + 32 - lx;
    let right_available = (mi_col + col_off + 8) < mi_cols;
    let tr_ok = have_above && right_available && xr > 0;
    let tr_px = if tr_ok { xr.min(32).max(0) as usize } else { 0 };
    let (ab, lf, corner) = intrapred::build_refs(
        recy, pw, y0, x0, 32, have_above, have_left, tr_px, 0, neutral,
    );
    dispatch_intra_pred(
        m,
        0,
        &ab,
        &lf,
        corner,
        have_above,
        have_left,
        32 + tr_px as i32,
        32,
    )
}

#[allow(clippy::too_many_arguments)]
pub(super) fn encode_luma_leaf32(
    recy: &mut [f32],
    yp: &[f32],
    pw: usize,
    mi_cols: i64,
    mi_rows: i64,
    sb_y: usize,
    sb_x: usize,
    luma: &Basis,
    qstep: i32,
    scan: &[u16],
    neutral: f32,
    qc: usize,
    rdoq_lambda: f64,
    speed: Speed,
    bd: i32,
) -> ([Vec<Coeff>; 2], usize) {
    let mut best_cost = f64::INFINITY;
    let mut best_mode = 0usize;
    let mut best_tus: [Vec<Coeff>; 2] = [Vec::new(), Vec::new()];
    let mut best_region = [0f32; 64 * 32];
    let cands: &[usize] = if speed.reduced_modes() {
        &[0usize, 1, 2]
    } else {
        &[0usize, 1, 2, 3, 4]
    };
    let search_lambda = if speed.per_candidate_rdoq() {
        rdoq_lambda
    } else {
        0.0
    };
    let encode_mode = |recy: &mut [f32], m: usize, lambda: f64| -> ([Vec<Coeff>; 2], f64) {
        let mut resid = [0f32; 1024];
        let mut cost = 0f64;
        let mut tus: [Vec<Coeff>; 2] = [Vec::new(), Vec::new()];
        for (ti, tu) in tus.iter_mut().enumerate() {
            let (y0, x0) = (sb_y, sb_x + ti * 32);
            let pblk = predict_luma_leaf32(recy, pw, mi_cols, mi_rows, sb_y, sb_x, ti, m, neutral);
            for r in 0..32 {
                let base = (y0 + r) * pw + x0;
                for c in 0..32 {
                    resid[r * 32 + c] =
                        (yp[base + c] - pblk[r * 32 + c]) * (luma.qstep as f32 / qstep as f32);
                }
            }
            let lev = project_luma_rdoq(luma, &resid, scan, qc, &mut cost, lambda);
            let rb = reconstruct_luma(&pblk, &lev, qstep, scan, bd);
            put_block(recy, pw, y0, x0, 32, &rb);
            *tu = levels_to_coeffs(&lev);
        }
        if m != 0 {
            cost += 6.0;
        }
        (tus, cost)
    };
    for &m in cands {
        let (tus, cost) = encode_mode(recy, m, search_lambda);
        if cost < best_cost {
            best_cost = cost;
            best_mode = m;
            best_tus = tus;
            for ry in 0..32 {
                let src = (sb_y + ry) * pw + sb_x;
                best_region[ry * 64..ry * 64 + 64].copy_from_slice(&recy[src..src + 64]);
            }
        }
    }
    if speed.per_candidate_rdoq() || rdoq_lambda <= 0.0 {
        for ry in 0..32 {
            let dst = (sb_y + ry) * pw + sb_x;
            recy[dst..dst + 64].copy_from_slice(&best_region[ry * 64..ry * 64 + 64]);
        }
    } else {
        let (tus, _) = encode_mode(recy, best_mode, rdoq_lambda);
        best_tus = tus;
    }
    (best_tus, best_mode)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn predict_luma_leaf_tu(
    recy: &[f32],
    pw: usize,
    mc: i64,
    mr: i64,
    sb_y: usize,
    sb_x: usize,
    ty: usize,
    tx: usize,
    i: usize,
    m: usize,
    neutral: f32,
    split_leaf: bool,
) -> Vec<f32> {
    let (y0, x0) = (sb_y + ty, sb_x + tx);
    if m == 0 {
        return vec![dc_pred(recy, pw, y0, x0, 32, neutral); 1024];
    }
    let have_above = y0 > 0;
    let have_left = x0 > 0;
    let sb_x0 = (x0 / 64) * 64;
    let sb_y0 = (y0 / 64) * 64;
    let is_right = (x0 - sb_x0) >= 32;
    let is_bottom = (y0 - sb_y0) >= 32;
    let mi_col = (sb_x >> 2) as i64;
    let mi_row = (sb_y >> 2) as i64;
    let (lx, ly) = (tx as i64, ty as i64);
    let (col_off, row_off) = (lx / 4, ly / 4);
    let xr = ((mc - mi_col - 16) << 2) + 32 - lx;
    let yd = ((mr - mi_row - 16) << 2) + 32 - ly;
    // top-right unavailable for the bottom-right leaf; bottom-left only for the top-left leaf.
    // avm has_top_right: top-row leaves (tr_mask_row<0) read above-right from the
    // coded SB row above, so TL and TR both qualify; only bottom-row leaves don't.
    #[allow(clippy::overly_complex_bool_expr)]
    let tr_avail = !(is_right && is_bottom) && !is_bottom && (mi_col + col_off + 8) < mc;
    #[allow(clippy::overly_complex_bool_expr)]
    let bl_avail = !is_right && !is_bottom && (mi_row + row_off + 8) < mr;
    // SMOOTH/SMOOTH_H/D45/D67 need above-right; SMOOTH/SMOOTH_V/D203 need bottom-left.
    let need_tr = matches!(m, 1 | 3 | 7) || m >= 12;
    let need_bl = matches!(m, 1 | 2 | 11);
    let tr_ok = need_tr && matches!(i, 0..=2) && have_above && tr_avail && xr > 0;
    let tr_px = if tr_ok { xr.min(32).max(0) as usize } else { 0 };
    let bl_ok = need_bl
        && i == 0
        && have_left
        && (bl_avail || (split_leaf && is_right && !is_bottom))
        && yd > 0;
    let bl_px = if bl_ok { yd.min(32).max(0) as usize } else { 0 };
    let (ab, lf, corner) = intrapred::build_refs(
        recy, pw, y0, x0, 32, have_above, have_left, tr_px, bl_px, neutral,
    );
    dispatch_intra_pred(
        m,
        0,
        &ab,
        &lf,
        corner,
        have_above,
        have_left,
        32 + tr_px as i32,
        32 + bl_px as i32,
    )
}

/// Project + trial-code a right-edge 32x64 luma leaf as two stacked TX_32X32
/// (top i=0, bottom i=2). Mirrors `encode_luma_leaf32` but vertical.
#[allow(clippy::too_many_arguments)]
pub(super) fn encode_luma_leaf_v32x64(
    recy: &mut [f32],
    yp: &[f32],
    pw: usize,
    mc: i64,
    mr: i64,
    sb_y: usize,
    sb_x: usize,
    luma: &Basis,
    qstep: i32,
    scan: &[u16],
    neutral: f32,
    qc: usize,
    rdoq_lambda: f64,
    speed: Speed,
    bd: i32,
) -> ([Vec<Coeff>; 2], usize) {
    let tu_i = [(0usize, 0usize), (32usize, 2usize)]; // (ty, raster-i)
    let mut best_cost = f64::INFINITY;
    let mut best_mode = 0usize;
    let mut best_tus: [Vec<Coeff>; 2] = [Vec::new(), Vec::new()];
    let mut best_region = vec![0f32; 32 * 64];
    let cands: &[usize] = if speed.reduced_modes() {
        &[0usize, 1, 2]
    } else {
        &[0usize, 1, 2, 3, 4]
    };
    let search_lambda = if speed.per_candidate_rdoq() {
        rdoq_lambda
    } else {
        0.0
    };
    let encode_mode = |recy: &mut [f32], m: usize, lambda: f64| -> ([Vec<Coeff>; 2], f64) {
        let mut resid = vec![0f32; 1024];
        let mut cost = 0f64;
        let mut tus: [Vec<Coeff>; 2] = [Vec::new(), Vec::new()];
        for (k, &(ty, i)) in tu_i.iter().enumerate() {
            let (y0, x0) = (sb_y + ty, sb_x);
            let pblk =
                predict_luma_leaf_tu(recy, pw, mc, mr, sb_y, sb_x, ty, 0, i, m, neutral, false);
            for r in 0..32 {
                let base = (y0 + r) * pw + x0;
                for c in 0..32 {
                    resid[r * 32 + c] =
                        (yp[base + c] - pblk[r * 32 + c]) * (luma.qstep as f32 / qstep as f32);
                }
            }
            let lev = project_luma_rdoq(luma, &resid, scan, qc, &mut cost, lambda);
            let rb = reconstruct_luma(&pblk, &lev, qstep, scan, bd);
            put_block(recy, pw, y0, x0, 32, &rb);
            tus[k] = levels_to_coeffs(&lev);
        }
        if m != 0 {
            cost += 6.0;
        }
        (tus, cost)
    };
    for &m in cands {
        let (tus, cost) = encode_mode(recy, m, search_lambda);
        if cost < best_cost {
            best_cost = cost;
            best_mode = m;
            best_tus = tus;
            for ry in 0..64 {
                let src = (sb_y + ry) * pw + sb_x;
                best_region[ry * 32..ry * 32 + 32].copy_from_slice(&recy[src..src + 32]);
            }
        }
    }
    if speed.per_candidate_rdoq() || rdoq_lambda <= 0.0 {
        for ry in 0..64 {
            let dst = (sb_y + ry) * pw + sb_x;
            recy[dst..dst + 32].copy_from_slice(&best_region[ry * 32..ry * 32 + 32]);
        }
    } else {
        let (tus, _) = encode_mode(recy, best_mode, rdoq_lambda);
        best_tus = tus;
    }
    (best_tus, best_mode)
}

/// Project + trial-code a corner 32x32 luma leaf as a single TX_32X32 (i=0).
#[allow(clippy::too_many_arguments)]
pub(super) fn encode_luma_leaf_s32x32(
    recy: &mut [f32],
    yp: &[f32],
    pw: usize,
    mc: i64,
    mr: i64,
    sb_y: usize,
    sb_x: usize,
    luma: &Basis,
    qstep: i32,
    scan: &[u16],
    neutral: f32,
    qc: usize,
    rdoq_lambda: f64,
    speed: Speed,
    bd: i32,
) -> (Vec<Coeff>, usize) {
    let cands: &[usize] = if speed.reduced_modes() {
        &[0usize, 1, 2]
    } else {
        &[0usize, 1, 2, 3, 4]
    };
    let search_lambda = if speed.per_candidate_rdoq() {
        rdoq_lambda
    } else {
        0.0
    };
    // Single TU: no intra-leaf feedback, so a mode is fully described by its
    // (recon, coeffs, cost) and the winner can simply be re-projected with RDOQ.
    let encode_mode = |recy: &[f32], m: usize, lambda: f64| -> ([f32; 1024], Vec<Coeff>, f64) {
        let pblk = predict_luma_leaf_tu(recy, pw, mc, mr, sb_y, sb_x, 0, 0, 0, m, neutral, true);
        let mut resid = [0f32; 1024];
        for r in 0..32 {
            let base = (sb_y + r) * pw + sb_x;
            for c in 0..32 {
                resid[r * 32 + c] =
                    (yp[base + c] - pblk[r * 32 + c]) * (luma.qstep as f32 / qstep as f32);
            }
        }
        let mut cost = 0f64;
        let lev = project_luma_rdoq(luma, &resid, scan, qc, &mut cost, lambda);
        if m != 0 {
            cost += 6.0;
        }
        let rb = reconstruct_luma(&pblk, &lev, qstep, scan, bd);
        (rb, levels_to_coeffs(&lev), cost)
    };
    let mut best_cost = f64::INFINITY;
    let mut best_mode = 0usize;
    let mut best_tu: Vec<Coeff> = Vec::new();
    let mut best_region = vec![0f32; 32 * 32];
    for &m in cands {
        let (rb, tu, cost) = encode_mode(recy, m, search_lambda);
        if cost < best_cost {
            best_cost = cost;
            best_mode = m;
            best_tu = tu;
            best_region.copy_from_slice(&rb);
        }
    }
    if !speed.per_candidate_rdoq() && rdoq_lambda > 0.0 {
        // Winner-only RDOQ: re-project the chosen mode with real RDOQ.
        let (rb, tu, _) = encode_mode(recy, best_mode, rdoq_lambda);
        best_tu = tu;
        best_region.copy_from_slice(&rb);
    }
    put_block(recy, pw, sb_y, sb_x, 32, &best_region);
    (best_tu, best_mode)
}