oxideav-vp8 0.2.10

Pure-Rust VP8 video codec — orphan-rebuild scaffold pending clean-room re-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
//! Motion-compensated temporal filtering for altref synthesis.
//!
//! Builds the *picture* that [`crate::encoder::encode_invisible_altref_update`]
//! installs into the §9.7 ALTREF slot: a noise-reduced blend of a small
//! window of source frames, aligned per 16×16 block by whole-pel motion
//! search. Prediction from a temporally-filtered anchor is stronger than
//! from any single source frame on noisy content, because the residual
//! against every nearby frame shrinks once the (uncorrelated) noise is
//! averaged out of the reference.
//!
//! RFC 6386 is silent on all of this by design — the bitstream only
//! defines how an altref picture is *transported* (§9.1 `show_frame`,
//! §9.7 `refresh_alternate_frame`), never how an encoder should build
//! one. The filter here is therefore a clean-room encoder-quality
//! decision, like the two-pass rate-control family:
//!
//! 1. For every 16×16 block of the **center** frame, each *other* frame
//!    in the window is aligned by a whole-pel three-round refinement
//!    search (±15 px, step 8 → 4 → 2 → 1) minimising SAD against the
//!    center block. Edge-clamped fetches make every candidate valid.
//! 2. A block whose best per-pixel SAD is still large is dropped from
//!    the blend for that block (occlusion / scene-change guard) — a bad
//!    match must not bleed foreign content into the anchor.
//! 3. Surviving pixels blend with a per-pixel weight that decays with
//!    the absolute difference from the center pixel
//!    (`w = W_MAX·S / (S + d²)`, `S` scaled by
//!    [`ArnrConfig::strength`]), so detail preserved in only one frame
//!    is not smeared. The center pixel always carries full weight —
//!    strength 0 degenerates to an exact copy of the center frame.
//!
//! Chroma planes reuse the luma motion (halved, as §18.2 does for
//! chroma MVs) with the same difference-driven weighting.

use crate::encoder::{EncodeError, I420Frame};

/// Full blend weight (the center pixel's constant weight).
const W_MAX: u32 = 16;

/// Per-pixel SAD ceiling (per luma pixel, ×256 per block) above which a
/// motion-compensated block is considered a bad match and excluded from
/// the blend entirely.
const BLOCK_SAD_PER_PIXEL_CUTOFF: u32 = 12;

/// Configuration for [`build_arnr_altref`].
///
/// `strength` is the only dial: `0` disables filtering (the output is a
/// copy of the center frame), higher values weight neighbouring frames'
/// pixels more aggressively at a given pixel difference. Values above
/// [`ArnrConfig::MAX_STRENGTH`] are clamped by [`ArnrConfig::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ArnrConfig {
    /// Filter aggressiveness, `0..=6`. `0` = pass-through (center frame
    /// copied verbatim); `6` = strongest blending. Default `3`.
    pub strength: u8,
}

impl ArnrConfig {
    /// Set `strength`.
    #[must_use]
    pub fn with_strength(mut self, v: u8) -> Self {
        self.strength = v;
        self
    }
}

impl ArnrConfig {
    /// Largest meaningful [`strength`](Self::strength).
    pub const MAX_STRENGTH: u8 = 6;

    /// Build a config, clamping `strength` into `0..=MAX_STRENGTH`.
    pub fn new(strength: u8) -> Self {
        ArnrConfig {
            strength: strength.min(Self::MAX_STRENGTH),
        }
    }
}

impl Default for ArnrConfig {
    fn default() -> Self {
        ArnrConfig { strength: 3 }
    }
}

/// An owned I420 picture produced by [`build_arnr_altref`] — the
/// synthetic altref anchor. Feed [`Self::as_i420`] to
/// [`crate::encoder::encode_invisible_altref_update`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct ArnrPicture {
    /// Visible width in luma pixels.
    pub width: u32,
    /// Visible height in luma pixels.
    pub height: u32,
    /// Luma plane, `width × height`, tightly packed.
    pub y: Vec<u8>,
    /// U plane, `((width+1)/2) × ((height+1)/2)`, tightly packed.
    pub u: Vec<u8>,
    /// V plane, same dimensions as `u`.
    pub v: Vec<u8>,
}

impl ArnrPicture {
    /// Set `width`.
    #[must_use]
    pub fn with_width(mut self, v: u32) -> Self {
        self.width = v;
        self
    }

    /// Set `height`.
    #[must_use]
    pub fn with_height(mut self, v: u32) -> Self {
        self.height = v;
        self
    }

    /// Set `y`.
    #[must_use]
    pub fn with_y(mut self, v: Vec<u8>) -> Self {
        self.y = v;
        self
    }

    /// Set `u`.
    #[must_use]
    pub fn with_u(mut self, v: Vec<u8>) -> Self {
        self.u = v;
        self
    }

    /// Set `v`.
    #[must_use]
    pub fn with_v(mut self, v: Vec<u8>) -> Self {
        self.v = v;
        self
    }
}

impl ArnrPicture {
    /// Borrow the picture as a tightly-packed [`I420Frame`].
    pub fn as_i420(&self) -> I420Frame<'_> {
        I420Frame::packed(self.width, self.height, &self.y, &self.u, &self.v)
    }
}

/// Edge-clamped pixel fetch from a strided plane.
#[inline]
fn pel(plane: &[u8], stride: usize, w: i32, h: i32, x: i32, y: i32) -> u8 {
    let cx = x.clamp(0, w - 1) as usize;
    let cy = y.clamp(0, h - 1) as usize;
    plane[cy * stride + cx]
}

