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
use std::num::NonZeroU8;

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

/// Default `thscd1` scene-change threshold used by motion-vector filters.
pub const MV_DEFAULT_SCD1: u64 = 400;
/// Default `thscd2` scene-change percentage used by motion-vector filters.
pub const MV_DEFAULT_SCD2: u64 = 130;

/// Subpixel precision used when building and refining motion vectors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Subpel {
    /// Use full-pixel motion vectors.
    Full = 1,
    /// Refine motion vectors to half-pixel positions.
    Half = 2,
    /// Refine motion vectors to quarter-pixel positions.
    Quarter = 4,
}

impl Subpel {
    /// Returns the pel level as the internal pyramid shift.
    #[must_use]
    #[inline]
    pub fn log(self) -> usize {
        u8::from(self) as usize >> 1
    }
}

impl TryFrom<i64> for Subpel {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            1 => Self::Full,
            2 => Self::Half,
            4 => Self::Quarter,
            _ => bail!("Invalid value for 'pel', must be 1, 2, or 4, got {val}."),
        })
    }
}

impl From<Subpel> for u8 {
    #[inline]
    fn from(value: Subpel) -> Self {
        match value {
            Subpel::Full => 1,
            Subpel::Half => 2,
            Subpel::Quarter => 4,
        }
    }
}

impl From<Subpel> for NonZeroU8 {
    #[inline]
    fn from(value: Subpel) -> Self {
        // SAFETY: the int value of this enum can never be zero
        unsafe { NonZeroU8::new_unchecked(u8::from(value)) }
    }
}

/// Interpolation kernel used to generate subpixel reference samples.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubpelMethod {
    /// Use bilinear interpolation.
    Bilinear = 0,
    /// Use bicubic interpolation.
    Bicubic = 1,
    /// Use Wiener interpolation.
    Wiener = 2,
}

impl TryFrom<i64> for SubpelMethod {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::Bilinear,
            1 => Self::Bicubic,
            2 => Self::Wiener,
            _ => bail!("Invalid value for 'sharp', must be 0-2, got {val}."),
        })
    }
}

/// Reduction filter used when building lower-resolution search levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReduceFilter {
    /// Average neighboring pixels.
    Average = 0,
    /// Use a triangle filter.
    Triangle = 1,
    /// Use bilinear reduction.
    Bilinear = 2,
    /// Use a quadratic reduction filter.
    Quadratic = 3,
    /// Use a cubic reduction filter.
    Cubic = 4,
}

impl TryFrom<i64> for ReduceFilter {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::Average,
            1 => Self::Triangle,
            2 => Self::Bilinear,
            3 => Self::Quadratic,
            4 => Self::Cubic,
            _ => bail!("Invalid value for 'rfilter', must be 0-4, got {val}."),
        })
    }
}

/// Search pattern used to locate matching motion blocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchType {
    /// Run a one-time predictor search.
    Onetime = 0,
    /// Run the classic n-step search.
    Nstep = 1,
    /// Run a logarithmic search pattern.
    Logarithmic = 2,
    /// Evaluate the full search window.
    Exhaustive = 3,
    /// Run the `hex2` hexagon search.
    Hex2 = 4,
    /// Run the uneven multi-hexagon search.
    UnevenMultiHexagon = 5,
    /// Search horizontal offsets only.
    Horizontal = 6,
    /// Search vertical offsets only.
    Vertical = 7,
}

impl TryFrom<i64> for SearchType {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::Onetime,
            1 => Self::Nstep,
            2 => Self::Logarithmic,
            3 => Self::Exhaustive,
            4 => Self::Hex2,
            5 => Self::UnevenMultiHexagon,
            6 => Self::Horizontal,
            7 => Self::Vertical,
            _ => bail!("Invalid value for 'search', must be 0-7, got {val}."),
        })
    }
}

