zoomvtools 2.0.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
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
use std::{
    cmp::min,
    num::{NonZeroU8, NonZeroUsize},
};

use anyhow::{Result, anyhow, bail};

use crate::{
    analysis::MVAnalysisData,
    frame::FrameView,
    group_of_planes::GroupOfPlanes,
    mv_gof::MVGroupOfFrames,
    params::{DctMode, DivideMode, MVPlaneSet, MotionFlags, PenaltyScaling, SearchType, Subpel},
    plane_of_blocks::MvsOutput,
    util::Pixel,
    video::{ColorFamily, SampleType, VideoInfo},
};

#[cfg(test)]
mod tests;

/// Metadata recovered from a [`Super`](crate::Super) clip.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SuperClipInfo {
    /// Source-frame height before the super clip padding is applied.
    pub height: NonZeroUsize,
    /// Horizontal padding, in source pixels.
    pub hpad: usize,
    /// Vertical padding, in source pixels.
    pub vpad: usize,
    /// Subpixel precision stored by the super clip.
    pub pel: Subpel,
    /// Plane set stored by the super clip.
    pub mode_yuv: MVPlaneSet,
    /// Number of pyramid levels carried by the super clip.
    pub levels: usize,
}

/// Options used to construct [`Analyse`].
///
/// `None` selects the MVTools-compatible default for optional fields.
#[derive(Debug, Clone, Copy)]
pub struct AnalyseOptions {
    /// Horizontal block size in pixels.
    pub blk_size_x: Option<usize>,
    /// Vertical block size in pixels.
    pub blk_size_y: Option<usize>,
    /// Number of search levels to analyse.
    pub levels: Option<usize>,
    /// Search strategy for the finest level.
    pub search_type: Option<SearchType>,
    /// Search radius or step count for the selected search strategy.
    pub search_param: Option<i32>,
    /// Subpixel refinement radius.
    pub pel_search: Option<usize>,
    /// Selects backward instead of forward vectors.
    pub is_backward: bool,
    /// Motion-vector penalty scale for block matching.
    pub lambda: Option<u32>,
    /// Enables chroma-guided motion search when `true`.
    pub chroma: Option<bool>,
    /// Reference-frame offset; negative values select an absolute frame index.
    pub delta_frame: isize,
    /// Enables MVTools true-motion defaults.
    pub truemotion: bool,
    /// Additional SAD weighting factor.
    pub lambda_sad: Option<u32>,
    /// Preset used to scale motion penalties.
    pub penalty_level: Option<PenaltyScaling>,
    /// Enables the global-motion predictor.
    pub global: Option<bool>,
    /// Penalty applied to new candidate vectors.
    pub penalty_new: Option<u16>,
    /// Penalty applied to the zero vector.
    pub penalty_zero: Option<u16>,
    /// Penalty applied to the global predictor.
    pub penalty_global: Option<u16>,
    /// Horizontal overlap between neighbouring blocks.
    pub overlap_x: Option<usize>,
    /// Vertical overlap between neighbouring blocks.
    pub overlap_y: Option<usize>,
    /// Optional extra block subdivision mode.
    pub divide_extra: Option<DivideMode>,
    /// SAD threshold used to mark unreliable vectors.
    pub bad_sad: Option<u64>,
    /// Search expansion used after a bad SAD match.
    pub bad_range: Option<i32>,
    /// Enables meander block traversal.
    pub meander: bool,
    /// Tries additional candidate predictors.
    pub try_many: bool,
    /// Treats the clip as field-based.
    pub fields: bool,
    /// Overrides top-field-first when `fields` is enabled.
    pub tff: Option<bool>,
    /// Search strategy for coarse pyramid levels.
    pub search_type_coarse: Option<SearchType>,
    /// DCT or SATD mode used for block matching.
    pub dct_mode: Option<DctMode>,
}

impl Default for AnalyseOptions {
    #[inline]
    fn default() -> Self {
        Self {
            blk_size_x: None,
            blk_size_y: None,
            levels: None,
            search_type: None,
            search_param: None,
            pel_search: None,
            is_backward: false,
            lambda: None,
            chroma: None,
            delta_frame: 1,
            truemotion: true,
            lambda_sad: None,
            penalty_level: None,
            global: None,
            penalty_new: None,
            penalty_zero: None,
            penalty_global: None,
            overlap_x: None,
            overlap_y: None,
            divide_extra: None,
            bad_sad: None,
            bad_range: None,
            meander: true,
            try_many: false,
            fields: false,
            tff: None,
            search_type_coarse: None,
            dct_mode: None,
        }
    }
}