/// SAD of one `bw × bh` block of `src` (anchored at `(bx, by)`, fully
/// in-bounds) against the edge-clamped block of `refp` displaced by
/// `(mvx, mvy)`, accumulating each candidate row exactly as
/// [`block_sad_generic`] does.
///
/// Two cost levers over the straightforward per-pixel form, neither of
/// which changes any returned value the caller can observe:
///
/// * **in-bounds fast path** — when the whole displaced block lands
///   strictly inside the reference plane (the overwhelmingly common
///   case away from frame edges), the per-pixel `clamp` + row-base
///   multiply of [`pel`] collapses to two straight row slices. The
///   clamped generic path is kept verbatim for the genuine edge case
///   and doubles as the equivalence reference
///   (`block_sad_fast_matches_generic` pins them pixel-for-pixel).
/// * **monotone early exit** — the row-partial SAD only ever grows, so
///   once it reaches `early_exit_at` the final SAD is guaranteed to be
///   `>= early_exit_at` and the candidate can be abandoned. The caller
///   ([`refine_search`]) only accepts a candidate on a *strictly
///   smaller* SAD, so returning any partial `>= early_exit_at` selects
///   the identical winner with the identical best SAD: a candidate
///   that would win never triggers the exit (every partial of a
///   winning candidate is below the incumbent best), and a losing
///   candidate is rejected either way
///   (`refine_search_matches_no_early_exit_reference` pins the whole
///   descent).
fn block_sad(
    src: &I420Frame<'_>,
    refp: &I420Frame<'_>,
    (bx, by, bw, bh): (usize, usize, usize, usize),
    (mvx, mvy): (i32, i32),
    early_exit_at: u32,
) -> u32 {
    let w = src.width as i32;
    let h = src.height as i32;
    let x0 = bx as i32 + mvx;
    let y0 = by as i32 + mvy;
    let in_bounds = x0 >= 0 && y0 >= 0 && x0 + bw as i32 <= w && y0 + bh as i32 <= h;
    if !in_bounds {
        return block_sad_generic(src, refp, (bx, by, bw, bh), (mvx, mvy), early_exit_at);
    }
    let (rx0, ry0) = (x0 as usize, y0 as usize);
    let mut sad = 0u32;
    for r in 0..bh {
        let sy = by + r;
        let src_row = &src.y[sy * src.y_stride + bx..sy * src.y_stride + bx + bw];
        let ref_base = (ry0 + r) * refp.y_stride + rx0;
        let ref_row = &refp.y[ref_base..ref_base + bw];
        // Whole 16-pixel runs as fixed-size arrays (the common block
        // width, summed in vector registers), then any remainder.
        let (src_runs, src_tail) = src_row.as_chunks::<16>();
        let (ref_runs, ref_tail) = ref_row.as_chunks::<16>();
        for (a, b) in src_runs.iter().zip(ref_runs) {
            let mut run = 0u32;
            for i in 0..16 {
                run += a[i].abs_diff(b[i]) as u32;
            }
            sad += run;
        }
        for (&s, &rp) in src_tail.iter().zip(ref_tail.iter()) {
            sad += s.abs_diff(rp) as u32;
        }
        if sad >= early_exit_at {
            return sad;
        }
    }
    sad
}

/// The straightforward per-pixel edge-clamped SAD — the reference form
/// [`block_sad`] must match, and the path it takes when the displaced
/// block genuinely crosses a frame edge. Carries the same per-row
/// monotone early exit (the partial sum is identical row-for-row, so
/// the exit fires at exactly the same row on both paths).
fn block_sad_generic(
    src: &I420Frame<'_>,
    refp: &I420Frame<'_>,
    (bx, by, bw, bh): (usize, usize, usize, usize),
    (mvx, mvy): (i32, i32),
    early_exit_at: u32,
) -> u32 {
    let w = src.width as i32;
    let h = src.height as i32;
    let mut sad = 0u32;
    for r in 0..bh {
        let sy = by + r;
        let src_row = &src.y[sy * src.y_stride + bx..sy * src.y_stride + bx + bw];
        for (c, &s) in src_row.iter().enumerate() {
            let rp = pel(
                refp.y,
                refp.y_stride,
                w,
                h,
                (bx + c) as i32 + mvx,
                sy as i32 + mvy,
            );
            sad += (s as i32 - rp as i32).unsigned_abs();
        }
        if sad >= early_exit_at {
            return sad;
        }
    }
    sad
}

/// Whole-pel three-round refinement search: start at the zero MV, probe
/// the 8 neighbours at step 8, recentre, halve the step (8 → 4 → 2 → 1).
/// Returns `(mvx, mvy, sad)` of the best whole-pel alignment within
/// ±15 px.
fn refine_search(
    src: &I420Frame<'_>,
    refp: &I420Frame<'_>,
    blk: (usize, usize, usize, usize),
) -> (i32, i32, u32) {
    let mut best = (0i32, 0i32);
    let mut best_sad = block_sad(src, refp, blk, (0, 0), u32::MAX);
    let mut step = 8i32;
    while step >= 1 {
        let center = best;
        for (dx, dy) in [
            (-step, -step),
            (0, -step),
            (step, -step),
            (-step, 0),
            (step, 0),
            (-step, step),
            (0, step),
            (step, step),
        ] {
            let cand = (center.0 + dx, center.1 + dy);
            if cand.0.abs() > 15 || cand.1.abs() > 15 {
                continue;
            }
            // `best_sad` as the exit bound: only a strictly smaller SAD
            // wins, so a candidate whose partial sum already reaches
            // `best_sad` is rejected with or without the exit.
            let sad = block_sad(src, refp, blk, cand, best_sad);
            if sad < best_sad {
                best_sad = sad;
                best = cand;
            }
        }
        step /= 2;
    }
    (best.0, best.1, best_sad)
}

