zoomvtools 1.1.0

Video motion vector analysis utilities in pure Rust
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
#[cfg(test)]
mod tests;

use std::num::{NonZeroU8, NonZeroUsize};

use anyhow::Result;
use semisafe::slice::get as semisafe_get;
use semisafe::slice::get_mut as semisafe_get_mut;
use smallvec::SmallVec;

use crate::{
    average::average2,
    pad::pad_reference_frame,
    params::{ReduceFilter, Subpel, SubpelMethod},
    reduce::{
        ReduceFn, reduce_average, reduce_bilinear, reduce_cubic, reduce_quadratic, reduce_triangle,
    },
    refine::{
        RefineFn, refine_diagonal_bilinear, refine_horizontal_bicubic, refine_horizontal_bilinear,
        refine_horizontal_wiener, refine_vertical_bicubic, refine_vertical_bilinear,
        refine_vertical_wiener,
    },
    util::{Pixel, vs_bitblt},
};

#[derive(Debug, Clone)]
pub struct MVPlane {
    pub subpel_window_offsets: SmallVec<[usize; 16]>,
    pub width: NonZeroUsize,
    pub height: NonZeroUsize,
    pub padded_width: NonZeroUsize,
    pub padded_height: NonZeroUsize,
    pub stride: NonZeroUsize,
    pub hpad: usize,
    pub vpad: usize,
    pub offset_padding: usize,
    #[allow(dead_code)]
    pub hpad_pel: usize,
    #[allow(dead_code)]
    pub vpad_pel: usize,
    pub bits_per_sample: NonZeroU8,
    pub pel: Subpel,
    pub is_padded: bool,
    pub is_refined: bool,
    pub is_filled: bool,
}

impl MVPlane {
    #[inline]
    pub fn new(
        width: NonZeroUsize,
        height: NonZeroUsize,
        pel: Subpel,
        hpad: usize,
        vpad: usize,
        bits_per_sample: NonZeroU8,
        plane_offset: usize,
        pitch: NonZeroUsize,
    ) -> Result<Self> {
        let pel_val = u8::from(pel) as usize;
        let padded_width = width.saturating_add(2 * hpad);
        let padded_height = height.saturating_add(2 * vpad);
        let offset_padding = pitch.get() * vpad + hpad;

        let windows = pel_val * pel_val;
        let mut offsets = SmallVec::with_capacity(windows);
        for i in 0..windows {
            let offset = i * pitch.get() * padded_height.get();
            offsets.push(plane_offset + offset);
        }

        Ok(Self {
            width,
            height,
            padded_width,
            padded_height,
            hpad,
            vpad,
            hpad_pel: hpad * pel_val,
            vpad_pel: vpad * pel_val,
            subpel_window_offsets: offsets,
            offset_padding,
            stride: pitch,
            bits_per_sample,
            pel,
            is_padded: false,
            is_refined: false,
            is_filled: false,
        })
    }