/// Motion-analysis filter state for repeated frame analysis.
#[derive(Debug, Clone)]
pub struct Analyse {
    search_type: SearchType,
    search_type_coarse: SearchType,
    search_param: i32,
    pel_search: i32,
    lambda: u32,
    lambda_sad: u32,
    penalty_level: PenaltyScaling,
    global: bool,
    penalty_new: u16,
    penalty_zero: u16,
    penalty_global: u16,
    dct_mode: DctMode,
    divide_extra: DivideMode,
    bad_sad: u64,
    bad_range: i32,
    meander: bool,
    try_many: bool,
    fields: bool,
    tff: Option<bool>,
    analysis_data: MVAnalysisData,
    analysis_data_divided: Option<MVAnalysisData>,
    super_info: SuperClipInfo,
    plane_count: usize,
    frame_count: usize,
}

/// Output of [`Analyse::analyse_frame`].
#[derive(Debug, Clone)]
pub struct AnalyseResult {
    /// Metadata describing the returned vector stream.
    pub analysis_data: MVAnalysisData,
    /// Packed vectors for the analysed frame.
    pub vectors: MvsOutput,
}

impl Analyse {
    /// Builds an analyser from clip metadata and validated options.
    ///
    /// # Errors
    /// Returns an error if the clip format, super metadata, or analysis options are invalid.
    #[inline]
    pub fn new(
        info: VideoInfo,
        super_info: SuperClipInfo,
        options: AnalyseOptions,
    ) -> Result<Self> {
        let blk_size_x = options.blk_size_x.unwrap_or(8);
        let blk_size_y = options.blk_size_y.unwrap_or(blk_size_x);
        let overlap_x = options.overlap_x.unwrap_or(0);
        let overlap_y = options.overlap_y.unwrap_or(overlap_x);
        let truemotion = options.truemotion;
        let penalty_new = options
            .penalty_new
            .unwrap_or(if truemotion { 50 } else { 0 });
        let penalty_zero = options.penalty_zero.unwrap_or(penalty_new);
        let penalty_global = options.penalty_global.unwrap_or(0);
        let dct_mode = options.dct_mode.unwrap_or(DctMode::Spatial);
        let search_type = options.search_type.unwrap_or(SearchType::Hex2);
        let mut search_param = options.search_param.unwrap_or(2);
        let divide_extra = options.divide_extra.unwrap_or(DivideMode::None);
        let mut chroma = options.chroma.unwrap_or(true);
        let mut lambda = options.lambda.unwrap_or(if truemotion {
            (1000 * blk_size_x * blk_size_y / 64) as u32
        } else {
            0
        });
        let mut lambda_sad = options
            .lambda_sad
            .unwrap_or(if truemotion { 1200 } else { 400 });
        let mut bad_sad = options.bad_sad.unwrap_or(10_000);
        let is_backward = options.is_backward;
        let delta_frame = options.delta_frame;
        let mut pel_search = options.pel_search.unwrap_or(0);

        if dct_mode.uses_satd() && blk_size_x == 16 && blk_size_y == 2 {
            bail!("Analyse: dct 5-10 cannot work with 16x2 blocks");
        }
        match (blk_size_x, blk_size_y) {
            (4, 4)
            | (8, 4)
            | (8, 8)
            | (16, 2)
            | (16, 8)
            | (16, 16)
            | (32, 16)
            | (32, 32)
            | (64, 32)
            | (64, 64)
            | (128, 64)
            | (128, 128) => (),
            _ => {
                bail!(
                    "Analyse: the block size must be 4x4, 8x4, 8x8, 16x2, 16x8, 16x16, 32x16, \
                     32x32, 64x32, 64x64, 128x64, or 128x128."
                );
            }
        }

        if penalty_new > 256 {
            bail!("Analyse: pnew must be between 0 and 256 (inclusive).");
        }
        if penalty_zero > 256 {
            bail!("Analyse: pzero must be between 0 and 256 (inclusive).");
        }
        if penalty_global > 256 {
            bail!("Analyse: pglobal must be between 0 and 256 (inclusive).");
        }

        if overlap_x > blk_size_x / 2 || overlap_y > blk_size_y / 2 {
            bail!(
                "Analyse: overlap must be at most half of blksize, and overlapv must be at most \
                 half of blksizev"
            );
        }

        if divide_extra != DivideMode::None && (blk_size_x < 8 || blk_size_y < 8) {
            bail!("Analyse: blksize and blksizev must be at least 8 when divide=True.");
        }

        if search_type == SearchType::Nstep {
            if search_param < 0 {
                search_param = 0;
            }
        } else if search_param < 1 {
            search_param = 1;
        }

        let format = info.format;
        if format.bits_per_sample.get() > 16 {
            bail!("Analyse: input clip must be 8-16 bits");
        }
        if format.sample_type != SampleType::Integer {
            bail!("Analyse: input clip must be integer super_format");
        }
        if ![ColorFamily::Yuv, ColorFamily::Gray].contains(&format.color_family)
            || format.sub_sampling_w > 1
            || format.sub_sampling_h > 1
        {
            bail!("Analyse: input clip must be GRAY, 420, 422, 440, or 444");
        }

        if format.color_family == ColorFamily::Gray {
            chroma = false;
        }

        let bits_per_sample = format.bits_per_sample;
        let pixel_max = (1u32 << bits_per_sample.get()) - 1;
        lambda_sad = (lambda_sad as f32 * pixel_max as f32 / 255.0 + 0.5) as u32;
        bad_sad = (bad_sad as f32 * pixel_max as f32 / 255.0 + 0.5) as u64;
        lambda = (lambda as f32 * pixel_max as f32 / 255.0 + 0.5) as u32;
        lambda_sad = (lambda_sad as usize * (blk_size_x * blk_size_y) / 64) as u32;
        bad_sad = bad_sad * (blk_size_x * blk_size_y) as u64 / 64;

        let mut motion_flags = MotionFlags::empty();
        if is_backward {
            motion_flags |= MotionFlags::IS_BACKWARD;
        }
        if chroma {
            motion_flags |= MotionFlags::USE_CHROMA_MOTION;
        }

        let mode_yuv = if chroma {
            MVPlaneSet::YUVPLANES
        } else {
            MVPlaneSet::YPLANE
        };

        if !overlap_x.is_multiple_of(1 << format.sub_sampling_w)
            || !overlap_y.is_multiple_of(1 << format.sub_sampling_h)
        {
            bail!(
                "Analyse: the requested overlap is incompatible with the super clip's subsampling."
            );
        }
        if divide_extra != DivideMode::None
            && (!overlap_x.is_multiple_of(2 << format.sub_sampling_w)
                || !overlap_y.is_multiple_of(2 << format.sub_sampling_h))
        {
            bail!(
                "Analyse: overlap and overlapv must be multiples of 2 or 4 when divide=True, \
                 depending on the super clip's subsampling."
            );
        }
        if delta_frame <= 0 && (-delta_frame) >= info.num_frames as isize {
            bail!("Analyse: delta points to frame past the input clip's end.");
        }

        let width = NonZeroUsize::new(info.resolution.width)
            .ok_or_else(|| anyhow!("Analyse: variable resolution input clips are not supported"))?;

        let x_ratio_uv = NonZeroU8::new(1 << format.sub_sampling_w)
            .ok_or_else(|| anyhow!("Analyse: invalid horizontal subsampling"))?;
        let y_ratio_uv = NonZeroU8::new(1 << format.sub_sampling_h)
            .ok_or_else(|| anyhow!("Analyse: invalid vertical subsampling"))?;

        let super_height = super_info.height;
        let super_hpad = super_info.hpad;
        let super_vpad = super_info.vpad;
        let super_pel = super_info.pel;
        let super_mode_yuv = super_info.mode_yuv;
        let super_levels = super_info.levels;
        if super_hpad >= super_height.get() / 2 {
            bail!("Analyse: parameters from super clip appear to be wrong.");
        }

        if mode_yuv & super_mode_yuv != mode_yuv {
            bail!("Analyse: super clip does not contain needed colour data.");
        }

        let super_width =
            NonZeroUsize::new(width.get().checked_sub(super_hpad * 2).ok_or_else(|| {
                anyhow!("Analyse: parameters from super clip appear to be wrong.")
            })?)
            .ok_or_else(|| anyhow!("Analyse: parameters from super clip appear to be wrong."))?;
        let blk_x = (super_width.get() - overlap_x) / (blk_size_x - overlap_x);
        let blk_y = (super_height.get() - overlap_y) / (blk_size_y - overlap_y);
        let width_b = (blk_size_x - overlap_x) * blk_x + overlap_x;
        let height_b = (blk_size_y - overlap_y) * blk_y + overlap_y;

        let mut levels_max = 0;
        while ((width_b >> levels_max) - overlap_x) / (blk_size_x - overlap_x) > 0
            && ((height_b >> levels_max) - overlap_y) / (blk_size_y - overlap_y) > 0
        {
            levels_max += 1;
        }
        let level_count = options
            .levels
            .filter(|levels| *levels > 0)
            .map_or(levels_max, |levels| min(levels_max, levels));
        debug_assert!(level_count > 0);

        if level_count > super_levels {
            bail!(
                "Analyse: super clip has {} levels. Analyse needs {} levels.",
                super_levels,
                level_count
            );
        }

        if pel_search == 0 {
            pel_search = usize::from(u8::from(super_pel));
        }

        let analysis_data = MVAnalysisData {
            blk_size_x: NonZeroUsize::new(blk_size_x)
                .ok_or_else(|| anyhow!("Analyse: blksize must be greater than 0"))?,
            blk_size_y: NonZeroUsize::new(blk_size_y)
                .ok_or_else(|| anyhow!("Analyse: blksizev must be greater than 0"))?,
            pel: super_pel,
            level_count,
            delta_frame,
            is_backward,
            motion_flags,
            width: super_width,
            height: super_height,
            overlap_x,
            overlap_y,
            blk_x: NonZeroUsize::new(blk_x).expect("block count should not be zero"),
            blk_y: NonZeroUsize::new(blk_y).expect("block count should not be zero"),
            bits_per_sample,
            y_ratio_uv,
            x_ratio_uv,
            h_padding: super_hpad,
            v_padding: super_vpad,
        };

        let analysis_data_divided = (divide_extra != DivideMode::None).then(|| {
            let mut div_data = analysis_data;
            div_data.blk_x = div_data
                .blk_x
                .saturating_mul(NonZeroUsize::new(2).expect("constant is non-zero"));
            div_data.blk_y = div_data
                .blk_y
                .saturating_mul(NonZeroUsize::new(2).expect("constant is non-zero"));
            div_data.blk_size_x = NonZeroUsize::new(div_data.blk_size_x.get() / 2)
                .expect("block width stays non-zero");
            div_data.blk_size_y = NonZeroUsize::new(div_data.blk_size_y.get() / 2)
                .expect("block height stays non-zero");
            div_data.overlap_x /= 2;
            div_data.overlap_y /= 2;
            div_data.level_count += 1;
            div_data
        });

        Ok(Self {
            search_type,
            search_type_coarse: options.search_type_coarse.unwrap_or(SearchType::Exhaustive),
            search_param,
            pel_search: pel_search as i32,
            lambda,
            lambda_sad,
            penalty_level: options.penalty_level.unwrap_or(if truemotion {
                PenaltyScaling::Linear
            } else {
                PenaltyScaling::None
            }),
            global: options.global.unwrap_or(truemotion),
            penalty_new,
            penalty_zero,
            penalty_global,
            dct_mode,
            divide_extra,
            bad_sad,
            bad_range: options.bad_range.unwrap_or(24),
            meander: options.meander,
            try_many: options.try_many,
            fields: options.fields,
            tff: options.tff,
            analysis_data,
            analysis_data_divided,
            super_info,
            plane_count: format.plane_count(),
            frame_count: info.num_frames,
        })
    }