/// Difference-driven blend weight: `W_MAX·S / (S + d²)` — full weight at
/// `d = 0`, decaying with the squared pixel difference; `S` grows with
/// the configured strength so stronger settings tolerate larger
/// differences before down-weighting.
#[inline]
fn pixel_weight(d: i32, s_scale: u32) -> u32 {
    (W_MAX * s_scale) / (s_scale + (d * d) as u32)
}

/// Precompute [`pixel_weight`] for every possible absolute pixel
/// difference (`|d| <= 255` for 8-bit planes). The weight depends on
/// `d` only through `d²`, so one 256-entry table replaces the per-pixel
/// integer division in the blend accumulation. Bit-identical by
/// construction (`weight_table_matches_pixel_weight` sweeps every
/// `(d, strength)` pair).
fn weight_table(s_scale: u32) -> [u32; 256] {
    let mut table = [0u32; 256];
    for (d, slot) in table.iter_mut().enumerate() {
        *slot = pixel_weight(d as i32, s_scale);
    }
    table
}

/// Accumulate one motion-aligned luma block of a window frame into the
/// blend accumulators.
///
/// `ctr_y` is the tightly-packed `w × h` center copy (`out.y`); the
/// reference plane arrives strided. The output positions `(bx..bx+bw,
/// by..by+bh)` are always in-bounds (the block grid never leaves the
/// frame); only the *displaced* reference fetch can cross an edge. When
/// it does not — the overwhelmingly common case — the per-pixel
/// edge-clamping [`pel`] collapses to a straight row slice; the clamped
/// generic form is kept verbatim below and pinned pixel-for-pixel by
/// `accumulate_luma_block_fast_matches_generic`.
#[allow(clippy::too_many_arguments)]
fn accumulate_luma_block(
    ctr_y: &[u8],
    (f_y, f_stride): (&[u8], usize),
    (w, h): (usize, usize),
    (bx, by, bw, bh): (usize, usize, usize, usize),
    (mvx, mvy): (i32, i32),
    wt_table: &[u32; 256],
    acc: &mut [u32],
    wsum: &mut [u32],
) {
    let x0 = bx as i32 + mvx;
    let y0 = by as i32 + mvy;
    if x0 >= 0 && y0 >= 0 && x0 + bw as i32 <= w as i32 && y0 + bh as i32 <= h as i32 {
        // In-bounds fast path: straight row slices, no per-pixel clamp.
        let (rx0, ry0) = (x0 as usize, y0 as usize);
        for r in 0..bh {
            let out_base = (by + r) * w + bx;
            let ref_base = (ry0 + r) * f_stride + rx0;
            let ctr_row = &ctr_y[out_base..out_base + bw];
            let ref_row = &f_y[ref_base..ref_base + bw];
            let acc_row = &mut acc[out_base..out_base + bw];
            let wsum_row = &mut wsum[out_base..out_base + bw];
            for c in 0..bw {
                let ref_px = ref_row[c] as i32;
                let d = ref_px - ctr_row[c] as i32;
                let wt = wt_table[d.unsigned_abs() as usize];
                acc_row[c] += wt * ref_px as u32;
                wsum_row[c] += wt;
            }
        }
        return;
    }
    // Edge-crossing generic path — the reference form.
    for r in 0..bh {
        let yy = by + r;
        for c in 0..bw {
            let xx = bx + c;
            let ctr_px = ctr_y[yy * w + xx] as i32;
            let ref_px = pel(
                f_y,
                f_stride,
                w as i32,
                h as i32,
                xx as i32 + mvx,
                yy as i32 + mvy,
            ) as i32;
            let wt = wt_table[(ref_px - ctr_px).unsigned_abs() as usize];
            acc[yy * w + xx] += wt * ref_px as u32;
            wsum[yy * w + xx] += wt;
        }
    }
}

