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
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;
#[derive(Clone, Debug)]
pub struct FrameInfo<T: Pixel> {
pub planes: [Plane<T>; 3],
pub bit_depth: usize,
pub chroma_sampling: ChromaSampling,
}
impl<T: Pixel> FrameInfo<T> {
pub(crate) fn can_compare(&self, other: &Self) -> Result<(), MetricsError> {
if self.bit_depth != other.bit_depth {
return Err(MetricsError::InputMismatch {
reason: "Bit depths do not match",
});
}
if self.bit_depth > 16 {
return Err(MetricsError::UnsupportedInput {
reason: "Bit depths above 16 are not supported",
});
}
if self.chroma_sampling != other.chroma_sampling {
return Err(MetricsError::InputMismatch {
reason: "Chroma subsampling offsets do not match",
});
}
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 {
fn get_chroma_weight(self) -> f64 {
match self {
ChromaSampling::Cs420 => 0.25,
ChromaSampling::Cs422 => 0.5,
ChromaSampling::Cs444 => 1.0,
ChromaSampling::Cs400 => 0.0,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ChromaSamplePosition {
Unknown,
Vertical,
Colocated,
Bilateral,
Interpolated,
}
impl Default for ChromaSamplePosition {
fn default() -> Self {
ChromaSamplePosition::Unknown
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct PlanarMetrics {
pub y: f64,
pub u: f64,
pub v: f64,
pub avg: f64,
}
trait VideoMetric: Send + Sync {
type FrameResult: Send + Sync;
type VideoResult: Send + Sync;
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_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: &FrameInfo<T>,
frame2: &FrameInfo<T>,
) -> 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);
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: {:?}\n\nframe2: {:?}",
frame1, frame2
));
}
} else {
break;
}
}
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).map_err(|e| {
format!(
"\n\n{} on\n\nframe1: {:?}\n\nand\n\nframe2: {:?}",
e.to_string(),
f1,
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 {:?} processing the two videos", e),
}
.into()),
}
}
}