forge
Explore
Log in

Don't you dare go Hollow

vk-video-ffi: Av1DecodeSession (Main 8-bit, distinct DPB/output, plain-struct sequence/frame headers); smoke example bit-exact vs ffmpeg on a key frame

Browse files at this commit

6c8698488801124db41caad121d4d60bc1945790Ahmet Kaan GümüşParent: 6f8f2a3
Cargo.lockmodified+1 -0
@@ -1895,6 +1895,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
18951895 name = "vk-video-ffi"
18961896 version = "0.1.0"
18971897 dependencies = [
1898+ "ec-av1-syntax",
18981899 "ec-h264-syntax",
18991900 "ec-h265-syntax",
19001901 "vulkanalia",
crates/ec-vk/src/lib.rsmodified+6 -2
@@ -10,8 +10,12 @@ mod h265;
1010 pub use av1::{Av1Encoder, Av1EncoderConfig};
1111 pub use h265::{H265Encoder, H265EncoderConfig};
1212 pub use vk_video_ffi::{
13- Codec, Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps,
14- H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,
13+ Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
14+ Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
15+ Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
16+ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction,
17+ Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot,
18+ H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession,
1519 H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists,
1620 H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists,
1721 };
shims/vk-video-ffi/Cargo.tomlmodified+1 -0
@@ -9,5 +9,6 @@ authors.workspace = true
99 vulkanalia = { version = "0.35", features = ["libloading"] }
1010
1111 [dev-dependencies]
12+ec-av1-syntax.workspace = true
1213 ec-h264-syntax.workspace = true
1314 ec-h265-syntax.workspace = true
shims/vk-video-ffi/examples/av1_decode_smoke.rsadded+318 -0
@@ -0,0 +1,318 @@
1+use std::fs;
2+use std::path::PathBuf;
3+use std::process::Command;
4+
5+use ec_av1_syntax::{
6+ Av1Parser, ChromaSamplePosition, ColorConfig, FrameHeader, FrameType, InterpolationFilter,
7+ ObuKind, RestorationType, SequenceHeader, TxMode, WarpModel,
8+};
9+use vk_video_ffi::{
10+ Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
11+ Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
12+ Av1LoopRestoration, Av1Quantization, Av1Restoration, Av1Segmentation, Av1SequenceHeader,
13+ Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Gpu,
14+};
15+
16+fn color(c: &ColorConfig) -> Av1ColorConfig {
17+ Av1ColorConfig {
18+ bit_depth: c.bit_depth,
19+ mono_chrome: c.mono_chrome,
20+ color_range: c.color_range,
21+ separate_uv_delta_q: c.separate_uv_delta_q,
22+ subsampling_x: c.subsampling_x,
23+ subsampling_y: c.subsampling_y,
24+ color_primaries: c.color_primaries,
25+ transfer_characteristics: c.transfer_characteristics,
26+ matrix_coefficients: c.matrix_coefficients,
27+ chroma_sample_position: match c.chroma_sample_position {
28+ ChromaSamplePosition::Unknown => 0,
29+ ChromaSamplePosition::Vertical => 1,
30+ ChromaSamplePosition::Colocated => 2,
31+ ChromaSamplePosition::Reserved => 3,
32+ },
33+ }
34+}
35+
36+fn sequence(s: &SequenceHeader) -> Av1SequenceHeader {
37+ Av1SequenceHeader {
38+ seq_profile: s.seq_profile,
39+ still_picture: s.still_picture,
40+ reduced_still_picture_header: s.reduced_still_picture_header,
41+ timing_info: s.timing_info.map(|t| Av1TimingInfo {
42+ equal_picture_interval: t.equal_picture_interval,
43+ num_units_in_display_tick: t.num_units_in_display_tick,
44+ time_scale: t.time_scale,
45+ num_ticks_per_picture_minus_1: t.num_ticks_per_picture.saturating_sub(1),
46+ }),
47+ initial_display_delay_present: s.initial_display_delay_present_flag,
48+ frame_width_bits_minus_1: (s.frame_width_bits - 1) as u8,
49+ frame_height_bits_minus_1: (s.frame_height_bits - 1) as u8,
50+ max_frame_width_minus_1: (s.max_frame_width - 1) as u16,
51+ max_frame_height_minus_1: (s.max_frame_height - 1) as u16,
52+ frame_id_numbers_present: s.frame_id_numbers_present_flag,
53+ delta_frame_id_length_minus_2: s.delta_frame_id_length.saturating_sub(2) as u8,
54+ additional_frame_id_length_minus_1: s.additional_frame_id_length.saturating_sub(1) as u8,
55+ order_hint_bits_minus_1: s.order_hint_bits.saturating_sub(1) as u8,
56+ seq_force_integer_mv: s.seq_force_integer_mv,
57+ seq_force_screen_content_tools: s.seq_force_screen_content_tools,
58+ use_128x128_superblock: s.use_128x128_superblock,
59+ enable_filter_intra: s.enable_filter_intra,
60+ enable_intra_edge_filter: s.enable_intra_edge_filter,
61+ enable_interintra_compound: s.enable_interintra_compound,
62+ enable_masked_compound: s.enable_masked_compound,
63+ enable_warped_motion: s.enable_warped_motion,
64+ enable_dual_filter: s.enable_dual_filter,
65+ enable_order_hint: s.enable_order_hint,
66+ enable_jnt_comp: s.enable_jnt_comp,
67+ enable_ref_frame_mvs: s.enable_ref_frame_mvs,
68+ enable_superres: s.enable_superres,
69+ enable_cdef: s.enable_cdef,
70+ enable_restoration: s.enable_restoration,
71+ color_config: color(&s.color_config),
72+ film_grain_params_present: s.film_grain_params_present,
73+ }
74+}
75+
76+fn restoration(r: RestorationType) -> Av1Restoration {
77+ match r {
78+ RestorationType::None => Av1Restoration::None,
79+ RestorationType::Wiener => Av1Restoration::Wiener,
80+ RestorationType::Sgrproj => Av1Restoration::Sgrproj,
81+ RestorationType::Switchable => Av1Restoration::Switchable,
82+ }
83+}
84+
85+fn frame(h: &FrameHeader, s: &SequenceHeader) -> Av1FrameHeader {
86+ let sb_shift = s.sb_shift();
87+ let mut global_motion = [Av1GlobalMotion::default(); 8];
88+ let mut order_hints = [0u8; 8];
89+ for i in 0..7 {
90+ global_motion[i + 1] = Av1GlobalMotion {
91+ model: match h.global_motion[i].model {
92+ WarpModel::Identity => Av1WarpModel::Identity,
93+ WarpModel::Translation => Av1WarpModel::Translation,
94+ WarpModel::Rotzoom => Av1WarpModel::Rotzoom,
95+ WarpModel::Affine => Av1WarpModel::Affine,
96+ },
97+ params: h.global_motion[i].params,
98+ };
99+ order_hints[i + 1] = h.order_hints[i] as u8;
100+ }
101+ Av1FrameHeader {
102+ frame_type: match h.frame_type {
103+ FrameType::Key => Av1FrameType::Key,
104+ FrameType::Inter => Av1FrameType::Inter,
105+ FrameType::IntraOnly => Av1FrameType::IntraOnly,
106+ FrameType::Switch => Av1FrameType::Switch,
107+ },
108+ show_frame: h.show_frame,
109+ showable_frame: h.showable_frame,
110+ error_resilient_mode: h.error_resilient_mode,
111+ disable_cdf_update: h.disable_cdf_update,
112+ allow_screen_content_tools: h.allow_screen_content_tools,
113+ force_integer_mv: h.force_integer_mv,
114+ current_frame_id: h.current_frame_id,
115+ frame_size_override_flag: h.frame_size_override_flag,
116+ order_hint: h.order_hint as u8,
117+ primary_ref_frame: h.primary_ref_frame,
118+ refresh_frame_flags: h.refresh_frame_flags,
119+ frame_width: h.frame_width,
120+ frame_height: h.frame_height,
121+ upscaled_width: h.upscaled_width,
122+ render_width: h.render_width,
123+ render_height: h.render_height,
124+ use_superres: h.use_superres,
125+ superres_denom: h.superres_denom,
126+ allow_intrabc: h.allow_intrabc,
127+ allow_high_precision_mv: h.allow_high_precision_mv,
128+ is_motion_mode_switchable: h.is_motion_mode_switchable,
129+ use_ref_frame_mvs: h.use_ref_frame_mvs,
130+ frame_refs_short_signaling: h.frame_refs_short_signaling,
131+ disable_frame_end_update_cdf: h.disable_frame_end_update_cdf,
132+ reference_select: h.reference_select,
133+ skip_mode_present: h.skip_mode_present,
134+ allow_warped_motion: h.allow_warped_motion,
135+ reduced_tx_set: h.reduced_tx_set,
136+ interpolation_filter: match h.interpolation_filter {
137+ InterpolationFilter::Eighttap => Av1InterpolationFilter::EightTap,
138+ InterpolationFilter::EighttapSmooth => Av1InterpolationFilter::EightTapSmooth,
139+ InterpolationFilter::EighttapSharp => Av1InterpolationFilter::EightTapSharp,
140+ InterpolationFilter::Bilinear => Av1InterpolationFilter::Bilinear,
141+ InterpolationFilter::Switchable => Av1InterpolationFilter::Switchable,
142+ },
143+ tx_mode: match h.tx_mode {
144+ TxMode::Only4x4 => Av1TxMode::Only4x4,
145+ TxMode::Largest => Av1TxMode::Largest,
146+ TxMode::Select => Av1TxMode::Select,
147+ },
148+ tile_info: Av1TileInfo {
149+ uniform_spacing: h.tile_info.uniform_spacing,
150+ cols: h.tile_info.cols as u8,
151+ rows: h.tile_info.rows as u8,
152+ mi_col_starts: h
153+ .tile_info
154+ .mi_col_starts
155+ .iter()
156+ .map(|&v| v as u16)
157+ .collect(),
158+ mi_row_starts: h
159+ .tile_info
160+ .mi_row_starts
161+ .iter()
162+ .map(|&v| v as u16)
163+ .collect(),
164+ width_in_sbs_minus_1: h.tile_info.width_in_sbs_minus_1(sb_shift),
165+ height_in_sbs_minus_1: h.tile_info.height_in_sbs_minus_1(sb_shift),
166+ context_update_tile_id: h.tile_info.context_update_tile_id as u16,
167+ tile_size_bytes_minus_1: h.tile_info.tile_size_bytes.saturating_sub(1) as u8,
168+ },
169+ quantization: Av1Quantization {
170+ base_q_idx: h.quantization.base_q_idx,
171+ delta_q_y_dc: h.quantization.delta_q_y_dc,
172+ delta_q_u_dc: h.quantization.delta_q_u_dc,
173+ delta_q_u_ac: h.quantization.delta_q_u_ac,
174+ delta_q_v_dc: h.quantization.delta_q_v_dc,
175+ delta_q_v_ac: h.quantization.delta_q_v_ac,
176+ using_qmatrix: h.quantization.using_qmatrix,
177+ qm_y: h.quantization.qm_y,
178+ qm_u: h.quantization.qm_u,
179+ qm_v: h.quantization.qm_v,
180+ },
181+ segmentation: Av1Segmentation {
182+ enabled: h.segmentation.enabled,
183+ update_map: h.segmentation.update_map,
184+ temporal_update: h.segmentation.temporal_update,
185+ update_data: h.segmentation.update_data,
186+ feature_enabled: h.segmentation.feature_enabled,
187+ feature_data: h.segmentation.feature_data,
188+ },
189+ delta: Av1DeltaParams {
190+ q_present: h.delta.q_present,
191+ q_res: h.delta.q_res,
192+ lf_present: h.delta.lf_present,
193+ lf_res: h.delta.lf_res,
194+ lf_multi: h.delta.lf_multi,
195+ },
196+ loop_filter: Av1LoopFilter {
197+ level: h.loop_filter.level,
198+ sharpness: h.loop_filter.sharpness,
199+ delta_enabled: h.loop_filter.delta_enabled,
200+ delta_update: h.loop_filter.delta_update,
201+ ref_deltas: h.loop_filter.ref_deltas,
202+ mode_deltas: h.loop_filter.mode_deltas,
203+ },
204+ cdef: Av1Cdef {
205+ damping_minus_3: h.cdef.damping.saturating_sub(3),
206+ bits: h.cdef.bits,
207+ y_pri: h.cdef.y_pri_strength,
208+ y_sec: h.cdef.y_sec_strength,
209+ uv_pri: h.cdef.uv_pri_strength,
210+ uv_sec: h.cdef.uv_sec_strength,
211+ },
212+ loop_restoration: Av1LoopRestoration {
213+ frame_restoration_type: h.loop_restoration.frame_restoration_type.map(restoration),
214+ loop_restoration_size: h.loop_restoration.loop_restoration_size.map(|v| v as u16),
215+ },
216+ global_motion,
217+ order_hints,
218+ skip_mode_frame: h.skip_mode_frame,
219+ expected_frame_id: [0; 8],
220+ apply_grain: h.film_grain.apply_grain,
221+ }
222+}
223+
224+fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
225+ a.iter()
226+ .zip(b)
227+ .map(|(&x, &y)| (f64::from(x) - f64::from(y)).abs())
228+ .sum::<f64>()
229+ / a.len() as f64
230+}
231+
232+fn main() {
233+ let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument"));
234+ let stream = dir.join("key.ivf");
235+ let reference = dir.join("av1_ref.yuv");
236+ let status = Command::new("ffmpeg")
237+ .args(["-y", "-loglevel", "error", "-f", "lavfi", "-i"])
238+ .arg("testsrc2=size=320x240:rate=30")
239+ .args(["-frames:v", "1", "-c:v", "libsvtav1", "-f", "ivf"])
240+ .arg(&stream)
241+ .status()
242+ .expect("run ffmpeg");
243+ assert!(status.success());
244+ let status = Command::new("ffmpeg")
245+ .args(["-y", "-loglevel", "error", "-i"])
246+ .arg(&stream)
247+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"])
248+ .arg(&reference)
249+ .status()
250+ .expect("run ffmpeg");
251+ assert!(status.success());
252+
253+ let ivf = fs::read(&stream).expect("read ivf");
254+ let header_len = u16::from_le_bytes([ivf[6], ivf[7]]) as usize;
255+ let frame_len =
256+ u32::from_le_bytes(ivf[header_len..header_len + 4].try_into().unwrap()) as usize;
257+ let data = &ivf[header_len + 12..header_len + 12 + frame_len];
258+
259+ let mut parser = Av1Parser::new();
260+ let obus = parser
261+ .parse_temporal_unit(data)
262+ .expect("parse temporal unit");
263+ let mut seq = None;
264+ let mut frame_obu = None;
265+ for obu in obus {
266+ match obu.kind {
267+ ObuKind::SequenceHeader(s) => seq = Some(*s),
268+ ObuKind::Frame(h, tiles) => frame_obu = Some((*h, tiles)),
269+ _ => {}
270+ }
271+ }
272+ let seq = seq.expect("sequence header");
273+ let (header, tiles) = frame_obu.expect("frame OBU");
274+ assert_eq!(header.frame_type, FrameType::Key);
275+
276+ let offsets: Vec<u32> = tiles.iter().map(|t| t.offset as u32).collect();
277+ let sizes: Vec<u32> = tiles.iter().map(|t| t.size as u32).collect();
278+ let plain_seq = sequence(&seq);
279+ let plain_frame = frame(&header, &seq);
280+ let (w, h) = (header.upscaled_width, header.frame_height);
281+
282+ let gpu = Gpu::open().expect("open GPU");
283+ println!("device: {}", gpu.device_name());
284+ let cfg = Av1DecodeConfig {
285+ max_width: w,
286+ max_height: h,
287+ max_dpb_slots: 9,
288+ };
289+ let mut session = Av1DecodeSession::new(&gpu, &cfg).expect("decode session");
290+ session
291+ .set_sequence_header(&plain_seq)
292+ .expect("sequence header");
293+ let pic = Av1DecodePicture {
294+ header: &plain_frame,
295+ setup_slot: 0,
296+ ref_frame_slot: [-1; 7],
297+ refs: &[],
298+ tile_data: data,
299+ tile_offsets: &offsets,
300+ tile_sizes: &sizes,
301+ };
302+ session.decode(&pic).expect("decode");
303+ let (y, uv) = session.read_output(w, h).expect("read output");
304+
305+ let reference = fs::read(&reference).expect("read reference");
306+ let luma = (w * h) as usize;
307+ let chroma = luma / 4;
308+ let ref_uv: Vec<u8> = reference[luma..luma + chroma]
309+ .iter()
310+ .zip(&reference[luma + chroma..luma + 2 * chroma])
311+ .flat_map(|(&u, &v)| [u, v])
312+ .collect();
313+ println!(
314+ "mean abs diff Y: {:.6}",
315+ mean_abs_diff(&y, &reference[..luma])
316+ );
317+ println!("mean abs diff UV: {:.6}", mean_abs_diff(&uv, &ref_uv));
318+}
shims/vk-video-ffi/src/av1_decode.rsadded+1405 -0
@@ -0,0 +1,1405 @@
1+use std::ffi::c_void;
2+
3+use vulkanalia::prelude::v1_3::*;
4+use vulkanalia::vk::{
5+ KhrVideoDecodeQueueExtensionDeviceCommands, KhrVideoQueueExtensionDeviceCommands,
6+ KhrVideoQueueExtensionInstanceCommands,
7+};
8+
9+use crate::h264_decode::{Buffer, Image, align_u64, allocate, new_buffer, new_image, submit};
10+use crate::h264_encode::{
11+ NV12, PLANE_0, PLANE_1, align, alloc_cb, barrier, copy_region, create_pool, picture_resource,
12+ vk, zeroed,
13+};
14+use crate::{Error, Gpu};
15+
16+/// Settings fixed for the life of a decode session.
17+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18+pub struct Av1DecodeConfig {
19+ /// Largest frame width in luma samples.
20+ pub max_width: u32,
21+ /// Largest frame height in luma samples.
22+ pub max_height: u32,
23+ /// DPB slots, including the slot the picture is decoded into.
24+ pub max_dpb_slots: u32,
25+}
26+
27+/// Frame type, values as in the spec and `StdVideoAV1FrameType`.
28+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29+#[repr(u8)]
30+pub enum Av1FrameType {
31+ /// KEY_FRAME.
32+ Key = 0,
33+ /// INTER_FRAME.
34+ Inter = 1,
35+ /// INTRA_ONLY_FRAME.
36+ IntraOnly = 2,
37+ /// SWITCH_FRAME.
38+ Switch = 3,
39+}
40+
41+/// Sub-pixel interpolation filter, as `StdVideoAV1InterpolationFilter`.
42+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43+#[repr(u8)]
44+pub enum Av1InterpolationFilter {
45+ /// EIGHTTAP.
46+ EightTap = 0,
47+ /// EIGHTTAP_SMOOTH.
48+ EightTapSmooth = 1,
49+ /// EIGHTTAP_SHARP.
50+ EightTapSharp = 2,
51+ /// BILINEAR.
52+ Bilinear = 3,
53+ /// SWITCHABLE.
54+ Switchable = 4,
55+}
56+
57+/// Transform size mode, as `StdVideoAV1TxMode`.
58+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59+#[repr(u8)]
60+pub enum Av1TxMode {
61+ /// ONLY_4X4.
62+ Only4x4 = 0,
63+ /// TX_MODE_LARGEST.
64+ Largest = 1,
65+ /// TX_MODE_SELECT.
66+ Select = 2,
67+}
68+
69+/// Loop restoration type of one plane, as `StdVideoAV1FrameRestorationType`.
70+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71+#[repr(u8)]
72+pub enum Av1Restoration {
73+ /// RESTORE_NONE.
74+ None = 0,
75+ /// RESTORE_WIENER.
76+ Wiener = 1,
77+ /// RESTORE_SGRPROJ.
78+ Sgrproj = 2,
79+ /// RESTORE_SWITCHABLE.
80+ Switchable = 3,
81+}
82+
83+/// Global motion model, as `GmType`.
84+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
85+#[repr(u8)]
86+pub enum Av1WarpModel {
87+ /// IDENTITY.
88+ #[default]
89+ Identity = 0,
90+ /// TRANSLATION.
91+ Translation = 1,
92+ /// ROTZOOM.
93+ Rotzoom = 2,
94+ /// AFFINE.
95+ Affine = 3,
96+}
97+
98+/// Color configuration of a sequence header (spec 5.5.2).
99+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100+pub struct Av1ColorConfig {
101+ /// BitDepth, 8 for this decoder.
102+ pub bit_depth: u8,
103+ /// mono_chrome, false for this decoder.
104+ pub mono_chrome: bool,
105+ /// color_range.
106+ pub color_range: bool,
107+ /// separate_uv_delta_q.
108+ pub separate_uv_delta_q: bool,
109+ /// subsampling_x, 1 for this decoder.
110+ pub subsampling_x: u8,
111+ /// subsampling_y, 1 for this decoder.
112+ pub subsampling_y: u8,
113+ /// color_primaries (H.273 code point).
114+ pub color_primaries: u8,
115+ /// transfer_characteristics (H.273 code point).
116+ pub transfer_characteristics: u8,
117+ /// matrix_coefficients (H.273 code point).
118+ pub matrix_coefficients: u8,
119+ /// chroma_sample_position.
120+ pub chroma_sample_position: u8,
121+}
122+
123+/// Timing info of a sequence header (spec 5.5.3).
124+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125+pub struct Av1TimingInfo {
126+ /// equal_picture_interval.
127+ pub equal_picture_interval: bool,
128+ /// num_units_in_display_tick.
129+ pub num_units_in_display_tick: u32,
130+ /// time_scale.
131+ pub time_scale: u32,
132+ /// num_ticks_per_picture_minus_1.
133+ pub num_ticks_per_picture_minus_1: u32,
134+}
135+
136+/// Sequence header fields a decoder needs (names follow `StdVideoAV1SequenceHeader`).
137+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138+pub struct Av1SequenceHeader {
139+ /// seq_profile, 0 for this decoder.
140+ pub seq_profile: u8,
141+ /// still_picture.
142+ pub still_picture: bool,
143+ /// reduced_still_picture_header.
144+ pub reduced_still_picture_header: bool,
145+ /// timing_info when present.
146+ pub timing_info: Option<Av1TimingInfo>,
147+ /// initial_display_delay_present_flag.
148+ pub initial_display_delay_present: bool,
149+ /// frame_width_bits_minus_1.
150+ pub frame_width_bits_minus_1: u8,
151+ /// frame_height_bits_minus_1.
152+ pub frame_height_bits_minus_1: u8,
153+ /// max_frame_width_minus_1.
154+ pub max_frame_width_minus_1: u16,
155+ /// max_frame_height_minus_1.
156+ pub max_frame_height_minus_1: u16,
157+ /// frame_id_numbers_present_flag.
158+ pub frame_id_numbers_present: bool,
159+ /// delta_frame_id_length_minus_2.
160+ pub delta_frame_id_length_minus_2: u8,
161+ /// additional_frame_id_length_minus_1.
162+ pub additional_frame_id_length_minus_1: u8,
163+ /// order_hint_bits_minus_1.
164+ pub order_hint_bits_minus_1: u8,
165+ /// seq_force_integer_mv.
166+ pub seq_force_integer_mv: u8,
167+ /// seq_force_screen_content_tools.
168+ pub seq_force_screen_content_tools: u8,
169+ /// use_128x128_superblock.
170+ pub use_128x128_superblock: bool,
171+ /// enable_filter_intra.
172+ pub enable_filter_intra: bool,
173+ /// enable_intra_edge_filter.
174+ pub enable_intra_edge_filter: bool,
175+ /// enable_interintra_compound.
176+ pub enable_interintra_compound: bool,
177+ /// enable_masked_compound.
178+ pub enable_masked_compound: bool,
179+ /// enable_warped_motion.
180+ pub enable_warped_motion: bool,
181+ /// enable_dual_filter.
182+ pub enable_dual_filter: bool,
183+ /// enable_order_hint.
184+ pub enable_order_hint: bool,
185+ /// enable_jnt_comp.
186+ pub enable_jnt_comp: bool,
187+ /// enable_ref_frame_mvs.
188+ pub enable_ref_frame_mvs: bool,
189+ /// enable_superres.
190+ pub enable_superres: bool,
191+ /// enable_cdef.
192+ pub enable_cdef: bool,
193+ /// enable_restoration.
194+ pub enable_restoration: bool,
195+ /// Color configuration.
196+ pub color_config: Av1ColorConfig,
197+ /// film_grain_params_present.
198+ pub film_grain_params_present: bool,
199+}
200+
201+/// Tile layout of a frame (names follow `StdVideoAV1TileInfo`).
202+#[derive(Debug, Clone, PartialEq, Eq)]
203+pub struct Av1TileInfo {
204+ /// uniform_tile_spacing_flag.
205+ pub uniform_spacing: bool,
206+ /// TileCols.
207+ pub cols: u8,
208+ /// TileRows.
209+ pub rows: u8,
210+ /// MiColStarts, TileCols + 1 entries, in mi units.
211+ pub mi_col_starts: Vec<u16>,
212+ /// MiRowStarts, TileRows + 1 entries, in mi units.
213+ pub mi_row_starts: Vec<u16>,
214+ /// width_in_sbs_minus_1 per tile column, TileCols entries.
215+ pub width_in_sbs_minus_1: Vec<u16>,
216+ /// height_in_sbs_minus_1 per tile row, TileRows entries.
217+ pub height_in_sbs_minus_1: Vec<u16>,
218+ /// context_update_tile_id.
219+ pub context_update_tile_id: u16,
220+ /// tile_size_bytes_minus_1.
221+ pub tile_size_bytes_minus_1: u8,
222+}
223+
224+/// Quantizer parameters of a frame.
225+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226+pub struct Av1Quantization {
227+ /// base_q_idx.
228+ pub base_q_idx: u8,
229+ /// DeltaQYDc.
230+ pub delta_q_y_dc: i8,
231+ /// DeltaQUDc.
232+ pub delta_q_u_dc: i8,
233+ /// DeltaQUAc.
234+ pub delta_q_u_ac: i8,
235+ /// DeltaQVDc.
236+ pub delta_q_v_dc: i8,
237+ /// DeltaQVAc.
238+ pub delta_q_v_ac: i8,
239+ /// using_qmatrix.
240+ pub using_qmatrix: bool,
241+ /// qm_y.
242+ pub qm_y: u8,
243+ /// qm_u.
244+ pub qm_u: u8,
245+ /// qm_v.
246+ pub qm_v: u8,
247+}
248+
249+/// Segmentation parameters of a frame.
250+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251+pub struct Av1Segmentation {
252+ /// segmentation_enabled.
253+ pub enabled: bool,
254+ /// segmentation_update_map.
255+ pub update_map: bool,
256+ /// segmentation_temporal_update.
257+ pub temporal_update: bool,
258+ /// segmentation_update_data.
259+ pub update_data: bool,
260+ /// FeatureEnabled[segment][feature].
261+ pub feature_enabled: [[bool; 8]; 8],
262+ /// FeatureData[segment][feature].
263+ pub feature_data: [[i16; 8]; 8],
264+}
265+
266+/// Delta quantizer and delta loop filter parameters of a frame.
267+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268+pub struct Av1DeltaParams {
269+ /// delta_q_present.
270+ pub q_present: bool,
271+ /// delta_q_res, as coded (log2).
272+ pub q_res: u8,
273+ /// delta_lf_present.
274+ pub lf_present: bool,
275+ /// delta_lf_res, as coded (log2).
276+ pub lf_res: u8,
277+ /// delta_lf_multi.
278+ pub lf_multi: bool,
279+}
280+
281+/// Loop filter parameters of a frame.
282+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283+pub struct Av1LoopFilter {
284+ /// loop_filter_level[4].
285+ pub level: [u8; 4],
286+ /// loop_filter_sharpness.
287+ pub sharpness: u8,
288+ /// loop_filter_delta_enabled.
289+ pub delta_enabled: bool,
290+ /// loop_filter_delta_update.
291+ pub delta_update: bool,
292+ /// loop_filter_ref_deltas, indexed by reference name (0 intra .. 7 ALTREF).
293+ pub ref_deltas: [i8; 8],
294+ /// loop_filter_mode_deltas.
295+ pub mode_deltas: [i8; 2],
296+}
297+
298+/// CDEF parameters of a frame.
299+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300+pub struct Av1Cdef {
301+ /// cdef_damping_minus_3.
302+ pub damping_minus_3: u8,
303+ /// cdef_bits.
304+ pub bits: u8,
305+ /// cdef_y_pri_strength.
306+ pub y_pri: [u8; 8],
307+ /// cdef_y_sec_strength, after the 3 becomes 4 adjustment.
308+ pub y_sec: [u8; 8],
309+ /// cdef_uv_pri_strength.
310+ pub uv_pri: [u8; 8],
311+ /// cdef_uv_sec_strength, after the 3 becomes 4 adjustment.
312+ pub uv_sec: [u8; 8],
313+}
314+
315+/// Loop restoration parameters of a frame.
316+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
317+pub struct Av1LoopRestoration {
318+ /// FrameRestorationType per plane.
319+ pub frame_restoration_type: [Av1Restoration; 3],
320+ /// LoopRestorationSize per plane, in samples.
321+ pub loop_restoration_size: [u16; 3],
322+}
323+
324+/// Global motion of one reference.
325+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
326+pub struct Av1GlobalMotion {
327+ /// GmType.
328+ pub model: Av1WarpModel,
329+ /// gm_params[6].
330+ pub params: [i32; 6],
331+}
332+
333+/// Frame header fields a decoder needs (names follow `StdVideoDecodeAV1PictureInfo`).
334+///
335+/// Arrays indexed by reference name use index 0 for INTRA_FRAME and 1 to 7 for LAST to ALTREF.
336+#[derive(Debug, Clone, PartialEq, Eq)]
337+pub struct Av1FrameHeader {
338+ /// frame_type.
339+ pub frame_type: Av1FrameType,
340+ /// show_frame.
341+ pub show_frame: bool,
342+ /// showable_frame.
343+ pub showable_frame: bool,
344+ /// error_resilient_mode.
345+ pub error_resilient_mode: bool,
346+ /// disable_cdf_update.
347+ pub disable_cdf_update: bool,
348+ /// allow_screen_content_tools.
349+ pub allow_screen_content_tools: bool,
350+ /// force_integer_mv.
351+ pub force_integer_mv: bool,
352+ /// current_frame_id.
353+ pub current_frame_id: u32,
354+ /// frame_size_override_flag.
355+ pub frame_size_override_flag: bool,
356+ /// OrderHint.
357+ pub order_hint: u8,
358+ /// primary_ref_frame.
359+ pub primary_ref_frame: u8,
360+ /// refresh_frame_flags.
361+ pub refresh_frame_flags: u8,
362+ /// FrameWidth, after superres downscaling.
363+ pub frame_width: u32,
364+ /// FrameHeight.
365+ pub frame_height: u32,
366+ /// UpscaledWidth.
367+ pub upscaled_width: u32,
368+ /// RenderWidth.
369+ pub render_width: u32,
370+ /// RenderHeight.
371+ pub render_height: u32,
372+ /// use_superres.
373+ pub use_superres: bool,
374+ /// SuperresDenom, 8 to 16.
375+ pub superres_denom: u8,
376+ /// allow_intrabc.
377+ pub allow_intrabc: bool,
378+ /// allow_high_precision_mv.
379+ pub allow_high_precision_mv: bool,
380+ /// is_motion_mode_switchable.
381+ pub is_motion_mode_switchable: bool,
382+ /// use_ref_frame_mvs.
383+ pub use_ref_frame_mvs: bool,
384+ /// frame_refs_short_signaling.
385+ pub frame_refs_short_signaling: bool,
386+ /// disable_frame_end_update_cdf.
387+ pub disable_frame_end_update_cdf: bool,
388+ /// reference_select.
389+ pub reference_select: bool,
390+ /// skip_mode_present.
391+ pub skip_mode_present: bool,
392+ /// allow_warped_motion.
393+ pub allow_warped_motion: bool,
394+ /// reduced_tx_set.
395+ pub reduced_tx_set: bool,
396+ /// interpolation_filter.
397+ pub interpolation_filter: Av1InterpolationFilter,
398+ /// TxMode.
399+ pub tx_mode: Av1TxMode,
400+ /// Tile layout.
401+ pub tile_info: Av1TileInfo,
402+ /// Quantizer parameters.
403+ pub quantization: Av1Quantization,
404+ /// Segmentation parameters.
405+ pub segmentation: Av1Segmentation,
406+ /// Delta quantizer and delta loop filter parameters.
407+ pub delta: Av1DeltaParams,
408+ /// Loop filter parameters.
409+ pub loop_filter: Av1LoopFilter,
410+ /// CDEF parameters.
411+ pub cdef: Av1Cdef,
412+ /// Loop restoration parameters.
413+ pub loop_restoration: Av1LoopRestoration,
414+ /// Global motion per reference name.
415+ pub global_motion: [Av1GlobalMotion; 8],
416+ /// OrderHints per reference name.
417+ pub order_hints: [u8; 8],
418+ /// SkipModeFrame[2].
419+ pub skip_mode_frame: [u8; 2],
420+ /// expectedFrameId per reference name, used with frame_id_numbers_present.
421+ pub expected_frame_id: [u32; 8],
422+ /// apply_grain, unsupported by this decoder.
423+ pub apply_grain: bool,
424+}
425+
426+/// A DPB slot holding a reference picture, with the state AV1 keeps per reference.
427+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
428+pub struct Av1RefSlot {
429+ /// DPB slot index.
430+ pub slot: u32,
431+ /// Frame type of the picture in the slot.
432+ pub frame_type: Av1FrameType,
433+ /// OrderHint of the picture in the slot.
434+ pub order_hint: u8,
435+ /// SavedOrderHints of the picture in the slot, per reference name.
436+ pub ref_order_hints: [u8; 8],
437+ /// RefFrameSignBias mask recorded when the picture was decoded.
438+ pub sign_bias: u8,
439+ /// disable_frame_end_update_cdf of the picture in the slot.
440+ pub disable_frame_end_update_cdf: bool,
441+ /// segmentation_enabled of the picture in the slot.
442+ pub segmentation_enabled: bool,
443+}
444+
445+/// One frame to decode, with the tile data as one buffer.
446+#[derive(Debug, Clone, Copy)]
447+pub struct Av1DecodePicture<'a> {
448+ /// Frame header.
449+ pub header: &'a Av1FrameHeader,
450+ /// DPB slot the picture is decoded into.
451+ pub setup_slot: u32,
452+ /// Slot of each reference name LAST to ALTREF, -1 when unused.
453+ pub ref_frame_slot: [i32; 7],
454+ /// Reference slots, each with a distinct slot index.
455+ pub refs: &'a [Av1RefSlot],
456+ /// Tile data, all tile groups concatenated.
457+ pub tile_data: &'a [u8],
458+ /// Byte offset of each tile in tile_data.
459+ pub tile_offsets: &'a [u32],
460+ /// Byte size of each tile.
461+ pub tile_sizes: &'a [u32],
462+}
463+
464+struct Caps {
465+ std_header_version: vk::ExtensionProperties,
466+ max_extent: vk::Extent2D,
467+ size_align: u64,
468+ max_dpb_slots: u32,
469+ max_active_refs: u32,
470+ distinct: bool,
471+}
472+
473+struct Profile {
474+ info: vk::VideoProfileInfoKHR,
475+ av1: vk::VideoDecodeAV1ProfileInfoKHR,
476+}
477+
478+impl Profile {
479+ fn new() -> Box<Self> {
480+ let mut p = Box::new(Profile {
481+ info: vk::VideoProfileInfoKHR::builder()
482+ .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_AV1)
483+ .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
484+ .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
485+ .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
486+ .build(),
487+ av1: vk::VideoDecodeAV1ProfileInfoKHR::builder()
488+ .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN)
489+ .film_grain_support(false)
490+ .build(),
491+ });
492+ p.info.next = &p.av1 as *const _ as *const c_void;
493+ p
494+ }
495+}
496+
497+/// An AV1 Main 8-bit 4:2:0 Vulkan Video decode session: NV12 DPB images per slot and a separate NV12 output image.
498+pub struct Av1DecodeSession {
499+ gpu: Gpu,
500+ family: u32,
501+ queue: vk::Queue,
502+ graphics: u32,
503+ graphics_queue: vk::Queue,
504+ video_session: vk::VideoSessionKHR,
505+ session_memories: Vec<vk::DeviceMemory>,
506+ params: Option<vk::VideoSessionParametersKHR>,
507+ sequence: Option<Av1SequenceHeader>,
508+ max_extent: vk::Extent2D,
509+ max_dpb_slots: u32,
510+ max_active_refs: u32,
511+ size_align: u64,
512+ dpb: Vec<Image>,
513+ output: Image,
514+ bitstream: Buffer,
515+ readback: Buffer,
516+ decode_pool: vk::CommandPool,
517+ decode_cb: vk::CommandBuffer,
518+ graphics_pool: vk::CommandPool,
519+ graphics_cb: vk::CommandBuffer,
520+ fence: vk::Fence,
521+ coded: bool,
522+}
523+
524+impl Av1DecodeSession {
525+ /// Creates a session with its DPB, bitstream and readback buffers.
526+ pub fn new(gpu: &Gpu, cfg: &Av1DecodeConfig) -> Result<Self, Error> {
527+ if cfg.max_width == 0 || cfg.max_height == 0 || cfg.max_dpb_slots == 0 {
528+ return Err(Error::Invalid(
529+ "decode size or DPB slot count is zero".into(),
530+ ));
531+ }
532+ let family = gpu
533+ .decode_family()
534+ .ok_or_else(|| Error::Unsupported("AV1 decode queue family".into()))?;
535+ let graphics = gpu
536+ .graphics_family()
537+ .ok_or_else(|| Error::Unsupported("graphics queue family for readback".into()))?;
538+ if !gpu
539+ .device()
540+ .extensions()
541+ .contains(&vk::KHR_VIDEO_DECODE_AV1_EXTENSION.name)
542+ {
543+ return Err(Error::Unsupported("AV1 decode".into()));
544+ }
545+ let width = align(cfg.max_width, 16);
546+ let height = align(cfg.max_height, 16);
547+ let profile = Profile::new();
548+ let caps = query_caps(gpu, &profile.info)?;
549+ if width > caps.max_extent.width
550+ || height > caps.max_extent.height
551+ || cfg.max_dpb_slots > caps.max_dpb_slots
552+ {
553+ return Err(Error::Unsupported(format!("AV1 decode {width}x{height}")));
554+ }
555+ if !caps.distinct {
556+ return Err(Error::Unsupported(
557+ "AV1 decode with DPB and output in one image".into(),
558+ ));
559+ }
560+ let max_active = caps.max_active_refs.min(cfg.max_dpb_slots);
561+
562+ let queue = unsafe { gpu.device().get_device_queue(family, 0) };
563+ let graphics_queue = unsafe { gpu.device().get_device_queue(graphics, 0) };
564+ let mut s = Av1DecodeSession {
565+ gpu: gpu.clone(),
566+ family,
567+ queue,
568+ graphics,
569+ graphics_queue,
570+ video_session: Default::default(),
571+ session_memories: Vec::new(),
572+ params: None,
573+ sequence: None,
574+ max_extent: vk::Extent2D { width, height },
575+ max_dpb_slots: cfg.max_dpb_slots,
576+ max_active_refs: max_active,
577+ size_align: caps.size_align,
578+ dpb: Vec::new(),
579+ output: Default::default(),
580+ bitstream: Default::default(),
581+ readback: Default::default(),
582+ decode_pool: Default::default(),
583+ decode_cb: Default::default(),
584+ graphics_pool: Default::default(),
585+ graphics_cb: Default::default(),
586+ fence: Default::default(),
587+ coded: false,
588+ };
589+ s.create_session(&profile, &caps, max_active)?;
590+ s.create_resources(&profile, &caps)?;
591+ s.init_dpb()?;
592+ Ok(s)
593+ }
594+
595+ /// Replaces the session parameters with the given sequence header.
596+ pub fn set_sequence_header(&mut self, seq: &Av1SequenceHeader) -> Result<(), Error> {
597+ let c = &seq.color_config;
598+ if seq.seq_profile != 0
599+ || c.bit_depth != 8
600+ || c.mono_chrome
601+ || c.subsampling_x != 1
602+ || c.subsampling_y != 1
603+ {
604+ return Err(Error::Unsupported(
605+ "AV1 sequence other than Main 8-bit 4:2:0".into(),
606+ ));
607+ }
608+ let gpu = self.gpu.clone();
609+ let d = gpu.device();
610+ let color = std_color(c);
611+ let timing = seq.timing_info.as_ref().map(std_timing);
612+
613+ let mut flags = zeroed::<vk::video::StdVideoAV1SequenceHeaderFlags>();
614+ flags.set_still_picture(u32::from(seq.still_picture));
615+ flags.set_reduced_still_picture_header(u32::from(seq.reduced_still_picture_header));
616+ flags.set_use_128x128_superblock(u32::from(seq.use_128x128_superblock));
617+ flags.set_enable_filter_intra(u32::from(seq.enable_filter_intra));
618+ flags.set_enable_intra_edge_filter(u32::from(seq.enable_intra_edge_filter));
619+ flags.set_enable_interintra_compound(u32::from(seq.enable_interintra_compound));
620+ flags.set_enable_masked_compound(u32::from(seq.enable_masked_compound));
621+ flags.set_enable_warped_motion(u32::from(seq.enable_warped_motion));
622+ flags.set_enable_dual_filter(u32::from(seq.enable_dual_filter));
623+ flags.set_enable_order_hint(u32::from(seq.enable_order_hint));
624+ flags.set_enable_jnt_comp(u32::from(seq.enable_jnt_comp));
625+ flags.set_enable_ref_frame_mvs(u32::from(seq.enable_ref_frame_mvs));
626+ flags.set_frame_id_numbers_present_flag(u32::from(seq.frame_id_numbers_present));
627+ flags.set_enable_superres(u32::from(seq.enable_superres));
628+ flags.set_enable_cdef(u32::from(seq.enable_cdef));
629+ flags.set_enable_restoration(u32::from(seq.enable_restoration));
630+ flags.set_film_grain_params_present(u32::from(seq.film_grain_params_present));
631+ flags.set_timing_info_present_flag(u32::from(timing.is_some()));
632+ flags.set_initial_display_delay_present_flag(u32::from(seq.initial_display_delay_present));
633+ let std_seq = vk::video::StdVideoAV1SequenceHeader {
634+ flags,
635+ seq_profile: vk::video::STD_VIDEO_AV1_PROFILE_MAIN,
636+ frame_width_bits_minus_1: seq.frame_width_bits_minus_1,
637+ frame_height_bits_minus_1: seq.frame_height_bits_minus_1,
638+ max_frame_width_minus_1: seq.max_frame_width_minus_1,
639+ max_frame_height_minus_1: seq.max_frame_height_minus_1,
640+ delta_frame_id_length_minus_2: seq.delta_frame_id_length_minus_2,
641+ additional_frame_id_length_minus_1: seq.additional_frame_id_length_minus_1,
642+ order_hint_bits_minus_1: seq.order_hint_bits_minus_1,
643+ seq_force_integer_mv: seq.seq_force_integer_mv,
644+ seq_force_screen_content_tools: seq.seq_force_screen_content_tools,
645+ reserved1: [0; 5],
646+ pColorConfig: &color,
647+ pTimingInfo: timing.as_ref().map_or(std::ptr::null(), |t| t as *const _),
648+ };
649+
650+ let mut av1 = vk::VideoDecodeAV1SessionParametersCreateInfoKHR::builder()
651+ .std_sequence_header(&std_seq)
652+ .build();
653+ let info = vk::VideoSessionParametersCreateInfoKHR::builder()
654+ .video_session(self.video_session)
655+ .push_next(&mut av1)
656+ .build();
657+ let params = unsafe {
658+ vk(
659+ d.create_video_session_parameters_khr(&info, None),
660+ "vkCreateVideoSessionParametersKHR",
661+ )?
662+ };
663+ if let Some(old) = self.params.replace(params) {
664+ unsafe { d.destroy_video_session_parameters_khr(old, None) };
665+ }
666+ self.sequence = Some(*seq);
667+ Ok(())
668+ }
669+
670+ /// Decodes one frame into its setup slot, referencing the given DPB slots.
671+ pub fn decode(&mut self, pic: &Av1DecodePicture) -> Result<(), Error> {
672+ let params = self
673+ .params
674+ .ok_or_else(|| Error::Invalid("sequence header not set".into()))?;
675+ let seq = self
676+ .sequence
677+ .ok_or_else(|| Error::Invalid("sequence header not set".into()))?;
678+ let h = pic.header;
679+ if h.apply_grain {
680+ return Err(Error::Unsupported("AV1 film grain".into()));
681+ }
682+ let extent = vk::Extent2D {
683+ width: h.upscaled_width,
684+ height: h.frame_height,
685+ };
686+ if extent.width == 0
687+ || extent.height == 0
688+ || extent.width > self.max_extent.width
689+ || extent.height > self.max_extent.height
690+ {
691+ return Err(Error::Invalid("frame size".into()));
692+ }
693+ let tiles = &h.tile_info;
694+ let cols = tiles.cols as usize;
695+ let rows = tiles.rows as usize;
696+ let count = cols * rows;
697+ if count == 0
698+ || pic.tile_offsets.len() != count
699+ || pic.tile_sizes.len() != count
700+ || tiles.mi_col_starts.len() != cols + 1
701+ || tiles.mi_row_starts.len() != rows + 1
702+ || tiles.width_in_sbs_minus_1.len() != cols
703+ || tiles.height_in_sbs_minus_1.len() != rows
704+ {
705+ return Err(Error::Invalid("tile layout".into()));
706+ }
707+ if pic
708+ .tile_offsets
709+ .iter()
710+ .zip(pic.tile_sizes)
711+ .any(|(&o, &s)| u64::from(o) + u64::from(s) > pic.tile_data.len() as u64)
712+ {
713+ return Err(Error::Invalid("tile outside tile data".into()));
714+ }
715+ if pic.tile_data.len() as u64 > self.bitstream.size {
716+ return Err(Error::Invalid(
717+ "tile data larger than bitstream buffer".into(),
718+ ));
719+ }
720+ if pic.setup_slot >= self.max_dpb_slots {
721+ return Err(Error::Invalid("setup DPB slot".into()));
722+ }
723+ if pic.refs.len() > self.max_active_refs as usize {
724+ return Err(Error::Invalid("too many reference pictures".into()));
725+ }
726+ for (i, r) in pic.refs.iter().enumerate() {
727+ if r.slot >= self.max_dpb_slots
728+ || r.slot == pic.setup_slot
729+ || pic.refs[..i].iter().any(|o| o.slot == r.slot)
730+ {
731+ return Err(Error::Invalid("reference DPB slot".into()));
732+ }
733+ }
734+ if pic
735+ .ref_frame_slot
736+ .iter()
737+ .any(|&s| s >= 0 && !pic.refs.iter().any(|r| i32::try_from(r.slot) == Ok(s)))
738+ {
739+ return Err(Error::Invalid(
740+ "reference name without a reference slot".into(),
741+ ));
742+ }
743+
744+ let ptr = self
745+ .bitstream
746+ .ptr
747+ .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?;
748+ let buf = unsafe { std::slice::from_raw_parts_mut(ptr, self.bitstream.size as usize) };
749+ buf[..pic.tile_data.len()].copy_from_slice(pic.tile_data);
750+ let range = align_u64(pic.tile_data.len() as u64, self.size_align);
751+
752+ let gpu = self.gpu.clone();
753+ let d = gpu.device();
754+ let cb = self.decode_cb;
755+ let pr: Vec<vk::VideoPictureResourceInfoKHR> = self
756+ .dpb
757+ .iter()
758+ .map(|i| picture_resource(i.view, extent))
759+ .collect();
760+
761+ let setup_std = ref_info(
762+ h.frame_type,
763+ h.order_hint,
764+ sign_bias_mask(&seq, h.order_hint, &h.order_hints),
765+ h.order_hints,
766+ h.disable_frame_end_update_cdf,
767+ h.segmentation.enabled,
768+ );
769+ let mut setup_dpb = vk::VideoDecodeAV1DpbSlotInfoKHR::builder()
770+ .std_reference_info(&setup_std)
771+ .build();
772+ let setup = vk::VideoReferenceSlotInfoKHR::builder()
773+ .slot_index(pic.setup_slot as i32)
774+ .picture_resource(&pr[pic.setup_slot as usize])
775+ .push_next(&mut setup_dpb)
776+ .build();
777+
778+ let ref_std: Vec<vk::video::StdVideoDecodeAV1ReferenceInfo> = pic
779+ .refs
780+ .iter()
781+ .map(|r| {
782+ ref_info(
783+ r.frame_type,
784+ r.order_hint,
785+ r.sign_bias,
786+ r.ref_order_hints,
787+ r.disable_frame_end_update_cdf,
788+ r.segmentation_enabled,
789+ )
790+ })
791+ .collect();
792+ let mut ref_dpb: Vec<vk::VideoDecodeAV1DpbSlotInfoKHR> = ref_std
793+ .iter()
794+ .map(|s| {
795+ vk::VideoDecodeAV1DpbSlotInfoKHR::builder()
796+ .std_reference_info(s)
797+ .build()
798+ })
799+ .collect();
800+ let refs: Vec<vk::VideoReferenceSlotInfoKHR> = pic
801+ .refs
802+ .iter()
803+ .zip(ref_dpb.iter_mut())
804+ .map(|(r, dpb)| {
805+ vk::VideoReferenceSlotInfoKHR::builder()
806+ .slot_index(r.slot as i32)
807+ .picture_resource(&pr[r.slot as usize])
808+ .push_next(dpb)
809+ .build()
810+ })
811+ .collect();
812+
813+ let mut begin: Vec<vk::VideoReferenceSlotInfoKHR> = vec![
814+ vk::VideoReferenceSlotInfoKHR::builder()
815+ .slot_index(-1)
816+ .picture_resource(&pr[pic.setup_slot as usize])
817+ .build(),
818+ ];
819+ begin.extend(pic.refs.iter().map(|r| {
820+ vk::VideoReferenceSlotInfoKHR::builder()
821+ .slot_index(r.slot as i32)
822+ .picture_resource(&pr[r.slot as usize])
823+ .build()
824+ }));
825+
826+ let tile = std_tile(tiles);
827+ let quant = std_quant(&h.quantization);
828+ let seg = std_segmentation(&h.segmentation);
829+ let lf = std_loop_filter(&h.loop_filter);
830+ let cdef = std_cdef(&h.cdef);
831+ let lr = std_loop_restoration(&h.loop_restoration);
832+ let gm = std_global_motion(&h.global_motion);
833+
834+ let mut std_pic = zeroed::<vk::video::StdVideoDecodeAV1PictureInfo>();
835+ std_pic.flags = picture_flags(h);
836+ std_pic.frame_type = std_frame_type(h.frame_type);
837+ std_pic.current_frame_id = h.current_frame_id;
838+ std_pic.OrderHint = h.order_hint;
839+ std_pic.primary_ref_frame = h.primary_ref_frame;
840+ std_pic.refresh_frame_flags = h.refresh_frame_flags;
841+ std_pic.interpolation_filter = std_interpolation(h.interpolation_filter);
842+ std_pic.TxMode = std_tx_mode(h.tx_mode);
843+ std_pic.delta_q_res = h.delta.q_res;
844+ std_pic.delta_lf_res = h.delta.lf_res;
845+ std_pic.SkipModeFrame = h.skip_mode_frame;
846+ std_pic.coded_denom = if h.use_superres {
847+ h.superres_denom.saturating_sub(9)
848+ } else {
849+ 0
850+ };
851+ std_pic.OrderHints = h.order_hints;
852+ std_pic.expectedFrameId = h.expected_frame_id;
853+ std_pic.pTileInfo = &tile;
854+ std_pic.pQuantization = &quant;
855+ std_pic.pSegmentation = &seg;
856+ std_pic.pLoopFilter = &lf;
857+ std_pic.pCDEF = &cdef;
858+ std_pic.pLoopRestoration = &lr;
859+ std_pic.pGlobalMotion = &gm;
860+
861+ let mut av1 = vk::VideoDecodeAV1PictureInfoKHR {
862+ std_picture_info: &std_pic,
863+ reference_name_slot_indices: pic.ref_frame_slot,
864+ frame_header_offset: 0,
865+ tile_count: count as u32,
866+ tile_offsets: pic.tile_offsets.as_ptr(),
867+ tile_sizes: pic.tile_sizes.as_ptr(),
868+ ..Default::default()
869+ };
870+ let decode = vk::VideoDecodeInfoKHR::builder()
871+ .src_buffer(self.bitstream.buffer)
872+ .src_buffer_offset(0)
873+ .src_buffer_range(range)
874+ .dst_picture_resource(picture_resource(self.output.view, extent))
875+ .setup_reference_slot(&setup)
876+ .reference_slots(&refs)
877+ .push_next(&mut av1)
878+ .build();
879+ let begin_info = vk::VideoBeginCodingInfoKHR::builder()
880+ .video_session(self.video_session)
881+ .video_session_parameters(params)
882+ .reference_slots(&begin)
883+ .build();
884+ let reset = !self.coded;
885+
886+ unsafe {
887+ let info = vk::CommandBufferBeginInfo::builder()
888+ .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
889+ vk(d.begin_command_buffer(cb, &info), "vkBeginCommandBuffer")?;
890+ barrier(
891+ d,
892+ cb,
893+ self.output.image,
894+ (
895+ vk::ImageLayout::UNDEFINED,
896+ vk::PipelineStageFlags2::NONE,
897+ vk::AccessFlags2::NONE,
898+ ),
899+ (
900+ vk::ImageLayout::VIDEO_DECODE_DST_KHR,
901+ vk::PipelineStageFlags2::ALL_COMMANDS,
902+ vk::AccessFlags2::NONE,
903+ ),
904+ );
905+ d.cmd_begin_video_coding_khr(cb, &begin_info);
906+ if reset {
907+ let control = vk::VideoCodingControlInfoKHR::builder()
908+ .flags(vk::VideoCodingControlFlagsKHR::RESET)
909+ .build();
910+ d.cmd_control_video_coding_khr(cb, &control);
911+ }
912+ d.cmd_decode_video_khr(cb, &decode);
913+ let end = vk::VideoEndCodingInfoKHR::builder().build();
914+ d.cmd_end_video_coding_khr(cb, &end);
915+ vk(d.end_command_buffer(cb), "vkEndCommandBuffer")?;
916+ }
917+ submit(d, self.fence, self.queue, cb)?;
918+ self.coded = true;
919+ Ok(())
920+ }
921+
922+ /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV).
923+ pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> {
924+ if !self.coded {
925+ return Err(Error::Invalid("nothing decoded".into()));
926+ }
927+ if width == 0
928+ || height == 0
929+ || width % 2 != 0
930+ || height % 2 != 0
931+ || width > self.max_extent.width
932+ || height > self.max_extent.height
933+ {
934+ return Err(Error::Invalid("readback size".into()));
935+ }
936+ let gpu = self.gpu.clone();
937+ let d = gpu.device();
938+ let cb = self.graphics_cb;
939+ let image = self.output.image;
940+ let luma = width as usize * height as usize;
941+ let copies = [
942+ copy_region(0, PLANE_0, width, height),
943+ copy_region(luma as u64, PLANE_1, width / 2, height / 2),
944+ ];
945+ unsafe {
946+ let info = vk::CommandBufferBeginInfo::builder()
947+ .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
948+ vk(d.begin_command_buffer(cb, &info), "vkBeginCommandBuffer")?;
949+ barrier(
950+ d,
951+ cb,
952+ image,
953+ (
954+ vk::ImageLayout::VIDEO_DECODE_DST_KHR,
955+ vk::PipelineStageFlags2::ALL_COMMANDS,
956+ vk::AccessFlags2::NONE,
957+ ),
958+ (
959+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
960+ vk::PipelineStageFlags2::COPY,
961+ vk::AccessFlags2::TRANSFER_READ,
962+ ),
963+ );
964+ d.cmd_copy_image_to_buffer(
965+ cb,
966+ image,
967+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
968+ self.readback.buffer,
969+ &copies,
970+ );
971+ barrier(
972+ d,
973+ cb,
974+ image,
975+ (
976+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
977+ vk::PipelineStageFlags2::COPY,
978+ vk::AccessFlags2::TRANSFER_READ,
979+ ),
980+ (
981+ vk::ImageLayout::VIDEO_DECODE_DST_KHR,
982+ vk::PipelineStageFlags2::ALL_COMMANDS,
983+ vk::AccessFlags2::NONE,
984+ ),
985+ );
986+ vk(d.end_command_buffer(cb), "vkEndCommandBuffer")?;
987+ }
988+ submit(d, self.fence, self.graphics_queue, cb)?;
989+ let ptr = self
990+ .readback
991+ .ptr
992+ .ok_or_else(|| Error::Invalid("readback buffer not mapped".into()))?;
993+ let bytes = unsafe { std::slice::from_raw_parts(ptr, luma * 3 / 2) };
994+ Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec()))
995+ }
996+
997+ fn create_session(&mut self, profile: &Profile, caps: &Caps, active: u32) -> Result<(), Error> {
998+ let gpu = self.gpu.clone();
999+ let d = gpu.device();
1000+ let info = vk::VideoSessionCreateInfoKHR::builder()
1001+ .queue_family_index(self.family)
1002+ .video_profile(&profile.info)
1003+ .picture_format(NV12)
1004+ .max_coded_extent(self.max_extent)
1005+ .reference_picture_format(NV12)
1006+ .max_dpb_slots(self.max_dpb_slots)
1007+ .max_active_reference_pictures(active)
1008+ .std_header_version(&caps.std_header_version)
1009+ .build();
1010+ self.video_session = unsafe {
1011+ vk(
1012+ d.create_video_session_khr(&info, None),
1013+ "vkCreateVideoSessionKHR",
1014+ )?
1015+ };
1016+ let reqs = unsafe {
1017+ vk(
1018+ d.get_video_session_memory_requirements_khr(self.video_session),
1019+ "vkGetVideoSessionMemoryRequirementsKHR",
1020+ )?
1021+ };
1022+ let mut binds = Vec::new();
1023+ for r in &reqs {
1024+ let mem = allocate(
1025+ &gpu,
1026+ r.memory_requirements,
1027+ vk::MemoryPropertyFlags::DEVICE_LOCAL,
1028+ )?;
1029+ self.session_memories.push(mem);
1030+ binds.push(
1031+ vk::BindVideoSessionMemoryInfoKHR::builder()
1032+ .memory_bind_index(r.memory_bind_index)
1033+ .memory(mem)
1034+ .memory_size(r.memory_requirements.size)
1035+ .build(),
1036+ );
1037+ }
1038+ unsafe {
1039+ vk(
1040+ d.bind_video_session_memory_khr(self.video_session, &binds),
1041+ "vkBindVideoSessionMemoryKHR",
1042+ )
1043+ }
1044+ }
1045+
1046+ fn create_resources(&mut self, profile: &Profile, caps: &Caps) -> Result<(), Error> {
1047+ let gpu = self.gpu.clone();
1048+ let d = gpu.device();
1049+ let mut list = vk::VideoProfileListInfoKHR::builder()
1050+ .profiles(std::slice::from_ref(&profile.info))
1051+ .build();
1052+ let width = self.max_extent.width;
1053+ let height = self.max_extent.height;
1054+ let families = if self.family == self.graphics {
1055+ vec![self.family]
1056+ } else {
1057+ vec![self.family, self.graphics]
1058+ };
1059+ let dpb = vk::ImageUsageFlags::VIDEO_DECODE_DPB_KHR;
1060+ for _ in 0..self.max_dpb_slots {
1061+ let image = new_image(&gpu, width, height, dpb, dpb, &[self.family], &mut list)?;
1062+ self.dpb.push(image);
1063+ }
1064+ let output = vk::ImageUsageFlags::VIDEO_DECODE_DST_KHR | vk::ImageUsageFlags::TRANSFER_SRC;
1065+ self.output = new_image(
1066+ &gpu,
1067+ width,
1068+ height,
1069+ output,
1070+ vk::ImageUsageFlags::VIDEO_DECODE_DST_KHR,
1071+ &families,
1072+ &mut list,
1073+ )?;
1074+
1075+ let bitstream_size = align_u64(width as u64 * height as u64 * 3 + 65536, caps.size_align);
1076+ self.bitstream = new_buffer(
1077+ &gpu,
1078+ bitstream_size,
1079+ vk::BufferUsageFlags::VIDEO_DECODE_SRC_KHR,
1080+ vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
1081+ Some(&mut list),
1082+ )?;
1083+ self.readback = new_buffer(
1084+ &gpu,
1085+ width as u64 * height as u64 * 3 / 2,
1086+ vk::BufferUsageFlags::TRANSFER_DST,
1087+ vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
1088+ None,
1089+ )?;
1090+
1091+ self.decode_pool = create_pool(d, self.family)?;
1092+ self.decode_cb = alloc_cb(d, self.decode_pool)?;
1093+ self.graphics_pool = create_pool(d, self.graphics)?;
1094+ self.graphics_cb = alloc_cb(d, self.graphics_pool)?;
1095+ self.fence = unsafe {
1096+ vk(
1097+ d.create_fence(&vk::FenceCreateInfo::builder().build(), None),
1098+ "vkCreateFence",
1099+ )?
1100+ };
1101+ Ok(())
1102+ }
1103+
1104+ fn init_dpb(&mut self) -> Result<(), Error> {
1105+ let gpu = self.gpu.clone();
1106+ let d = gpu.device();
1107+ let cb = self.decode_cb;
1108+ unsafe {
1109+ let info = vk::CommandBufferBeginInfo::builder()
1110+ .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
1111+ vk(d.begin_command_buffer(cb, &info), "vkBeginCommandBuffer")?;
1112+ for img in &self.dpb {
1113+ barrier(
1114+ d,
1115+ cb,
1116+ img.image,
1117+ (
1118+ vk::ImageLayout::UNDEFINED,
1119+ vk::PipelineStageFlags2::NONE,
1120+ vk::AccessFlags2::NONE,
1121+ ),
1122+ (
1123+ vk::ImageLayout::VIDEO_DECODE_DPB_KHR,
1124+ vk::PipelineStageFlags2::ALL_COMMANDS,
1125+ vk::AccessFlags2::NONE,
1126+ ),
1127+ );
1128+ }
1129+ vk(d.end_command_buffer(cb), "vkEndCommandBuffer")?;
1130+ }
1131+ submit(d, self.fence, self.queue, cb)
1132+ }
1133+}
1134+
1135+impl Drop for Av1DecodeSession {
1136+ fn drop(&mut self) {
1137+ let gpu = self.gpu.clone();
1138+ let d = gpu.device();
1139+ unsafe {
1140+ let _ = d.device_wait_idle();
1141+ d.destroy_fence(self.fence, None);
1142+ d.destroy_command_pool(self.decode_pool, None);
1143+ d.destroy_command_pool(self.graphics_pool, None);
1144+ for img in self.dpb.iter().chain(std::iter::once(&self.output)) {
1145+ d.destroy_image_view(img.view, None);
1146+ d.destroy_image(img.image, None);
1147+ d.free_memory(img.memory, None);
1148+ }
1149+ for buf in [&self.bitstream, &self.readback] {
1150+ d.destroy_buffer(buf.buffer, None);
1151+ d.free_memory(buf.memory, None);
1152+ }
1153+ if let Some(params) = self.params {
1154+ d.destroy_video_session_parameters_khr(params, None);
1155+ }
1156+ d.destroy_video_session_khr(self.video_session, None);
1157+ for m in &self.session_memories {
1158+ d.free_memory(*m, None);
1159+ }
1160+ }
1161+ }
1162+}
1163+
1164+fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> {
1165+ let mut av1 = vk::VideoDecodeAV1CapabilitiesKHR::builder();
1166+ let mut decode = vk::VideoDecodeCapabilitiesKHR::builder();
1167+ let mut caps = vk::VideoCapabilitiesKHR::builder()
1168+ .push_next(&mut av1)
1169+ .push_next(&mut decode);
1170+ unsafe {
1171+ vk(
1172+ gpu.instance().get_physical_device_video_capabilities_khr(
1173+ gpu.physical(),
1174+ profile,
1175+ &mut caps,
1176+ ),
1177+ "vkGetPhysicalDeviceVideoCapabilitiesKHR",
1178+ )?;
1179+ }
1180+ let caps = caps.build();
1181+ let decode = decode.build();
1182+ Ok(Caps {
1183+ std_header_version: caps.std_header_version,
1184+ max_extent: caps.max_coded_extent,
1185+ size_align: caps.min_bitstream_buffer_size_alignment,
1186+ max_dpb_slots: caps.max_dpb_slots,
1187+ max_active_refs: caps.max_active_reference_pictures,
1188+ distinct: decode
1189+ .flags
1190+ .contains(vk::VideoDecodeCapabilityFlagsKHR::DPB_AND_OUTPUT_DISTINCT),
1191+ })
1192+}
1193+
1194+fn relative_dist(a: u8, b: u8, bits: u32) -> i32 {
1195+ let diff = i32::from(a) - i32::from(b);
1196+ let m: i32 = 1 << (bits - 1);
1197+ (diff & (m - 1)) - (diff & m)
1198+}
1199+
1200+fn sign_bias_mask(seq: &Av1SequenceHeader, hint: u8, hints: &[u8; 8]) -> u8 {
1201+ if !seq.enable_order_hint {
1202+ return 0;
1203+ }
1204+ let bits = u32::from(seq.order_hint_bits_minus_1) + 1;
1205+ (1..8)
1206+ .filter(|&n| relative_dist(hints[n], hint, bits) > 0)
1207+ .fold(0u8, |mask, n| mask | (1 << n))
1208+}
1209+
1210+fn ref_info(
1211+ frame_type: Av1FrameType,
1212+ order_hint: u8,
1213+ sign_bias: u8,
1214+ saved_order_hints: [u8; 8],
1215+ disable_frame_end_update_cdf: bool,
1216+ segmentation_enabled: bool,
1217+) -> vk::video::StdVideoDecodeAV1ReferenceInfo {
1218+ let mut info = zeroed::<vk::video::StdVideoDecodeAV1ReferenceInfo>();
1219+ info.flags
1220+ .set_disable_frame_end_update_cdf(u32::from(disable_frame_end_update_cdf));
1221+ info.flags
1222+ .set_segmentation_enabled(u32::from(segmentation_enabled));
1223+ info.frame_type = frame_type as u8;
1224+ info.RefFrameSignBias = sign_bias;
1225+ info.OrderHint = order_hint;
1226+ info.SavedOrderHints = saved_order_hints;
1227+ info
1228+}
1229+
1230+fn std_color(c: &Av1ColorConfig) -> vk::video::StdVideoAV1ColorConfig {
1231+ let mut flags = zeroed::<vk::video::StdVideoAV1ColorConfigFlags>();
1232+ flags.set_mono_chrome(u32::from(c.mono_chrome));
1233+ flags.set_color_range(u32::from(c.color_range));
1234+ flags.set_separate_uv_delta_q(u32::from(c.separate_uv_delta_q));
1235+ vk::video::StdVideoAV1ColorConfig {
1236+ flags,
1237+ BitDepth: c.bit_depth,
1238+ subsampling_x: c.subsampling_x,
1239+ subsampling_y: c.subsampling_y,
1240+ reserved1: 0,
1241+ color_primaries: vk::video::StdVideoAV1ColorPrimaries(i32::from(c.color_primaries)),
1242+ transfer_characteristics: vk::video::StdVideoAV1TransferCharacteristics(i32::from(
1243+ c.transfer_characteristics,
1244+ )),
1245+ matrix_coefficients: vk::video::StdVideoAV1MatrixCoefficients(i32::from(
1246+ c.matrix_coefficients,
1247+ )),
1248+ chroma_sample_position: vk::video::StdVideoAV1ChromaSamplePosition(i32::from(
1249+ c.chroma_sample_position,
1250+ )),
1251+ }
1252+}
1253+
1254+fn std_timing(t: &Av1TimingInfo) -> vk::video::StdVideoAV1TimingInfo {
1255+ let mut flags = zeroed::<vk::video::StdVideoAV1TimingInfoFlags>();
1256+ flags.set_equal_picture_interval(u32::from(t.equal_picture_interval));
1257+ vk::video::StdVideoAV1TimingInfo {
1258+ flags,
1259+ num_units_in_display_tick: t.num_units_in_display_tick,
1260+ time_scale: t.time_scale,
1261+ num_ticks_per_picture_minus_1: t.num_ticks_per_picture_minus_1,
1262+ }
1263+}
1264+
1265+fn std_tile(t: &Av1TileInfo) -> vk::video::StdVideoAV1TileInfo {
1266+ let mut flags = zeroed::<vk::video::StdVideoAV1TileInfoFlags>();
1267+ flags.set_uniform_tile_spacing_flag(u32::from(t.uniform_spacing));
1268+ vk::video::StdVideoAV1TileInfo {
1269+ flags,
1270+ TileCols: t.cols,
1271+ TileRows: t.rows,
1272+ context_update_tile_id: t.context_update_tile_id,
1273+ tile_size_bytes_minus_1: t.tile_size_bytes_minus_1,
1274+ reserved1: [0; 7],
1275+ pMiColStarts: t.mi_col_starts.as_ptr(),
1276+ pMiRowStarts: t.mi_row_starts.as_ptr(),
1277+ pWidthInSbsMinus1: t.width_in_sbs_minus_1.as_ptr(),
1278+ pHeightInSbsMinus1: t.height_in_sbs_minus_1.as_ptr(),
1279+ }
1280+}
1281+
1282+fn std_quant(q: &Av1Quantization) -> vk::video::StdVideoAV1Quantization {
1283+ let mut flags = zeroed::<vk::video::StdVideoAV1QuantizationFlags>();
1284+ flags.set_using_qmatrix(u32::from(q.using_qmatrix));
1285+ vk::video::StdVideoAV1Quantization {
1286+ flags,
1287+ base_q_idx: q.base_q_idx,
1288+ DeltaQYDc: q.delta_q_y_dc,
1289+ DeltaQUDc: q.delta_q_u_dc,
1290+ DeltaQUAc: q.delta_q_u_ac,
1291+ DeltaQVDc: q.delta_q_v_dc,
1292+ DeltaQVAc: q.delta_q_v_ac,
1293+ qm_y: q.qm_y,
1294+ qm_u: q.qm_u,
1295+ qm_v: q.qm_v,
1296+ }
1297+}
1298+
1299+fn std_segmentation(s: &Av1Segmentation) -> vk::video::StdVideoAV1Segmentation {
1300+ let mut out = zeroed::<vk::video::StdVideoAV1Segmentation>();
1301+ for segment in 0..8 {
1302+ for feature in 0..8 {
1303+ if s.feature_enabled[segment][feature] {
1304+ out.FeatureEnabled[segment] |= 1 << feature;
1305+ }
1306+ }
1307+ out.FeatureData[segment] = s.feature_data[segment];
1308+ }
1309+ out
1310+}
1311+
1312+fn std_loop_filter(l: &Av1LoopFilter) -> vk::video::StdVideoAV1LoopFilter {
1313+ let mut flags = zeroed::<vk::video::StdVideoAV1LoopFilterFlags>();
1314+ flags.set_loop_filter_delta_enabled(u32::from(l.delta_enabled));
1315+ flags.set_loop_filter_delta_update(u32::from(l.delta_update));
1316+ vk::video::StdVideoAV1LoopFilter {
1317+ flags,
1318+ loop_filter_level: l.level,
1319+ loop_filter_sharpness: l.sharpness,
1320+ update_ref_delta: 0,
1321+ loop_filter_ref_deltas: l.ref_deltas,
1322+ update_mode_delta: 0,
1323+ loop_filter_mode_deltas: l.mode_deltas,
1324+ }
1325+}
1326+
1327+fn std_cdef(c: &Av1Cdef) -> vk::video::StdVideoAV1CDEF {
1328+ vk::video::StdVideoAV1CDEF {
1329+ cdef_damping_minus_3: c.damping_minus_3,
1330+ cdef_bits: c.bits,
1331+ cdef_y_pri_strength: c.y_pri,
1332+ cdef_y_sec_strength: c.y_sec,
1333+ cdef_uv_pri_strength: c.uv_pri,
1334+ cdef_uv_sec_strength: c.uv_sec,
1335+ }
1336+}
1337+
1338+fn std_loop_restoration(l: &Av1LoopRestoration) -> vk::video::StdVideoAV1LoopRestoration {
1339+ vk::video::StdVideoAV1LoopRestoration {
1340+ FrameRestorationType: l.frame_restoration_type.map(std_restoration),
1341+ LoopRestorationSize: l.loop_restoration_size,
1342+ }
1343+}
1344+
1345+fn std_global_motion(g: &[Av1GlobalMotion; 8]) -> vk::video::StdVideoAV1GlobalMotion {
1346+ vk::video::StdVideoAV1GlobalMotion {
1347+ GmType: g.map(|m| m.model as u8),
1348+ gm_params: g.map(|m| m.params),
1349+ }
1350+}
1351+
1352+fn picture_flags(h: &Av1FrameHeader) -> vk::video::StdVideoDecodeAV1PictureInfoFlags {
1353+ let lr = h.loop_restoration.frame_restoration_type;
1354+ let mut f = zeroed::<vk::video::StdVideoDecodeAV1PictureInfoFlags>();
1355+ f.set_error_resilient_mode(u32::from(h.error_resilient_mode));
1356+ f.set_disable_cdf_update(u32::from(h.disable_cdf_update));
1357+ f.set_use_superres(u32::from(h.use_superres));
1358+ f.set_render_and_frame_size_different(u32::from(
1359+ h.render_width != h.upscaled_width || h.render_height != h.frame_height,
1360+ ));
1361+ f.set_allow_screen_content_tools(u32::from(h.allow_screen_content_tools));
1362+ f.set_is_filter_switchable(u32::from(
1363+ h.interpolation_filter == Av1InterpolationFilter::Switchable,
1364+ ));
1365+ f.set_force_integer_mv(u32::from(h.force_integer_mv));
1366+ f.set_frame_size_override_flag(u32::from(h.frame_size_override_flag));
1367+ f.set_allow_intrabc(u32::from(h.allow_intrabc));
1368+ f.set_frame_refs_short_signaling(u32::from(h.frame_refs_short_signaling));
1369+ f.set_allow_high_precision_mv(u32::from(h.allow_high_precision_mv));
1370+ f.set_is_motion_mode_switchable(u32::from(h.is_motion_mode_switchable));
1371+ f.set_use_ref_frame_mvs(u32::from(h.use_ref_frame_mvs));
1372+ f.set_disable_frame_end_update_cdf(u32::from(h.disable_frame_end_update_cdf));
1373+ f.set_allow_warped_motion(u32::from(h.allow_warped_motion));
1374+ f.set_reduced_tx_set(u32::from(h.reduced_tx_set));
1375+ f.set_reference_select(u32::from(h.reference_select));
1376+ f.set_skip_mode_present(u32::from(h.skip_mode_present));
1377+ f.set_delta_q_present(u32::from(h.delta.q_present));
1378+ f.set_delta_lf_present(u32::from(h.delta.lf_present));
1379+ f.set_delta_lf_multi(u32::from(h.delta.lf_multi));
1380+ f.set_segmentation_enabled(u32::from(h.segmentation.enabled));
1381+ f.set_segmentation_update_map(u32::from(h.segmentation.update_map));
1382+ f.set_segmentation_temporal_update(u32::from(h.segmentation.temporal_update));
1383+ f.set_segmentation_update_data(u32::from(h.segmentation.update_data));
1384+ f.set_UsesLr(u32::from(lr.iter().any(|&t| t != Av1Restoration::None)));
1385+ f.set_usesChromaLr(u32::from(
1386+ lr[1..].iter().any(|&t| t != Av1Restoration::None),
1387+ ));
1388+ f
1389+}
1390+
1391+fn std_frame_type(t: Av1FrameType) -> vk::video::StdVideoAV1FrameType {
1392+ vk::video::StdVideoAV1FrameType(i32::from(t as u8))
1393+}
1394+
1395+fn std_interpolation(f: Av1InterpolationFilter) -> vk::video::StdVideoAV1InterpolationFilter {
1396+ vk::video::StdVideoAV1InterpolationFilter(i32::from(f as u8))
1397+}
1398+
1399+fn std_tx_mode(m: Av1TxMode) -> vk::video::StdVideoAV1TxMode {
1400+ vk::video::StdVideoAV1TxMode(i32::from(m as u8))
1401+}
1402+
1403+fn std_restoration(r: Av1Restoration) -> vk::video::StdVideoAV1FrameRestorationType {
1404+ vk::video::StdVideoAV1FrameRestorationType(i32::from(r as u8))
1405+}
shims/vk-video-ffi/src/lib.rsmodified+7 -0
@@ -6,6 +6,7 @@ use std::ffi::c_char;
66 use std::fmt;
77 use std::sync::Arc;
88
9+mod av1_decode;
910 mod av1_encode;
1011 mod h264_decode;
1112 mod h264_encode;
@@ -13,6 +14,12 @@ mod h265_decode;
1314 mod h265_encode;
1415 mod rgb_convert;
1516
17+pub use av1_decode::{
18+ Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
19+ Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
20+ Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation,
21+ Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel,
22+};
1623 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
1724 pub use h264_decode::{
1825 H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps,