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 | //! Stateless HEVC decoding. |
| 2 | //! |
| 3 | //! HEVC keeps no `frame_num` and no sliding window: every picture states its |
| 4 | //! whole reference picture set, and anything the set does not name stops being |
| 5 | //! a reference there and then (8.3.2). That makes the DPB smaller than H.264's |
| 6 | //! but the *derivation* larger, and all of it has to happen here — a stateless |
| 7 | //! driver is handed `RefPicSetStCurrBefore`, `StCurrAfter` and `LtCurr` as |
| 8 | //! finished picture lists. |
| 9 | |
| 10 | use std::rc::Rc; |
| 11 | |
| 12 | use ec_core::color::{ColorDescription, ContentLight, Tags}; |
| 13 | use ec_h265_syntax::{ |
| 14 | NalUnitType, ParsePositions, Pps, SliceHeader, SliceType, Sps, Vps, split_annex_b, |
| 15 | unescape_rbsp, |
| 16 | }; |
| 17 | use ec_va::caps::Profile; |
| 18 | use ec_va::{Buffer, Display}; |
| 19 | |
| 20 | use super::{ReadyFrames, Session, StreamInfo}; |
| 21 | use crate::error::{Error, Result}; |
| 22 | use crate::frame::{Colour, Frame}; |
| 23 | use crate::hevc_dpb::{ |
| 24 | Dpb, Mark, Rps, StoredPicture, hevc_ctb16_broken, is_bla_picture, is_rasl_picture, |
| 25 | is_reference_picture, is_leading_picture, peek_pps_id, vui_colour_tags, |
| 26 | }; |
| 27 | use crate::params::hevc::{ |
| 28 | IQMatrixBufferHEVC, LongSliceFlags, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, |
| 29 | PICTURE_RPS_LT_CURR, PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PicFields, |
| 30 | PictureParameterBufferHEVC, SliceParameterBufferHEVC, SliceParsingFields, VAPictureHEVC, |
| 31 | }; |
| 32 | use crate::pool::PooledSurface; |
| 33 | |
| 34 | /// Beyond `sps_max_dec_pic_buffering`: the picture being decoded plus the ones |
| 35 | /// a caller is still holding. |
| 36 | const EXTRA_SURFACES: usize = 6; |
| 37 | |
| 38 | /// One DPB slot as the parameter builder sees it: its surface, POC and marking. |
| 39 | #[derive(Clone, Copy)] |
| 40 | struct DpbSlot { |
| 41 | id: u32, |
| 42 | poc: i32, |
| 43 | mark: Mark, |
| 44 | } |
| 45 | |
| 46 | impl DpbSlot { |
| 47 | fn of(p: &StoredPicture<Rc<PooledSurface>>) -> DpbSlot { |
| 48 | DpbSlot { |
| 49 | id: p.surface.id(), |
| 50 | poc: p.poc, |
| 51 | mark: p.mark, |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// The picture being assembled from its slices. |
| 57 | struct Current { |
| 58 | surface: Rc<PooledSurface>, |
| 59 | sps_id: u32, |
| 60 | poc: i32, |
| 61 | timestamp: i64, |
| 62 | is_reference: bool, |
| 63 | /// True when this picture may be `prevTid0Pic` for the next one (8.3.1). |
| 64 | is_tid0_anchor: bool, |
| 65 | output: bool, |
| 66 | rps: Rps, |
| 67 | buffers: Vec<Buffer>, |
| 68 | slices: usize, |
| 69 | /// Index into `PictureParameterBufferHEVC::reference_frames` per DPB index. |
| 70 | va_index: Vec<u8>, |
| 71 | } |
| 72 | |
| 73 | /// A stateless HEVC decoder. |
| 74 | pub struct HevcDecoder { |
| 75 | display: Rc<Display>, |
| 76 | vps_map: Vec<Option<Vps>>, |
| 77 | sps_map: Vec<Option<Sps>>, |
| 78 | pps_map: Vec<Option<Pps>>, |
| 79 | session: Option<Session>, |
| 80 | dpb: Dpb<Rc<PooledSurface>>, |
| 81 | ready: ReadyFrames, |
| 82 | current: Option<Current>, |
| 83 | /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures |
| 84 | /// associated with it must not be decoded or output when set, because |
| 85 | /// they predict from pictures before a random-access point this decoder |
| 86 | /// never saw. |
| 87 | no_rasl_output: bool, |
| 88 | /// The most recent SPS's VUI colour tags, sticky across pictures. |
| 89 | colour_tags: Tags, |
| 90 | /// The prefix SEI HDR peak seen so far, merged so a later access unit that |
| 91 | /// says nothing does not erase what an earlier IRAP declared. |
| 92 | colour_light: ContentLight, |
| 93 | } |
| 94 | |
| 95 | impl HevcDecoder { |
| 96 | /// A decoder with no stream state. |
| 97 | pub fn new(display: &Rc<Display>) -> HevcDecoder { |
| 98 | HevcDecoder { |
| 99 | display: Rc::clone(display), |
| 100 | vps_map: (0..16).map(|_| None).collect(), |
| 101 | sps_map: (0..16).map(|_| None).collect(), |
| 102 | pps_map: (0..64).map(|_| None).collect(), |
| 103 | session: None, |
| 104 | dpb: Dpb::new(), |
| 105 | ready: ReadyFrames::default(), |
| 106 | current: None, |
| 107 | no_rasl_output: false, |
| 108 | colour_tags: Tags::default(), |
| 109 | colour_light: ContentLight::default(), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// Decode one Annex B access unit. |
| 114 | pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { |
| 115 | for nal in split_annex_b(data) { |
| 116 | match nal.header.nal_type { |
| 117 | NalUnitType::Vps => { |
| 118 | let vps = Vps::parse(&nal.rbsp())?; |
| 119 | let id = usize::from(vps.id); |
| 120 | if id < self.vps_map.len() { |
| 121 | self.vps_map[id] = Some(vps); |
| 122 | } |
| 123 | } |
| 124 | NalUnitType::Sps => { |
| 125 | let sps = Sps::parse(&nal.rbsp())?; |
| 126 | self.dpb.max_reorder = sps.max_num_reorder_pics as usize; |
| 127 | self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; |
| 128 | self.colour_tags = vui_colour_tags(&sps); |
| 129 | let id = sps.id as usize; |
| 130 | if id < self.sps_map.len() { |
| 131 | self.sps_map[id] = Some(sps); |
| 132 | } |
| 133 | } |
| 134 | NalUnitType::Pps => { |
| 135 | let pps = Pps::parse(&nal.rbsp())?; |
| 136 | let id = pps.id as usize; |
| 137 | if id < self.pps_map.len() { |
| 138 | self.pps_map[id] = Some(pps); |
| 139 | } |
| 140 | } |
| 141 | t if t.is_vcl() => { |
| 142 | self.slice(t, nal.header.temporal_id, nal.payload, timestamp)?; |
| 143 | } |
| 144 | _ => {} |
| 145 | } |
| 146 | } |
| 147 | // The HDR SEI messages (mastering display, content light level) live |
| 148 | // outside the slice loop above and are read on the whole access unit: |
| 149 | // an encoder writes them once, ahead of the IRAP they describe, and |
| 150 | // they otherwise say nothing (`ContentLight::default()`), so a later |
| 151 | // access unit that carries neither never overwrites what an earlier |
| 152 | // one declared. |
| 153 | let light = ec_core::color::hevc_sei_light(data); |
| 154 | if light != ContentLight::default() { |
| 155 | self.colour_light = light.over(self.colour_light); |
| 156 | } |
| 157 | self.finish_picture()?; |
| 158 | Ok(()) |
| 159 | } |
| 160 | |
| 161 | /// This stream's colour metadata, once its first SPS has been seen. |
| 162 | pub fn colour(&self) -> Option<Colour> { |
| 163 | let session = self.session.as_ref()?; |
| 164 | Some(Colour { |
| 165 | description: ColorDescription::resolve( |
| 166 | Tags::default(), |
| 167 | self.colour_tags, |
| 168 | session.display_size.1, |
| 169 | ), |
| 170 | light: self.colour_light, |
| 171 | }) |
| 172 | } |
| 173 | |
| 174 | /// The next frame in output order. |
| 175 | pub fn next_frame(&mut self) -> Option<Frame> { |
| 176 | self.ready.pop() |
| 177 | } |
| 178 | |
| 179 | /// Push every buffered picture out (end of stream). |
| 180 | pub fn flush(&mut self) { |
| 181 | let _ = self.finish_picture(); |
| 182 | self.bump(true); |
| 183 | } |
| 184 | |
| 185 | /// Drop all picture state after a seek; parameter sets survive. |
| 186 | pub fn reset(&mut self) { |
| 187 | self.current = None; |
| 188 | self.dpb.pictures.clear(); |
| 189 | self.ready.clear(); |
| 190 | self.dpb.prev_tid0_poc = 0; |
| 191 | self.dpb.started = false; |
| 192 | self.no_rasl_output = false; |
| 193 | } |
| 194 | |
| 195 | /// What the stream turned out to be. |
| 196 | pub fn stream_info(&self) -> Option<StreamInfo> { |
| 197 | self.session.as_ref().map(Session::info) |
| 198 | } |
| 199 | |
| 200 | fn slice( |
| 201 | &mut self, |
| 202 | nal_type: NalUnitType, |
| 203 | temporal_id: u8, |
| 204 | payload: &[u8], |
| 205 | timestamp: i64, |
| 206 | ) -> Result<()> { |
| 207 | let rbsp = unescape_rbsp(payload); |
| 208 | // The header cannot be parsed without its PPS, and the PPS names the SPS. |
| 209 | let pps_id = peek_pps_id(&rbsp, nal_type)?; |
| 210 | let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { |
| 211 | return Ok(()); |
| 212 | }; |
| 213 | let Some(sps) = self |
| 214 | .sps_map |
| 215 | .get(pps.sps_id as usize) |
| 216 | .and_then(|s| s.clone()) |
| 217 | else { |
| 218 | return Ok(()); |
| 219 | }; |
| 220 | let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?; |
| 221 | |
| 222 | if sh.first_slice_segment_in_pic { |
| 223 | self.finish_picture()?; |
| 224 | // 8.1.3 / C.5.2.2: a RASL picture associated with an IRAP whose |
| 225 | // NoRaslOutputFlag is 1 predicts from pictures before that IRAP, |
| 226 | // which a mid-stream start never decoded. It is not output and |
| 227 | // is not guaranteed decodable, so it is dropped whole rather than |
| 228 | // handed to the driver. |
| 229 | if !(is_rasl_picture(nal_type) && self.no_rasl_output) { |
| 230 | self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?; |
| 231 | } |
| 232 | } |
| 233 | if self.current.is_none() { |
| 234 | return Ok(()); |
| 235 | } |
| 236 | self.render_slice(&sps, &pps, &sh, &pos, payload, nal_type) |
| 237 | } |
| 238 | |
| 239 | fn ensure_session(&mut self, sps: &Sps) -> Result<()> { |
| 240 | let amd = || { |
| 241 | ec_va::display::vendor(&self.display) |
| 242 | .is_ok_and(|v| v.contains("AMD") || v.contains("radeonsi")) |
| 243 | }; |
| 244 | if hevc_ctb16_broken(sps, amd) { |
| 245 | return Err(Error::unsupported( |
| 246 | "VA-API H.265 decode", |
| 247 | "16x16 CTBs on AMD decode with wrong chroma", |
| 248 | )); |
| 249 | } |
| 250 | let bit_depth = (sps.bit_depth_luma_minus8 + 8) as u8; |
| 251 | let profile = match (sps.chroma_format_idc, bit_depth) { |
| 252 | (1, 8) => Profile::HEVCMain, |
| 253 | (1, 10) => Profile::HEVCMain10, |
| 254 | (chroma, depth) => { |
| 255 | return Err(Error::unsupported( |
| 256 | format!("HEVC chroma_format_idc {chroma} at {depth} bits"), |
| 257 | "only Main and Main10 (4:2:0, 8 or 10 bit) are decoded in hardware", |
| 258 | )); |
| 259 | } |
| 260 | }; |
| 261 | let coded = ( |
| 262 | sps.pic_width_in_luma_samples, |
| 263 | sps.pic_height_in_luma_samples, |
| 264 | ); |
| 265 | if let Some(session) = &self.session |
| 266 | && session.coded_size == coded |
| 267 | && session.bit_depth == bit_depth |
| 268 | && session.profile == profile |
| 269 | { |
| 270 | return Ok(()); |
| 271 | } |
| 272 | self.current = None; |
| 273 | self.dpb.pictures.clear(); |
| 274 | self.session = Some(Session::new( |
| 275 | &self.display, |
| 276 | profile, |
| 277 | coded, |
| 278 | sps.display_size(), |
| 279 | bit_depth, |
| 280 | self.dpb.max_dec_pic_buffering + EXTRA_SURFACES, |
| 281 | )?); |
| 282 | Ok(()) |
| 283 | } |
| 284 | |
| 285 | fn start_picture( |
| 286 | &mut self, |
| 287 | sps: &Sps, |
| 288 | sh: &SliceHeader, |
| 289 | nal_type: NalUnitType, |
| 290 | temporal_id: u8, |
| 291 | timestamp: i64, |
| 292 | ) -> Result<()> { |
| 293 | self.ensure_session(sps)?; |
| 294 | |
| 295 | if nal_type.is_irap() { |
| 296 | // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded |
| 297 | // video sequence — which a mid-stream start's first IRAP always |
| 298 | // is, `self.started` still being false at that point. |
| 299 | self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.dpb.started; |
| 300 | } |
| 301 | |
| 302 | let poc = self.dpb.picture_order_count(sps, sh, nal_type); |
| 303 | // 8.3.2 runs before the picture is decoded and after its POC is known: |
| 304 | // every stored picture the set does not name stops being a reference. |
| 305 | let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?; |
| 306 | |
| 307 | if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { |
| 308 | // An IRAP that restarts output order: everything ahead of it in the |
| 309 | // buffer belongs ahead of it on screen too. |
| 310 | self.bump(true); |
| 311 | } |
| 312 | |
| 313 | if std::env::var_os("EC_HW_DEBUG").is_some() { |
| 314 | eprintln!( |
| 315 | "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}", |
| 316 | nal_type, |
| 317 | sh.poc_lsb, |
| 318 | self.dpb.pictures.len(), |
| 319 | self.ready.len(), |
| 320 | rps.st_curr_before.len(), |
| 321 | rps.st_curr_after.len(), |
| 322 | rps.lt_curr.len(), |
| 323 | self.session |
| 324 | .as_ref() |
| 325 | .map(|s| s.pool.available()) |
| 326 | .unwrap_or(0), |
| 327 | ); |
| 328 | } |
| 329 | let session = self |
| 330 | .session |
| 331 | .as_ref() |
| 332 | .ok_or_else(|| Error::config("HEVC picture before any SPS"))?; |
| 333 | let surface = session.acquire()?; |
| 334 | |
| 335 | // The driver indexes RefPicList into `reference_frames`, so the mapping |
| 336 | // from DPB slot to that array is fixed once, here. |
| 337 | let mut va_index = vec![0xffu8; self.dpb.pictures.len()]; |
| 338 | let mut n = 0u8; |
| 339 | for (i, pic) in self.dpb.pictures.iter().enumerate() { |
| 340 | if pic.mark != Mark::Unused && n < 15 { |
| 341 | va_index[i] = n; |
| 342 | n += 1; |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | self.current = Some(Current { |
| 347 | surface, |
| 348 | sps_id: sps.id, |
| 349 | poc, |
| 350 | timestamp, |
| 351 | // A "_N" picture (an even NAL type below 16) is a sub-layer |
| 352 | // non-reference: nothing in its own sub-layer may predict from it, |
| 353 | // and a decoder that stores it as a reference lets the next |
| 354 | // picture's reference picture set match the wrong picture by POC. |
| 355 | is_reference: is_reference_picture(nal_type), |
| 356 | // 8.3.1: `prevTid0Pic` is the previous picture with TemporalId 0 |
| 357 | // that is neither RASL, RADL nor sub-layer non-reference. Taking |
| 358 | // the previous picture instead — which a stream with temporal |
| 359 | // sub-layers immediately punishes — puts the picture order count |
| 360 | // MSB one wrap out and hands the driver the wrong references. |
| 361 | is_tid0_anchor: temporal_id == 0 |
| 362 | && is_reference_picture(nal_type) |
| 363 | && !is_leading_picture(nal_type), |
| 364 | output: sh.pic_output_flag, |
| 365 | rps, |
| 366 | buffers: Vec::new(), |
| 367 | slices: 0, |
| 368 | va_index, |
| 369 | }); |
| 370 | Ok(()) |
| 371 | } |
| 372 | |
| 373 | fn render_slice( |
| 374 | &mut self, |
| 375 | sps: &Sps, |
| 376 | pps: &Pps, |
| 377 | sh: &SliceHeader, |
| 378 | pos: &ParsePositions, |
| 379 | payload: &[u8], |
| 380 | nal_type: NalUnitType, |
| 381 | ) -> Result<()> { |
| 382 | let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else { |
| 383 | return Ok(()); |
| 384 | }; |
| 385 | if current.sps_id != sps.id { |
| 386 | return Err(Error::Stream(ec_core::Error::corrupt( |
| 387 | "HEVC SPS changed mid-picture", |
| 388 | ))); |
| 389 | } |
| 390 | |
| 391 | if current.slices == 0 { |
| 392 | let slots: Vec<DpbSlot> = self.dpb.pictures.iter().map(DpbSlot::of).collect(); |
| 393 | let pic_param = picture_parameters( |
| 394 | sps, |
| 395 | pps, |
| 396 | sh, |
| 397 | pos, |
| 398 | nal_type, |
| 399 | (current.surface.id(), current.poc), |
| 400 | ¤t.rps, |
| 401 | &slots, |
| 402 | ); |
| 403 | current.buffers.push(ec_va::picture::buffer( |
| 404 | &session.context, |
| 405 | pic_param.to_buffer(), |
| 406 | )?); |
| 407 | if sps.scaling_list_enabled { |
| 408 | // The PPS lists override the SPS lists, and with neither sent the |
| 409 | // defaults of Tables 7-5 and 7-6 apply. |
| 410 | let list = pps |
| 411 | .scaling_list |
| 412 | .clone() |
| 413 | .or_else(|| sps.scaling_list.clone()) |
| 414 | .unwrap_or_default(); |
| 415 | current.buffers.push(ec_va::picture::buffer( |
| 416 | &session.context, |
| 417 | iq_matrix(&list).to_buffer(), |
| 418 | )?); |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | // The NAL unit header is part of the slice data the driver is handed, |
| 423 | // and every offset it is given is measured from there. |
| 424 | let nal_bytes = payload.len() + 2; |
| 425 | let mut slice_param = SliceParameterBufferHEVC { |
| 426 | slice_data_size: nal_bytes as u32, |
| 427 | slice_data_offset: 0, |
| 428 | slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL |
| 429 | slice_data_byte_offset: pos.slice_data_byte_offset(payload) as u32, |
| 430 | slice_segment_address: sh.segment_address, |
| 431 | collocated_ref_idx: if sh.temporal_mvp_enabled { |
| 432 | sh.collocated_ref_idx as u8 |
| 433 | } else { |
| 434 | 0xff |
| 435 | }, |
| 436 | num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active_minus1 as u8, |
| 437 | num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active_minus1 as u8, |
| 438 | slice_qp_delta: sh.qp_delta as i8, |
| 439 | slice_cb_qp_offset: sh.cb_qp_offset as i8, |
| 440 | slice_cr_qp_offset: sh.cr_qp_offset as i8, |
| 441 | slice_beta_offset_div2: sh.beta_offset_div2 as i8, |
| 442 | slice_tc_offset_div2: sh.tc_offset_div2 as i8, |
| 443 | five_minus_max_num_merge_cand: sh.five_minus_max_num_merge_cand as u8, |
| 444 | num_entry_point_offsets: entry_point_count(&sh.entry_point_offsets), |
| 445 | slice_data_num_emu_prevn_bytes: ec_h265_syntax::count_emulation_prevention_bytes( |
| 446 | payload, |
| 447 | ) |
| 448 | .min(u16::MAX as usize) as u16, |
| 449 | ..SliceParameterBufferHEVC::default() |
| 450 | }; |
| 451 | slice_param.long_slice_flags = LongSliceFlags { |
| 452 | last_slice_of_pic: 0, |
| 453 | dependent_slice_segment_flag: u32::from(sh.dependent_slice_segment), |
| 454 | slice_type: sh.slice_type.code(), |
| 455 | color_plane_id: u32::from(sh.colour_plane_id), |
| 456 | slice_sao_luma_flag: u32::from(sh.sao_luma), |
| 457 | slice_sao_chroma_flag: u32::from(sh.sao_chroma), |
| 458 | mvd_l1_zero_flag: u32::from(sh.mvd_l1_zero), |
| 459 | cabac_init_flag: u32::from(sh.cabac_init), |
| 460 | slice_temporal_mvp_enabled_flag: u32::from(sh.temporal_mvp_enabled), |
| 461 | slice_deblocking_filter_disabled_flag: u32::from(sh.deblocking_filter_disabled), |
| 462 | collocated_from_l0_flag: u32::from(sh.collocated_from_l0), |
| 463 | slice_loop_filter_across_slices_enabled_flag: u32::from( |
| 464 | sh.loop_filter_across_slices_enabled, |
| 465 | ), |
| 466 | }; |
| 467 | |
| 468 | if sh.slice_type != SliceType::I { |
| 469 | let lists = reference_lists(sh, ¤t.rps); |
| 470 | // A P or B slice with no reference picture at all is a broken GOP: |
| 471 | // its list would name no surface. |
| 472 | if lists[0].is_empty() || (sh.slice_type == SliceType::B && lists[1].is_empty()) { |
| 473 | return Err(Error::Stream(ec_core::Error::corrupt( |
| 474 | "HEVC inter slice with no reference picture in its reference picture set", |
| 475 | ))); |
| 476 | } |
| 477 | for (x, list) in lists.iter().enumerate() { |
| 478 | for (i, &dpb_idx) in list.iter().take(15).enumerate() { |
| 479 | slice_param.ref_pic_list[x][i] = |
| 480 | current.va_index.get(dpb_idx).copied().unwrap_or(0xff); |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | write_weights(&mut slice_param, sh); |
| 485 | |
| 486 | current.buffers.push(ec_va::picture::buffer( |
| 487 | &session.context, |
| 488 | slice_param.to_buffer(), |
| 489 | )?); |
| 490 | // Rebuild the NAL unit: `split_annex_b` hands over the payload without |
| 491 | // its two header bytes, and the driver counts from them. |
| 492 | let mut nal = Vec::with_capacity(nal_bytes); |
| 493 | nal.extend_from_slice(&ec_h265_syntax::NalHeader::new(nal_type).to_bytes()); |
| 494 | nal.extend_from_slice(payload); |
| 495 | current.buffers.push(ec_va::picture::buffer( |
| 496 | &session.context, |
| 497 | ec_va::va::BufferType::SliceData(nal), |
| 498 | )?); |
| 499 | current.slices += 1; |
| 500 | Ok(()) |
| 501 | } |
| 502 | |
| 503 | fn finish_picture(&mut self) -> Result<()> { |
| 504 | let Some(current) = self.current.take() else { |
| 505 | return Ok(()); |
| 506 | }; |
| 507 | let Some(session) = self.session.as_ref() else { |
| 508 | return Ok(()); |
| 509 | }; |
| 510 | if current.slices == 0 { |
| 511 | return Ok(()); |
| 512 | } |
| 513 | session.submit(¤t.surface, current.buffers)?; |
| 514 | |
| 515 | self.dpb.pictures.push(StoredPicture { |
| 516 | surface: Rc::clone(¤t.surface), |
| 517 | poc: current.poc, |
| 518 | timestamp: current.timestamp, |
| 519 | mark: if current.is_reference { |
| 520 | Mark::ShortTerm |
| 521 | } else { |
| 522 | Mark::Unused |
| 523 | }, |
| 524 | output: current.output, |
| 525 | }); |
| 526 | if current.is_tid0_anchor { |
| 527 | self.dpb.prev_tid0_poc = current.poc; |
| 528 | } |
| 529 | self.dpb.started = true; |
| 530 | self.bump(false); |
| 531 | Ok(()) |
| 532 | } |
| 533 | |
| 534 | /// The bumping process (C.5.2.4): output while the buffer holds more than |
| 535 | /// its reordering or storage limit allows. |
| 536 | fn bump(&mut self, flush: bool) { |
| 537 | let Some(session) = self.session.as_ref() else { |
| 538 | return; |
| 539 | }; |
| 540 | while let Some(idx) = self.dpb.next_output(flush) { |
| 541 | let pic = &self.dpb.pictures[idx]; |
| 542 | self.ready.push(Frame::new( |
| 543 | Rc::clone(&pic.surface), |
| 544 | Rc::clone(&self.display), |
| 545 | pic.timestamp, |
| 546 | session.display_size, |
| 547 | session.coded_size, |
| 548 | session.bit_depth, |
| 549 | self.colour(), |
| 550 | )); |
| 551 | self.dpb.released(idx); |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | /// Reference list construction (8.3.4), as DPB indices. |
| 557 | fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec<usize>; 2] { |
| 558 | let mut out = [Vec::new(), Vec::new()]; |
| 559 | let counts = [ |
| 560 | sh.num_ref_idx_l0_active_minus1 as usize + 1, |
| 561 | sh.num_ref_idx_l1_active_minus1 as usize + 1, |
| 562 | ]; |
| 563 | for x in 0..2 { |
| 564 | if x == 1 && sh.slice_type != SliceType::B { |
| 565 | continue; |
| 566 | } |
| 567 | // RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; list 1 swaps the |
| 568 | // first two, which is the whole difference between the two lists. |
| 569 | let mut temp: Vec<usize> = Vec::new(); |
| 570 | while temp.len() < counts[x] { |
| 571 | let before = if x == 0 { |
| 572 | &rps.st_curr_before |
| 573 | } else { |
| 574 | &rps.st_curr_after |
| 575 | }; |
| 576 | let after = if x == 0 { |
| 577 | &rps.st_curr_after |
| 578 | } else { |
| 579 | &rps.st_curr_before |
| 580 | }; |
| 581 | let round = before.len() + after.len() + rps.lt_curr.len(); |
| 582 | if round == 0 { |
| 583 | break; |
| 584 | } |
| 585 | temp.extend(before.iter().copied()); |
| 586 | temp.extend(after.iter().copied()); |
| 587 | temp.extend(rps.lt_curr.iter().copied()); |
| 588 | } |
| 589 | if temp.is_empty() { |
| 590 | continue; |
| 591 | } |
| 592 | for i in 0..counts[x] { |
| 593 | let idx = match sh.list_entry[x].get(i) { |
| 594 | Some(&entry) => *temp.get(entry as usize).unwrap_or(&temp[0]), |
| 595 | None => temp[i.min(temp.len() - 1)], |
| 596 | }; |
| 597 | out[x].push(idx); |
| 598 | } |
| 599 | } |
| 600 | out |
| 601 | } |
| 602 | |
| 603 | #[allow(clippy::too_many_arguments)] |
| 604 | fn picture_parameters( |
| 605 | sps: &Sps, |
| 606 | pps: &Pps, |
| 607 | sh: &SliceHeader, |
| 608 | pos: &ParsePositions, |
| 609 | nal_type: NalUnitType, |
| 610 | (curr_id, curr_poc): (u32, i32), |
| 611 | rps: &Rps, |
| 612 | dpb: &[DpbSlot], |
| 613 | ) -> PictureParameterBufferHEVC { |
| 614 | let mut p = PictureParameterBufferHEVC { |
| 615 | curr_pic: VAPictureHEVC::new(curr_id, curr_poc, 0), |
| 616 | pic_width_in_luma_samples: sps.pic_width_in_luma_samples as u16, |
| 617 | pic_height_in_luma_samples: sps.pic_height_in_luma_samples as u16, |
| 618 | sps_max_dec_pic_buffering_minus1: sps.max_dec_pic_buffering_minus1 as u8, |
| 619 | bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, |
| 620 | bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, |
| 621 | pcm_sample_bit_depth_luma_minus1: sps.pcm.map(|p| p.0 as u8).unwrap_or(0), |
| 622 | pcm_sample_bit_depth_chroma_minus1: sps.pcm.map(|p| p.1 as u8).unwrap_or(0), |
| 623 | log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, |
| 624 | log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, |
| 625 | log2_min_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, |
| 626 | log2_diff_max_min_transform_block_size: sps.log2_diff_max_min_tb_size as u8, |
| 627 | log2_min_pcm_luma_coding_block_size_minus3: sps.pcm.map(|p| p.2 as u8).unwrap_or(0), |
| 628 | log2_diff_max_min_pcm_luma_coding_block_size: sps.pcm.map(|p| p.3 as u8).unwrap_or(0), |
| 629 | max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, |
| 630 | max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, |
| 631 | init_qp_minus26: pps.init_qp_minus26 as i8, |
| 632 | diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, |
| 633 | pps_cb_qp_offset: pps.cb_qp_offset as i8, |
| 634 | pps_cr_qp_offset: pps.cr_qp_offset as i8, |
| 635 | log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, |
| 636 | num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, |
| 637 | num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, |
| 638 | log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, |
| 639 | num_short_term_ref_pic_sets: sps.num_short_term_ref_pic_sets as u8, |
| 640 | num_long_term_ref_pic_sps: sps.num_long_term_ref_pics_sps as u8, |
| 641 | num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, |
| 642 | num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, |
| 643 | pps_beta_offset_div2: pps.beta_offset_div2 as i8, |
| 644 | pps_tc_offset_div2: pps.tc_offset_div2 as i8, |
| 645 | num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, |
| 646 | // The size of an `st_ref_pic_set()` the slice header carried itself, |
| 647 | // so the driver can skip it; zero when the slice named an SPS set, |
| 648 | // which is what the parser reports. |
| 649 | st_rps_bits: pos.st_rps_bits, |
| 650 | ..PictureParameterBufferHEVC::default() |
| 651 | }; |
| 652 | |
| 653 | // Tile geometry: uniform spacing is expanded here because libva wants the |
| 654 | // widths either way (`va_dec_hevc.h:125`). |
| 655 | let (cols, rows) = ( |
| 656 | pps.num_tile_columns_minus1 as usize + 1, |
| 657 | pps.num_tile_rows_minus1 as usize + 1, |
| 658 | ); |
| 659 | if pps.tiles_enabled { |
| 660 | let ctb_cols = sps.pic_width_in_ctbs(); |
| 661 | let ctb_rows = sps.pic_height_in_ctbs(); |
| 662 | for i in 0..cols.min(p.column_width_minus1.len()) { |
| 663 | let width = if pps.uniform_spacing { |
| 664 | ((i + 1) as u32 * ctb_cols) / cols as u32 - (i as u32 * ctb_cols) / cols as u32 |
| 665 | } else { |
| 666 | pps.column_width_minus1.get(i).copied().unwrap_or(0) + 1 |
| 667 | }; |
| 668 | p.column_width_minus1[i] = width.saturating_sub(1) as u16; |
| 669 | } |
| 670 | for i in 0..rows.min(p.row_height_minus1.len()) { |
| 671 | let height = if pps.uniform_spacing { |
| 672 | ((i + 1) as u32 * ctb_rows) / rows as u32 - (i as u32 * ctb_rows) / rows as u32 |
| 673 | } else { |
| 674 | pps.row_height_minus1.get(i).copied().unwrap_or(0) + 1 |
| 675 | }; |
| 676 | p.row_height_minus1[i] = height.saturating_sub(1) as u16; |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | let mut n = 0usize; |
| 681 | for (i, pic) in dpb.iter().enumerate() { |
| 682 | if pic.mark == Mark::Unused || n >= p.reference_frames.len() { |
| 683 | continue; |
| 684 | } |
| 685 | let mut flags = 0; |
| 686 | if pic.mark == Mark::LongTerm { |
| 687 | flags |= PICTURE_LONG_TERM_REFERENCE; |
| 688 | } |
| 689 | if rps.st_curr_before.contains(&i) { |
| 690 | flags |= PICTURE_RPS_ST_CURR_BEFORE; |
| 691 | } else if rps.st_curr_after.contains(&i) { |
| 692 | flags |= PICTURE_RPS_ST_CURR_AFTER; |
| 693 | } else if rps.lt_curr.contains(&i) { |
| 694 | flags |= PICTURE_RPS_LT_CURR; |
| 695 | } |
| 696 | p.reference_frames[n] = VAPictureHEVC::new(pic.id, pic.poc, flags); |
| 697 | n += 1; |
| 698 | } |
| 699 | for entry in p.reference_frames.iter_mut().skip(n) { |
| 700 | *entry = VAPictureHEVC::new(ec_va::va::VA_INVALID_SURFACE, 0, PICTURE_INVALID); |
| 701 | } |
| 702 | |
| 703 | p.pic_fields = PicFields { |
| 704 | chroma_format_idc: sps.chroma_format_idc, |
| 705 | separate_colour_plane_flag: u32::from(sps.separate_colour_plane), |
| 706 | pcm_enabled_flag: u32::from(sps.pcm_enabled), |
| 707 | scaling_list_enabled_flag: u32::from(sps.scaling_list_enabled), |
| 708 | transform_skip_enabled_flag: u32::from(pps.transform_skip_enabled), |
| 709 | amp_enabled_flag: u32::from(sps.amp_enabled), |
| 710 | strong_intra_smoothing_enabled_flag: u32::from(sps.strong_intra_smoothing), |
| 711 | sign_data_hiding_enabled_flag: u32::from(pps.sign_data_hiding_enabled), |
| 712 | constrained_intra_pred_flag: u32::from(pps.constrained_intra_pred), |
| 713 | cu_qp_delta_enabled_flag: u32::from(pps.cu_qp_delta_enabled), |
| 714 | weighted_pred_flag: u32::from(pps.weighted_pred), |
| 715 | weighted_bipred_flag: u32::from(pps.weighted_bipred), |
| 716 | transquant_bypass_enabled_flag: u32::from(pps.transquant_bypass_enabled), |
| 717 | tiles_enabled_flag: u32::from(pps.tiles_enabled), |
| 718 | entropy_coding_sync_enabled_flag: u32::from(pps.entropy_coding_sync_enabled), |
| 719 | pps_loop_filter_across_slices_enabled_flag: u32::from(pps.loop_filter_across_slices_enabled), |
| 720 | loop_filter_across_tiles_enabled_flag: u32::from(pps.loop_filter_across_tiles_enabled), |
| 721 | pcm_loop_filter_disabled_flag: u32::from(sps.pcm.map(|p| p.4).unwrap_or(false)), |
| 722 | no_pic_reordering_flag: u32::from(sps.max_num_reorder_pics == 0), |
| 723 | no_bi_pred_flag: u32::from(sh.slice_type != SliceType::B), |
| 724 | }; |
| 725 | |
| 726 | |
| 727 | p.slice_parsing_fields = SliceParsingFields { |
| 728 | lists_modification_present_flag: u32::from(pps.lists_modification_present), |
| 729 | long_term_ref_pics_present_flag: u32::from(sps.long_term_ref_pics_present), |
| 730 | sps_temporal_mvp_enabled_flag: u32::from(sps.temporal_mvp_enabled), |
| 731 | cabac_init_present_flag: u32::from(pps.cabac_init_present), |
| 732 | output_flag_present_flag: u32::from(pps.output_flag_present), |
| 733 | dependent_slice_segments_enabled_flag: u32::from(pps.dependent_slice_segments_enabled), |
| 734 | pps_slice_chroma_qp_offsets_present_flag: u32::from(pps.slice_chroma_qp_offsets_present), |
| 735 | sample_adaptive_offset_enabled_flag: u32::from(sps.sao_enabled), |
| 736 | deblocking_filter_override_enabled_flag: u32::from(pps.deblocking_filter_override_enabled), |
| 737 | pps_disable_deblocking_filter_flag: u32::from(pps.deblocking_filter_disabled), |
| 738 | slice_segment_header_extension_present_flag: u32::from(pps.slice_segment_header_extension_present), |
| 739 | rap_pic_flag: u32::from(nal_type.is_irap()), |
| 740 | idr_pic_flag: u32::from(nal_type.is_idr()), |
| 741 | intra_pic_flag: u32::from(sh.slice_type == SliceType::I), |
| 742 | }; |
| 743 | p |
| 744 | } |
| 745 | |
| 746 | /// `num_entry_point_offsets` for the slice parameter buffer. The count comes from |
| 747 | /// the stream, not a fixed array: a 4K wavefront HEVC has 33 (one past the 32 a |
| 748 | /// fixed `[u32; 32]` holds), and a tiled one can pass 255. |
| 749 | fn entry_point_count(offsets: &[u32]) -> u16 { |
| 750 | offsets.len().min(u16::MAX as usize) as u16 |
| 751 | } |
| 752 | |
| 753 | /// Copy the parsed `pred_weight_table()` into the slice parameter buffer. |
| 754 | fn write_weights(s: &mut SliceParameterBufferHEVC, sh: &SliceHeader) { |
| 755 | let Some(w) = sh.pred_weight_table.as_ref() else { |
| 756 | return; |
| 757 | }; |
| 758 | s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8; |
| 759 | s.delta_chroma_log2_weight_denom = w.delta_chroma_log2_weight_denom as i8; |
| 760 | for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] { |
| 761 | let (dlw, lo, dcw, co) = if list == 0 { |
| 762 | ( |
| 763 | &mut s.delta_luma_weight_l0, |
| 764 | &mut s.luma_offset_l0, |
| 765 | &mut s.delta_chroma_weight_l0, |
| 766 | &mut s.chroma_offset_l0, |
| 767 | ) |
| 768 | } else { |
| 769 | ( |
| 770 | &mut s.delta_luma_weight_l1, |
| 771 | &mut s.luma_offset_l1, |
| 772 | &mut s.delta_chroma_weight_l1, |
| 773 | &mut s.chroma_offset_l1, |
| 774 | ) |
| 775 | }; |
| 776 | for (i, entry) in entries.iter().take(15).enumerate() { |
| 777 | if let Some((weight, offset)) = entry.luma { |
| 778 | dlw[i] = weight as i8; |
| 779 | lo[i] = offset as i8; |
| 780 | } |
| 781 | if let Some(pair) = entry.chroma { |
| 782 | for c in 0..2 { |
| 783 | dcw[i][c] = pair[c].0 as i8; |
| 784 | co[i][c] = pair[c].1 as i8; |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | /// The `VAIQMatrixBufferHEVC` for a parsed list set. VA takes the coefficients in |
| 792 | /// up-right diagonal order, which is how the syntax crate stores them. For 32x32 |
| 793 | /// only matrixId 0 (intra luma) and 3 (inter luma) are coded, so VA's two entries |
| 794 | /// are those. |
| 795 | fn iq_matrix(list: &ec_h265_syntax::ScalingList) -> IQMatrixBufferHEVC { |
| 796 | let mut iq = IQMatrixBufferHEVC::default(); |
| 797 | for m in 0..6 { |
| 798 | iq.scaling_list_4x4[m].copy_from_slice(&list.coefficients[0][m][..16]); |
| 799 | iq.scaling_list_8x8[m] = list.coefficients[1][m]; |
| 800 | iq.scaling_list_16x16[m] = list.coefficients[2][m]; |
| 801 | iq.scaling_list_dc_16x16[m] = list.dc[2][m]; |
| 802 | } |
| 803 | for (slot, matrix_id) in [0usize, 3].into_iter().enumerate() { |
| 804 | iq.scaling_list_32x32[slot] = list.coefficients[3][matrix_id]; |
| 805 | iq.scaling_list_dc_32x32[slot] = list.dc[3][matrix_id]; |
| 806 | } |
| 807 | iq |
| 808 | } |
| 809 | |
| 810 | /// Fuzzing entry point for the VA-API picture and slice parameter builders. Walks |
| 811 | /// the Annex B `data` as a stream: each SPS and PPS replaces the last, and each |
| 812 | /// slice that parses against them runs through [`picture_parameters`] and |
| 813 | /// [`write_weights`] with a synthetic DPB of up to 15 slots. Returns the number of |
| 814 | /// slices built. No GPU: the surface ids are plain numbers here. |
| 815 | #[doc(hidden)] |
| 816 | pub fn fuzz_build_parameters(data: &[u8]) -> usize { |
| 817 | let mut sps: Option<Sps> = None; |
| 818 | let mut pps: Option<Pps> = None; |
| 819 | let mut built = 0usize; |
| 820 | for nal in ec_h265_syntax::split_annex_b(data) { |
| 821 | let rbsp = nal.rbsp(); |
| 822 | match nal.header.nal_type { |
| 823 | NalUnitType::Sps => sps = Sps::parse(&rbsp).ok(), |
| 824 | NalUnitType::Pps => pps = Pps::parse(&rbsp).ok(), |
| 825 | nal_type => { |
| 826 | let (Some(s), Some(p)) = (sps.as_ref(), pps.as_ref()) else { |
| 827 | continue; |
| 828 | }; |
| 829 | let Ok((sh, pos)) = SliceHeader::parse(&rbsp, s, p, nal_type) else { |
| 830 | continue; |
| 831 | }; |
| 832 | let n = (data.len() % 16).max(1); |
| 833 | let slots: Vec<DpbSlot> = (0..n) |
| 834 | .map(|i| DpbSlot { |
| 835 | id: 0x100 + i as u32, |
| 836 | poc: i as i32 - (n as i32 / 2), |
| 837 | mark: match i % 3 { |
| 838 | 0 => Mark::ShortTerm, |
| 839 | 1 => Mark::LongTerm, |
| 840 | _ => Mark::Unused, |
| 841 | }, |
| 842 | }) |
| 843 | .collect(); |
| 844 | let rps = Rps { |
| 845 | st_curr_before: (0..n).step_by(2).collect(), |
| 846 | st_curr_after: (1..n).step_by(3).collect(), |
| 847 | lt_curr: (2..n).step_by(4).collect(), |
| 848 | }; |
| 849 | let pic = picture_parameters( |
| 850 | s, |
| 851 | p, |
| 852 | &sh, |
| 853 | &pos, |
| 854 | nal_type, |
| 855 | (0x200, data.len() as i32), |
| 856 | &rps, |
| 857 | &slots, |
| 858 | ); |
| 859 | let mut slice = SliceParameterBufferHEVC::default(); |
| 860 | write_weights(&mut slice, &sh); |
| 861 | slice.num_entry_point_offsets = entry_point_count(&sh.entry_point_offsets); |
| 862 | std::hint::black_box((pic, slice)); |
| 863 | built += 1; |
| 864 | } |
| 865 | } |
| 866 | } |
| 867 | built |
| 868 | } |
| 869 | |
| 870 | #[cfg(test)] |
| 871 | mod tests { |
| 872 | use super::*; |
| 873 | |
| 874 | #[test] |
| 875 | fn entry_points_are_counted_past_32_and_past_u8() { |
| 876 | // 33 is a 4K wavefront film (PicHeightInCtbsY - 1); 440 is 20 x 22 tiles. |
| 877 | assert_eq!(entry_point_count(&[1; 33]), 33); |
| 878 | assert_eq!(entry_point_count(&[1; 440]), 440); |
| 879 | // Past u16 saturates rather than wrapping to a small count. |
| 880 | assert_eq!(entry_point_count(&vec![1; 70_000]), u16::MAX); |
| 881 | assert_eq!(entry_point_count(&[]), 0); |
| 882 | } |
| 883 | |
| 884 | #[test] |
| 885 | fn fuzz_entry_is_total_on_garbage() { |
| 886 | assert_eq!(fuzz_build_parameters(&[]), 0); |
| 887 | assert_eq!(fuzz_build_parameters(&[0, 0, 1, 0x26, 0x01, 0xff, 0xff]), 0); |
| 888 | } |
| 889 | } |