/// Accumulate one motion-aligned chroma block (one plane — called once
/// for U and once for V) into the blend accumulators.
///
/// Unlike luma, the chroma *output* coordinates are themselves clamped
/// (`.min(cw - 1)` / `.min(ch - 1)`) because an odd-dimension plane's
/// last block row/column can overhang — and that clamping deliberately
/// accumulates twice into the edge pixel, which must be preserved. The
/// fast path therefore requires the output block to be overhang-free
/// *and* the displaced reference fetch to be in-bounds; anything else
/// takes the generic clamped form (pinned by
/// `accumulate_chroma_block_fast_matches_generic`).
#[allow(clippy::too_many_arguments)]
fn accumulate_chroma_block(
    ctr_plane: &[u8],
    (f_plane, f_stride): (&[u8], usize),
    (cw, ch): (usize, usize),
    (cbx, cby, cbw, cbh): (usize, usize, usize, usize),
    (cmvx, cmvy): (i32, i32),
    wt_table: &[u32; 256],
    acc: &mut [u32],
    wsum: &mut [u32],
) {
    let x0 = cbx as i32 + cmvx;
    let y0 = cby as i32 + cmvy;
    let output_in_bounds = cbx + cbw <= cw && cby + cbh <= ch;
    if output_in_bounds
        && x0 >= 0
        && y0 >= 0
        && x0 + cbw as i32 <= cw as i32
        && y0 + cbh as i32 <= ch as i32
    {
        let (rx0, ry0) = (x0 as usize, y0 as usize);
        for r in 0..cbh {
            let out_base = (cby + r) * cw + cbx;
            let ref_base = (ry0 + r) * f_stride + rx0;
            let ctr_row = &ctr_plane[out_base..out_base + cbw];
            let ref_row = &f_plane[ref_base..ref_base + cbw];
            let acc_row = &mut acc[out_base..out_base + cbw];
            let wsum_row = &mut wsum[out_base..out_base + cbw];
            for c in 0..cbw {
                let ref_px = ref_row[c] as i32;
                let d = ref_px - ctr_row[c] as i32;
                let wt = wt_table[d.unsigned_abs() as usize];
                acc_row[c] += wt * ref_px as u32;
                wsum_row[c] += wt;
            }
        }
        return;
    }
    // Overhanging / edge-crossing generic path — the reference form,
    // including the double-accumulation into clamped edge pixels.
    for r in 0..cbh {
        let yy = (cby + r).min(ch - 1);
        for c in 0..cbw {
            let xx = (cbx + c).min(cw - 1);
            let ctr_px = ctr_plane[yy * cw + xx] as i32;
            let ref_px = pel(
                f_plane,
                f_stride,
                cw as i32,
                ch as i32,
                xx as i32 + cmvx,
                yy as i32 + cmvy,
            ) as i32;
            let wt = wt_table[(ref_px - ctr_px).unsigned_abs() as usize];
            acc[yy * cw + xx] += wt * ref_px as u32;
            wsum[yy * cw + xx] += wt;
        }
    }
}