    #[inline]
    pub fn fill_plane<T: Pixel>(&mut self, src: &[T], src_pitch: NonZeroUsize, dest: &mut [T]) {
        if self.is_filled {
            return;
        }

        let offset = *semisafe_get(&self.subpel_window_offsets, 0) + self.offset_padding;
        vs_bitblt(
            semisafe_get_mut(dest, offset..),
            self.stride,
            src,
            src_pitch,
            self.width,
            self.height,
        );

        self.is_filled = true;
    }

    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, name = "mv_plane::refine_ext", fields(self.pel, self.is_refined))
    )]
    #[inline]
    pub fn refine_ext<T: Pixel>(
        &mut self,
        src_2x: &[T],
        src_2x_pitch: NonZeroUsize,
        is_ext_padded: bool,
        dest: &mut [T],
    ) {
        if !self.is_refined {
            match self.pel {
                Subpel::Full => {
                    // No refinement needed
                }
                Subpel::Half => {
                    self.refine_ext_pel2(src_2x, src_2x_pitch, is_ext_padded, dest);
                }
                Subpel::Quarter => {
                    self.refine_ext_pel4(src_2x, src_2x_pitch, is_ext_padded, dest);
                }
            }
        }
        self.is_refined = true;
    }

    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, name = "mv_plane::reduce_to", fields(filter, reduced_plane.is_filled))
    )]
    #[inline]
    pub fn reduce_to<T: Pixel>(
        &self,
        reduced_plane: &mut MVPlane,
        filter: ReduceFilter,
        dest: &mut [T],
        src: &[T],
        dest_pitch: NonZeroUsize,
        src_pitch: NonZeroUsize,
        dest_width: NonZeroUsize,
        dest_height: NonZeroUsize,
    ) {
        if reduced_plane.is_filled {
            return;
        }

        let dest = semisafe_get_mut(
            dest,
            *semisafe_get(&reduced_plane.subpel_window_offsets, 0) + reduced_plane.offset_padding..,
        );
        let src = semisafe_get(
            src,
            *semisafe_get(&self.subpel_window_offsets, 0) + self.offset_padding..,
        );
        let reduce: ReduceFn<T> = match filter {
            ReduceFilter::Average => reduce_average,
            ReduceFilter::Triangle => reduce_triangle,
            ReduceFilter::Bilinear => reduce_bilinear,
            ReduceFilter::Quadratic => reduce_quadratic,
            ReduceFilter::Cubic => reduce_cubic,
        };

        reduce(dest, src, dest_pitch, src_pitch, dest_width, dest_height);

        reduced_plane.is_filled = true;
    }

    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, name = "mv_plane::pad", fields(self.is_padded))
    )]
    #[inline]
    pub fn pad<T: Pixel>(&mut self, src: &mut [T]) {
        if !self.is_padded {
            pad_reference_frame(
                *semisafe_get(&self.subpel_window_offsets, 0),
                self.stride,
                self.hpad,
                self.vpad,
                self.width,
                self.height,
                src,
            );
            self.is_padded = true;
        }
    }

    /// Helper function to safely perform refinement operation without cloning
    /// by ensuring non-overlapping source and destination slices.
    fn refine_with_split<T: Pixel>(
        plane: &mut [T],
        src_offset: usize,
        dest_offset: usize,
        refine_fn: RefineFn<T>,
        pitch: NonZeroUsize,
        padded_width: NonZeroUsize,
        padded_height: NonZeroUsize,
        bits_per_sample: NonZeroU8,
    ) {
        debug_assert!(
            bits_per_sample.get() as usize > (size_of::<T>() - 1) * 8
                && (bits_per_sample.get() as usize <= size_of::<T>() * 8)
        );

        if src_offset <= dest_offset {
            // Source comes before destination, split at destination
            let (left, right) = plane.split_at_mut(dest_offset);
            refine_fn(
                right,
                semisafe_get(left, src_offset..),
                pitch,
                padded_width,
                padded_height,
                bits_per_sample,
            );
        } else {
            // Destination comes before source, split at source
            let (left, right) = plane.split_at_mut(src_offset);
            refine_fn(
                semisafe_get_mut(left, dest_offset..),
                right,
                pitch,
                padded_width,
                padded_height,
                bits_per_sample,
            );
        }
    }

    /// Helper function to safely perform average2 operation without cloning
    /// by ensuring non-overlapping source and destination slices.
    fn average2_with_split<T: Pixel>(
        plane: &mut [T],
        src1_offset: usize,
        src2_offset: usize,
        dest_offset: usize,
        pitch: NonZeroUsize,
        width: NonZeroUsize,
        height: NonZeroUsize,
    ) {
        // Find the ordering of the three offsets
        let mut offsets = [
            (src1_offset, 1u8), // 1 = src1
            (src2_offset, 2u8), // 2 = src2
            (dest_offset, 0u8), // 0 = dest
        ];
        offsets.sort_by_key(|&(offset, _)| offset);

        let _first_offset = offsets[0].0;
        let second_offset = offsets[1].0;
        let third_offset = offsets[2].0;

        let first_type = offsets[0].1;
        let second_type = offsets[1].1;
        let third_type = offsets[2].1;

        // Split the slice to get non-overlapping regions
        let (first_part, rest) = plane.split_at_mut(second_offset);
        let (second_part, third_part) = rest.split_at_mut(third_offset - second_offset);

        // Determine which slice corresponds to which source/destination
        let (src1_slice, src2_slice, dest_slice) = match (first_type, second_type, third_type) {
            (1, 2, 0) => (
                semisafe_get(first_part, src1_offset..),
                semisafe_get(second_part, ..),
                semisafe_get_mut(third_part, ..),
            ),
            (1, 0, 2) => (
                semisafe_get(first_part, src1_offset..),
                semisafe_get(third_part, src2_offset - third_offset..),
                semisafe_get_mut(second_part, dest_offset - second_offset..),
            ),
            (2, 1, 0) => (
                semisafe_get(second_part, src1_offset - second_offset..),
                semisafe_get(first_part, src2_offset..),
                semisafe_get_mut(third_part, ..),
            ),
            (2, 0, 1) => (
                semisafe_get(third_part, src1_offset - third_offset..),
                semisafe_get(first_part, src2_offset..),
                semisafe_get_mut(second_part, dest_offset - second_offset..),
            ),
            (0, 1, 2) => (
                semisafe_get(second_part, src1_offset - second_offset..),
                semisafe_get(third_part, src2_offset - third_offset..),
                semisafe_get_mut(first_part, dest_offset..),
            ),
            (0, 2, 1) => (
                semisafe_get(third_part, src1_offset - third_offset..),
                semisafe_get(second_part, src2_offset - second_offset..),
                semisafe_get_mut(first_part, dest_offset..),
            ),
            _ => unreachable!(),
        };

        average2(dest_slice, src1_slice, src2_slice, pitch, width, height);
    }

    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip_all, name = "mv_plane::refine", fields(method))
    )]
    #[inline]
    pub fn refine<T: Pixel>(&mut self, method: SubpelMethod, plane: &mut [T]) {
        if self.is_refined {
            return;
        }

        if self.pel == Subpel::Full {
            self.is_refined = true;
            return;
        }

        let refine: [RefineFn<T>; 3] = match method {
            SubpelMethod::Bilinear => [
                refine_horizontal_bilinear,
                refine_vertical_bilinear,
                refine_diagonal_bilinear,
            ],
            SubpelMethod::Bicubic => [
                refine_horizontal_bicubic,
                refine_vertical_bicubic,
                refine_horizontal_bicubic,
            ],
            SubpelMethod::Wiener => [
                refine_horizontal_wiener,
                refine_vertical_wiener,
                refine_horizontal_wiener,
            ],
        };

        let mut src_offsets = [0; 3];
        let mut dest_offsets = [0; 3];
        match self.pel {
            Subpel::Full => unreachable!(),
            Subpel::Half => {
                dest_offsets[0] = *semisafe_get(&self.subpel_window_offsets, 1);
                dest_offsets[1] = *semisafe_get(&self.subpel_window_offsets, 2);
                dest_offsets[2] = *semisafe_get(&self.subpel_window_offsets, 3);
                src_offsets[0] = *semisafe_get(&self.subpel_window_offsets, 0);
                src_offsets[1] = *semisafe_get(&self.subpel_window_offsets, 0);
                if method == SubpelMethod::Bilinear {
                    src_offsets[2] = *semisafe_get(&self.subpel_window_offsets, 0);
                } else {
                    src_offsets[2] = *semisafe_get(&self.subpel_window_offsets, 2);
                }
            }
            Subpel::Quarter => {
                dest_offsets[0] = *semisafe_get(&self.subpel_window_offsets, 2);
                dest_offsets[1] = *semisafe_get(&self.subpel_window_offsets, 8);
                dest_offsets[2] = *semisafe_get(&self.subpel_window_offsets, 10);
                src_offsets[0] = *semisafe_get(&self.subpel_window_offsets, 0);
                src_offsets[1] = *semisafe_get(&self.subpel_window_offsets, 0);
                if method == SubpelMethod::Bilinear {
                    src_offsets[2] = *semisafe_get(&self.subpel_window_offsets, 0);
                } else {
                    src_offsets[2] = *semisafe_get(&self.subpel_window_offsets, 8);
                }
            }
        }

        // Use the helper function to avoid clones
        for i in 0..3 {
            Self::refine_with_split(
                plane,
                *semisafe_get(&src_offsets, i),
                *semisafe_get(&dest_offsets, i),
                *semisafe_get(&refine, i),
                self.stride,
                self.padded_width,
                self.padded_height,
                self.bits_per_sample,
            );
        }

        // Use helper function to avoid clones in average2 calls
        if self.pel == Subpel::Quarter {
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 0),
                *semisafe_get(&self.subpel_window_offsets, 2),
                *semisafe_get(&self.subpel_window_offsets, 1),
                self.stride,
                self.padded_width,
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 8),
                *semisafe_get(&self.subpel_window_offsets, 10),
                *semisafe_get(&self.subpel_window_offsets, 9),
                self.stride,
                self.padded_width,
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 0),
                *semisafe_get(&self.subpel_window_offsets, 8),
                *semisafe_get(&self.subpel_window_offsets, 4),
                self.stride,
                self.padded_width,
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 2),
                *semisafe_get(&self.subpel_window_offsets, 10),
                *semisafe_get(&self.subpel_window_offsets, 6),
                self.stride,
                self.padded_width,
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 4),
                *semisafe_get(&self.subpel_window_offsets, 6),
                *semisafe_get(&self.subpel_window_offsets, 5),
                self.stride,
                self.padded_width,
                self.padded_height,
            );

            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 0) + 1,
                *semisafe_get(&self.subpel_window_offsets, 2),
                *semisafe_get(&self.subpel_window_offsets, 3),
                self.stride,
                // SAFETY: Since we are doing qpel refinement, we know res is at least 4x4
                unsafe { NonZeroUsize::new_unchecked(self.padded_width.get() - 1) },
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 8) + 1,
                *semisafe_get(&self.subpel_window_offsets, 10),
                *semisafe_get(&self.subpel_window_offsets, 11),
                self.stride,
                // SAFETY: Since we are doing qpel refinement, we know res is at least 4x4
                unsafe { NonZeroUsize::new_unchecked(self.padded_width.get() - 1) },
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 0) + self.stride.get(),
                *semisafe_get(&self.subpel_window_offsets, 8),
                *semisafe_get(&self.subpel_window_offsets, 12),
                self.stride,
                self.padded_width,
                // SAFETY: Since we are doing qpel refinement, we know res is at least 4x4
                unsafe { NonZeroUsize::new_unchecked(self.padded_height.get() - 1) },
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 2) + self.stride.get(),
                *semisafe_get(&self.subpel_window_offsets, 10),
                *semisafe_get(&self.subpel_window_offsets, 14),
                self.stride,
                self.padded_width,
                // SAFETY: Since we are doing qpel refinement, we know res is at least 4x4
                unsafe { NonZeroUsize::new_unchecked(self.padded_height.get() - 1) },
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 12),
                *semisafe_get(&self.subpel_window_offsets, 14),
                *semisafe_get(&self.subpel_window_offsets, 13),
                self.stride,
                self.padded_width,
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 4) + 1,
                *semisafe_get(&self.subpel_window_offsets, 6),
                *semisafe_get(&self.subpel_window_offsets, 7),
                self.stride,
                // SAFETY: Since we are doing qpel refinement, we know res is at least 4x4
                unsafe { NonZeroUsize::new_unchecked(self.padded_width.get() - 1) },
                self.padded_height,
            );
            Self::average2_with_split(
                plane,
                *semisafe_get(&self.subpel_window_offsets, 12) + 1,
                *semisafe_get(&self.subpel_window_offsets, 14),
                *semisafe_get(&self.subpel_window_offsets, 15),
                self.stride,
                // SAFETY: Since we are doing qpel refinement, we know res is at least 4x4
                unsafe { NonZeroUsize::new_unchecked(self.padded_width.get() - 1) },
                self.padded_height,
            );
        }

        self.is_refined = true;
    }

    #[must_use]
    #[inline]
    pub fn get_absolute_pix_offset(&self, x: i32, y: i32) -> usize {
        match self.pel {
            Subpel::Full => self.get_absolute_pix_offset_pel1(x, y),
            Subpel::Half => self.get_absolute_pix_offset_pel2(x, y),
            Subpel::Quarter => self.get_absolute_pix_offset_pel4(x, y),
        }
    }

    #[must_use]
    #[inline]
    pub fn get_absolute_pix_offset_pel<const PEL: usize>(&self, x: i32, y: i32) -> usize {
        match PEL {
            1 => self.get_absolute_pix_offset_pel1(x, y),
            2 => self.get_absolute_pix_offset_pel2(x, y),
            4 => self.get_absolute_pix_offset_pel4(x, y),
            _ => unreachable!(),
        }
    }

    #[must_use]
    #[inline]
    pub fn get_pel_pix_offset(&self, x: i32, y: i32) -> usize {
        (*semisafe_get(&self.subpel_window_offsets, 0) as i32 + x + y * self.stride.get() as i32)
            as usize
    }

    #[must_use]
    #[inline]
    pub fn get_absolute_pix_offset_pel1(&self, x: i32, y: i32) -> usize {
        self.get_pel_pix_offset(x, y)
    }

    #[must_use]
    #[inline]
    pub fn get_absolute_pix_offset_pel2(&self, mut x: i32, mut y: i32) -> usize {
        let idx = ((x & 1) | ((y & 1) << 1)) as usize;
        x >>= 1;
        y >>= 1;
        (*semisafe_get(&self.subpel_window_offsets, idx) as i32 + x + y * self.stride.get() as i32)
            as usize
    }

    #[must_use]
    #[inline]
    pub fn get_absolute_pix_offset_pel4(&self, mut x: i32, mut y: i32) -> usize {
        let idx = ((x & 3) | ((y & 3) << 2)) as usize;
        x >>= 2;
        y >>= 2;
        (*semisafe_get(&self.subpel_window_offsets, idx) as i32 + x + y * self.stride.get() as i32)
            as usize
    }

    #[must_use]
    #[inline]
    pub fn get_pix_offset(&self, x: i32, y: i32) -> usize {
        self.get_absolute_pix_offset(x + self.hpad_pel as i32, y + self.vpad_pel as i32)
    }

    pub(crate) fn update(&mut self, src_offset: usize, pitch: NonZeroUsize) {
        self.stride = pitch;
        self.offset_padding = self.stride.get() * self.vpad + self.hpad;

        for i in 0..(self.pel as usize).pow(2) {
            *semisafe_get_mut(&mut self.subpel_window_offsets, i) =
                src_offset + i * self.stride.get() * self.padded_height.get();
        }
        self.reset_state();
    }

    const fn reset_state(&mut self) {
        self.is_refined = false;
        self.is_filled = false;
        self.is_padded = false;
    }
}

/// Calculates the height of a luma plane at a specific hierarchical level.
///
/// This function computes the height of a luma plane after downscaling through
/// multiple hierarchical levels in a motion estimation pyramid. At each level,
/// the height is divided by the UV ratio and then by 2, creating progressively
/// smaller reference frames for coarse-to-fine motion estimation.
///
/// The function accounts for chroma subsampling ratios and padding requirements
/// to ensure proper alignment at each level of the hierarchy.
///
/// # Parameters
/// - `src_height`: Original source image height
/// - `level`: Hierarchical level (0 = original size, higher = more downscaled)
/// - `y_ratio_uv`: Vertical chroma subsampling ratio (1 for 4:4:4, 2 for 4:2:0, etc.)
/// - `vpad`: Vertical padding amount in pixels
///
/// # Returns
/// The calculated height for the luma plane at the specified level
#[must_use]
#[inline]
pub fn plane_height_luma(
    src_height: NonZeroUsize,
    level: usize,
    y_ratio_uv: NonZeroU8,
    vpad: usize,
) -> NonZeroUsize {
    let mut height = src_height.get();
    let y_ratio_uv_val = y_ratio_uv.get() as usize;

    for _i in 1..=level {
        height = if vpad >= y_ratio_uv_val {
            (height / y_ratio_uv_val + 1) / 2 * y_ratio_uv_val
        } else {
            ((height / y_ratio_uv_val) / 2) * y_ratio_uv_val
        };
    }

    // Call sites guarantee that the result will be non-zero
    debug_assert!(
        height > 0,
        "Calculated height must be non-zero. src_height: {}, level: {}, y_ratio_uv: {}, vpad: {}",
        src_height,
        level,
        y_ratio_uv,
        vpad
    );

    // SAFETY: Call sites enforce that this will never produce a 0 output height
    unsafe { NonZeroUsize::new_unchecked(height) }
}