/// Specifies how block differences (SAD) are calculated between frames.
/// Can use spatial data, DCT coefficients, SATD, or combinations to improve motion estimation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DctMode {
    /// Calculate differences using raw pixel values in spatial domain.
    Spatial = 0,
    /// Calculate differences using DCT coefficients. Slower, especially for block sizes other than 8x8.
    Dct = 1,
    /// Use both spatial and DCT data, weighted based on the average luma difference between frames.
    MixedSpatialDct = 2,
    /// Adaptively choose between spatial data or an equal mix of spatial and DCT data for each block.
    AdaptiveSpatialMixed = 3,
    /// Adaptively choose between spatial data or DCT-weighted mixed mode for each block.
    AdaptiveSpatialDct = 4,
    /// Use Sum of Absolute Transformed Differences (SATD) instead of SAD for luma comparison.
    Satd = 5,
    /// Use both SATD and DCT data, weighted based on the average luma difference between frames.
    MixedSatdDct = 6,
    /// Adaptively choose between SATD data or an equal mix of SATD and DCT data for each block.
    AdaptiveSatdMixed = 7,
    /// Adaptively choose between SATD data or DCT-weighted mixed mode for each block.
    AdaptiveSatdDct = 8,
    /// Mix of SAD, SATD and DCT data. Weight varies from SAD-only to equal SAD/SATD mix.
    MixedSadEqSatdDct = 9,
    /// Adaptively use SATD weighted by SAD, but only when there are significant luma changes.
    AdaptiveSatdLuma = 10,
}

impl TryFrom<i64> for DctMode {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::Spatial,
            1 => Self::Dct,
            2 => Self::MixedSpatialDct,
            3 => Self::AdaptiveSpatialMixed,
            4 => Self::AdaptiveSpatialDct,
            5 => Self::Satd,
            6 => Self::MixedSatdDct,
            7 => Self::AdaptiveSatdMixed,
            8 => Self::AdaptiveSatdDct,
            9 => Self::MixedSadEqSatdDct,
            10 => Self::AdaptiveSatdLuma,
            _ => bail!("Invalid value for 'dct', must be 0-10, got {val}."),
        })
    }
}

impl From<DctMode> for u8 {
    #[inline]
    fn from(value: DctMode) -> Self {
        match value {
            DctMode::Spatial => 0,
            DctMode::Dct => 1,
            DctMode::MixedSpatialDct => 2,
            DctMode::AdaptiveSpatialMixed => 3,
            DctMode::AdaptiveSpatialDct => 4,
            DctMode::Satd => 5,
            DctMode::MixedSatdDct => 6,
            DctMode::AdaptiveSatdMixed => 7,
            DctMode::AdaptiveSatdDct => 8,
            DctMode::MixedSadEqSatdDct => 9,
            DctMode::AdaptiveSatdLuma => 10,
        }
    }
}

impl DctMode {
    /// Returns whether this mode uses SATD-based block matching.
    #[must_use]
    #[inline]
    pub const fn uses_satd(self) -> bool {
        matches!(
            self,
            DctMode::Satd
                | DctMode::MixedSatdDct
                | DctMode::AdaptiveSatdMixed
                | DctMode::AdaptiveSatdDct
                | DctMode::MixedSadEqSatdDct
                | DctMode::AdaptiveSatdLuma
        )
    }
}

/// Penalty scaling applied to motion-vector predictors across levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PenaltyScaling {
    /// Disable predictor penalty scaling.
    None = 0,
    /// Scale penalties linearly with level size.
    Linear = 1,
    /// Scale penalties quadratically with level size.
    Quadratic = 2,
}

impl TryFrom<i64> for PenaltyScaling {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::None,
            1 => Self::Linear,
            2 => Self::Quadratic,
            _ => bail!("Invalid value for 'plevel', must be 0-2, got {val}."),
        })
    }
}

/// Block-division mode used to split vectors into smaller subblocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DivideMode {
    /// Keep the original block grid.
    None = 0,
    /// Split blocks and copy the original vector into each subblock.
    Original = 1,
    /// Split blocks and seed subblocks from median neighbor vectors.
    Median = 2,
}

impl TryFrom<i64> for DivideMode {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::None,
            1 => Self::Original,
            2 => Self::Median,
            _ => bail!("Invalid value for 'divide', must be 0-2, got {val}."),
        })
    }
}

