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
//! Contains metrics related to video/image quality.

pub mod ciede;
pub mod decode;
mod pixel;
pub mod psnr;
pub mod psnr_hvs;
pub mod ssim;

use crate::MetricsError;
use decode::*;
use std::error::Error;

pub use pixel::*;
pub use v_frame::frame::Frame;
pub use v_frame::plane::Plane;

trait FrameCompare {
    fn can_compare(&self, other: &Self) -> Result<(), MetricsError>;
}

impl<T: Pixel> FrameCompare for Frame<T> {
    fn can_compare(&self, other: &Self) -> Result<(), MetricsError> {
        self.planes[0].can_compare(&other.planes[0])?;
        self.planes[1].can_compare(&other.planes[1])?;
        self.planes[2].can_compare(&other.planes[2])?;

        Ok(())
    }
}

pub(crate) trait PlaneCompare {
    fn can_compare(&self, other: &Self) -> Result<(), MetricsError>;
}

impl<T: Pixel> PlaneCompare for Plane<T> {
    fn can_compare(&self, other: &Self) -> Result<(), MetricsError> {
        if self.cfg != other.cfg {
            return Err(MetricsError::InputMismatch {
                reason: "Video resolution does not match",
            });
        }
        Ok(())
    }
}

pub use v_frame::pixel::ChromaSampling;

pub(crate) trait ChromaWeight {
    fn get_chroma_weight(self) -> f64;
}

impl ChromaWeight for ChromaSampling {
    /// The relative impact of chroma planes compared to luma
    fn get_chroma_weight(self) -> f64 {
        match self {
            ChromaSampling::Cs420 => 0.25,
            ChromaSampling::Cs422 => 0.5,
            ChromaSampling::Cs444 => 1.0,
            ChromaSampling::Cs400 => 0.0,
        }
    }
}

/// Sample position for subsampled chroma
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum ChromaSamplePosition {
    /// The source video transfer function is not signaled. This crate will assume
    /// no transformation needs to be done on this data, but there is a risk of metric
    /// calculations being inaccurate.
    #[default]
    Unknown,
    /// Horizontally co-located with (0, 0) luma sample, vertically positioned
    /// in the middle between two luma samples.
    Vertical,
    /// Co-located with (0, 0) luma sample.
    Colocated,
    /// Bilaterally located chroma plane in the diagonal space between luma samples.
    Bilateral,
    /// Interlaced content with interpolated chroma samples.
    Interpolated,
}

/// Certain metrics return a value per plane. This struct contains the output
/// for those metrics per plane, as well as a weighted average of the planes.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PlanarMetrics {
    /// Metric value for the Y plane.
    pub y: f64,
    /// Metric value for the U/Cb plane.
    pub u: f64,
    /// Metric value for the V/Cb plane.
    pub v: f64,
    /// Weighted average of the three planes.
    pub avg: f64,
}

trait VideoMetric: Send + Sync {
    type FrameResult: Send + Sync;
    type VideoResult: Send + Sync;

    /// Generic method for internal use that processes multiple frames from a video
    /// into an aggregate metric.
    ///
    /// `frame_fn` is the function to calculate metrics on one frame of the video.
    /// `acc_fn` is the accumulator function to calculate the aggregate metric.
    fn process_video<D: Decoder, F: Fn(usize) + Send>(
        &mut self,
        decoder1: &mut D,
        decoder2: &mut D,
        frame_limit: Option<usize>,
        progress_callback: F,
    ) -> Result<Self::VideoResult, Box<dyn Error>> {
        if decoder1.get_bit_depth() != decoder2.get_bit_depth() {
            return Err(Box::new(MetricsError::InputMismatch {
                reason: "Bit depths do not match",
            }));
        }
        if decoder1.get_video_details().chroma_sampling
            != decoder2.get_video_details().chroma_sampling
        {
            return Err(Box::new(MetricsError::InputMismatch {
                reason: "Chroma samplings do not match",
            }));
        }

        if decoder1.get_bit_depth() > 8 {
            self.process_video_mt::<D, u16, F>(decoder1, decoder2, frame_limit, progress_callback)
        } else {
            self.process_video_mt::<D, u8, F>(decoder1, decoder2, frame_limit, progress_callback)
        }
    }

    fn process_frame<T: Pixel>(
        &self,
        frame1: &Frame<T>,
        frame2: &Frame<T>,
        bit_depth: usize,
        chroma_sampling: ChromaSampling,
    ) -> Result<Self::FrameResult, Box<dyn Error>>;

    fn aggregate_frame_results(
        &self,
        metrics: &[Self::FrameResult],
    ) -> Result<Self::VideoResult, Box<dyn Error>>;

    fn process_video_mt<D: Decoder, P: Pixel, F: Fn(usize) + Send>(
        &mut self,
        decoder1: &mut D,
        decoder2: &mut D,
        frame_limit: Option<usize>,
        progress_callback: F,
    ) -> Result<Self::VideoResult, Box<dyn Error>> {
        let num_threads = (rayon::current_num_threads() - 1).max(1);

        let mut out = Vec::new();

        let (send, recv) = crossbeam::channel::bounded(num_threads);
        let vid_info = decoder1.get_video_details();

        match crossbeam::scope(|s| {
            let send_result = s.spawn(move |_| {
                let mut decoded = 0;
                while frame_limit.map(|limit| limit > decoded).unwrap_or(true) {
                    decoded += 1;
                    let frame1 = decoder1.read_video_frame::<P>();
                    let frame2 = decoder2.read_video_frame::<P>();
                    if let (Some(frame1), Some(frame2)) = (frame1, frame2) {
                        progress_callback(decoded);
                        if let Err(e) = send.send((frame1, frame2)) {
                            let (frame1, frame2) = e.into_inner();
                            return Err(format!(
                                "Error sending\n\nframe1: {frame1:?}\n\nframe2: {frame2:?}"
                            ));
                        }
                    } else {
                        break;
                    }
                }
                // Mark the end of the decoding process
                progress_callback(usize::MAX);
                Ok(())
            });

            use rayon::prelude::*;
            let mut metrics = Vec::with_capacity(frame_limit.unwrap_or(0));
            let mut process_error = Ok(());
            loop {
                let working_set: Vec<_> = (0..num_threads)
                    .into_par_iter()
                    .filter_map(|_w| {
                        recv.recv()
                            .map(|(f1, f2)| {
                                self.process_frame(
                                    &f1,
                                    &f2,
                                    vid_info.bit_depth,
                                    vid_info.chroma_sampling,
                                )
                                .map_err(|e| {
                                    format!("\n\n{e} on\n\nframe1: {f1:?}\n\nand\n\nframe2: {f2:?}")
                                })
                            })
                            .ok()
                    })
                    .collect();
                let work_set: Vec<_> = working_set
                    .into_iter()
                    .filter_map(|v| v.map_err(|e| process_error = Err(e)).ok())
                    .collect();
                if work_set.is_empty() || process_error.is_err() {
                    break;
                } else {
                    metrics.extend(work_set);
                }
            }

            out = metrics;

            (
                send_result
                    .join()
                    .unwrap_or_else(|_| Err("Failed joining the sender thread".to_owned())),
                process_error,
            )
        }) {
            Ok((send_error, process_error)) => {
                if let Err(error) = send_error {
                    return Err(MetricsError::SendError { reason: error }.into());
                }

                if let Err(error) = process_error {
                    return Err(MetricsError::ProcessError { reason: error }.into());
                }

                if out.is_empty() {
                    return Err(MetricsError::UnsupportedInput {
                        reason: "No readable frames found in one or more input files",
                    }
                    .into());
                }

                self.aggregate_frame_results(&out)
            }
            Err(e) => Err(MetricsError::VideoError {
                reason: format!("\n\nError {e:?} processing the two videos"),
            }
            .into()),
        }
    }
}