/// Calculates the width of a luma plane at a specific hierarchical level.
///
/// This function computes the width of a luma plane after downscaling through
/// multiple hierarchical levels in a motion estimation pyramid. At each level,
/// the width is divided by the UV ratio and then by 2, creating progressively
/// smaller reference frames for coarse-to-fine motion estimation.
///
/// The function accounts for chroma subsampling ratios and padding requirements
/// to ensure proper alignment at each level of the hierarchy.
///
/// # Parameters
/// - `src_width`: Original source image width
/// - `level`: Hierarchical level (0 = original size, higher = more downscaled)
/// - `x_ratio_uv`: Horizontal chroma subsampling ratio (1 for 4:4:4, 2 for 4:2:0, etc.)
/// - `hpad`: Horizontal padding amount in pixels
///
/// # Returns
/// The calculated width for the luma plane at the specified level
#[must_use]
#[inline]
pub fn plane_width_luma(
    src_width: NonZeroUsize,
    level: usize,
    x_ratio_uv: NonZeroU8,
    hpad: usize,
) -> NonZeroUsize {
    let mut width = src_width.get();
    let x_ratio_uv_val = x_ratio_uv.get() as usize;

    for _i in 1..=level {
        width = if hpad >= x_ratio_uv_val {
            (width / x_ratio_uv_val + 1) / 2 * x_ratio_uv_val
        } else {
            ((width / x_ratio_uv_val) / 2) * x_ratio_uv_val
        };
    }

    // Call sites guarantee that the result will be non-zero
    debug_assert!(
        width > 0,
        "Calculated width must be non-zero. src_width: {}, level: {}, x_ratio_uv: {}, hpad: {}",
        src_width,
        level,
        x_ratio_uv,
        hpad
    );

    // SAFETY: Call sites enforce that this will never produce a 0 output width
    unsafe { NonZeroUsize::new_unchecked(width) }
}