    /// Returns metadata for vectors produced by this analyser.
    #[must_use]
    #[inline]
    pub const fn analysis_data(&self) -> MVAnalysisData {
        self.analysis_data
    }

    /// Returns metadata for the divided vector stream when division is enabled.
    #[must_use]
    #[inline]
    pub const fn analysis_data_divided(&self) -> Option<MVAnalysisData> {
        self.analysis_data_divided
    }

    /// Returns the super-clip metadata used by this analyser.
    #[must_use]
    #[inline]
    pub const fn super_info(&self) -> SuperClipInfo {
        self.super_info
    }

    /// Returns the number of image planes processed per frame.
    #[must_use]
    #[inline]
    pub const fn plane_count(&self) -> usize {
        self.plane_count
    }

    /// Returns the source clip frame count captured at construction time.
    #[must_use]
    #[inline]
    pub const fn frame_count(&self) -> usize {
        self.frame_count
    }

    /// Returns the finest-level search strategy.
    #[must_use]
    #[inline]
    pub const fn search_type(&self) -> SearchType {
        self.search_type
    }

    /// Returns the coarse-level search strategy.
    #[must_use]
    #[inline]
    pub const fn search_type_coarse(&self) -> SearchType {
        self.search_type_coarse
    }

    /// Returns the validated search parameter.
    #[must_use]
    #[inline]
    pub const fn search_param(&self) -> i32 {
        self.search_param
    }