bitflags! {
    #[repr(C)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    /// Motion-vector flags stored alongside analysis metadata.
    pub struct MotionFlags: u8 {
        /// Marks vectors that point backward in time.
        const IS_BACKWARD = 0x00000002;
        /// Marks vectors from the smallest analysis plane.
        const SMALLEST_PLANE = 0x00000004;
        /// Enables chroma-assisted motion matching.
        const USE_CHROMA_MOTION = 0x00000008;
        /// Uses SSD instead of SAD for block cost.
        const USE_SSD = 0x00000010;
        /// Uses SATD for block cost.
        const USE_SATD =  0x00000020;
    }
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    /// Set of planes enabled for analysis or mask generation.
    pub struct MVPlaneSet: u8 {
        /// Enable the luma plane.
        const YPLANE = (1 << 0);
        /// Enable the U chroma plane.
        const UPLANE = (1 << 1);
        /// Enable the V chroma plane.
        const VPLANE = (1 << 2);
        /// Enable luma and U chroma.
        const YUPLANES = Self::YPLANE.bits() | Self::UPLANE.bits();
        /// Enable luma and V chroma.
        const YVPLANES = Self::YPLANE.bits() | Self::VPLANE.bits();
        /// Enable both chroma planes.
        const UVPLANES = Self::UPLANE.bits() | Self::VPLANE.bits();
        /// Enable luma and both chroma planes.
        const YUVPLANES = Self::YPLANE.bits() | Self::UPLANE.bits() | Self::VPLANE.bits();
    }
}

impl From<PlaneSelection> for MVPlaneSet {
    #[inline]
    fn from(value: PlaneSelection) -> Self {
        match value {
            PlaneSelection::Luma => Self::YPLANE,
            PlaneSelection::ChromaU => Self::UPLANE,
            PlaneSelection::ChromaV => Self::VPLANE,
            PlaneSelection::ChromaBoth => Self::UVPLANES,
            PlaneSelection::All => Self::YUVPLANES,
        }
    }
}

/// Frame source used when scene-change detection marks vectors unusable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SceneChangeBehavior {
    /// Output the reference frame on scene changes.
    ReferenceFrame = 0,
    /// Output the current source frame on scene changes.
    #[default]
    CurrentFrame = 1,
}

impl TryFrom<i64> for SceneChangeBehavior {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::ReferenceFrame,
            1 => Self::CurrentFrame,
            _ => bail!("Invalid value for 'scbehavior', must be 0 or 1, got {val}."),
        })
    }
}

/// Plane selection used by plane-restricted filters.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum PlaneSelection {
    /// Select the luma plane.
    Luma = 0,
    /// Select the U chroma plane.
    ChromaU = 1,
    /// Select the V chroma plane.
    ChromaV = 2,
    /// Select both chroma planes.
    ChromaBoth = 3,
    /// Select luma and both chroma planes.
    #[default]
    All = 4,
}

impl TryFrom<i64> for PlaneSelection {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::Luma,
            1 => Self::ChromaU,
            2 => Self::ChromaV,
            3 => Self::ChromaBoth,
            4 => Self::All,
            _ => bail!("Invalid value for 'plane', must be 0-4, got {val}."),
        })
    }
}

/// Mask output mode used by the `Mask` filter family.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MaskKind {
    /// Output vector-length magnitude.
    #[default]
    VectorLength = 0,
    /// Output block SAD as a mask.
    SadMask = 1,
    /// Output the occlusion mask.
    OcclusionMask = 2,
    /// Output horizontal motion.
    HorizontalMotion = 3,
    /// Output vertical motion.
    VerticalMotion = 4,
    /// Output the motion color map.
    MotionColormap = 5,
}

impl TryFrom<i64> for MaskKind {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(val: i64) -> Result<Self> {
        Ok(match val {
            0 => Self::VectorLength,
            1 => Self::SadMask,
            2 => Self::OcclusionMask,
            3 => Self::HorizontalMotion,
            4 => Self::VerticalMotion,
            5 => Self::MotionColormap,
            _ => bail!("Invalid value for 'kind', must be 0-5, got {val}."),
        })
    }
}