/// Calculates the memory offset for a plane within a hierarchical superframe structure.
///
/// This function computes the pixel offset where a specific plane begins within
/// a superframe that contains multiple hierarchical levels and sub-pixel refinements.
/// Superframes store multiple downscaled versions of the same image along with
/// sub-pixel interpolated versions for efficient hierarchical motion estimation.
///
/// The offset calculation accounts for:
/// - Sub-pixel precision levels (pel parameter)
/// - Multiple hierarchical levels with different dimensions
/// - Chroma vs luma plane differences
/// - Padding requirements at each level
///
/// # Parameters
/// - `chroma`: Whether this is a chroma plane (affects subsampling calculations)
/// - `src_height`: Original source image height
/// - `level`: Target hierarchical level for the offset calculation
/// - `pel`: Sub-pixel precision level (1=integer, 2=half-pixel, 4=quarter-pixel)
/// - `vpad`: Vertical padding amount in pixels
/// - `plane_pitch`: Number of pixels per row in the plane buffer
/// - `y_ratio_uv`: Vertical chroma subsampling ratio
///
/// # Returns
/// The pixel offset where the specified plane begins in the superframe
#[must_use]
#[inline]
pub fn plane_super_offset(
    chroma: bool,
    src_height: NonZeroUsize,
    level: usize,
    pel: Subpel,
    vpad: usize,
    plane_pitch: NonZeroUsize,
    y_ratio_uv: NonZeroU8,
) -> usize {
    // storing subplanes in superframes may be implemented by various ways
    let mut height; // luma or chroma

    let mut offset;

    if level == 0 {
        offset = 0;
    } else {
        let pel = u8::from(pel) as usize;
        let plane_pitch_val = plane_pitch.get();
        let src_height_val = src_height.get();
        let y_ratio_uv_val = y_ratio_uv.get() as usize;
        offset = pel * pel * plane_pitch_val * (src_height_val + vpad * 2);

        for i in 1..level {
            // NOTE: We use `src_height` here (not a running `height` variable) because
            // plane_height_luma internally handles the hierarchical scaling by applying
            // the division `level` times in its own loop. Each call calculates the height
            // at the specific level `i` starting from the original source dimensions.
            height = if chroma {
                plane_height_luma(
                    src_height.saturating_mul(y_ratio_uv.into()),
                    i,
                    y_ratio_uv,
                    vpad * y_ratio_uv_val,
                )
                .get()
                    / y_ratio_uv_val
            } else {
                plane_height_luma(src_height, i, y_ratio_uv, vpad).get()
            };

            offset += plane_pitch_val * (height + vpad * 2);
        }
    }

    offset
}