    /// Returns the validated subpixel refinement radius.
    #[must_use]
    #[inline]
    pub const fn pel_search(&self) -> i32 {
        self.pel_search
    }

    /// Returns the motion penalty scale.
    #[must_use]
    #[inline]
    pub const fn lambda(&self) -> u32 {
        self.lambda
    }

    /// Returns the additional SAD weighting factor.
    #[must_use]
    #[inline]
    pub const fn lambda_sad(&self) -> u32 {
        self.lambda_sad
    }

    /// Returns the configured penalty-scaling preset.
    #[must_use]
    #[inline]
    pub const fn penalty_level(&self) -> PenaltyScaling {
        self.penalty_level
    }

    /// Returns whether the global-motion predictor is enabled.
    #[must_use]
    #[inline]
    pub const fn global(&self) -> bool {
        self.global
    }

    /// Returns the penalty applied to new candidate vectors.
    #[must_use]
    #[inline]
    pub const fn penalty_new(&self) -> u16 {
        self.penalty_new
    }

    /// Returns the penalty applied to the zero vector.
    #[must_use]
    #[inline]
    pub const fn penalty_zero(&self) -> u16 {
        self.penalty_zero
    }

    /// Returns the penalty applied to the global predictor.
    #[must_use]
    #[inline]
    pub const fn penalty_global(&self) -> u16 {
        self.penalty_global
    }

