forge
Explore
Log in

Don't you dare go Hollow

ec-hw: reference picture selection for Vulkan H.265 (explicit short-term RPS keeps all 8 slots) and H.264 (every picture long-term idx = slot via MMCO6, list modification picks the reference); acks are cumulative; recovery evicts frames newer than its base; H.264 Vk decoder prunes unused gap frames before giving them slots

Browse files at this commit

c41118999fb42403cf9a01e109f8f9a010992ec3Ahmet Kaan GümüşParent: 8737b14
crates/ec-hw/src/dpb264.rsmodified+1 -0
@@ -356,6 +356,7 @@ impl<S: Clone> Dpb<S> {
356 };356 };
357 self.number_short_term(unused, sps);357 self.number_short_term(unused, sps);
358 self.sliding_window(sps);358 self.sliding_window(sps);
359+ self.frames.retain(|p| p.stored());
359 let id = self.next_id();360 let id = self.next_id();
360 self.frames.push(Picture {361 self.frames.push(Picture {
361 id,362 id,
crates/ec-hw/src/hw.rsmodified+13 -6
@@ -695,21 +695,28 @@ impl HwEncoder {
695 }695 }
696 }696 }
697 697
698- /// Frame `timestamp` was decoded by every receiver. A frame after [`HwEncoder::recover`] may then reference it instead of being a keyframe. Vulkan AV1 only; elsewhere a no-op.698+ /// Every frame up to `timestamp` was decoded by every receiver. A frame after [`HwEncoder::recover`] may then reference one of them instead of being a keyframe. Vulkan only; a no-op on VA-API.
699 pub fn ack(&mut self, timestamp: i64) {699 pub fn ack(&mut self, timestamp: i64) {
700- let Some(&(_, id)) = self.ids.iter().rev().find(|(ts, _)| *ts == timestamp) else {700+ let Some(&(_, id)) = self.ids.iter().rev().find(|(ts, _)| *ts <= timestamp) else {
701 return;701 return;
702 };702 };
703- if let EncInner::Vk(VkEncoder::Av1(enc)) = &mut self.inner {703+ match &mut self.inner {
704- enc.ack(id);704+ EncInner::Vk(VkEncoder::Av1(enc)) => enc.ack(id),
705+ EncInner::Vk(VkEncoder::H265(enc)) => enc.ack(id),
706+ EncInner::Vk(VkEncoder::H264(enc)) => enc.ack(id),
707+ #[cfg(target_os = "linux")]
708+ EncInner::Va(_) => {}
705 }709 }
706 }710 }
707 711
708- /// Recover the receivers from loss: the next frame references the newest acknowledged frame still held ([`CodedFrame::recovery`]), or is a keyframe when none is. Codecs without reference selection always send a keyframe.712+ /// Recover the receivers from loss: the next frame references the newest acknowledged frame still held ([`CodedFrame::recovery`]), or is a keyframe when none is. VA-API always sends a keyframe.
709 pub fn recover(&mut self) {713 pub fn recover(&mut self) {
710 match &mut self.inner {714 match &mut self.inner {
711 EncInner::Vk(VkEncoder::Av1(enc)) => enc.recover(),715 EncInner::Vk(VkEncoder::Av1(enc)) => enc.recover(),
712- _ => self.keyframe_next = true,716+ EncInner::Vk(VkEncoder::H265(enc)) => enc.recover(),
717+ EncInner::Vk(VkEncoder::H264(enc)) => enc.recover(),
718+ #[cfg(target_os = "linux")]
719+ EncInner::Va(_) => self.keyframe_next = true,
713 }720 }
714 }721 }
715 722
crates/ec-hw/src/vkdec264.rsmodified+4 -2
@@ -299,11 +299,13 @@ impl VkH264Decoder {
299 }299 }
300 300
301 fn fill_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> {301 fn fill_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> {
302- let before = self.dpb.frames.len();302+ let before: Vec<i32> = self.dpb.frames.iter().map(|p| p.id).collect();
303 self.dpb.fill_frame_num_gap(sps, frame_num)?;303 self.dpb.fill_frame_num_gap(sps, frame_num)?;
304- for i in before..self.dpb.frames.len() {304+ for i in 0..self.dpb.frames.len() {
305+ if !before.contains(&self.dpb.frames[i].id) {
305 self.dpb.frames[i].surface = self.free_slot()?;306 self.dpb.frames[i].surface = self.free_slot()?;
306 }307 }
308+ }
307 Ok(())309 Ok(())
308 }310 }
309 311
crates/ec-vk/src/av1.rsmodified+1 -1
@@ -236,7 +236,7 @@ impl Av1Encoder {
236 }236 }
237 }237 }
238 238
239- /// The receiver decoded frame `id` ([`CodedFrame::id`]); a recovery frame may reference it while it stays in the DPB.239+ /// The receiver decoded every frame up to `id` ([`CodedFrame::id`]); a recovery frame may reference one while it stays in the DPB.
240 pub fn ack(&mut self, id: u64) {240 pub fn ack(&mut self, id: u64) {
241 self.history.ack(id);241 self.history.ack(id);
242 }242 }
crates/ec-vk/src/h265.rsmodified+30 -24
@@ -2,6 +2,7 @@ use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref};
2 2
3 #[cfg(target_os = "linux")]3 #[cfg(target_os = "linux")]
4 use crate::DmaBuf;4 use crate::DmaBuf;
5+use crate::history::History;
5 use crate::{CodedFrame, Colour, Error, Flight, Gpu, Meta, RateControl, last_frame};6 use crate::{CodedFrame, Colour, Error, Flight, Gpu, Meta, RateControl, last_frame};
6 7
7 /// H.265 encoder settings.8 /// H.265 encoder settings.
@@ -34,11 +35,10 @@ pub struct H265Encoder {
34 gop_size: u32,35 gop_size: u32,
35 position: u32,36 position: u32,
36 poc: i32,37 poc: i32,
37- reference: Option<H265Ref>,38+ history: History<i32>,
38 uv: Vec<u8>,39 uv: Vec<u8>,
39 uv16: Vec<u16>,40 uv16: Vec<u16>,
40 flight: Flight,41 flight: Flight,
41- next_id: u64,
42 }42 }
43 43
44 impl H265Encoder {44 impl H265Encoder {
@@ -68,11 +68,10 @@ impl H265Encoder {
68 gop_size: cfg.gop_size,68 gop_size: cfg.gop_size,
69 position: 0,69 position: 0,
70 poc: 0,70 poc: 0,
71- reference: None,71+ history: History::new(),
72 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],72 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
73 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],73 uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
74 flight: Flight::default(),74 flight: Flight::default(),
75- next_id: 0,
76 })75 })
77 }76 }
78 77
@@ -212,28 +211,35 @@ impl H265Encoder {
212 }211 }
213 212
214 fn next_picture(&mut self, force_keyframe: bool) -> H265Picture {213 fn next_picture(&mut self, force_keyframe: bool) -> H265Picture {
215- let keyframe = force_keyframe || self.reference.is_none() || self.position >= self.gop_size;214+ let step = self
216- self.poc = if keyframe { 0 } else { self.poc + 1 };215+ .history
217- let reference = if keyframe { None } else { self.reference };216+ .next(force_keyframe || self.position >= self.gop_size);
218- let slot = reference.map_or(0, |r| 1 - r.slot);217+ self.poc = if step.key { 0 } else { self.poc + 1 };
219- let pic = H265Picture {218+ let keep = self.history.kept(&step);
220- idr: keyframe,219+ self.history.store(&step, self.poc);
221- poc: self.poc,220+ self.position = if step.key { 1 } else { self.position + 1 };
222- slot,
223- reference,
224- };
225- self.reference = Some(H265Ref {
226- slot: pic.slot,
227- poc: pic.poc,
228- });
229- self.position = if keyframe { 1 } else { self.position + 1 };
230 self.flight.push(Meta {221 self.flight.push(Meta {
231- keyframe,222+ keyframe: step.key,
232- recovery: false,223+ recovery: step.recovery,
233- id: self.next_id,224+ id: step.id,
234 });225 });
235- self.next_id += 1;226+ H265Picture {
236- pic227+ idr: step.key,
228+ poc: self.poc,
229+ slot: step.slot,
230+ reference: step.reference.map(|(slot, poc)| H265Ref { slot, poc }),
231+ keep,
232+ }
233+ }
234+
235+ /// The receiver decoded every frame up to `id` ([`CodedFrame::id`]); a recovery frame may reference one while it stays in the DPB.
236+ pub fn ack(&mut self, id: u64) {
237+ self.history.ack(id);
238+ }
239+
240+ /// Make the next frame reference the newest acknowledged frame still held, or an IDR when none is.
241+ pub fn recover(&mut self) {
242+ self.history.arm();
237 }243 }
238 244
239 fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {245 fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {
crates/ec-vk/src/history.rsmodified+26 -10
@@ -1,6 +1,6 @@
1 use vk_video_ffi::DPB_SLOTS;1 use vk_video_ffi::DPB_SLOTS;
2 2
3-const CHAIN: usize = 2;3+const ANCHORS: usize = DPB_SLOTS - 2;
4 const ANCHOR_EVERY: u64 = 16;4 const ANCHOR_EVERY: u64 = 16;
5 const MAX_AGE: u64 = 120;5 const MAX_AGE: u64 = 120;
6 6
@@ -21,9 +21,9 @@ pub(crate) struct Step<T> {
21 pub(crate) reference: Option<(u32, T)>,21 pub(crate) reference: Option<(u32, T)>,
22 }22 }
23 23
24-/// DPB slot bookkeeping: two slots chain each picture to the previous one, the24+/// DPB slot bookkeeping: the first slots keep the keyframe and every sixteenth
25-/// rest keep every sixteenth picture as an anchor a recovery picture can25+/// picture as anchors a recovery picture can reference once the receiver
26-/// reference once the receiver acknowledged it.26+/// acknowledged them, the last two chain each picture to the previous one.
27 pub(crate) struct History<T> {27 pub(crate) struct History<T> {
28 next_id: u64,28 next_id: u64,
29 slots: [Option<Held<T>>; DPB_SLOTS],29 slots: [Option<Held<T>>; DPB_SLOTS],
@@ -49,7 +49,7 @@ impl<T: Copy> History<T> {
49 49
50 pub(crate) fn ack(&mut self, id: u64) {50 pub(crate) fn ack(&mut self, id: u64) {
51 for held in self.slots.iter_mut().flatten() {51 for held in self.slots.iter_mut().flatten() {
52- if held.id == id {52+ if held.id <= id {
53 held.acked = true;53 held.acked = true;
54 }54 }
55 }55 }
@@ -75,6 +75,14 @@ impl<T: Copy> History<T> {
75 self.slots = [None; DPB_SLOTS];75 self.slots = [None; DPB_SLOTS];
76 self.next_anchor = 0;76 self.next_anchor = 0;
77 }77 }
78+ if let Some((slot, _)) = acked {
79+ let base = self.slots[slot].map_or(0, |h| h.id);
80+ for held in &mut self.slots {
81+ if held.is_some_and(|h| h.id > base) {
82+ *held = None;
83+ }
84+ }
85+ }
78 let slot = if key || id % ANCHOR_EVERY == 0 {86 let slot = if key || id % ANCHOR_EVERY == 0 {
79 self.anchor_slot(reference_slot)87 self.anchor_slot(reference_slot)
80 } else {88 } else {
@@ -99,6 +107,15 @@ impl<T: Copy> History<T> {
99 self.last = Some((slot, data));107 self.last = Some((slot, data));
100 }108 }
101 109
110+ pub(crate) fn kept(&self, step: &Step<T>) -> [Option<T>; DPB_SLOTS] {
111+ let reference = step.reference.map(|(slot, _)| slot as usize);
112+ std::array::from_fn(|i| {
113+ self.slots[i]
114+ .filter(|_| i != step.slot as usize && Some(i) != reference)
115+ .map(|h| h.data)
116+ })
117+ }
118+
102 fn newest_acked(&self, id: u64) -> Option<(usize, T)> {119 fn newest_acked(&self, id: u64) -> Option<(usize, T)> {
103 (0..DPB_SLOTS)120 (0..DPB_SLOTS)
104 .filter_map(|i| self.slots[i].map(|h| (i, h)))121 .filter_map(|i| self.slots[i].map(|h| (i, h)))
@@ -108,10 +125,9 @@ impl<T: Copy> History<T> {
108 }125 }
109 126
110 fn anchor_slot(&mut self, reference: Option<usize>) -> usize {127 fn anchor_slot(&mut self, reference: Option<usize>) -> usize {
111- let anchors = DPB_SLOTS - CHAIN;
112 loop {128 loop {
113- let slot = CHAIN + self.next_anchor;129+ let slot = self.next_anchor;
114- self.next_anchor = (self.next_anchor + 1) % anchors;130+ self.next_anchor = (self.next_anchor + 1) % ANCHORS;
115 if Some(slot) != reference {131 if Some(slot) != reference {
116 return slot;132 return slot;
117 }133 }
@@ -119,9 +135,9 @@ impl<T: Copy> History<T> {
119 }135 }
120 136
121 fn chain_slot(&self, reference: Option<usize>) -> usize {137 fn chain_slot(&self, reference: Option<usize>) -> usize {
122- (0..CHAIN)138+ (ANCHORS..DPB_SLOTS)
123 .filter(|&i| Some(i) != reference)139 .filter(|&i| Some(i) != reference)
124 .min_by_key(|&i| self.slots[i].map_or(0, |h| h.id + 1))140 .min_by_key(|&i| self.slots[i].map_or(0, |h| h.id + 1))
125- .unwrap_or(0)141+ .unwrap_or(ANCHORS)
126 }142 }
127 }143 }
crates/ec-vk/src/lib.rsmodified+28 -24
@@ -4,7 +4,8 @@
4 4
5 use std::collections::VecDeque;5 use std::collections::VecDeque;
6 6
7-use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref};7+use history::History;
8+use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, LOG2_MAX_FRAME_NUM};
8 9
9 mod av1;10 mod av1;
10 mod h265;11 mod h265;
@@ -102,10 +103,9 @@ pub struct H264Encoder {
102 frame_num: u32,103 frame_num: u32,
103 poc: i32,104 poc: i32,
104 idr_pic_id: u16,105 idr_pic_id: u16,
105- reference: Option<H264Ref>,106+ history: History<(u32, i32)>,
106 uv: Vec<u8>,107 uv: Vec<u8>,
107 flight: Flight,108 flight: Flight,
108- next_id: u64,
109 }109 }
110 110
111 impl H264Encoder {111 impl H264Encoder {
@@ -137,10 +137,9 @@ impl H264Encoder {
137 frame_num: 0,137 frame_num: 0,
138 poc: 0,138 poc: 0,
139 idr_pic_id: 0,139 idr_pic_id: 0,
140- reference: None,140+ history: History::new(),
141 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],141 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
142 flight: Flight::default(),142 flight: Flight::default(),
143- next_id: 0,
144 })143 })
145 }144 }
146 145
@@ -246,42 +245,47 @@ impl H264Encoder {
246 }245 }
247 246
248 fn next_picture(&mut self, force_keyframe: bool) -> H264Picture {247 fn next_picture(&mut self, force_keyframe: bool) -> H264Picture {
249- let keyframe = force_keyframe || self.reference.is_none() || self.position >= self.gop_size;248+ let step = self
250- if keyframe {249+ .history
250+ .next(force_keyframe || self.position >= self.gop_size);
251+ if step.key {
251 self.frame_num = 0;252 self.frame_num = 0;
252 self.poc = 0;253 self.poc = 0;
253 } else {254 } else {
254- self.frame_num = (self.frame_num + 1) % 16;255+ self.frame_num = (self.frame_num + 1) % (1 << LOG2_MAX_FRAME_NUM);
255 self.poc += 2;256 self.poc += 2;
256 }257 }
257- let reference = if keyframe { None } else { self.reference };
258- let slot = reference.map_or(0, |r| 1 - r.slot);
259 let pic = H264Picture {258 let pic = H264Picture {
260- idr: keyframe,259+ idr: step.key,
261 idr_pic_id: self.idr_pic_id,260 idr_pic_id: self.idr_pic_id,
262 frame_num: self.frame_num,261 frame_num: self.frame_num,
263 poc: self.poc,262 poc: self.poc,
264- slot,263+ slot: step.slot,
265- reference,264+ reference: step.reference.map(|(slot, (frame_num, poc))| H264Ref { slot, frame_num, poc }),
266 };265 };
267- self.reference = Some(H264Ref {266+ self.history.store(&step, (self.frame_num, self.poc));
268- slot: pic.slot,267+ self.position = if step.key { 1 } else { self.position + 1 };
269- frame_num: pic.frame_num,268+ if step.key {
270- poc: pic.poc,
271- });
272- self.position = if keyframe { 1 } else { self.position + 1 };
273- if keyframe {
274 self.idr_pic_id = self.idr_pic_id.wrapping_add(1);269 self.idr_pic_id = self.idr_pic_id.wrapping_add(1);
275 }270 }
276 self.flight.push(Meta {271 self.flight.push(Meta {
277- keyframe,272+ keyframe: step.key,
278- recovery: false,273+ recovery: step.recovery,
279- id: self.next_id,274+ id: step.id,
280 });275 });
281- self.next_id += 1;
282 pic276 pic
283 }277 }
284 278
279+ /// The receiver decoded every frame up to `id` ([`CodedFrame::id`]); a recovery frame may reference one while it stays in the DPB.
280+ pub fn ack(&mut self, id: u64) {
281+ self.history.ack(id);
282+ }
283+
284+ /// Make the next frame reference the newest acknowledged frame still held, or an IDR when none is.
285+ pub fn recover(&mut self) {
286+ self.history.arm();
287+ }
288+
285 fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {289 fn coded(&mut self, bytes: Vec<u8>) -> CodedFrame {
286 let meta = self.flight.pop();290 let meta = self.flight.pop();
287 let data = if meta.keyframe {291 let data = if meta.keyframe {
shims/vk-video-ffi/examples/dmabuf_smoke.rsmodified+1 -0
@@ -165,6 +165,7 @@ fn h265_picture(i: usize) -> H265Picture {
165 slot: ((i - 1) % 2) as u32,165 slot: ((i - 1) % 2) as u32,
166 poc: 2 * (i - 1) as i32,166 poc: 2 * (i - 1) as i32,
167 }),167 }),
168+ keep: [None; vk_video_ffi::DPB_SLOTS],
168 }169 }
169 }170 }
170 171
shims/vk-video-ffi/src/h264_encode.rsmodified+48 -10
@@ -110,6 +110,10 @@ pub struct H264EncodeConfig {
110 pub colour: Option<Colour>,110 pub colour: Option<Colour>,
111 }111 }
112 112
113+/// frame_num wraps at 1 << LOG2_MAX_FRAME_NUM.
114+pub const LOG2_MAX_FRAME_NUM: u8 = 8;
115+const MAX_REF_FRAMES: u8 = DPB_SLOTS as u8 + 1;
116+
113 /// One picture to encode.117 /// One picture to encode.
114 #[derive(Debug, Clone, Copy, PartialEq, Eq)]118 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
115 pub struct H264Picture {119 pub struct H264Picture {
@@ -121,13 +125,13 @@ pub struct H264Picture {
121 pub frame_num: u32,125 pub frame_num: u32,
122 /// PicOrderCnt.126 /// PicOrderCnt.
123 pub poc: i32,127 pub poc: i32,
124- /// DPB slot this picture is written to, below `DPB_SLOTS`.128+ /// DPB slot this picture is written to, below `DPB_SLOTS`, 0 for IDR; it becomes long-term reference `slot`.
125 pub slot: u32,129 pub slot: u32,
126 /// Reference for a P picture, None for IDR.130 /// Reference for a P picture, None for IDR.
127 pub reference: Option<H264Ref>,131 pub reference: Option<H264Ref>,
128 }132 }
129 133
130-/// A picture held in the DPB.134+/// A picture held in the DPB as a long-term reference, LongTermFrameIdx = slot.
131 #[derive(Debug, Clone, Copy, PartialEq, Eq)]135 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
132 pub struct H264Ref {136 pub struct H264Ref {
133 /// DPB slot, below `DPB_SLOTS`.137 /// DPB slot, below `DPB_SLOTS`.
@@ -239,6 +243,7 @@ impl RateChain {
239 /// An H.264 Vulkan Video encode session: IDR and P pictures, one reference, NV12 uploaded from CPU.243 /// An H.264 Vulkan Video encode session: IDR and P pictures, one reference, NV12 uploaded from CPU.
240 pub struct H264EncodeSession {244 pub struct H264EncodeSession {
241 enc: Encoder,245 enc: Encoder,
246+ long_term_open: bool,
242 }247 }
243 248
244 impl H264EncodeSession {249 impl H264EncodeSession {
@@ -298,7 +303,10 @@ impl H264EncodeSession {
298 )?;303 )?;
299 let params = create_parameters(&enc.vs, cfg, level)?;304 let params = create_parameters(&enc.vs, cfg, level)?;
300 enc.vs.set_params(params);305 enc.vs.set_params(params);
301- Ok(H264EncodeSession { enc })306+ Ok(H264EncodeSession {
307+ enc,
308+ long_term_open: false,
309+ })
302 }310 }
303 311
304 /// Annex-B SPS and PPS of this session.312 /// Annex-B SPS and PPS of this session.
@@ -384,10 +392,10 @@ impl H264EncodeSession {
384 let dpb_pr = self.enc.dpb.each_ref().map(|d| picture_resource(d.view, extent));392 let dpb_pr = self.enc.dpb.each_ref().map(|d| picture_resource(d.view, extent));
385 let src_pr = picture_resource(self.enc.src_view(), extent);393 let src_pr = picture_resource(self.enc.src_view(), extent);
386 394
387- let new_std = reference_info(primary, pic.frame_num, pic.poc);395+ let new_std = reference_info(primary, pic.frame_num, pic.poc, pic.slot);
388- let ref_std = pic396+ let ref_std = pic.reference.map(|r| {
389- .reference397+ reference_info(vk::video::STD_VIDEO_H264_PICTURE_TYPE_P, r.frame_num, r.poc, r.slot)
390- .map(|r| reference_info(vk::video::STD_VIDEO_H264_PICTURE_TYPE_P, r.frame_num, r.poc));398+ });
391 let mut new_dpb = vk::VideoEncodeH264DpbSlotInfoKHR::builder()399 let mut new_dpb = vk::VideoEncodeH264DpbSlotInfoKHR::builder()
392 .std_reference_info(&new_std)400 .std_reference_info(&new_std)
393 .build();401 .build();
@@ -435,13 +443,37 @@ impl H264EncodeSession {
435 if let Some(r) = pic.reference {443 if let Some(r) = pic.reference {
436 list0[0] = r.slot as u8;444 list0[0] = r.slot as u8;
437 }445 }
446+ let mut modification = zeroed::<vk::video::StdVideoEncodeH264RefListModEntry>();
447+ modification.modification_of_pic_nums_idc =
448+ vk::video::STD_VIDEO_H264_MODIFICATION_OF_PIC_NUMS_IDC_LONG_TERM;
449+ modification.long_term_pic_num = pic.reference.map_or(0, |r| r.slot as u16);
450+ let mut marking = [zeroed::<vk::video::StdVideoEncodeH264RefPicMarkingEntry>(); 3];
451+ marking[0].memory_management_control_operation =
452+ vk::video::STD_VIDEO_H264_MEM_MGMT_CONTROL_OP_SET_MAX_LONG_TERM_INDEX;
453+ marking[0].max_long_term_frame_idx_plus1 = DPB_SLOTS as u16;
454+ marking[1].memory_management_control_operation =
455+ vk::video::STD_VIDEO_H264_MEM_MGMT_CONTROL_OP_MARK_CURRENT_AS_LONG_TERM;
456+ marking[1].long_term_frame_idx = pic.slot as u16;
457+ marking[2].memory_management_control_operation =
458+ vk::video::STD_VIDEO_H264_MEM_MGMT_CONTROL_OP_END;
438 let mut lists = zeroed::<vk::video::StdVideoEncodeH264ReferenceListsInfo>();459 let mut lists = zeroed::<vk::video::StdVideoEncodeH264ReferenceListsInfo>();
439 lists.RefPicList0 = list0;460 lists.RefPicList0 = list0;
440 lists.RefPicList1 = [0xff; 32];461 lists.RefPicList1 = [0xff; 32];
462+ if !pic.idr {
463+ let first = usize::from(self.long_term_open);
464+ lists.flags.set_ref_pic_list_modification_flag_l0(1);
465+ lists.refList0ModOpCount = 1;
466+ lists.pRefList0ModOperations = &modification;
467+ lists.refPicMarkingOpCount = (marking.len() - first) as u8;
468+ lists.pRefPicMarkingOperations = marking[first..].as_ptr();
469+ }
470+ self.long_term_open = !pic.idr;
441 471
442 let mut pic_std = zeroed::<vk::video::StdVideoEncodeH264PictureInfo>();472 let mut pic_std = zeroed::<vk::video::StdVideoEncodeH264PictureInfo>();
443 pic_std.flags.set_IdrPicFlag(pic.idr as u32);473 pic_std.flags.set_IdrPicFlag(pic.idr as u32);
444 pic_std.flags.set_is_reference(1);474 pic_std.flags.set_is_reference(1);
475+ pic_std.flags.set_long_term_reference_flag(pic.idr as u32);
476+ pic_std.flags.set_adaptive_ref_pic_marking_mode_flag(!pic.idr as u32);
445 pic_std.idr_pic_id = pic.idr_pic_id;477 pic_std.idr_pic_id = pic.idr_pic_id;
446 pic_std.primary_pic_type = primary;478 pic_std.primary_pic_type = primary;
447 pic_std.frame_num = pic.frame_num;479 pic_std.frame_num = pic.frame_num;
@@ -523,7 +555,7 @@ impl H264EncodeSession {
523 return Err(Error::Invalid("DPB slot".into()));555 return Err(Error::Invalid("DPB slot".into()));
524 }556 }
525 match pic.reference {557 match pic.reference {
526- None if pic.idr => Ok(()),558+ None if pic.idr && pic.slot == 0 => Ok(()),
527 Some(r) if !pic.idr && (r.slot as usize) < DPB_SLOTS && r.slot != pic.slot => Ok(()),559 Some(r) if !pic.idr && (r.slot as usize) < DPB_SLOTS && r.slot != pic.slot => Ok(()),
528 _ => Err(Error::Invalid("picture and reference do not match".into())),560 _ => Err(Error::Invalid("picture and reference do not match".into())),
529 }561 }
@@ -552,7 +584,7 @@ fn create_parameters(
552 vui.num_units_in_tick = cfg.fps.1;584 vui.num_units_in_tick = cfg.fps.1;
553 vui.time_scale = cfg.fps.0 * 2;585 vui.time_scale = cfg.fps.0 * 2;
554 vui.max_num_reorder_frames = 0;586 vui.max_num_reorder_frames = 0;
555- vui.max_dec_frame_buffering = 1;587+ vui.max_dec_frame_buffering = MAX_REF_FRAMES;
556 if let Some(c) = cfg.colour {588 if let Some(c) = cfg.colour {
557 vui.flags.set_video_signal_type_present_flag(1);589 vui.flags.set_video_signal_type_present_flag(1);
558 vui.flags.set_video_full_range_flag(c.full_range as u32);590 vui.flags.set_video_full_range_flag(c.full_range as u32);
@@ -574,7 +606,9 @@ fn create_parameters(
574 sps.level_idc = level;606 sps.level_idc = level;
575 sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420;607 sps.chroma_format_idc = vk::video::STD_VIDEO_H264_CHROMA_FORMAT_IDC_420;
576 sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2;608 sps.pic_order_cnt_type = vk::video::STD_VIDEO_H264_POC_TYPE_2;
577- sps.max_num_ref_frames = 1;609+ sps.max_num_ref_frames = MAX_REF_FRAMES;
610+ sps.log2_max_frame_num_minus4 = LOG2_MAX_FRAME_NUM - 4;
611+ sps.flags.set_gaps_in_frame_num_value_allowed_flag(1);
578 sps.pic_width_in_mbs_minus1 = aw / 16 - 1;612 sps.pic_width_in_mbs_minus1 = aw / 16 - 1;
579 sps.pic_height_in_map_units_minus1 = ah / 16 - 1;613 sps.pic_height_in_map_units_minus1 = ah / 16 - 1;
580 sps.frame_crop_right_offset = (aw - cfg.width) / 2;614 sps.frame_crop_right_offset = (aw - cfg.width) / 2;
@@ -645,11 +679,15 @@ fn reference_info(
645 primary: vk::video::StdVideoH264PictureType,679 primary: vk::video::StdVideoH264PictureType,
646 frame_num: u32,680 frame_num: u32,
647 poc: i32,681 poc: i32,
682+ slot: u32,
648 ) -> vk::video::StdVideoEncodeH264ReferenceInfo {683 ) -> vk::video::StdVideoEncodeH264ReferenceInfo {
649 let mut info = zeroed::<vk::video::StdVideoEncodeH264ReferenceInfo>();684 let mut info = zeroed::<vk::video::StdVideoEncodeH264ReferenceInfo>();
685+ info.flags.set_used_for_long_term_reference(1);
650 info.primary_pic_type = primary;686 info.primary_pic_type = primary;
651 info.FrameNum = frame_num;687 info.FrameNum = frame_num;
652 info.PicOrderCnt = poc;688 info.PicOrderCnt = poc;
689+ info.long_term_pic_num = slot as u16;
690+ info.long_term_frame_idx = slot as u16;
653 info691 info
654 }692 }
655 693
shims/vk-video-ffi/src/h265_encode.rsmodified+19 -8
@@ -45,6 +45,8 @@ pub struct H265Picture {
45 pub slot: u32,45 pub slot: u32,
46 /// Reference for a P picture, None for IDR.46 /// Reference for a P picture, None for IDR.
47 pub reference: Option<H265Ref>,47 pub reference: Option<H265Ref>,
48+ /// PicOrderCntVal of every other picture the decoder keeps for a later reference, none for IDR.
49+ pub keep: [Option<i32>; DPB_SLOTS],
48 }50 }
49 51
50 /// A picture held in the DPB.52 /// A picture held in the DPB.
@@ -402,7 +404,7 @@ impl H265EncodeSession {
402 lists.RefPicList0 = list0;404 lists.RefPicList0 = list0;
403 lists.RefPicList1 = [0xff; 15];405 lists.RefPicList1 = [0xff; 15];
404 406
405- let rps = pic.reference.map(|r| short_term_rps(pic.poc - r.poc));407+ let rps = pic.reference.map(|r| short_term_rps(pic.poc, r.poc, &pic.keep));
406 408
407 let mut pic_std = zeroed::<vk::video::StdVideoEncodeH265PictureInfo>();409 let mut pic_std = zeroed::<vk::video::StdVideoEncodeH265PictureInfo>();
408 pic_std.flags.set_IrapPicFlag(pic.idr as u32);410 pic_std.flags.set_IrapPicFlag(pic.idr as u32);
@@ -495,12 +497,13 @@ impl H265EncodeSession {
495 return Err(Error::Invalid("DPB slot".into()));497 return Err(Error::Invalid("DPB slot".into()));
496 }498 }
497 match pic.reference {499 match pic.reference {
498- None if pic.idr && pic.poc == 0 => Ok(()),500+ None if pic.idr && pic.poc == 0 && pic.keep.iter().all(Option::is_none) => Ok(()),
499 Some(r)501 Some(r)
500 if !pic.idr502 if !pic.idr
501 && (r.slot as usize) < DPB_SLOTS503 && (r.slot as usize) < DPB_SLOTS
502 && r.slot != pic.slot504 && r.slot != pic.slot
503- && (1..=65536).contains(&(pic.poc - r.poc)) =>505+ && pic.keep.iter().flatten().chain([&r.poc]).all(|&p| (1..=32768).contains(&(pic.poc - p)))
506+ && pic.keep.iter().flatten().filter(|&&p| p == r.poc).count() == 0 =>
504 {507 {
505 Ok(())508 Ok(())
506 }509 }
@@ -523,7 +526,7 @@ fn create_parameters(
523 ptl.flags.set_general_frame_only_constraint_flag(1);526 ptl.flags.set_general_frame_only_constraint_flag(1);
524 527
525 let mut dpb = zeroed::<vk::video::StdVideoH265DecPicBufMgr>();528 let mut dpb = zeroed::<vk::video::StdVideoH265DecPicBufMgr>();
526- dpb.max_dec_pic_buffering_minus1[0] = 1;529+ dpb.max_dec_pic_buffering_minus1[0] = (DPB_SLOTS - 1) as u8;
527 530
528 let mut vui = zeroed::<vk::video::StdVideoH265SequenceParameterSetVui>();531 let mut vui = zeroed::<vk::video::StdVideoH265SequenceParameterSetVui>();
529 vui.flags.set_vui_timing_info_present_flag(1);532 vui.flags.set_vui_timing_info_present_flag(1);
@@ -711,10 +714,18 @@ fn reference_info(
711 info714 info
712 }715 }
713 716
714-fn short_term_rps(delta: i32) -> vk::video::StdVideoH265ShortTermRefPicSet {717+fn short_term_rps(poc: i32, used: i32, keep: &[Option<i32>]) -> vk::video::StdVideoH265ShortTermRefPicSet {
718+ let mut pocs: Vec<i32> = keep.iter().flatten().copied().chain([used]).collect();
719+ pocs.sort_unstable_by(|a, b| b.cmp(a));
715 let mut rps = zeroed::<vk::video::StdVideoH265ShortTermRefPicSet>();720 let mut rps = zeroed::<vk::video::StdVideoH265ShortTermRefPicSet>();
716- rps.num_negative_pics = 1;721+ rps.num_negative_pics = pocs.len() as u8;
717- rps.delta_poc_s0_minus1[0] = (delta - 1) as u16;722+ let mut prev = poc;
718- rps.used_by_curr_pic_s0_flag = 1;723+ for (i, &p) in pocs.iter().enumerate() {
724+ rps.delta_poc_s0_minus1[i] = (prev - p - 1) as u16;
725+ if p == used {
726+ rps.used_by_curr_pic_s0_flag |= 1 << i;
727+ }
728+ prev = p;
729+ }
719 rps730 rps
720 }731 }
shims/vk-video-ffi/src/lib.rsmodified+2 -1
@@ -38,7 +38,8 @@ pub use h264_decode::{
38 ScalingLists,38 ScalingLists,
39 };39 };
40 pub use h264_encode::{40 pub use h264_encode::{
41- H264EncodeConfig, H264EncodeSession, H264Picture, H264Profile, H264Ref, RateControl,41+ H264EncodeConfig, H264EncodeSession, H264Picture, H264Profile, H264Ref, LOG2_MAX_FRAME_NUM,
42+ RateControl,
42 };43 };
43 pub use h265_decode::{44 pub use h265_decode::{
44 H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps,45 H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps,