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
use std::cell::Ref;
use std::cell::RefCell;
use std::cell::RefMut;
use std::rc::Rc;
use anyhow::anyhow;
use anyhow::Result;
use log::debug;
use crate::decoders::h264::picture::Field;
use crate::decoders::h264::picture::IsIdr;
use crate::decoders::h264::picture::PictureData;
use crate::decoders::h264::picture::Reference;
use crate::decoders::DecodedHandle;
#[derive(Clone)]
pub struct DpbEntry<T: DecodedHandle>(pub Rc<RefCell<PictureData>>, pub Option<T>);
pub struct Dpb<T: DecodedHandle> {
entries: Vec<DpbEntry<T>>,
max_num_pics: usize,
interlaced: bool,
}
impl<T: DecodedHandle> Dpb<T> {
pub fn pictures(&self) -> impl Iterator<Item = Ref<'_, PictureData>> {
self.entries.iter().map(|h| h.0.borrow())
}
pub fn pictures_mut(&mut self) -> impl Iterator<Item = RefMut<'_, PictureData>> {
self.entries.iter().map(|h| h.0.borrow_mut())
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn entries(&self) -> &Vec<DpbEntry<T>> {
&self.entries
}
pub fn set_max_num_pics(&mut self, max_num_pics: usize) {
self.max_num_pics = max_num_pics;
}
pub fn max_num_pics(&self) -> usize {
self.max_num_pics
}
pub fn num_ref_frames(&self) -> usize {
self.pictures()
.filter(|p| p.is_ref() && !p.is_second_field())
.count()
}
pub fn interlaced(&self) -> bool {
self.interlaced
}
pub fn set_interlaced(&mut self, interlaced: bool) {
self.interlaced = interlaced;
}
pub fn find_short_term_lowest_frame_num_wrap(&self) -> Option<Rc<RefCell<PictureData>>> {
let lowest = self
.entries
.iter()
.filter(|h| {
let p = h.0.borrow();
matches!(p.reference(), Reference::ShortTerm)
})
.cloned()
.map(|h| h.0)
.min_by_key(|h| {
let p = h.borrow();
p.frame_num_wrap
});
lowest
}
pub fn mark_all_as_unused_for_ref(&mut self) {
for mut picture in self.pictures_mut() {
picture.set_reference(Reference::None, false);
}
}
pub fn remove_unused(&mut self) {
self.entries.retain(|handle| {
let pic = handle.0.borrow();
let discard = !pic.is_ref() && !pic.needed_for_output;
if discard {
log::debug!("Removing unused picture {:#?}", pic);
}
!discard
});
}
pub fn find_short_term_with_pic_num(&self, pic_num: i32) -> Option<DpbEntry<T>> {
let position = self
.pictures()
.position(|p| matches!(p.reference(), Reference::ShortTerm) && p.pic_num == pic_num);
log::debug!(
"find_short_term_with_pic_num: {}, found position {:?}",
pic_num,
position
);
Some(self.entries[position?].clone())
}
pub fn find_long_term_with_long_term_pic_num(
&self,
long_term_pic_num: i32,
) -> Option<DpbEntry<T>> {
let position = self.pictures().position(|p| {
matches!(p.reference(), Reference::LongTerm) && p.long_term_pic_num == long_term_pic_num
});
log::debug!(
"find_long_term_with_long_term_pic_num: {}, found position {:?}",
long_term_pic_num,
position
);
Some(self.entries[position?].clone())
}
pub fn store_picture(
&mut self,
picture: Rc<RefCell<PictureData>>,
handle: Option<T>,
) -> Result<()> {
let max_pics = if self.interlaced {
self.max_num_pics * 2
} else {
self.max_num_pics
};
if self.entries.len() >= max_pics {
return Err(anyhow!("Can't add a picture to the DPB: DPB is full."));
}
let mut pic_mut = picture.borrow_mut();
if !pic_mut.nonexisting {
pic_mut.needed_for_output = true;
} else {
pic_mut.needed_for_output = false;
}
if pic_mut.is_second_field() {
let first_field_rc = pic_mut.other_field_unchecked();
drop(pic_mut);
let mut first_field = first_field_rc.borrow_mut();
first_field.set_second_field_to(&picture);
} else {
drop(pic_mut);
}
let pic = picture.borrow();
debug!(
"Stored picture POC {:?}, field {:?}, the DPB length is {:?}",
pic.pic_order_cnt,
pic.field,
self.entries.len()
);
drop(pic);
self.entries.push(DpbEntry(picture, handle));
Ok(())
}
pub fn has_empty_frame_buffer(&self) -> bool {
if !self.interlaced {
self.entries.len() < self.max_num_pics
} else {
let count = self
.pictures()
.filter(|pic| {
!pic.is_second_field()
&& (matches!(pic.field, Field::Frame) || pic.other_field().is_some())
})
.count();
count < self.max_num_pics
}
}
pub fn needs_bumping(&self, to_insert: &PictureData) -> bool {
if self.has_empty_frame_buffer() {
return false;
}
if to_insert.nonexisting {
return true;
}
let is_ref = !matches!(to_insert.reference(), Reference::None);
let non_idr_ref = is_ref && matches!(to_insert.is_idr, IsIdr::No);
if non_idr_ref {
return true;
}
let lowest_poc = match self.find_lowest_poc_for_bumping() {
Some(handle) => handle.0.borrow().pic_order_cnt,
None => return false,
};
!to_insert.is_second_field_of_complementary_ref_pair()
&& to_insert.pic_order_cnt > lowest_poc
}
fn find_lowest_poc_for_bumping(&self) -> Option<DpbEntry<T>> {
let lowest = self
.pictures()
.filter(|pic| {
if !pic.needed_for_output {
return false;
}
let skip = !matches!(pic.field, Field::Frame)
&& (pic.other_field().is_none() || pic.is_second_field());
!skip
})
.min_by_key(|pic| pic.pic_order_cnt)?;
let position = self
.entries
.iter()
.position(|handle| handle.0.borrow().pic_order_cnt == lowest.pic_order_cnt)
.unwrap();
Some(self.entries[position].clone())
}
fn get_position(&self, needle: &Rc<RefCell<PictureData>>) -> Option<usize> {
self.entries
.iter()
.position(|handle| Rc::ptr_eq(&handle.0, needle))
}
pub fn bump(&mut self, flush: bool) -> Option<DpbEntry<T>> {
let handle = self.find_lowest_poc_for_bumping()?;
let mut pic = handle.0.borrow_mut();
debug!("Bumping picture {:#?} from the dpb", pic);
pic.needed_for_output = false;
if !pic.is_ref() || flush {
let index = self.get_position(&handle.0).unwrap();
log::debug!("removed picture {:#?} from dpb", pic);
self.entries.remove(index);
}
if pic.other_field().is_some() {
let other_field_rc = pic.other_field_unchecked();
let mut other_field = other_field_rc.borrow_mut();
other_field.needed_for_output = false;
if !other_field.is_ref() {
log::debug!("other_field: removed picture {:#?} from dpb", other_field);
let index = self.get_position(&other_field_rc).unwrap();
self.entries.remove(index);
}
}
drop(pic);
Some(handle)
}
pub fn drain(&mut self) -> Vec<DpbEntry<T>> {
debug!("Draining the DPB.");
let mut pics = vec![];
while let Some(pic) = self.bump(true) {
pics.push(pic);
}
pics
}
pub fn clear(&mut self) {
debug!("Clearing the DPB");
let max_num_pics = self.max_num_pics;
let interlaced = self.interlaced;
*self = Default::default();
self.max_num_pics = max_num_pics;
self.interlaced = interlaced;
}
pub fn get_short_term_refs(&self, out: &mut Vec<DpbEntry<T>>) {
out.extend(
self.entries
.iter()
.filter(|&handle| matches!(handle.0.borrow().reference(), Reference::ShortTerm))
.cloned(),
)
}
pub fn get_long_term_refs(&self, out: &mut Vec<DpbEntry<T>>) {
out.extend(
self.entries
.iter()
.filter(|&handle| matches!(handle.0.borrow().reference(), Reference::LongTerm))
.cloned(),
)
}
}
impl<T: DecodedHandle> Default for Dpb<T> {
fn default() -> Self {
Self {
entries: Default::default(),
max_num_pics: Default::default(),
interlaced: Default::default(),
}
}
}
impl<T: DecodedHandle> std::fmt::Debug for Dpb<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let pics = self
.entries
.iter()
.map(|h| &h.0)
.enumerate()
.collect::<Vec<_>>();
f.debug_struct("Dpb")
.field("pictures", &pics)
.field("max_num_pics", &self.max_num_pics)
.field("interlaced", &self.interlaced)
.finish()
}
}