    /// Returns the configured block-matching metric.
    #[must_use]
    #[inline]
    pub const fn dct_mode(&self) -> DctMode {
        self.dct_mode
    }

    /// Returns the extra block-division mode.
    #[must_use]
    #[inline]
    pub const fn divide_extra(&self) -> DivideMode {
        self.divide_extra
    }

    /// Returns the bad-match SAD threshold.
    #[must_use]
    #[inline]
    pub const fn bad_sad(&self) -> u64 {
        self.bad_sad
    }

    /// Returns the extra search range used after a bad match.
    #[must_use]
    #[inline]
    pub const fn bad_range(&self) -> i32 {
        self.bad_range
    }

    /// Returns whether meander traversal is enabled.
    #[must_use]
    #[inline]
    pub const fn meander(&self) -> bool {
        self.meander
    }

    /// Returns whether additional predictors are tried.
    #[must_use]
    #[inline]
    pub const fn try_many(&self) -> bool {
        self.try_many
    }

    /// Returns whether the analyser is configured for field-based search.
    #[must_use]
    #[inline]
    pub const fn fields(&self) -> bool {
        self.fields
    }

    /// Returns the top-field-first override used for field-based search.
    #[must_use]
    #[inline]
    pub const fn tff(&self) -> Option<bool> {
        self.tff
    }

    /// Returns the reference frame index paired with source frame `n`.
    ///
    /// Returns `None` when the reference would fall outside the source clip.
    #[must_use]
    #[inline]
    pub fn reference_frame_number(&self, n: usize) -> Option<usize> {
        let nref = if self.analysis_data.delta_frame > 0 {
            let offset = if self.analysis_data.is_backward {
                self.analysis_data.delta_frame
            } else {
                -self.analysis_data.delta_frame
            };
            n as isize + offset
        } else {
            -self.analysis_data.delta_frame
        };

        (nref >= 0 && (nref as usize) < self.frame_count).then_some(nref as usize)
    }

    /// Analyses one source frame and returns packed vectors plus their metadata.
    ///
    /// # Errors
    /// Returns an error if the input frames, field flags, or frame geometry do not match the
    /// analyser configuration.
    #[inline]
    pub fn analyse_frame<T: Pixel>(
        &self,
        n: usize,
        src: &FrameView<'_, T>,
        reference: Option<&FrameView<'_, T>>,
        src_top_field: Option<bool>,
        ref_top_field: Option<bool>,
    ) -> Result<AnalyseResult> {
        let mut vector_fields = GroupOfPlanes::<T>::new(
            self.analysis_data.blk_size_x,
            self.analysis_data.blk_size_y,
            self.analysis_data.level_count,
            self.analysis_data.pel,
            self.analysis_data.motion_flags,
            self.analysis_data.overlap_x,
            self.analysis_data.overlap_y,
            self.analysis_data.blk_x,
            self.analysis_data.blk_y,
            self.analysis_data.x_ratio_uv,
            self.analysis_data.y_ratio_uv,
            self.divide_extra,
            self.analysis_data.bits_per_sample,
        )?;

        let vectors = if let Some(reference) = reference {
            let src_top_field = self.resolve_top_field(n, src_top_field, "source")?;
            let ref_top_field = self.resolve_top_field(n, ref_top_field, "reference")?;
            let field_shift = self.field_shift(src_top_field, ref_top_field);

            let src_gof = MVGroupOfFrames::new(
                self.super_info.levels,
                self.analysis_data.width,
                self.analysis_data.height,
                self.super_info.pel,
                self.super_info.hpad,
                self.super_info.vpad,
                self.super_info.mode_yuv,
                self.analysis_data.x_ratio_uv,
                self.analysis_data.y_ratio_uv,
                self.analysis_data.bits_per_sample,
                src.pitch(),
                self.plane_count,
            )?;
            let ref_gof = MVGroupOfFrames::new(
                self.super_info.levels,
                self.analysis_data.width,
                self.analysis_data.height,
                self.super_info.pel,
                self.super_info.hpad,
                self.super_info.vpad,
                self.super_info.mode_yuv,
                self.analysis_data.x_ratio_uv,
                self.analysis_data.y_ratio_uv,
                self.analysis_data.bits_per_sample,
                reference.pitch(),
                self.plane_count,
            )?;

            let mut vectors = vector_fields.search_mvs(
                &src_gof,
                src.planes(),
                &ref_gof,
                reference.planes(),
                self.search_type,
                self.search_type_coarse,
                self.search_param,
                self.pel_search,
                self.lambda,
                self.lambda_sad,
                self.penalty_new,
                self.penalty_level,
                self.global,
                field_shift,
                self.dct_mode,
                self.penalty_zero,
                self.penalty_global,
                self.bad_sad,
                self.bad_range,
                self.meander,
                self.try_many,
            )?;
            if self.divide_extra != DivideMode::None {
                vector_fields.extra_divide(&mut vectors);
            }
            vectors
        } else {
            vector_fields.write_default_to_array()
        };

        Ok(AnalyseResult {
            analysis_data: self.analysis_data_for_output(),
            vectors,
        })
    }

    #[must_use]
    #[inline]
    fn analysis_data_for_output(&self) -> MVAnalysisData {
        self.analysis_data_divided.unwrap_or(self.analysis_data)
    }

    #[inline]
    fn resolve_top_field(&self, n: usize, field: Option<bool>, frame_name: &str) -> Result<bool> {
        if let Some(tff) = self.tff {
            return Ok((tff as u8 ^ (n % 2) as u8) > 0);
        }

        if self.fields {
            field.ok_or_else(|| {
                anyhow!(
                    "Analyse: {frame_name} field order is required when fields=true and tff is not set."
                )
            })
        } else {
            Ok(field.unwrap_or(false))
        }
    }

    #[must_use]
    #[inline]
    fn field_shift(&self, src_top_field: bool, ref_top_field: bool) -> i32 {
        if self.fields
            && self.analysis_data.pel > Subpel::Full
            && (self.analysis_data.delta_frame % 2) > 0
        {
            if src_top_field && !ref_top_field {
                (u8::from(self.analysis_data.pel) as u32 / 2) as i32
            } else if ref_top_field && !src_top_field {
                -((u8::from(self.analysis_data.pel) as u32 / 2) as i32)
            } else {
                0
            }
        } else {
            0
        }
    }
}