/// Build a temporally-filtered altref anchor from a window of source
/// frames.
///
/// * `frames` — the lookahead window, oldest first. All frames must
///   share the center frame's dimensions
///   ([`EncodeError::ReferenceDimensionsMismatch`] otherwise).
/// * `center` — index of the anchor frame the output is aligned to
///   (panics if out of range — a caller bug, not a data condition).
/// * `cfg` — see [`ArnrConfig`]; `strength = 0` (or a single-frame
///   window) returns an exact copy of the center frame.
///
/// The output picture is what the caller should feed to
/// [`crate::encoder::encode_invisible_altref_update`]; it is **not**
/// itself a displayed frame, so blending artifacts trade off only
/// against prediction quality, never against on-screen fidelity.
pub fn build_arnr_altref(
    frames: &[I420Frame<'_>],
    center: usize,
    cfg: &ArnrConfig,
) -> Result<ArnrPicture, EncodeError> {
    build_arnr_altref_threaded(frames, center, cfg, 1)
}

/// [`build_arnr_altref`] with the per-block alignment searches spread
/// over up to `threads` threads. The searches only read the frames, and
/// the blend that follows runs in the serial order, so the picture does
/// not depend on the budget.
pub(crate) fn build_arnr_altref_threaded(
    frames: &[I420Frame<'_>],
    center: usize,
    cfg: &ArnrConfig,
    threads: usize,
) -> Result<ArnrPicture, EncodeError> {
    assert!(
        center < frames.len(),
        "build_arnr_altref: center index {center} out of range ({} frames)",
        frames.len()
    );
    let ctr = &frames[center];
    let w = ctr.width as usize;
    let h = ctr.height as usize;
    if ctr.width == 0 || ctr.height == 0 || ctr.width > 0x3FFF || ctr.height > 0x3FFF {
        return Err(EncodeError::InvalidDimensions {
            width: ctr.width,
            height: ctr.height,
        });
    }
    for f in frames {
        if f.width != ctr.width || f.height != ctr.height {
            return Err(EncodeError::ReferenceDimensionsMismatch {
                source: (ctr.width, ctr.height),
                reference: (f.width, f.height),
            });
        }
    }
    let cw = w.div_ceil(2);
    let ch = h.div_ceil(2);

    // Pass-through short-circuits: nothing to blend.
    let mut out = ArnrPicture {
        width: ctr.width,
        height: ctr.height,
        y: copy_plane(ctr.y, ctr.y_stride, w, h),
        u: copy_plane(ctr.u, ctr.uv_stride, cw, ch),
        v: copy_plane(ctr.v, ctr.uv_stride, cw, ch),
    };
    if cfg.strength == 0 || frames.len() < 2 {
        return Ok(out);
    }
    // Strength → weight-curve scale. Doubling per step: strength 1
    // down-weights a |d| = 4 pixel to ~1/3, strength 6 keeps it at
    // ~14/16.
    let s_scale = 8u32 << cfg.strength.min(ArnrConfig::MAX_STRENGTH);
    // One weight per possible |ref − center| difference — replaces the
    // per-pixel division in the accumulation loops below.
    let wt_table = weight_table(s_scale);

    // Per-16×16-block accumulation over the window.
    let mut acc_y = vec![0u32; w * h];
    let mut wsum_y = vec![0u32; w * h];
    let mut acc_u = vec![0u32; cw * ch];
    let mut wsum_u = vec![0u32; cw * ch];
    let mut acc_v = vec![0u32; cw * ch];
    let mut wsum_v = vec![0u32; cw * ch];

    // Seed with the center frame at full weight.
    accumulate_center(&out.y, &mut acc_y, &mut wsum_y);
    accumulate_center(&out.u, &mut acc_u, &mut wsum_u);
    accumulate_center(&out.v, &mut acc_v, &mut wsum_v);

    // Alignment of every block of every frame against the center: one
    // unit of work per (frame, block row).
    let (bcols, brows) = (w.div_ceil(16), h.div_ceil(16));
    let mut aligned = vec![(0i32, 0i32, 0u32); frames.len() * brows * bcols];
    {
        let units = std::sync::Mutex::new(aligned.chunks_mut(bcols).enumerate());
        let worker = || {
            loop {
                let next = units
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .next();
                let Some((unit, row)) = next else {
                    break;
                };
                let (fi, brow) = (unit / brows, unit % brows);
                if fi == center {
                    continue;
                }
                let by = brow * 16;
                let bh = (h - by).min(16);
                for (bcol, slot) in row.iter_mut().enumerate() {
                    let bx = bcol * 16;
                    let bw = (w - bx).min(16);
                    *slot = refine_search(ctr, &frames[fi], (bx, by, bw, bh));
                }
            }
        };
        let workers = threads.clamp(1, (frames.len() * brows).max(1));
        if workers == 1 {
            worker();
        } else {
            std::thread::scope(|scope| {
                for _ in 1..workers {
                    scope.spawn(worker);
                }
                worker();
            });
        }
    }

    for (fi, f) in frames.iter().enumerate() {
        if fi == center {
            continue;
        }
        let mut by = 0usize;
        while by < h {
            let bh = (h - by).min(16);
            let mut bx = 0usize;
            while bx < w {
                let bw = (w - bx).min(16);
                let (mvx, mvy, sad) = aligned[(fi * brows + by / 16) * bcols + bx / 16];
                // Occlusion / scene-change guard: a block that still
                // mismatches after alignment is excluded outright.
                if sad / (bw * bh) as u32 > BLOCK_SAD_PER_PIXEL_CUTOFF {
                    bx += 16;
                    continue;
                }
                // Luma accumulation.
                accumulate_luma_block(
                    &out.y,
                    (f.y, f.y_stride),
                    (w, h),
                    (bx, by, bw, bh),
                    (mvx, mvy),
                    &wt_table,
                    &mut acc_y,
                    &mut wsum_y,
                );
                // Chroma accumulation — luma MV halved (round toward
                // zero), §18.2-style.
                let (cmvx, cmvy) = (mvx / 2, mvy / 2);
                let (cbx, cby) = (bx / 2, by / 2);
                let (cbw, cbh) = (bw.div_ceil(2), bh.div_ceil(2));
                for (ctr_plane, fp, acc, wsum) in [
                    (&out.u, f.u, &mut acc_u, &mut wsum_u),
                    (&out.v, f.v, &mut acc_v, &mut wsum_v),
                ] {
                    accumulate_chroma_block(
                        ctr_plane,
                        (fp, f.uv_stride),
                        (cw, ch),
                        (cbx, cby, cbw, cbh),
                        (cmvx, cmvy),
                        &wt_table,
                        acc,
                        wsum,
                    );
                }
                bx += 16;
            }
            by += 16;
        }
    }

    resolve_plane(&mut out.y, &acc_y, &wsum_y);
    resolve_plane(&mut out.u, &acc_u, &wsum_u);
    resolve_plane(&mut out.v, &acc_v, &wsum_v);
    Ok(out)
}

/// Copy a possibly-strided plane into a tightly-packed buffer.
fn copy_plane(plane: &[u8], stride: usize, w: usize, h: usize) -> Vec<u8> {
    let mut out = Vec::with_capacity(w * h);
    for r in 0..h {
        out.extend_from_slice(&plane[r * stride..r * stride + w]);
    }
    out
}

/// Seed the accumulators with the center plane at full weight.
fn accumulate_center(center: &[u8], acc: &mut [u32], wsum: &mut [u32]) {
    for ((a, ws), &px) in acc.iter_mut().zip(wsum.iter_mut()).zip(center.iter()) {
        *a += W_MAX * px as u32;
        *ws += W_MAX;
    }
}

/// Rounded weighted mean, in place over the center-copy plane.
fn resolve_plane(plane: &mut [u8], acc: &[u32], wsum: &[u32]) {
    for ((px, &a), &ws) in plane.iter_mut().zip(acc.iter()).zip(wsum.iter()) {
        debug_assert!(ws >= W_MAX);
        *px = ((a + ws / 2) / ws) as u8;
    }
}

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

    const W: usize = 48;
    const H: usize = 48;

    /// Deterministic LCG noise in `-amp..=amp`.
    struct Lcg(u64);
    impl Lcg {
        fn next(&mut self) -> u64 {
            self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1);
            self.0 >> 33
        }
        fn noise(&mut self, amp: i32) -> i32 {
            (self.next() % (2 * amp as u64 + 1)) as i32 - amp
        }
    }

    /// A clean textured scene.
    fn clean_scene() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
        let mut y = vec![0u8; W * H];
        for r in 0..H {
            for c in 0..W {
                y[r * W + c] = (64 + ((r * 3 + c * 2) & 0x7f)) as u8;
            }
        }
        let (cw, ch) = (W / 2, H / 2);
        let u = vec![120u8; cw * ch];
        let v = vec![136u8; cw * ch];
        (y, u, v)
    }

    /// Add ±amp LCG noise to a plane (seeded per frame).
    fn noisy(plane: &[u8], seed: u64, amp: i32) -> Vec<u8> {
        let mut rng = Lcg(seed);
        plane
            .iter()
            .map(|&p| (p as i32 + rng.noise(amp)).clamp(0, 255) as u8)
            .collect()
    }

    fn mse(a: &[u8], b: &[u8]) -> f64 {
        assert_eq!(a.len(), b.len());
        let sse: u64 = a
            .iter()
            .zip(b.iter())
            .map(|(&x, &y)| {
                let d = x as i64 - y as i64;
                (d * d) as u64
            })
            .sum();
        sse as f64 / a.len() as f64
    }

    #[test]
    fn strength_zero_and_single_frame_are_identity() {
        let (y, u, v) = clean_scene();
        let f = I420Frame::packed(W as u32, H as u32, &y, &u, &v);
        let frames = [f];
        let out = build_arnr_altref(&frames, 0, &ArnrConfig::default()).unwrap();
        assert_eq!(out.y, y);
        assert_eq!(out.u, u);
        assert_eq!(out.v, v);

        let ny = noisy(&y, 7, 6);
        let f0 = I420Frame::packed(W as u32, H as u32, &ny, &u, &v);
        let f1 = I420Frame::packed(W as u32, H as u32, &y, &u, &v);
        let frames = [f0, f1];
        let out = build_arnr_altref(&frames, 0, &ArnrConfig::new(0)).unwrap();
        assert_eq!(out.y, ny, "strength 0 must be a pass-through");
    }

    #[test]
    fn static_noisy_window_denoises_toward_the_clean_scene() {
        let (cy, cu, cv) = clean_scene();
        let noisy_planes: Vec<Vec<u8>> = (0..5).map(|i| noisy(&cy, 1000 + i, 6)).collect();
        let frames: Vec<I420Frame<'_>> = noisy_planes
            .iter()
            .map(|ny| I420Frame::packed(W as u32, H as u32, ny, &cu, &cv))
            .collect();
        let out = build_arnr_altref(&frames, 2, &ArnrConfig::default()).unwrap();
        let center_mse = mse(&noisy_planes[2], &cy);
        let filtered_mse = mse(&out.y, &cy);
        assert!(
            filtered_mse < center_mse / 2.0,
            "temporal blend must denoise: center {center_mse:.2} vs filtered {filtered_mse:.2}"
        );
    }

    #[test]
    fn motion_compensation_tracks_a_translating_scene() {
        // The window translates 4 px right per frame; each frame carries
        // independent noise. Without MC the blend of misaligned frames
        // would *add* error; with MC it must still denoise.
        let (cy, cu, cv) = clean_scene();
        let mut planes: Vec<Vec<u8>> = Vec::new();
        for i in 0..3i32 {
            let dx = (i - 1) * 4; // -4, 0, +4
            let mut y = vec![0u8; W * H];
            for r in 0..H {
                for c in 0..W {
                    let sc = (c as i32 - dx).clamp(0, W as i32 - 1) as usize;
                    y[r * W + c] = cy[r * W + sc];
                }
            }
            planes.push(noisy(&y, 2000 + i as u64, 6));
        }
        let frames: Vec<I420Frame<'_>> = planes
            .iter()
            .map(|p| I420Frame::packed(W as u32, H as u32, p, &cu, &cv))
            .collect();
        let out = build_arnr_altref(&frames, 1, &ArnrConfig::default()).unwrap();
        let center_mse = mse(&planes[1], &cy);
        let filtered_mse = mse(&out.y, &cy);
        assert!(
            filtered_mse < center_mse,
            "MC blend must denoise a translating scene: center {center_mse:.2} vs filtered {filtered_mse:.2}"
        );
    }

    #[test]
    fn scene_change_neighbour_is_excluded() {
        // Frame 1 is unrelated content: the SAD cutoff must exclude every
        // block, leaving the output exactly the center frame.
        let (cy, cu, cv) = clean_scene();
        let alien: Vec<u8> = cy.iter().map(|&p| 255 - p).collect();
        let f0 = I420Frame::packed(W as u32, H as u32, &cy, &cu, &cv);
        let f1 = I420Frame::packed(W as u32, H as u32, &alien, &cu, &cv);
        let frames = [f0, f1];
        let out = build_arnr_altref(&frames, 0, &ArnrConfig::new(6)).unwrap();
        assert_eq!(out.y, cy, "an unmatchable neighbour must not bleed in");
    }

    #[test]
    fn dimension_mismatch_is_rejected() {
        let (cy, cu, cv) = clean_scene();
        let f0 = I420Frame::packed(W as u32, H as u32, &cy, &cu, &cv);
        let small_y = vec![0u8; 32 * 32];
        let small_c = vec![128u8; 16 * 16];
        let f1 = I420Frame::packed(32, 32, &small_y, &small_c, &small_c);
        let err = build_arnr_altref(&[f0, f1], 0, &ArnrConfig::default()).unwrap_err();
        assert!(matches!(
            err,
            EncodeError::ReferenceDimensionsMismatch { .. }
        ));
    }

    #[test]
    fn config_clamps_strength() {
        assert_eq!(ArnrConfig::new(99).strength, ArnrConfig::MAX_STRENGTH);
        assert_eq!(ArnrConfig::new(2).strength, 2);
    }

    // =====================================================================
    // Fast-path equivalence pins (round 409). Each optimized path must be
    // pixel-for-pixel the straightforward per-pixel clamped form.
    // =====================================================================

    /// The weight table is a pure precomputation of `pixel_weight`.
    #[test]
    fn weight_table_matches_pixel_weight() {
        for strength in 0..=ArnrConfig::MAX_STRENGTH {
            let s_scale = 8u32 << strength;
            let table = weight_table(s_scale);
            for d in -255i32..=255 {
                assert_eq!(
                    table[d.unsigned_abs() as usize],
                    pixel_weight(d, s_scale),
                    "strength {strength} d {d}"
                );
            }
        }
    }

    /// A pair of textured, noisy frames for the block-level pins.
    fn stress_pair() -> (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>) {
        let (cy, cu, _cv) = clean_scene();
        let ry = noisy(&cy, 4242, 20);
        let ru = noisy(&cu, 2424, 12);
        (cy, ry, cu, ru)
    }

    /// `block_sad` (fast dispatch, no early exit) equals the clamped
    /// generic form on interior blocks, edge blocks, and every MV the
    /// refinement search can probe.
    #[test]
    fn block_sad_fast_matches_generic() {
        let (cy, ry, cu, cv_) = stress_pair();
        let src = I420Frame::packed(W as u32, H as u32, &cy, &cu, &cv_);
        let refp = I420Frame::packed(W as u32, H as u32, &ry, &cu, &cv_);
        // Interior, corner, and partial (right/bottom overhang-free)
        // blocks; W = H = 48 so blocks at 32 touch the frame edge.
        for &blk in &[
            (16usize, 16usize, 16usize, 16usize),
            (0, 0, 16, 16),
            (32, 32, 16, 16),
            (32, 0, 16, 16),
            (0, 32, 16, 16),
        ] {
            for mvy in -16i32..=16 {
                for mvx in -16i32..=16 {
                    let fast = block_sad(&src, &refp, blk, (mvx, mvy), u32::MAX);
                    let generic = block_sad_generic(&src, &refp, blk, (mvx, mvy), u32::MAX);
                    assert_eq!(fast, generic, "blk {blk:?} mv ({mvx},{mvy})");
                }
            }
        }
    }

    /// The whole refinement descent — with the monotone early exit and
    /// the in-bounds fast path — returns exactly the `(mv, sad)` the
    /// exhaustive no-early-exit generic descent returns.
    #[test]
    fn refine_search_matches_no_early_exit_reference() {
        /// The original descent shape: generic SAD, no early exit.
        fn refine_search_reference(
            src: &I420Frame<'_>,
            refp: &I420Frame<'_>,
            blk: (usize, usize, usize, usize),
        ) -> (i32, i32, u32) {
            let mut best = (0i32, 0i32);
            let mut best_sad = block_sad_generic(src, refp, blk, (0, 0), u32::MAX);
            let mut step = 8i32;
            while step >= 1 {
                let center = best;
                for (dx, dy) in [
                    (-step, -step),
                    (0, -step),
                    (step, -step),
                    (-step, 0),
                    (step, 0),
                    (-step, step),
                    (0, step),
                    (step, step),
                ] {
                    let cand = (center.0 + dx, center.1 + dy);
                    if cand.0.abs() > 15 || cand.1.abs() > 15 {
                        continue;
                    }
                    let sad = block_sad_generic(src, refp, blk, cand, u32::MAX);
                    if sad < best_sad {
                        best_sad = sad;
                        best = cand;
                    }
                }
                step /= 2;
            }
            (best.0, best.1, best_sad)
        }

        let (cy, cu, cv_) = clean_scene();
        // Reference scenes: pure noise, a genuine +4 px translation, and
        // an unrelated (inverted) frame — bracketing convergent,
        // walking, and hopeless descents.
        let noise_only = noisy(&cy, 99, 8);
        let mut translated = vec![0u8; W * H];
        for r in 0..H {
            for c in 0..W {
                let sc = (c as i32 - 4).clamp(0, W as i32 - 1) as usize;
                translated[r * W + c] = cy[r * W + sc];
            }
        }
        let translated = noisy(&translated, 7331, 5);
        let alien: Vec<u8> = cy.iter().map(|&p| 255 - p).collect();

        let src = I420Frame::packed(W as u32, H as u32, &cy, &cu, &cv_);
        for ref_y in [&noise_only, &translated, &alien] {
            let refp = I420Frame::packed(W as u32, H as u32, ref_y, &cu, &cv_);
            let mut by = 0usize;
            while by < H {
                let bh = (H - by).min(16);
                let mut bx = 0usize;
                while bx < W {
                    let bw = (W - bx).min(16);
                    let blk = (bx, by, bw, bh);
                    assert_eq!(
                        refine_search(&src, &refp, blk),
                        refine_search_reference(&src, &refp, blk),
                        "blk {blk:?}"
                    );
                    bx += 16;
                }
                by += 16;
            }
        }
    }

    /// `accumulate_luma_block` (in-bounds fast path + generic edge path)
    /// equals the original per-pixel `pel` + `pixel_weight` form on
    /// every probed MV, in-bounds and edge-crossing alike.
    #[test]
    fn accumulate_luma_block_fast_matches_generic() {
        /// The original accumulation loop, verbatim.
        #[allow(clippy::too_many_arguments)]
        fn reference(
            ctr_y: &[u8],
            f_y: &[u8],
            f_stride: usize,
            (w, h): (usize, usize),
            (bx, by, bw, bh): (usize, usize, usize, usize),
            (mvx, mvy): (i32, i32),
            s_scale: u32,
            acc: &mut [u32],
            wsum: &mut [u32],
        ) {
            for r in 0..bh {
                let yy = by + r;
                for c in 0..bw {
                    let xx = bx + c;
                    let ctr_px = ctr_y[yy * w + xx] as i32;
                    let ref_px = pel(
                        f_y,
                        f_stride,
                        w as i32,
                        h as i32,
                        xx as i32 + mvx,
                        yy as i32 + mvy,
                    ) as i32;
                    let wt = pixel_weight(ref_px - ctr_px, s_scale);
                    acc[yy * w + xx] += wt * ref_px as u32;
                    wsum[yy * w + xx] += wt;
                }
            }
        }

        let (cy, ry, _cu, _ru) = stress_pair();
        let s_scale = 8u32 << 3;
        let table = weight_table(s_scale);
        for &blk in &[
            (16usize, 16usize, 16usize, 16usize),
            (0, 0, 16, 16),
            (32, 32, 16, 16),
        ] {
            for mvy in [-15i32, -7, -1, 0, 1, 7, 15] {
                for mvx in [-15i32, -7, -1, 0, 1, 7, 15] {
                    let mut acc_a = vec![3u32; W * H];
                    let mut wsum_a = vec![5u32; W * H];
                    let mut acc_b = acc_a.clone();
                    let mut wsum_b = wsum_a.clone();
                    accumulate_luma_block(
                        &cy,
                        (&ry, W),
                        (W, H),
                        blk,
                        (mvx, mvy),
                        &table,
                        &mut acc_a,
                        &mut wsum_a,
                    );
                    reference(
                        &cy,
                        &ry,
                        W,
                        (W, H),
                        blk,
                        (mvx, mvy),
                        s_scale,
                        &mut acc_b,
                        &mut wsum_b,
                    );
                    assert_eq!(acc_a, acc_b, "acc blk {blk:?} mv ({mvx},{mvy})");
                    assert_eq!(wsum_a, wsum_b, "wsum blk {blk:?} mv ({mvx},{mvy})");
                }
            }
        }
    }

    /// `accumulate_chroma_block` equals the original clamped form —
    /// including the deliberate double-accumulation into clamped edge
    /// pixels on an odd-dimension plane's overhanging last block.
    #[test]
    fn accumulate_chroma_block_fast_matches_generic() {
        /// The original chroma accumulation loop, verbatim.
        #[allow(clippy::too_many_arguments)]
        fn reference(
            ctr_plane: &[u8],
            f_plane: &[u8],
            f_stride: usize,
            (cw, ch): (usize, usize),
            (cbx, cby, cbw, cbh): (usize, usize, usize, usize),
            (cmvx, cmvy): (i32, i32),
            s_scale: u32,
            acc: &mut [u32],
            wsum: &mut [u32],
        ) {
            for r in 0..cbh {
                let yy = (cby + r).min(ch - 1);
                for c in 0..cbw {
                    let xx = (cbx + c).min(cw - 1);
                    let ctr_px = ctr_plane[yy * cw + xx] as i32;
                    let ref_px = pel(
                        f_plane,
                        f_stride,
                        cw as i32,
                        ch as i32,
                        xx as i32 + cmvx,
                        yy as i32 + cmvy,
                    ) as i32;
                    let wt = pixel_weight(ref_px - ctr_px, s_scale);
                    acc[yy * cw + xx] += wt * ref_px as u32;
                    wsum[yy * cw + xx] += wt;
                }
            }
        }

        // A deliberately odd chroma geometry (25×23) so `div_ceil`
        // blocks overhang on the right and bottom.
        let (cw, ch) = (25usize, 23usize);
        let mut ctr = vec![0u8; cw * ch];
        for r in 0..ch {
            for c in 0..cw {
                ctr[r * cw + c] = (100 + ((r * 5 + c * 3) & 0x3f)) as u8;
            }
        }
        let refp = noisy(&ctr, 555, 10);
        let s_scale = 8u32 << 3;
        let table = weight_table(s_scale);
        // 8×8 chroma blocks over the odd plane, all halved MVs the luma
        // search can produce.
        for &blk in &[
            (0usize, 0usize, 8usize, 8usize),
            (8, 8, 8, 8),
            (24, 16, 8, 8), // right + bottom overhang (cbx = 24 on cw = 25)
            (16, 16, 8, 8),
        ] {
            for cmvy in [-7i32, -3, 0, 3, 7] {
                for cmvx in [-7i32, -3, 0, 3, 7] {
                    let mut acc_a = vec![1u32; cw * ch];
                    let mut wsum_a = vec![2u32; cw * ch];
                    let mut acc_b = acc_a.clone();
                    let mut wsum_b = wsum_a.clone();
                    accumulate_chroma_block(
                        &ctr,
                        (&refp, cw),
                        (cw, ch),
                        blk,
                        (cmvx, cmvy),
                        &table,
                        &mut acc_a,
                        &mut wsum_a,
                    );
                    reference(
                        &ctr,
                        &refp,
                        cw,
                        (cw, ch),
                        blk,
                        (cmvx, cmvy),
                        s_scale,
                        &mut acc_b,
                        &mut wsum_b,
                    );
                    assert_eq!(acc_a, acc_b, "acc blk {blk:?} cmv ({cmvx},{cmvy})");
                    assert_eq!(wsum_a, wsum_b, "wsum blk {blk:?} cmv ({cmvx},{cmvy})");
                }
            }
        }
    }
}