edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! VP9 decoding over Vulkan Video: the reference slots over DPB slot indices. |
| 2 | |
| 3 | use std::cell::RefCell; |
| 4 | use std::collections::VecDeque; |
| 5 | use std::rc::Rc; |
| 6 | |
| 7 | use ec_core::color::{ColorDescription, Tags}; |
| 8 | use ec_vk::{ |
| 9 | Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, |
| 10 | Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, |
| 11 | }; |
| 12 | use ec_vp9_syntax::{ |
| 13 | ColorSpace, FrameHeader, FrameType, InterpolationFilter, NUM_REF_FRAMES, REFS_PER_FRAME, |
| 14 | Vp9Parser, superframe, |
| 15 | }; |
| 16 | |
| 17 | use crate::error::{Error, Result}; |
| 18 | use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; |
| 19 | use crate::ref_slots::RefSlots; |
| 20 | |
| 21 | const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; |
| 22 | |
| 23 | struct Session { |
| 24 | vp9: Rc<RefCell<Vp9DecodeSession>>, |
| 25 | ring: Ring, |
| 26 | bit_depth: u8, |
| 27 | width: u32, |
| 28 | height: u32, |
| 29 | } |
| 30 | |
| 31 | struct Reference { |
| 32 | slot: u32, |
| 33 | picture: VkPicture, |
| 34 | } |
| 35 | |
| 36 | /// What the next frame needs from the one before it (spec 7.2, UsePrevFrameMvs). |
| 37 | #[derive(Clone, Copy)] |
| 38 | struct PreviousFrame { |
| 39 | width: u32, |
| 40 | height: u32, |
| 41 | show_frame: bool, |
| 42 | intra_only: bool, |
| 43 | } |
| 44 | |
| 45 | /// VP9 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. |
| 46 | pub(crate) struct VkVp9Decoder { |
| 47 | gpu: ec_vk::Gpu, |
| 48 | parser: Vp9Parser, |
| 49 | session: Option<Session>, |
| 50 | refs: RefSlots<Rc<Reference>>, |
| 51 | previous: Option<PreviousFrame>, |
| 52 | ready: VecDeque<HwPicture>, |
| 53 | } |
| 54 | |
| 55 | impl VkVp9Decoder { |
| 56 | pub(crate) fn new() -> Result<Self> { |
| 57 | let gpu = crate::hw::vk_gpu() |
| 58 | .ok_or_else(|| Error::unsupported("Vulkan Video VP9 decode", "no Vulkan device"))?; |
| 59 | Ok(VkVp9Decoder { |
| 60 | gpu, |
| 61 | parser: Vp9Parser::new(), |
| 62 | session: None, |
| 63 | refs: RefSlots::new(), |
| 64 | previous: None, |
| 65 | ready: VecDeque::new(), |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { |
| 70 | if data.is_empty() { |
| 71 | return Ok(()); |
| 72 | } |
| 73 | for frame in superframe::split(data)? { |
| 74 | self.decode_frame(frame, timestamp)?; |
| 75 | } |
| 76 | Ok(()) |
| 77 | } |
| 78 | |
| 79 | pub(crate) fn next_frame(&mut self) -> Option<HwPicture> { |
| 80 | self.ready.pop_front() |
| 81 | } |
| 82 | |
| 83 | pub(crate) fn reset(&mut self) { |
| 84 | self.parser = Vp9Parser::new(); |
| 85 | self.refs = RefSlots::new(); |
| 86 | self.previous = None; |
| 87 | self.ready.clear(); |
| 88 | } |
| 89 | |
| 90 | pub(crate) fn flush(&mut self) -> Result<()> { |
| 91 | Ok(()) |
| 92 | } |
| 93 | |
| 94 | fn decode_frame(&mut self, data: &[u8], timestamp: i64) -> Result<()> { |
| 95 | let header = self.parser.parse_frame(data)?; |
| 96 | if header.show_existing_frame { |
| 97 | let reference = self |
| 98 | .refs |
| 99 | .get(usize::from(header.frame_to_show_map_idx)) |
| 100 | .cloned() |
| 101 | .ok_or_else(|| { |
| 102 | Error::Stream(ec_core::Error::corrupt( |
| 103 | "VP9 show_existing_frame names an empty reference slot", |
| 104 | )) |
| 105 | })?; |
| 106 | self.ready |
| 107 | .push_back(HwPicture::vk(timestamp, reference.picture.clone())); |
| 108 | if let Some(previous) = self.previous.as_mut() { |
| 109 | previous.show_frame = true; |
| 110 | } |
| 111 | return Ok(()); |
| 112 | } |
| 113 | check_supported(&header)?; |
| 114 | self.ensure_session(&header)?; |
| 115 | |
| 116 | let mut ref_name_slot = [-1i32; REFS_PER_FRAME]; |
| 117 | let mut refs: Vec<u32> = Vec::new(); |
| 118 | if !header.frame_is_intra { |
| 119 | for (name, &index) in header.ref_frame_idx.iter().enumerate() { |
| 120 | let reference = self.refs.get(usize::from(index)).ok_or_else(|| { |
| 121 | Error::Stream(ec_core::Error::corrupt(format!( |
| 122 | "VP9 inter frame names reference slot {index} (ref {name}), \ |
| 123 | which no decoded frame has filled" |
| 124 | ))) |
| 125 | })?; |
| 126 | ref_name_slot[name] = reference.slot as i32; |
| 127 | if !refs.contains(&reference.slot) { |
| 128 | refs.push(reference.slot); |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | let setup_slot = self.free_slot()?; |
| 134 | let use_prev_frame_mvs = !header.error_resilient_mode |
| 135 | && self.previous.is_some_and(|p| { |
| 136 | p.width == header.width |
| 137 | && p.height == header.height |
| 138 | && p.show_frame |
| 139 | && !p.intra_only |
| 140 | }); |
| 141 | let frame = frame_header(&header, use_prev_frame_mvs); |
| 142 | let picture = Vp9DecodePicture { |
| 143 | header: &frame, |
| 144 | setup_slot, |
| 145 | ref_name_slot, |
| 146 | refs: &refs, |
| 147 | data, |
| 148 | }; |
| 149 | let session = self |
| 150 | .session |
| 151 | .as_mut() |
| 152 | .ok_or_else(|| Error::config("VP9 picture before any session"))?; |
| 153 | let slot = session.ring.take(|| Ok(session.vp9.borrow_mut().add_ring_slot()?))?; |
| 154 | session.vp9.borrow_mut().decode(&picture)?; |
| 155 | self.previous = Some(PreviousFrame { |
| 156 | width: header.width, |
| 157 | height: header.height, |
| 158 | show_frame: header.show_frame, |
| 159 | intra_only: header.intra_only, |
| 160 | }); |
| 161 | |
| 162 | if !(header.show_frame || header.refresh_frame_flags != 0) { |
| 163 | return Ok(()); |
| 164 | } |
| 165 | let (width, height) = (header.width, header.height); |
| 166 | let codes = Tags::from_codes(u64::from(header.color_space.h273().map_or(2, |c| c.2)), 0, 0); |
| 167 | let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; |
| 168 | session.vp9.borrow_mut().store_output(slot.index(), (0, 0, width, height))?; |
| 169 | let decoded = VkPicture::new( |
| 170 | Surfaces::Vp9(session.vp9.clone()), |
| 171 | slot, |
| 172 | (width, height), |
| 173 | session.bit_depth, |
| 174 | matrix, |
| 175 | ); |
| 176 | if header.show_frame { |
| 177 | self.ready |
| 178 | .push_back(HwPicture::vk(timestamp, decoded.clone())); |
| 179 | } |
| 180 | if header.refresh_frame_flags != 0 { |
| 181 | let reference = Rc::new(Reference { |
| 182 | slot: setup_slot, |
| 183 | picture: decoded, |
| 184 | }); |
| 185 | self.refs |
| 186 | .refresh(header.refresh_frame_flags, Some(reference)); |
| 187 | } |
| 188 | Ok(()) |
| 189 | } |
| 190 | |
| 191 | fn ensure_session(&mut self, header: &FrameHeader) -> Result<()> { |
| 192 | if let Some(s) = &self.session |
| 193 | && s.bit_depth == header.bit_depth |
| 194 | && header.width <= s.width |
| 195 | && header.height <= s.height |
| 196 | { |
| 197 | return Ok(()); |
| 198 | } |
| 199 | let (width, height) = match &self.session { |
| 200 | Some(s) if s.bit_depth == header.bit_depth => { |
| 201 | (header.width.max(s.width), header.height.max(s.height)) |
| 202 | } |
| 203 | _ => (header.width, header.height), |
| 204 | }; |
| 205 | self.refs = RefSlots::new(); |
| 206 | let vp9 = Vp9DecodeSession::new( |
| 207 | &self.gpu, |
| 208 | &Vp9DecodeConfig { |
| 209 | max_width: width, |
| 210 | max_height: height, |
| 211 | max_dpb_slots: DPB_SLOTS, |
| 212 | bit_depth: header.bit_depth, |
| 213 | }, |
| 214 | )?; |
| 215 | let ring = Ring::new(vp9.ring_len()); |
| 216 | self.session = Some(Session { |
| 217 | vp9: Rc::new(RefCell::new(vp9)), |
| 218 | ring, |
| 219 | bit_depth: header.bit_depth, |
| 220 | width, |
| 221 | height, |
| 222 | }); |
| 223 | Ok(()) |
| 224 | } |
| 225 | |
| 226 | fn free_slot(&self) -> Result<u32> { |
| 227 | (0..DPB_SLOTS) |
| 228 | .find(|slot| self.refs.filled().all(|r| r.slot != *slot)) |
| 229 | .ok_or_else(|| Error::config("VP9 Vulkan decode: every DPB slot is in use")) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | fn check_supported(h: &FrameHeader) -> Result<()> { |
| 234 | if !matches!((h.profile, h.bit_depth), (0, 8) | (2, 10)) |
| 235 | || h.subsampling_x != 1 |
| 236 | || h.subsampling_y != 1 |
| 237 | { |
| 238 | return Err(Error::unsupported( |
| 239 | "Vulkan VP9 decode", |
| 240 | "only 4:2:0 profile 0 8-bit and profile 2 10-bit", |
| 241 | )); |
| 242 | } |
| 243 | if h.width % 2 != 0 || h.height % 2 != 0 { |
| 244 | return Err(Error::unsupported("Vulkan VP9 decode", "odd frame size")); |
| 245 | } |
| 246 | Ok(()) |
| 247 | } |
| 248 | |
| 249 | fn color_code(c: ColorSpace) -> u8 { |
| 250 | match c { |
| 251 | ColorSpace::Unknown => 0, |
| 252 | ColorSpace::Bt601 => 1, |
| 253 | ColorSpace::Bt709 => 2, |
| 254 | ColorSpace::Smpte170 => 3, |
| 255 | ColorSpace::Smpte240 => 4, |
| 256 | ColorSpace::Bt2020 => 5, |
| 257 | ColorSpace::Reserved => 6, |
| 258 | ColorSpace::Rgb => 7, |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | fn interpolation(f: InterpolationFilter) -> Vp9InterpolationFilter { |
| 263 | match f { |
| 264 | InterpolationFilter::Eighttap => Vp9InterpolationFilter::EightTap, |
| 265 | InterpolationFilter::EighttapSmooth => Vp9InterpolationFilter::EightTapSmooth, |
| 266 | InterpolationFilter::EighttapSharp => Vp9InterpolationFilter::EightTapSharp, |
| 267 | InterpolationFilter::Bilinear => Vp9InterpolationFilter::Bilinear, |
| 268 | InterpolationFilter::Switchable => Vp9InterpolationFilter::Switchable, |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | fn frame_header(h: &FrameHeader, use_prev_frame_mvs: bool) -> Vp9FrameHeader { |
| 273 | let s = &h.segmentation; |
| 274 | let feature_enabled = std::array::from_fn(|segment| { |
| 275 | (0..s.feature_enabled[segment].len()) |
| 276 | .filter(|&f| s.feature_enabled[segment][f]) |
| 277 | .fold(0u8, |mask, f| mask | 1 << f) |
| 278 | }); |
| 279 | let sign_bias = h |
| 280 | .ref_frame_sign_bias |
| 281 | .iter() |
| 282 | .enumerate() |
| 283 | .filter(|(_, set)| **set) |
| 284 | .fold(0u8, |mask, (name, _)| mask | 1 << (name + 1)); |
| 285 | let lf = &h.loop_filter; |
| 286 | Vp9FrameHeader { |
| 287 | key_frame: h.frame_type == FrameType::Key, |
| 288 | show_frame: h.show_frame, |
| 289 | error_resilient_mode: h.error_resilient_mode, |
| 290 | intra_only: h.intra_only, |
| 291 | allow_high_precision_mv: h.allow_high_precision_mv, |
| 292 | refresh_frame_context: h.refresh_frame_context, |
| 293 | frame_parallel_decoding_mode: h.frame_parallel_decoding_mode, |
| 294 | use_prev_frame_mvs, |
| 295 | frame_context_idx: h.frame_context_idx, |
| 296 | reset_frame_context: h.reset_frame_context, |
| 297 | refresh_frame_flags: h.refresh_frame_flags, |
| 298 | ref_frame_sign_bias_mask: sign_bias, |
| 299 | interpolation_filter: interpolation(h.interpolation_filter), |
| 300 | base_q_idx: h.quantization.base_q_idx, |
| 301 | delta_q_y_dc: h.quantization.delta_q_y_dc, |
| 302 | delta_q_uv_dc: h.quantization.delta_q_uv_dc, |
| 303 | delta_q_uv_ac: h.quantization.delta_q_uv_ac, |
| 304 | tile_cols_log2: h.tile_info.cols_log2, |
| 305 | tile_rows_log2: h.tile_info.rows_log2, |
| 306 | width: h.width, |
| 307 | height: h.height, |
| 308 | bit_depth: h.bit_depth, |
| 309 | color: Vp9ColorConfig { |
| 310 | color_space: color_code(h.color_space), |
| 311 | color_range: h.color_range, |
| 312 | subsampling_x: h.subsampling_x, |
| 313 | subsampling_y: h.subsampling_y, |
| 314 | }, |
| 315 | loop_filter: Vp9LoopFilter { |
| 316 | level: lf.level, |
| 317 | sharpness: lf.sharpness, |
| 318 | delta_enabled: lf.delta_enabled, |
| 319 | delta_update: lf.delta_update, |
| 320 | ref_deltas: lf.ref_deltas, |
| 321 | mode_deltas: lf.mode_deltas, |
| 322 | }, |
| 323 | segmentation: Vp9Segmentation { |
| 324 | enabled: s.enabled, |
| 325 | update_map: s.update_map, |
| 326 | temporal_update: s.temporal_update, |
| 327 | update_data: s.update_data, |
| 328 | abs_or_delta_update: s.abs_or_delta_update, |
| 329 | tree_probs: s.tree_probs, |
| 330 | pred_probs: s.pred_probs, |
| 331 | feature_enabled, |
| 332 | feature_data: s.feature_data, |
| 333 | }, |
| 334 | uncompressed_header_size: u32::from(h.uncompressed_header_size), |
| 335 | compressed_header_size: u32::from(h.header_size_in_bytes), |
| 336 | } |
| 337 | } |