forge
Explore
Log in

Don't you dare go Hollow

ec-hw: Vulkan H.264 decode behind HwDecoder (Vk first, VA fallback), shared dpb264 with slot surfaces; bit-exact vs ffmpeg on B-frame/multi-ref streams; hw_decode example

Browse files at this commit

18fc8572e95c39dc8ac47448a887172471ced4a6Ahmet Kaan GümüşParent: bb05374
crates/ec-hw/examples/hw_decode.rsadded+105 -0
@@ -0,0 +1,105 @@
1+//! Decodes ffmpeg libx264 streams with B-frames and three references through HwDecoder and compares luma with ffmpeg's decode.
2+//!
3+//! ```text
4+//! cargo run -p ec-hw --example hw_decode -- <scratch dir>
5+//! ```
6+
7+use std::fs;
8+use std::path::{Path, PathBuf};
9+use std::process::Command;
10+
11+use ec_hw::{Codec, HwDecoder, I420};
12+
13+fn main() {
14+ let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
15+ run(&dir, "bf640", "640x360", 60);
16+ run(&dir, "bf1280", "1280x720", 30);
17+}
18+
19+fn ffmpeg(args: &[&str]) {
20+ let status = Command::new("ffmpeg")
21+ .args(["-y", "-loglevel", "error"])
22+ .args(args)
23+ .status()
24+ .expect("run ffmpeg");
25+ assert!(status.success(), "ffmpeg {args:?}");
26+}
27+
28+fn run(dir: &Path, name: &str, size: &str, frames: usize) {
29+ let stream = dir.join(format!("{name}.h264"));
30+ let reference = dir.join(format!("{name}.yuv"));
31+ let source = format!("testsrc2=size={size}:rate=30");
32+ let frames = frames.to_string();
33+ let stream_arg = stream.to_str().expect("utf-8 path");
34+ let reference_arg = reference.to_str().expect("utf-8 path");
35+ ffmpeg(&[
36+ "-f",
37+ "lavfi",
38+ "-i",
39+ &source,
40+ "-frames:v",
41+ &frames,
42+ "-c:v",
43+ "libx264",
44+ "-profile:v",
45+ "high",
46+ "-bf",
47+ "2",
48+ "-refs",
49+ "3",
50+ "-bsf:v",
51+ "h264_mp4toannexb",
52+ "-f",
53+ "h264",
54+ stream_arg,
55+ ]);
56+ ffmpeg(&[
57+ "-i",
58+ stream_arg,
59+ "-f",
60+ "rawvideo",
61+ "-pix_fmt",
62+ "yuv420p",
63+ reference_arg,
64+ ]);
65+
66+ let data = fs::read(&stream).expect("read stream");
67+ let mut decoder = HwDecoder::open(Codec::H264).expect("open H.264 decoder");
68+ let backend = decoder.backend();
69+ decoder.decode(&data, 0).expect("decode");
70+ decoder.flush().expect("flush");
71+ let mut decoded: Vec<I420> = Vec::new();
72+ while let Some((_, frame)) = decoder.next_frame().expect("next frame") {
73+ decoded.push(frame);
74+ }
75+
76+ let raw = fs::read(&reference).expect("read reference");
77+ let (w, h) = size
78+ .split_once('x')
79+ .map(|(w, h)| {
80+ (
81+ w.parse::<usize>().expect("width"),
82+ h.parse::<usize>().expect("height"),
83+ )
84+ })
85+ .expect("size");
86+ let frame_len = w * h * 3 / 2;
87+ let worst = decoded
88+ .iter()
89+ .zip(raw.chunks_exact(frame_len))
90+ .map(|(ours, theirs)| {
91+ let sum: f64 = ours
92+ .y
93+ .iter()
94+ .zip(&theirs[..w * h])
95+ .map(|(&a, &b)| (a as f64 - b as f64).abs())
96+ .sum();
97+ sum / (w * h) as f64
98+ })
99+ .fold(0.0f64, f64::max);
100+ println!(
101+ "{name} {backend:?} {size}: decoded {} frames, ffmpeg {} frames, max mean |diff| Y {worst:.6}",
102+ decoded.len(),
103+ raw.len() / frame_len
104+ );
105+}
crates/ec-hw/src/hw.rsmodified+60 -48
@@ -3,6 +3,7 @@
3 use crate::error::{Error, Result};3 use crate::error::{Error, Result};
4 use crate::picture::I420;4 use crate::picture::I420;
5 use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode};5 use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode};
6+use crate::vkdec264::VkH264Decoder;
6 7
7 #[cfg(target_os = "linux")]8 #[cfg(target_os = "linux")]
8 use crate::dec::Decoder as VaDecoder;9 use crate::dec::Decoder as VaDecoder;
@@ -46,7 +47,7 @@ thread_local! {
46 static GPU: Option<ec_vk::Gpu> = ec_vk::Gpu::open().ok();47 static GPU: Option<ec_vk::Gpu> = ec_vk::Gpu::open().ok();
47 }48 }
48 49
49-fn vk_gpu() -> Option<ec_vk::Gpu> {50+pub(crate) fn vk_gpu() -> Option<ec_vk::Gpu> {
50 GPU.with(|gpu| gpu.clone())51 GPU.with(|gpu| gpu.clone())
51 }52 }
52 53
@@ -54,11 +55,10 @@ fn vk_gpu() -> Option<ec_vk::Gpu> {
54 pub fn capabilities() -> Vec<Capability> {55 pub fn capabilities() -> Vec<Capability> {
55 let mut out = Vec::new();56 let mut out = Vec::new();
56 if let Some(gpu) = vk_gpu() {57 if let Some(gpu) = vk_gpu() {
57- for caps in gpu58+ for caps in gpu.caps().into_iter().filter(|c| {
58- .caps()59+ c.direction == ec_vk::Direction::Encode
59- .into_iter()60+ || (c.direction == ec_vk::Direction::Decode && c.codec == ec_vk::Codec::H264)
60- .filter(|c| c.direction == ec_vk::Direction::Encode)61+ }) {
61- {
62 let codec = match caps.codec {62 let codec = match caps.codec {
63 ec_vk::Codec::H264 => Codec::H264,63 ec_vk::Codec::H264 => Codec::H264,
64 ec_vk::Codec::H265 => Codec::H265,64 ec_vk::Codec::H265 => Codec::H265,
@@ -417,76 +417,88 @@ fn open_va(config: EncoderConfig) -> Result<EncInner> {
417 ))417 ))
418 }418 }
419 419
420-/// A hardware decoder. Only VA-API decodes for now.420+enum DecInner {
421-pub struct HwDecoder {421+ Vk(VkH264Decoder),
422 #[cfg(target_os = "linux")]422 #[cfg(target_os = "linux")]
423- inner: VaDecoder,423+ Va(VaDecoder),
424+}
425+
426+/// A hardware decoder on whichever backend opened.
427+pub struct HwDecoder {
428+ inner: DecInner,
424 }429 }
425 430
426 impl HwDecoder {431 impl HwDecoder {
427- /// Open a decoder for `codec`. Non-Linux: always `Unsupported`.432+ /// Open a decoder for `codec`. H.264 tries Vulkan Video first, then VA-API (Linux).
428 pub fn open(codec: Codec) -> Result<HwDecoder> {433 pub fn open(codec: Codec) -> Result<HwDecoder> {
429- #[cfg(target_os = "linux")]434+ let mut reasons = Vec::new();
430- {435+ if matches!(codec, Codec::H264) {
431- let display = ec_va::open()?;436+ match VkH264Decoder::new() {
432- Ok(HwDecoder {437+ Ok(inner) => {
433- inner: VaDecoder::new(&display, codec)?,438+ return Ok(HwDecoder {
434- })439+ inner: DecInner::Vk(inner),
440+ });
441+ }
442+ Err(e) => reasons.push(format!("Vk: {e}")),
443+ }
435 }444 }
436- #[cfg(not(target_os = "linux"))]445+ #[cfg(target_os = "linux")]
437 {446 {
438- Err(Error::unsupported(447+ let va = (|| -> Result<VaDecoder> {
439- format!("{codec:?} hardware decode"),448+ let display = ec_va::open()?;
440- "VA-API is Linux only",449+ VaDecoder::new(&display, codec)
441- ))450+ })();
451+ match va {
452+ Ok(inner) => {
453+ return Ok(HwDecoder {
454+ inner: DecInner::Va(inner),
455+ });
456+ }
457+ Err(e) => reasons.push(format!("Va: {e}")),
458+ }
442 }459 }
460+ Err(Error::unsupported(
461+ format!("{codec:?} hardware decode"),
462+ reasons.join("; "),
463+ ))
443 }464 }
444 465
445 /// The backend this decoder runs on.466 /// The backend this decoder runs on.
446 pub fn backend(&self) -> Backend {467 pub fn backend(&self) -> Backend {
447- Backend::Va468+ match self.inner {
469+ DecInner::Vk(_) => Backend::Vk,
470+ #[cfg(target_os = "linux")]
471+ DecInner::Va(_) => Backend::Va,
472+ }
448 }473 }
449 474
450 /// Feed one access unit.475 /// Feed one access unit.
451 pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {476 pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
452- #[cfg(target_os = "linux")]477+ match &mut self.inner {
453- {478+ DecInner::Vk(d) => d.decode(data, timestamp),
454- self.inner.decode(data, timestamp)479+ #[cfg(target_os = "linux")]
455- }480+ DecInner::Va(d) => d.decode(data, timestamp),
456- #[cfg(not(target_os = "linux"))]
457- {
458- let _ = (data, timestamp);
459- Err(Error::unsupported(
460- "hardware decode",
461- "VA-API is Linux only",
462- ))
463 }481 }
464 }482 }
465 483
466 /// The next picture in display order, as 8-bit I420 with its timestamp.484 /// The next picture in display order, as 8-bit I420 with its timestamp.
467 pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {485 pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {
468- #[cfg(target_os = "linux")]486+ match &mut self.inner {
469- {487+ DecInner::Vk(d) => Ok(d.next_frame()),
470- match self.inner.next_frame() {488+ #[cfg(target_os = "linux")]
489+ DecInner::Va(d) => match d.next_frame() {
471 Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))),490 Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))),
472 None => Ok(None),491 None => Ok(None),
473- }492+ },
474- }
475- #[cfg(not(target_os = "linux"))]
476- {
477- Ok(None)
478 }493 }
479 }494 }
480 495
481 /// Emit every picture still held for reordering.496 /// Emit every picture still held for reordering.
482 pub fn flush(&mut self) -> Result<()> {497 pub fn flush(&mut self) -> Result<()> {
483- #[cfg(target_os = "linux")]498+ match &mut self.inner {
484- {499+ DecInner::Vk(d) => d.flush(),
485- self.inner.flush()500+ #[cfg(target_os = "linux")]
486- }501+ DecInner::Va(d) => d.flush(),
487- #[cfg(not(target_os = "linux"))]
488- {
489- Ok(())
490 }502 }
491 }503 }
492 }504 }
crates/ec-hw/src/lib.rsmodified+1 -0
@@ -73,6 +73,7 @@ pub mod params;
73 pub mod pool;73 pub mod pool;
74 pub mod reset;74 pub mod reset;
75 pub mod types;75 pub mod types;
76+pub(crate) mod vkdec264;
76 77
77 #[cfg(target_os = "linux")]78 #[cfg(target_os = "linux")]
78 pub use dec::{Decoder, StreamInfo};79 pub use dec::{Decoder, StreamInfo};
crates/ec-hw/src/vkdec264.rsadded+449 -0
@@ -0,0 +1,449 @@
1+//! H.264 decoding over Vulkan Video: the shared DPB over DPB slot indices.
2+
3+use std::collections::{HashMap, VecDeque};
4+
5+use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8};
6+use ec_h264_syntax::{
7+ AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, SliceHeader, Sps, unescape_rbsp,
8+};
9+use ec_vk::{
10+ H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,
11+ ScalingLists,
12+};
13+
14+use crate::dpb264::{self, Mark, PicInfo, Poc};
15+use crate::error::{Error, Result};
16+use crate::h264_common::peek_pps_id;
17+use crate::picture::{I420, nv12_to_i420};
18+
19+const MAX_SLOTS: u32 = 17;
20+
21+type Dpb = dpb264::Dpb<u32>;
22+type Picture = dpb264::Picture<u32>;
23+
24+struct Session {
25+ h264: H264DecodeSession,
26+ max_width: u32,
27+ max_height: u32,
28+ slots: u32,
29+}
30+
31+struct Current {
32+ slot: u32,
33+ id: i32,
34+ sps_id: u8,
35+ pps_id: u8,
36+ info: PicInfo,
37+ poc: Poc,
38+ idr_pic_id: u16,
39+ timestamp: i64,
40+ marking: Option<DecRefPicMarking>,
41+ slices: Vec<Vec<u8>>,
42+}
43+
44+struct Side {
45+ fields: [i32; 2],
46+ output: Option<(i64, I420)>,
47+}
48+
49+/// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots.
50+pub(crate) struct VkH264Decoder {
51+ gpu: ec_vk::Gpu,
52+ session: Option<Session>,
53+ params_dirty: bool,
54+ sps_map: [Option<Sps>; 32],
55+ pps_map: Vec<Option<Pps>>,
56+ dpb: Dpb,
57+ pics: HashMap<i32, Side>,
58+ current: Option<Current>,
59+ ready: VecDeque<(i64, I420)>,
60+ rbsp: Vec<u8>,
61+}
62+
63+impl VkH264Decoder {
64+ pub(crate) fn new() -> Result<Self> {
65+ let gpu = crate::hw::vk_gpu()
66+ .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?;
67+ Ok(VkH264Decoder {
68+ gpu,
69+ session: None,
70+ params_dirty: false,
71+ sps_map: [const { None }; 32],
72+ pps_map: (0..256).map(|_| None).collect(),
73+ dpb: Dpb::default(),
74+ pics: HashMap::new(),
75+ current: None,
76+ ready: VecDeque::new(),
77+ rbsp: Vec::new(),
78+ })
79+ }
80+
81+ pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> {
82+ for nal in AnnexBIter::new(data) {
83+ let Some((&first, payload)) = nal.split_first() else {
84+ continue;
85+ };
86+ let header = NalHeader::parse(first)?;
87+ match header.unit_type {
88+ NalUnitType::Sps => {
89+ let mut rbsp = std::mem::take(&mut self.rbsp);
90+ unescape_rbsp(payload, &mut rbsp);
91+ let sps = Sps::parse(&rbsp);
92+ self.rbsp = rbsp;
93+ let sps = sps?;
94+ self.dpb.configure(&sps);
95+ let id = usize::from(sps.id);
96+ self.sps_map[id] = Some(sps);
97+ self.params_dirty = true;
98+ }
99+ NalUnitType::Pps => {
100+ let mut rbsp = std::mem::take(&mut self.rbsp);
101+ unescape_rbsp(payload, &mut rbsp);
102+ let pps = Pps::parse(&rbsp, |id| self.sps_map[usize::from(id)].as_ref());
103+ self.rbsp = rbsp;
104+ let pps = pps?;
105+ let id = pps.id as usize;
106+ if id < self.pps_map.len() {
107+ self.pps_map[id] = Some(pps);
108+ self.params_dirty = true;
109+ }
110+ }
111+ NalUnitType::Slice | NalUnitType::SliceIdr => {
112+ self.slice(header, nal, payload, timestamp)?;
113+ }
114+ _ => {}
115+ }
116+ }
117+ self.finish_picture()
118+ }
119+
120+ pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> {
121+ self.ready.pop_front()
122+ }
123+
124+ pub(crate) fn flush(&mut self) -> Result<()> {
125+ self.finish_picture()?;
126+ self.bump(true);
127+ Ok(())
128+ }
129+
130+ fn slice(
131+ &mut self,
132+ header: NalHeader,
133+ nal: &[u8],
134+ payload: &[u8],
135+ timestamp: i64,
136+ ) -> Result<()> {
137+ let mut rbsp = std::mem::take(&mut self.rbsp);
138+ unescape_rbsp(payload, &mut rbsp);
139+ let result = self.slice_rbsp(header, nal, &rbsp, timestamp);
140+ self.rbsp = rbsp;
141+ result
142+ }
143+
144+ fn slice_rbsp(
145+ &mut self,
146+ header: NalHeader,
147+ nal: &[u8],
148+ rbsp: &[u8],
149+ timestamp: i64,
150+ ) -> Result<()> {
151+ let pps_id = peek_pps_id(rbsp)?;
152+ let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else {
153+ return Ok(());
154+ };
155+ let Some(sps) = self.sps_map[usize::from(pps.sps_id)].clone() else {
156+ return Ok(());
157+ };
158+ let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?;
159+ if sh.first_mb_in_slice == 0 {
160+ self.finish_picture()?;
161+ self.start_picture(&sps, &sh, header, timestamp)?;
162+ }
163+ if let Some(current) = self.current.as_mut() {
164+ current.slices.push(nal.to_vec());
165+ }
166+ Ok(())
167+ }
168+
169+ fn start_picture(
170+ &mut self,
171+ sps: &Sps,
172+ sh: &SliceHeader,
173+ header: NalHeader,
174+ timestamp: i64,
175+ ) -> Result<()> {
176+ self.ensure_session(sps)?;
177+ if self.params_dirty {
178+ self.set_parameters()?;
179+ }
180+ let info = PicInfo {
181+ is_idr: header.is_idr(),
182+ is_reference: header.ref_idc != 0,
183+ frame_num: sh.frame_num,
184+ pic_order_cnt_lsb: sh.pic_order_cnt_lsb,
185+ delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom,
186+ delta_pic_order_cnt: sh.delta_pic_order_cnt,
187+ };
188+ if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) {
189+ self.fill_gap(sps, sh.frame_num)?;
190+ }
191+ let poc = self.dpb.picture_order_count(sps, &info)?;
192+ let slot = self.free_slot()?;
193+ let id = self.dpb.next_id();
194+ self.current = Some(Current {
195+ slot,
196+ id,
197+ sps_id: sps.id,
198+ pps_id: sh.pps_id as u8,
199+ info,
200+ poc,
201+ idr_pic_id: sh.idr_pic_id.unwrap_or(0) as u16,
202+ timestamp,
203+ marking: sh.dec_ref_pic_marking.clone(),
204+ slices: Vec::new(),
205+ });
206+ Ok(())
207+ }
208+
209+ fn ensure_session(&mut self, sps: &Sps) -> Result<()> {
210+ if sps.chroma_format_idc != 1 || sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 {
211+ return Err(Error::unsupported(
212+ "Vulkan H.264 decode",
213+ "only 8-bit 4:2:0",
214+ ));
215+ }
216+ let slots = (self.dpb.capacity() as u32 + 1).min(MAX_SLOTS);
217+ let (w, h) = (sps.coded_width, sps.coded_height);
218+ let (max_width, max_height, slots) = match &self.session {
219+ Some(s) if w <= s.max_width && h <= s.max_height && slots <= s.slots => return Ok(()),
220+ Some(s) => (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)),
221+ None => (w, h, slots),
222+ };
223+ self.current = None;
224+ self.dpb.clear();
225+ self.pics.clear();
226+ self.session = None;
227+ let h264 = H264DecodeSession::new(
228+ &self.gpu,
229+ &H264DecodeConfig {
230+ max_width,
231+ max_height,
232+ max_dpb_slots: slots,
233+ profile_idc: sps.profile_idc,
234+ },
235+ )?;
236+ self.session = Some(Session {
237+ h264,
238+ max_width,
239+ max_height,
240+ slots,
241+ });
242+ self.params_dirty = true;
243+ Ok(())
244+ }
245+
246+ fn set_parameters(&mut self) -> Result<()> {
247+ let sps: Vec<H264Sps> = self.sps_map.iter().flatten().map(vk_sps).collect();
248+ let pps: Vec<H264Pps> = self.pps_map.iter().flatten().map(vk_pps).collect();
249+ let session = self
250+ .session
251+ .as_mut()
252+ .ok_or_else(|| Error::config("H.264 parameters before any SPS"))?;
253+ session.h264.set_parameters(&sps, &pps)?;
254+ self.params_dirty = false;
255+ Ok(())
256+ }
257+
258+ fn free_slot(&self) -> Result<u32> {
259+ let session = self
260+ .session
261+ .as_ref()
262+ .ok_or_else(|| Error::config("H.264 picture before any SPS"))?;
263+ (0..session.slots)
264+ .find(|slot| self.dpb.frames.iter().all(|p| p.surface != *slot))
265+ .ok_or_else(|| Error::config("H.264 Vulkan decode: every DPB slot is in use"))
266+ }
267+
268+ fn fill_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> {
269+ let before = self.dpb.frames.len();
270+ self.dpb.fill_frame_num_gap(sps, frame_num)?;
271+ for i in before..self.dpb.frames.len() {
272+ self.dpb.frames[i].surface = self.free_slot()?;
273+ }
274+ Ok(())
275+ }
276+
277+ fn finish_picture(&mut self) -> Result<()> {
278+ let Some(current) = self.current.take() else {
279+ return Ok(());
280+ };
281+ let Some(sps) = self.sps_map[usize::from(current.sps_id)].clone() else {
282+ return Ok(());
283+ };
284+ let fields = field_pocs(current.poc.value, current.info.delta_pic_order_cnt_bottom);
285+ let refs: Vec<H264RefSlot> = if current.info.is_idr {
286+ Vec::new()
287+ } else {
288+ self.dpb
289+ .frames
290+ .iter()
291+ .filter(|p| p.mark != Mark::Unused)
292+ .map(|p| H264RefSlot {
293+ slot: p.surface,
294+ frame_num: p.frame_num as u16,
295+ poc: self.pics.get(&p.id).map_or([p.poc, p.poc], |s| s.fields),
296+ long_term: p.mark == Mark::Long,
297+ non_existing: p.non_existing,
298+ })
299+ .collect()
300+ };
301+ let slices: Vec<&[u8]> = current.slices.iter().map(Vec::as_slice).collect();
302+ let session = self
303+ .session
304+ .as_mut()
305+ .ok_or_else(|| Error::config("H.264 picture before any SPS"))?;
306+ session.h264.decode(&H264DecodePicture {
307+ sps_id: current.sps_id,
308+ pps_id: current.pps_id,
309+ idr: current.info.is_idr,
310+ reference: current.info.is_reference,
311+ frame_num: current.info.frame_num as u16,
312+ idr_pic_id: current.idr_pic_id,
313+ poc: fields,
314+ setup_slot: current.slot,
315+ refs: &refs,
316+ slices: &slices,
317+ })?;
318+ let (y, uv) = session
319+ .h264
320+ .read_output(sps.coded_width, sps.coded_height)?;
321+ let out = crop(&sps, &y, &uv);
322+
323+ let picture = Picture {
324+ id: current.id,
325+ surface: current.slot,
326+ timestamp: current.timestamp,
327+ frame_num: current.info.frame_num,
328+ frame_num_wrap: current.info.frame_num as i32,
329+ pic_num: current.info.frame_num as i32,
330+ long_term_frame_idx: 0,
331+ poc: current.poc.value,
332+ poc_msb: current.poc.msb,
333+ poc_lsb: current.poc.lsb,
334+ frame_num_offset: current.poc.frame_num_offset,
335+ mark: Mark::Unused,
336+ non_existing: false,
337+ output: true,
338+ };
339+ self.pics.insert(
340+ current.id,
341+ Side {
342+ fields,
343+ output: Some((current.timestamp, out)),
344+ },
345+ );
346+ self.dpb
347+ .store(picture, &sps, &current.info, current.marking.as_ref(), true)?;
348+ self.bump(false);
349+ Ok(())
350+ }
351+
352+ fn bump(&mut self, flush: bool) {
353+ while let Some(idx) = self.dpb.next_output(flush) {
354+ let id = self.dpb.frames[idx].id;
355+ if let Some((ts, frame)) = self.pics.get_mut(&id).and_then(|s| s.output.take()) {
356+ self.ready.push_back((ts, frame));
357+ }
358+ self.dpb.released(idx);
359+ }
360+ let frames = &self.dpb.frames;
361+ self.pics.retain(|id, _| frames.iter().any(|p| p.id == *id));
362+ }
363+}
364+
365+fn field_pocs(poc: i32, delta_bottom: i32) -> [i32; 2] {
366+ [poc - delta_bottom.min(0), poc + delta_bottom.max(0)]
367+}
368+
369+fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> I420 {
370+ let (left, _, top, _) = sps.crop;
371+ let (left, top) = (left as usize, top as usize);
372+ let pitch = sps.coded_width as usize;
373+ nv12_to_i420(
374+ &y[top * pitch + left..],
375+ pitch,
376+ &uv[(top / 2) * pitch + left..],
377+ pitch,
378+ sps.width as usize,
379+ sps.height as usize,
380+ )
381+}
382+
383+fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists {
384+ let mut out = ScalingLists {
385+ l4x4: [[0; 16]; 6],
386+ l8x8: [[0; 64]; 6],
387+ };
388+ for i in 0..6 {
389+ out.l4x4[i] = ZIGZAG_4X4.map(|r| l.list_4x4[i][usize::from(r)]);
390+ out.l8x8[i] = ZIGZAG_8X8.map(|r| l.list_8x8[i][usize::from(r)]);
391+ }
392+ out
393+}
394+
395+fn vk_sps(sps: &Sps) -> H264Sps {
396+ let unit_y = if sps.frame_mbs_only { 2 } else { 4 };
397+ let (left, right, top, bottom) = sps.crop;
398+ H264Sps {
399+ id: sps.id,
400+ profile_idc: sps.profile_idc,
401+ level_idc: sps.level_idc,
402+ chroma_format_idc: sps.chroma_format_idc,
403+ bit_depth_luma_minus8: sps.bit_depth_luma.saturating_sub(8),
404+ bit_depth_chroma_minus8: sps.bit_depth_chroma.saturating_sub(8),
405+ log2_max_frame_num_minus4: sps.log2_max_frame_num.saturating_sub(4),
406+ pic_order_cnt_type: sps.pic_order_cnt_type,
407+ log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_pic_order_cnt_lsb.saturating_sub(4),
408+ offset_for_non_ref_pic: sps.offset_for_non_ref_pic,
409+ offset_for_top_to_bottom_field: sps.offset_for_top_to_bottom_field,
410+ offset_for_ref_frame: sps.offsets_for_ref_frame.clone(),
411+ max_num_ref_frames: sps.max_num_ref_frames as u8,
412+ pic_width_in_mbs_minus1: sps.mb_width.saturating_sub(1),
413+ pic_height_in_map_units_minus1: (if sps.frame_mbs_only {
414+ sps.mb_height
415+ } else {
416+ sps.mb_height / 2
417+ })
418+ .saturating_sub(1),
419+ frame_mbs_only: sps.frame_mbs_only,
420+ mb_adaptive_frame_field: sps.mb_adaptive_frame_field,
421+ direct_8x8_inference: sps.direct_8x8_inference,
422+ delta_pic_order_always_zero: sps.delta_pic_order_always_zero,
423+ frame_crop_offsets: [left / 2, right / 2, top / unit_y, bottom / unit_y],
424+ qpprime_y_zero_transform_bypass: sps.transform_bypass,
425+ seq_scaling_matrix: sps.scaling_lists.as_ref().map(lists),
426+ }
427+}
428+
429+fn vk_pps(pps: &Pps) -> H264Pps {
430+ H264Pps {
431+ id: pps.id as u8,
432+ sps_id: pps.sps_id,
433+ entropy_coding_mode: pps.entropy_coding_mode,
434+ bottom_field_pic_order_in_frame_present: pps.bottom_field_pic_order_in_frame_present,
435+ num_ref_idx_l0_default_active_minus1: (pps.num_ref_idx_l0_default_active - 1) as u8,
436+ num_ref_idx_l1_default_active_minus1: (pps.num_ref_idx_l1_default_active - 1) as u8,
437+ weighted_pred: pps.weighted_pred,
438+ weighted_bipred_idc: pps.weighted_bipred_idc,
439+ pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8,
440+ pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8,
441+ chroma_qp_index_offset: pps.chroma_qp_index_offset as i8,
442+ second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8,
443+ deblocking_filter_control_present: pps.deblocking_filter_control_present,
444+ constrained_intra_pred: pps.constrained_intra_pred,
445+ redundant_pic_cnt_present: pps.redundant_pic_cnt_present,
446+ transform_8x8_mode: pps.transform_8x8_mode,
447+ pic_scaling_matrix: pps.scaling_lists.as_ref().map(lists),
448+ }
449+}
crates/ec-vk/src/lib.rsmodified+4 -1
@@ -9,7 +9,10 @@ mod h265;
9 9
10 pub use av1::{Av1Encoder, Av1EncoderConfig};10 pub use av1::{Av1Encoder, Av1EncoderConfig};
11 pub use h265::{H265Encoder, H265EncoderConfig};11 pub use h265::{H265Encoder, H265EncoderConfig};
12-pub use vk_video_ffi::{Codec, Direction, Error, Gpu, RateControl};12+pub use vk_video_ffi::{
13+ Codec, Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps,
14+ H264RefSlot, H264Sps, RateControl, ScalingLists,
15+};
13 16
14 /// Encoder settings.17 /// Encoder settings.
15 #[derive(Debug, Clone, Copy, PartialEq, Eq)]18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]