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
mod pixel;
mod y4m;
use self::pixel::*;
use ::y4m::{Colorspace, Decoder};
use std::cmp;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
pub struct DetectionOptions {
pub use_chroma: bool,
pub ignore_flashes: bool,
pub min_scenecut_distance: Option<usize>,
pub max_scenecut_distance: Option<usize>,
pub lookahead_distance: usize,
pub progress_callback: Option<Box<dyn Fn(usize, usize)>>,
}
impl Default for DetectionOptions {
fn default() -> Self {
DetectionOptions {
use_chroma: true,
ignore_flashes: false,
lookahead_distance: 5,
min_scenecut_distance: None,
max_scenecut_distance: None,
progress_callback: None,
}
}
}
pub fn detect_scene_changes<R: Read, T: Pixel>(
dec: &mut Decoder<R>,
opts: DetectionOptions,
) -> Vec<usize> {
assert!(opts.lookahead_distance >= 1);
let bit_depth = dec.get_bit_depth() as u8;
let chroma_sampling = ChromaSampling::from(dec.get_colorspace());
let mut detector = SceneChangeDetector::new(bit_depth, chroma_sampling, &opts);
let mut frame_queue = BTreeMap::new();
let mut keyframes = BTreeSet::new();
let mut frameno = 0;
loop {
let mut next_input_frameno = frame_queue
.keys()
.last()
.copied()
.map(|key| key + 1)
.unwrap_or(0);
while next_input_frameno < frameno + opts.lookahead_distance {
let frame = y4m::read_video_frame::<R, T>(dec);
if let Ok(frame) = frame {
frame_queue.insert(next_input_frameno, frame);
next_input_frameno += 1;
} else {
break;
}
}
let frame_set = frame_queue
.iter()
.skip_while(|&(&key, _)| key < frameno)
.map(|(_, value)| value)
.take(opts.lookahead_distance)
.collect::<Vec<_>>();
if frame_set.is_empty() {
break;
}
detector.analyze_next_frame(
if frameno == 0 {
None
} else {
frame_queue.get(&(frameno - 1))
},
&frame_set,
frameno,
&mut keyframes,
);
if frameno > 0 {
frame_queue.remove(&(frameno - 1));
}
frameno += 1;
if let Some(ref progress_fn) = opts.progress_callback {
progress_fn(frameno, keyframes.len());
}
}
keyframes.into_iter().collect()
}
type PlaneData<T> = [Vec<T>; 3];
#[derive(Copy, Clone, Debug, PartialEq)]
enum ChromaSampling {
Cs420,
Cs422,
Cs444,
Cs400,
}
impl From<Colorspace> for ChromaSampling {
fn from(other: Colorspace) -> Self {
use Colorspace::*;
match other {
Cmono => ChromaSampling::Cs400,
C420 | C420p10 | C420p12 | C420jpeg | C420paldv | C420mpeg2 => ChromaSampling::Cs420,
C422 | C422p10 | C422p12 => ChromaSampling::Cs422,
C444 | C444p10 | C444p12 => ChromaSampling::Cs444,
}
}
}
impl ChromaSampling {
pub fn get_decimation(self) -> Option<(usize, usize)> {
use self::ChromaSampling::*;
match self {
Cs420 => Some((1, 1)),
Cs422 => Some((1, 0)),
Cs444 => Some((0, 0)),
Cs400 => None,
}
}
}
struct SceneChangeDetector<'a> {
threshold: u8,
opts: &'a DetectionOptions,
excluded_frames: BTreeSet<usize>,
chroma_sampling: ChromaSampling,
}
impl<'a> SceneChangeDetector<'a> {
pub fn new(bit_depth: u8, chroma_sampling: ChromaSampling, opts: &'a DetectionOptions) -> Self {
const BASE_THRESHOLD: u8 = 12;
Self {
threshold: BASE_THRESHOLD * bit_depth / 8,
opts,
excluded_frames: BTreeSet::new(),
chroma_sampling,
}
}
pub fn analyze_next_frame<T: Pixel>(
&mut self,
previous_frame: Option<&PlaneData<T>>,
frame_set: &[&PlaneData<T>],
input_frameno: usize,
keyframes: &mut BTreeSet<usize>,
) {
let frame_set = match previous_frame {
Some(frame) => [frame]
.iter()
.chain(frame_set.iter())
.cloned()
.collect::<Vec<_>>(),
None => {
keyframes.insert(0);
return;
}
};
self.exclude_scene_flashes(&frame_set, input_frameno);
if self.is_key_frame(&frame_set[0], &frame_set[1], input_frameno, keyframes) {
keyframes.insert(input_frameno);
}
}
fn is_key_frame<T: Pixel>(
&self,
previous_frame: &PlaneData<T>,
current_frame: &PlaneData<T>,
current_frameno: usize,
keyframes: &mut BTreeSet<usize>,
) -> bool {
let previous_keyframe = keyframes.iter().last().unwrap();
let distance = current_frameno - previous_keyframe;
if distance < self.opts.min_scenecut_distance.unwrap_or(0) {
return false;
}
if distance
>= self
.opts
.max_scenecut_distance
.unwrap_or(usize::max_value())
{
return true;
}
if self.excluded_frames.contains(¤t_frameno) {
return false;
}
self.has_scenecut(previous_frame, current_frame)
}
fn exclude_scene_flashes<T: Pixel>(&mut self, frame_subset: &[&PlaneData<T>], frameno: usize) {
let lookahead_distance = cmp::min(self.opts.lookahead_distance, frame_subset.len() - 1);
for j in 1..=lookahead_distance {
if !self.has_scenecut(&frame_subset[0], &frame_subset[j]) {
for i in 0..=j {
let frameno = frameno + i - 1;
self.excluded_frames.insert(frameno);
}
}
}
for i in 1..lookahead_distance {
if self.has_scenecut(&frame_subset[i], &frame_subset[lookahead_distance]) {
let frameno = frameno + i - 1;
self.excluded_frames.insert(frameno);
}
}
}
fn has_scenecut<T: Pixel>(&self, frame1: &PlaneData<T>, frame2: &PlaneData<T>) -> bool {
let mut delta = Self::get_plane_sad(&frame1[0], &frame2[0]);
let mut len = frame1[0].len() as u64;
if self.opts.use_chroma && self.chroma_sampling != ChromaSampling::Cs400 {
let (x_dec, y_dec) = self.chroma_sampling.get_decimation().unwrap();
let dec = x_dec + y_dec;
delta += Self::get_plane_sad(&frame1[1], &frame2[1]) << dec;
len += (frame1[1].len() as u64) << dec;
delta += Self::get_plane_sad(&frame1[2], &frame2[2]) << dec;
len += (frame1[2].len() as u64) << dec;
}
delta >= self.threshold as u64 * len
}
#[inline(always)]
fn get_plane_sad<T: Pixel>(plane1: &[T], plane2: &[T]) -> u64 {
assert_eq!(plane1.len(), plane2.len());
plane1
.iter()
.zip(plane2.iter())
.map(|(&p1, &p2)| (i16::cast_from(p1) - i16::cast_from(p2)).abs() as u64)
.sum::<u64>()
}
}