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 H.264 decoding. |
| 2 | |
| 3 | use std::rc::Rc; |
| 4 | |
| 5 | use ec_core::color::{ColorDescription, ContentLight, Tags}; |
| 6 | use ec_h264_syntax::{ |
| 7 | AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader, |
| 8 | SliceType, Sps, unescape_rbsp, |
| 9 | }; |
| 10 | use ec_va::caps::Profile; |
| 11 | use ec_va::{Buffer, Display}; |
| 12 | |
| 13 | use super::{ReadyFrames, Session, StreamInfo}; |
| 14 | use crate::dpb264::{self, Mark, PicInfo, Poc, RefList}; |
| 15 | use crate::error::{Error, Result}; |
| 16 | use crate::frame::{Colour, Frame}; |
| 17 | use crate::h264_common::{peek_pps_id, vui_colour_tags}; |
| 18 | use crate::params::h264::{ |
| 19 | IQMatrixBufferH264, PICTURE_LONG_TERM_REFERENCE, PICTURE_SHORT_TERM_REFERENCE, PicFields, |
| 20 | PictureParameterBufferH264, SeqFields, SliceParameterBufferH264, VAPictureH264, |
| 21 | }; |
| 22 | use crate::pool::PooledSurface; |
| 23 | |
| 24 | /// Extra surfaces beyond the DPB: one being decoded, one or two in the caller's |
| 25 | /// hands, plus slack so a `frame_num` gap fill never starves the decoder. |
| 26 | const EXTRA_SURFACES: usize = 6; |
| 27 | |
| 28 | /// One stored picture as the parameter builders read it: its surface id and the |
| 29 | /// numbers its reference entry carries. Plain values, so the builders run with no |
| 30 | /// display; the fuzz target calls them the same way. |
| 31 | #[derive(Clone, Copy, Debug)] |
| 32 | struct RefView { |
| 33 | id: u32, |
| 34 | frame_num: u32, |
| 35 | long_term_frame_idx: u32, |
| 36 | poc: i32, |
| 37 | mark: Mark, |
| 38 | } |
| 39 | |
| 40 | impl RefView { |
| 41 | fn of(pic: &Picture) -> RefView { |
| 42 | RefView { |
| 43 | id: pic.surface.id(), |
| 44 | frame_num: pic.frame_num, |
| 45 | long_term_frame_idx: pic.long_term_frame_idx, |
| 46 | poc: pic.poc, |
| 47 | mark: pic.mark, |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// The picture being decoded, as the parameter builders read it. |
| 53 | #[derive(Clone, Copy, Debug)] |
| 54 | struct CurrentView { |
| 55 | id: u32, |
| 56 | frame_num: u32, |
| 57 | poc: i32, |
| 58 | is_reference: bool, |
| 59 | } |
| 60 | |
| 61 | /// The picture currently being assembled from its slices. |
| 62 | struct Current { |
| 63 | surface: Rc<PooledSurface>, |
| 64 | id: i32, |
| 65 | sps_id: u8, |
| 66 | info: PicInfo, |
| 67 | poc: Poc, |
| 68 | timestamp: i64, |
| 69 | /// `dec_ref_pic_marking()` from the picture's first slice header, which is |
| 70 | /// what 8.2.5 applies once the whole picture is decoded. |
| 71 | marking: Option<DecRefPicMarking>, |
| 72 | /// Parameter and data buffers submitted so far. |
| 73 | buffers: Vec<Buffer>, |
| 74 | slices: usize, |
| 75 | /// Set if any slice's ref list build had to pad (see `H264Decoder::recovery_poc`). |
| 76 | ref_padded: bool, |
| 77 | } |
| 78 | |
| 79 | type Dpb = dpb264::Dpb<Rc<PooledSurface>>; |
| 80 | type Picture = dpb264::Picture<Rc<PooledSurface>>; |
| 81 | |
| 82 | /// A stateless H.264 decoder. |
| 83 | pub struct H264Decoder { |
| 84 | display: Rc<Display>, |
| 85 | sps_map: [Option<Sps>; 32], |
| 86 | pps_map: Vec<Option<Pps>>, |
| 87 | session: Option<Session>, |
| 88 | dpb: Dpb, |
| 89 | ready: ReadyFrames, |
| 90 | current: Option<Current>, |
| 91 | /// Reusable unescape buffer; NAL payloads are rewritten into it in turn. |
| 92 | rbsp: Vec<u8>, |
| 93 | gap_frames: u64, |
| 94 | /// `PicOrderCnt` of the random-access point most recently established by |
| 95 | /// `reset()` — the first picture decoded after it. `None` before that |
| 96 | /// picture completes. Absent a recovery_point SEI (not parsed here), |
| 97 | /// D.2.8's recovery point defaults to this picture itself: anything with |
| 98 | /// a smaller POC that had to guess a reference (`Current::ref_padded`) |
| 99 | /// predicts from something never decoded since the seek and must not |
| 100 | /// reach the caller. |
| 101 | recovery_poc: Option<i32>, |
| 102 | /// The most recent SPS's VUI colour tags, sticky across pictures. |
| 103 | colour_tags: Tags, |
| 104 | } |
| 105 | |
| 106 | impl H264Decoder { |
| 107 | /// A decoder with no stream state. The GPU context is created when the |
| 108 | /// first SPS arrives, because only then is the size and bit depth known. |
| 109 | pub fn new(display: &Rc<Display>) -> H264Decoder { |
| 110 | H264Decoder { |
| 111 | display: Rc::clone(display), |
| 112 | sps_map: [const { None }; 32], |
| 113 | pps_map: (0..256).map(|_| None).collect(), |
| 114 | session: None, |
| 115 | dpb: Dpb::default(), |
| 116 | ready: ReadyFrames::default(), |
| 117 | current: None, |
| 118 | rbsp: Vec::new(), |
| 119 | gap_frames: 0, |
| 120 | recovery_poc: None, |
| 121 | colour_tags: Tags::default(), |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /// Decode one Annex B access unit. |
| 126 | pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { |
| 127 | for nal in AnnexBIter::new(data) { |
| 128 | let Some((&first, payload)) = nal.split_first() else { |
| 129 | continue; |
| 130 | }; |
| 131 | let header = NalHeader::parse(first)?; |
| 132 | match header.unit_type { |
| 133 | NalUnitType::Sps => { |
| 134 | let mut rbsp = std::mem::take(&mut self.rbsp); |
| 135 | unescape_rbsp(payload, &mut rbsp); |
| 136 | let sps = Sps::parse(&rbsp); |
| 137 | self.rbsp = rbsp; |
| 138 | let sps = sps?; |
| 139 | self.dpb.configure(&sps); |
| 140 | self.colour_tags = vui_colour_tags(&sps); |
| 141 | let id = usize::from(sps.id); |
| 142 | self.sps_map[id] = Some(sps); |
| 143 | } |
| 144 | NalUnitType::Pps => { |
| 145 | let mut rbsp = std::mem::take(&mut self.rbsp); |
| 146 | unescape_rbsp(payload, &mut rbsp); |
| 147 | let pps = Pps::parse(&rbsp, |id| self.sps_map[usize::from(id)].as_ref()); |
| 148 | self.rbsp = rbsp; |
| 149 | let pps = pps?; |
| 150 | let id = pps.id as usize; |
| 151 | if id < self.pps_map.len() { |
| 152 | self.pps_map[id] = Some(pps); |
| 153 | } |
| 154 | } |
| 155 | NalUnitType::Slice | NalUnitType::SliceIdr => { |
| 156 | self.slice(header, nal, payload, timestamp)?; |
| 157 | } |
| 158 | // SEI, AUD, filler and everything else carries nothing a |
| 159 | // stateless decode submission needs. |
| 160 | _ => {} |
| 161 | } |
| 162 | } |
| 163 | // One access unit is one picture: close it here rather than waiting for |
| 164 | // the next first_mb_in_slice == 0, so a caller gets its frame in the |
| 165 | // call that fed the data. |
| 166 | self.finish_picture()?; |
| 167 | Ok(()) |
| 168 | } |
| 169 | |
| 170 | /// The next frame in display order. |
| 171 | pub fn next_frame(&mut self) -> Option<Frame> { |
| 172 | self.ready.pop() |
| 173 | } |
| 174 | |
| 175 | /// Push every buffered picture out (end of stream). |
| 176 | pub fn flush(&mut self) { |
| 177 | let _ = self.finish_picture(); |
| 178 | self.bump(true); |
| 179 | } |
| 180 | |
| 181 | /// Drop all picture state; parameter sets and the GPU session survive. |
| 182 | pub fn reset(&mut self) { |
| 183 | self.current = None; |
| 184 | self.dpb.clear(); |
| 185 | self.ready.clear(); |
| 186 | self.gap_frames = 0; |
| 187 | self.recovery_poc = None; |
| 188 | } |
| 189 | |
| 190 | /// What the stream turned out to be, once its first SPS was seen. |
| 191 | pub fn stream_info(&self) -> Option<StreamInfo> { |
| 192 | self.session.as_ref().map(Session::info) |
| 193 | } |
| 194 | |
| 195 | /// Pictures inferred for `frame_num` gaps (8.2.5.2) since the last reset. |
| 196 | /// |
| 197 | /// Exposed because it is the difference between a stream that stays on the |
| 198 | /// hardware and one that falls back to software: a gap is normal, and a |
| 199 | /// caller watching this counter can tell "the encoder skipped pictures" |
| 200 | /// from "the decoder is guessing". |
| 201 | pub fn gap_frames_synthesized(&self) -> u64 { |
| 202 | self.gap_frames |
| 203 | } |
| 204 | |
| 205 | fn slice( |
| 206 | &mut self, |
| 207 | header: NalHeader, |
| 208 | nal: &[u8], |
| 209 | payload: &[u8], |
| 210 | timestamp: i64, |
| 211 | ) -> Result<()> { |
| 212 | let mut rbsp = std::mem::take(&mut self.rbsp); |
| 213 | unescape_rbsp(payload, &mut rbsp); |
| 214 | let result = self.slice_rbsp(header, nal, &rbsp, timestamp); |
| 215 | self.rbsp = rbsp; |
| 216 | result |
| 217 | } |
| 218 | |
| 219 | fn slice_rbsp( |
| 220 | &mut self, |
| 221 | header: NalHeader, |
| 222 | nal: &[u8], |
| 223 | rbsp: &[u8], |
| 224 | timestamp: i64, |
| 225 | ) -> Result<()> { |
| 226 | // Two passes over the parameter sets: the slice header needs the PPS to |
| 227 | // parse, and the PPS names its SPS. |
| 228 | let pps_id = peek_pps_id(rbsp)?; |
| 229 | let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { |
| 230 | // A slice referring to a parameter set we never received is what a |
| 231 | // seek into the middle of a stream looks like; skip it rather than |
| 232 | // failing the whole access unit. |
| 233 | return Ok(()); |
| 234 | }; |
| 235 | let Some(sps) = self.sps_map[usize::from(pps.sps_id)].clone() else { |
| 236 | return Ok(()); |
| 237 | }; |
| 238 | let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?; |
| 239 | |
| 240 | if sh.first_mb_in_slice == 0 { |
| 241 | self.finish_picture()?; |
| 242 | self.start_picture(&sps, &sh, header, timestamp)?; |
| 243 | } |
| 244 | if self.current.is_none() { |
| 245 | // Mid-picture entry after a seek: no first slice, nothing to add to. |
| 246 | return Ok(()); |
| 247 | } |
| 248 | self.render_slice(&sps, &pps, &sh, nal, header) |
| 249 | } |
| 250 | |
| 251 | /// Create the GPU session if this stream has not had one yet. |
| 252 | fn ensure_session(&mut self, sps: &Sps) -> Result<()> { |
| 253 | if sps.chroma_format_idc != 1 { |
| 254 | return Err(Error::unsupported( |
| 255 | format!("H.264 chroma_format_idc {}", sps.chroma_format_idc), |
| 256 | "VA-API H.264 decode is 4:2:0 only", |
| 257 | )); |
| 258 | } |
| 259 | let profile = profile_for(sps)?; |
| 260 | let coded = (sps.coded_width, sps.coded_height); |
| 261 | let bit_depth = sps.bit_depth_luma; |
| 262 | if let Some(session) = &self.session |
| 263 | && session.coded_size == coded |
| 264 | && session.bit_depth == bit_depth |
| 265 | && session.profile == profile |
| 266 | { |
| 267 | return Ok(()); |
| 268 | } |
| 269 | // A resolution change starts a new session; the old one drops with its |
| 270 | // surfaces once the frames still out there are released. |
| 271 | self.current = None; |
| 272 | self.dpb.clear(); |
| 273 | let surfaces = self.dpb.capacity() + EXTRA_SURFACES; |
| 274 | self.session = Some(Session::new( |
| 275 | &self.display, |
| 276 | profile, |
| 277 | coded, |
| 278 | (sps.width, sps.height), |
| 279 | bit_depth, |
| 280 | surfaces, |
| 281 | )?); |
| 282 | Ok(()) |
| 283 | } |
| 284 | |
| 285 | fn start_picture( |
| 286 | &mut self, |
| 287 | sps: &Sps, |
| 288 | sh: &SliceHeader, |
| 289 | header: NalHeader, |
| 290 | timestamp: i64, |
| 291 | ) -> Result<()> { |
| 292 | self.ensure_session(sps)?; |
| 293 | let info = PicInfo { |
| 294 | is_idr: header.is_idr(), |
| 295 | is_reference: header.ref_idc != 0, |
| 296 | frame_num: sh.frame_num, |
| 297 | pic_order_cnt_lsb: sh.pic_order_cnt_lsb, |
| 298 | delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom, |
| 299 | delta_pic_order_cnt: sh.delta_pic_order_cnt, |
| 300 | }; |
| 301 | |
| 302 | // 8.2.5.2: missing frame_num values are normal (a seek, a dropped |
| 303 | // packet, an encoder that skipped a picture). Synthesising the frames |
| 304 | // keeps the reference numbering aligned, which is the difference |
| 305 | // between decoding the rest of the GOP and falling back to software. |
| 306 | if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) { |
| 307 | self.gap_frames += self.dpb.fill_frame_num_gap(sps, sh.frame_num)? as u64; |
| 308 | } |
| 309 | |
| 310 | let poc = self.dpb.picture_order_count(sps, &info)?; |
| 311 | let session = self |
| 312 | .session |
| 313 | .as_ref() |
| 314 | .ok_or_else(|| Error::config("H.264 picture before any SPS"))?; |
| 315 | let surface = session.acquire()?; |
| 316 | let id = self.dpb.next_id(); |
| 317 | self.current = Some(Current { |
| 318 | surface, |
| 319 | id, |
| 320 | sps_id: sps.id, |
| 321 | info, |
| 322 | poc, |
| 323 | timestamp, |
| 324 | marking: sh.dec_ref_pic_marking.clone(), |
| 325 | buffers: Vec::new(), |
| 326 | slices: 0, |
| 327 | ref_padded: false, |
| 328 | }); |
| 329 | Ok(()) |
| 330 | } |
| 331 | |
| 332 | fn render_slice( |
| 333 | &mut self, |
| 334 | sps: &Sps, |
| 335 | pps: &Pps, |
| 336 | sh: &SliceHeader, |
| 337 | nal: &[u8], |
| 338 | header: NalHeader, |
| 339 | ) -> Result<()> { |
| 340 | let (Some(current), Some(session)) = (self.current.as_mut(), self.session.as_ref()) else { |
| 341 | return Ok(()); |
| 342 | }; |
| 343 | if current.sps_id != sps.id { |
| 344 | return Err(Error::Stream(ec_core::Error::corrupt( |
| 345 | "H.264 SPS changed mid-picture", |
| 346 | ))); |
| 347 | } |
| 348 | |
| 349 | // The picture parameter buffer goes in once, with the first slice: it |
| 350 | // describes the picture, and the DPB it names must not change under the |
| 351 | // driver between slices. |
| 352 | if current.slices == 0 { |
| 353 | let curr = CurrentView { |
| 354 | id: current.surface.id(), |
| 355 | frame_num: current.info.frame_num, |
| 356 | poc: current.poc.value, |
| 357 | is_reference: current.info.is_reference, |
| 358 | }; |
| 359 | let refs: Vec<RefView> = self.dpb.frames.iter().map(RefView::of).collect(); |
| 360 | let pic_param = picture_parameters(sps, pps, sh, header, curr, &refs); |
| 361 | current.buffers.push(ec_va::picture::buffer( |
| 362 | &session.context, |
| 363 | pic_param.to_buffer(), |
| 364 | )?); |
| 365 | // The matrices are sent for every picture, flat or not: a driver |
| 366 | // that never receives them dequantises with a zero matrix and |
| 367 | // hands back a uniformly grey surface (radeonsi does exactly this). |
| 368 | // A PPS scaling matrix overrides the SPS one (7.4.2.2). |
| 369 | let iq = match pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()) { |
| 370 | Some(lists) => IQMatrixBufferH264 { |
| 371 | scaling_list_4x4: lists.list_4x4, |
| 372 | scaling_list_8x8: [lists.list_8x8[0], lists.list_8x8[1]], |
| 373 | }, |
| 374 | None => IQMatrixBufferH264::default(), |
| 375 | }; |
| 376 | current |
| 377 | .buffers |
| 378 | .push(ec_va::picture::buffer(&session.context, iq.to_buffer())?); |
| 379 | } |
| 380 | |
| 381 | let max_pic_num = 1i32 << sps.log2_max_frame_num; |
| 382 | let lists = if sh.slice_type.is_intra() { |
| 383 | [RefList::default(), RefList::default()] |
| 384 | } else { |
| 385 | self.dpb.number_short_term(sh.frame_num, sps); |
| 386 | let (lists, padded) = self.dpb.build_ref_lists( |
| 387 | sh.slice_type, |
| 388 | current.poc.value, |
| 389 | sh.frame_num as i32, |
| 390 | max_pic_num, |
| 391 | sh.num_ref_idx_l0_active as usize, |
| 392 | sh.num_ref_idx_l1_active as usize, |
| 393 | (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), |
| 394 | )?; |
| 395 | current.ref_padded |= padded; |
| 396 | lists |
| 397 | }; |
| 398 | |
| 399 | let refs: Vec<RefView> = self.dpb.frames.iter().map(RefView::of).collect(); |
| 400 | let slice_param = slice_parameters(sh, pps, nal, &lists, &refs); |
| 401 | current.buffers.push(ec_va::picture::buffer( |
| 402 | &session.context, |
| 403 | slice_param.to_buffer(), |
| 404 | )?); |
| 405 | current.buffers.push(ec_va::picture::buffer( |
| 406 | &session.context, |
| 407 | ec_va::va::BufferType::SliceData(nal.to_vec()), |
| 408 | )?); |
| 409 | current.slices += 1; |
| 410 | Ok(()) |
| 411 | } |
| 412 | |
| 413 | fn finish_picture(&mut self) -> Result<()> { |
| 414 | let Some(current) = self.current.take() else { |
| 415 | return Ok(()); |
| 416 | }; |
| 417 | let Some(session) = self.session.as_ref() else { |
| 418 | return Ok(()); |
| 419 | }; |
| 420 | if current.slices == 0 { |
| 421 | // No slice data reached the driver, so there is nothing to submit; |
| 422 | // the surface returns to the pool with `current`. |
| 423 | return Ok(()); |
| 424 | } |
| 425 | let Some(sps) = self.sps_map[usize::from(current.sps_id)].clone() else { |
| 426 | return Ok(()); |
| 427 | }; |
| 428 | |
| 429 | session.submit(¤t.surface, current.buffers)?; |
| 430 | |
| 431 | // See `recovery_poc`'s doc comment. |
| 432 | let recovery_poc = *self.recovery_poc.get_or_insert(current.poc.value); |
| 433 | let output_ok = !(current.ref_padded && current.poc.value < recovery_poc); |
| 434 | |
| 435 | let picture = Picture { |
| 436 | id: current.id, |
| 437 | surface: Rc::clone(¤t.surface), |
| 438 | timestamp: current.timestamp, |
| 439 | frame_num: current.info.frame_num, |
| 440 | frame_num_wrap: current.info.frame_num as i32, |
| 441 | pic_num: current.info.frame_num as i32, |
| 442 | long_term_frame_idx: 0, |
| 443 | poc: current.poc.value, |
| 444 | poc_msb: current.poc.msb, |
| 445 | poc_lsb: current.poc.lsb, |
| 446 | frame_num_offset: current.poc.frame_num_offset, |
| 447 | mark: Mark::Unused, |
| 448 | non_existing: false, |
| 449 | output: true, |
| 450 | }; |
| 451 | self.dpb.store( |
| 452 | picture, |
| 453 | &sps, |
| 454 | ¤t.info, |
| 455 | current.marking.as_ref(), |
| 456 | output_ok, |
| 457 | )?; |
| 458 | self.bump(false); |
| 459 | Ok(()) |
| 460 | } |
| 461 | |
| 462 | /// Move whatever the bumping process releases into the ready queue. |
| 463 | fn bump(&mut self, flush: bool) { |
| 464 | let Some(session) = self.session.as_ref() else { |
| 465 | return; |
| 466 | }; |
| 467 | while let Some(idx) = self.dpb.next_output(flush) { |
| 468 | let pic = &self.dpb.frames[idx]; |
| 469 | let frame = Frame::new( |
| 470 | Rc::clone(&pic.surface), |
| 471 | Rc::clone(&self.display), |
| 472 | pic.timestamp, |
| 473 | session.display_size, |
| 474 | session.coded_size, |
| 475 | session.bit_depth, |
| 476 | self.colour(), |
| 477 | ); |
| 478 | self.ready.push(frame); |
| 479 | self.dpb.released(idx); |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | /// This stream's colour metadata, once its first SPS has been seen. No SEI |
| 484 | /// here — H.264's mastering-display/content-light-level SEI is not parsed |
| 485 | /// by this family today, so this is VUI-only. |
| 486 | pub fn colour(&self) -> Option<Colour> { |
| 487 | let session = self.session.as_ref()?; |
| 488 | Some(Colour { |
| 489 | description: ColorDescription::resolve( |
| 490 | Tags::default(), |
| 491 | self.colour_tags, |
| 492 | session.display_size.1, |
| 493 | ), |
| 494 | light: ContentLight::default(), |
| 495 | }) |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | /// The VA profile for a stream, from its SPS. |
| 500 | fn profile_for(sps: &Sps) -> Result<Profile> { |
| 501 | Ok(match sps.profile_idc { |
| 502 | 66 => { |
| 503 | // Constrained baseline is a subset of main and every driver that |
| 504 | // decodes main decodes it; plain baseline (FMO/ASO) is not, and |
| 505 | // this crate does not implement slice groups either way. |
| 506 | Profile::H264ConstrainedBaseline |
| 507 | } |
| 508 | 77 | 88 => Profile::H264Main, |
| 509 | 100 | 110 | 122 | 244 if sps.bit_depth_luma > 8 => Profile::H264High10, |
| 510 | 100 => Profile::H264High, |
| 511 | other => { |
| 512 | return Err(Error::unsupported( |
| 513 | format!("H.264 profile_idc {other}"), |
| 514 | "no VA profile covers it", |
| 515 | )); |
| 516 | } |
| 517 | }) |
| 518 | } |
| 519 | |
| 520 | /// `slice_type` as the driver wants it: the modulo-5 value of Table 7-6. |
| 521 | fn slice_type_code(slice_type: SliceType) -> u8 { |
| 522 | match slice_type { |
| 523 | SliceType::P => 0, |
| 524 | SliceType::B => 1, |
| 525 | SliceType::I => 2, |
| 526 | SliceType::Sp => 3, |
| 527 | SliceType::Si => 4, |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | /// The VA reference entry for a stored picture. |
| 532 | fn reference_entry(pic: &RefView) -> VAPictureH264 { |
| 533 | let flags = match pic.mark { |
| 534 | Mark::Long => PICTURE_LONG_TERM_REFERENCE, |
| 535 | _ => PICTURE_SHORT_TERM_REFERENCE, |
| 536 | }; |
| 537 | let frame_idx = if pic.mark == Mark::Long { |
| 538 | pic.long_term_frame_idx |
| 539 | } else { |
| 540 | pic.frame_num |
| 541 | }; |
| 542 | VAPictureH264::frame(pic.id, frame_idx, pic.poc, flags) |
| 543 | } |
| 544 | |
| 545 | fn picture_parameters( |
| 546 | sps: &Sps, |
| 547 | pps: &Pps, |
| 548 | sh: &SliceHeader, |
| 549 | header: NalHeader, |
| 550 | curr: CurrentView, |
| 551 | dpb: &[RefView], |
| 552 | ) -> PictureParameterBufferH264 { |
| 553 | let mut p = PictureParameterBufferH264 { |
| 554 | curr_pic: VAPictureH264::frame( |
| 555 | curr.id, |
| 556 | curr.frame_num, |
| 557 | curr.poc, |
| 558 | if curr.is_reference { |
| 559 | PICTURE_SHORT_TERM_REFERENCE |
| 560 | } else { |
| 561 | 0 |
| 562 | }, |
| 563 | ), |
| 564 | picture_width_in_mbs_minus1: (sps.mb_width.max(1) - 1) as u16, |
| 565 | picture_height_in_mbs_minus1: (sps.mb_height.max(1) - 1) as u16, |
| 566 | bit_depth_luma_minus8: sps.bit_depth_luma.saturating_sub(8), |
| 567 | bit_depth_chroma_minus8: sps.bit_depth_chroma.saturating_sub(8), |
| 568 | num_ref_frames: sps.max_num_ref_frames.min(255) as u8, |
| 569 | pic_init_qp_minus26: (pps.pic_init_qp - 26) as i8, |
| 570 | pic_init_qs_minus26: (pps.pic_init_qs - 26) as i8, |
| 571 | chroma_qp_index_offset: pps.chroma_qp_index_offset as i8, |
| 572 | second_chroma_qp_index_offset: pps.second_chroma_qp_index_offset as i8, |
| 573 | frame_num: sh.frame_num as u16, |
| 574 | ..PictureParameterBufferH264::default() |
| 575 | }; |
| 576 | |
| 577 | for (n, pic) in dpb |
| 578 | .iter() |
| 579 | .filter(|p| p.mark != Mark::Unused) |
| 580 | .take(p.reference_frames.len()) |
| 581 | .enumerate() |
| 582 | { |
| 583 | p.reference_frames[n] = reference_entry(pic); |
| 584 | } |
| 585 | |
| 586 | p.seq_fields = SeqFields { |
| 587 | chroma_format_idc: u32::from(sps.chroma_format_idc), |
| 588 | residual_colour_transform_flag: u32::from(sps.separate_colour_plane), |
| 589 | gaps_in_frame_num_value_allowed_flag: u32::from(sps.gaps_in_frame_num_allowed), |
| 590 | frame_mbs_only_flag: u32::from(sps.frame_mbs_only), |
| 591 | mb_adaptive_frame_field_flag: u32::from(sps.mb_adaptive_frame_field), |
| 592 | direct_8x8_inference_flag: u32::from(sps.direct_8x8_inference), |
| 593 | // A.3.3.2: 8x8 bi-prediction is restricted from level 3.1 up. |
| 594 | min_luma_bipred_size8x8: u32::from(sps.level_idc >= 31), |
| 595 | log2_max_frame_num_minus4: u32::from(sps.log2_max_frame_num.saturating_sub(4)), |
| 596 | pic_order_cnt_type: u32::from(sps.pic_order_cnt_type), |
| 597 | log2_max_pic_order_cnt_lsb_minus4: u32::from( |
| 598 | sps.log2_max_pic_order_cnt_lsb.saturating_sub(4), |
| 599 | ), |
| 600 | delta_pic_order_always_zero_flag: u32::from(sps.delta_pic_order_always_zero), |
| 601 | }; |
| 602 | |
| 603 | p.pic_fields = PicFields { |
| 604 | entropy_coding_mode_flag: u32::from(pps.entropy_coding_mode), |
| 605 | weighted_pred_flag: u32::from(pps.weighted_pred), |
| 606 | weighted_bipred_idc: u32::from(pps.weighted_bipred_idc), |
| 607 | transform_8x8_mode_flag: u32::from(pps.transform_8x8_mode), |
| 608 | field_pic_flag: u32::from(sh.field_pic), |
| 609 | constrained_intra_pred_flag: u32::from(pps.constrained_intra_pred), |
| 610 | pic_order_present_flag: u32::from(pps.bottom_field_pic_order_in_frame_present), |
| 611 | deblocking_filter_control_present_flag: u32::from(pps.deblocking_filter_control_present), |
| 612 | redundant_pic_cnt_present_flag: u32::from(pps.redundant_pic_cnt_present), |
| 613 | reference_pic_flag: u32::from(header.ref_idc != 0), |
| 614 | }; |
| 615 | p |
| 616 | } |
| 617 | |
| 618 | fn slice_parameters( |
| 619 | sh: &SliceHeader, |
| 620 | pps: &Pps, |
| 621 | nal: &[u8], |
| 622 | lists: &[RefList; 2], |
| 623 | dpb: &[RefView], |
| 624 | ) -> SliceParameterBufferH264 { |
| 625 | let mut s = SliceParameterBufferH264 { |
| 626 | slice_data_size: nal.len() as u32, |
| 627 | slice_data_offset: 0, |
| 628 | slice_data_flag: 0, // VA_SLICE_DATA_FLAG_ALL |
| 629 | // "relative to and includes the NAL unit byte", counted in the |
| 630 | // unescaped RBSP: the syntax crate's header_bits starts *after* that |
| 631 | // byte, hence the 8. |
| 632 | slice_data_bit_offset: (sh.header_bits + 8) as u16, |
| 633 | first_mb_in_slice: sh.first_mb_in_slice as u16, |
| 634 | slice_type: slice_type_code(sh.slice_type), |
| 635 | direct_spatial_mv_pred_flag: u8::from(sh.direct_spatial_mv_pred), |
| 636 | num_ref_idx_l0_active_minus1: sh.num_ref_idx_l0_active.saturating_sub(1) as u8, |
| 637 | num_ref_idx_l1_active_minus1: sh.num_ref_idx_l1_active.saturating_sub(1) as u8, |
| 638 | cabac_init_idc: sh.cabac_init_idc as u8, |
| 639 | // The syntax crate resolves SliceQPY; the driver wants the delta back. |
| 640 | slice_qp_delta: (sh.slice_qp - pps.pic_init_qp) as i8, |
| 641 | disable_deblocking_filter_idc: sh.deblock.disable_idc, |
| 642 | slice_alpha_c0_offset_div2: (sh.deblock.alpha_c0_offset / 2) as i8, |
| 643 | slice_beta_offset_div2: (sh.deblock.beta_offset / 2) as i8, |
| 644 | ..SliceParameterBufferH264::default() |
| 645 | }; |
| 646 | |
| 647 | for (x, list) in lists.iter().enumerate() { |
| 648 | let out = if x == 0 { |
| 649 | &mut s.ref_pic_list0 |
| 650 | } else { |
| 651 | &mut s.ref_pic_list1 |
| 652 | }; |
| 653 | for i in 0..list.len().min(out.len()) { |
| 654 | if let Some(idx) = list.get(i) |
| 655 | && let Some(pic) = dpb.get(idx) |
| 656 | { |
| 657 | out[i] = reference_entry(pic); |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | if let Some(w) = sh.pred_weight_table.as_ref() { |
| 663 | write_weights(&mut s, w); |
| 664 | } |
| 665 | s |
| 666 | } |
| 667 | |
| 668 | /// Copy a parsed `pred_weight_table()` into the slice parameter buffer. |
| 669 | /// |
| 670 | /// The spec's default weights are `(1 << denom, 0)`, and a driver reads every |
| 671 | /// entry the active count names — so an absent entry has to be *written* as the |
| 672 | /// default rather than left at zero, which would black out the prediction. |
| 673 | fn write_weights(s: &mut SliceParameterBufferH264, w: &PredWeightTable) { |
| 674 | s.luma_log2_weight_denom = w.luma_log2_weight_denom as u8; |
| 675 | s.chroma_log2_weight_denom = w.chroma_log2_weight_denom as u8; |
| 676 | let luma_default = 1i16 << w.luma_log2_weight_denom; |
| 677 | let chroma_default = 1i16 << w.chroma_log2_weight_denom; |
| 678 | |
| 679 | for (list, entries) in [(0usize, &w.l0), (1usize, &w.l1)] { |
| 680 | let (weights, offsets, cweights, coffsets, luma_flag, chroma_flag) = if list == 0 { |
| 681 | ( |
| 682 | &mut s.luma_weight_l0, |
| 683 | &mut s.luma_offset_l0, |
| 684 | &mut s.chroma_weight_l0, |
| 685 | &mut s.chroma_offset_l0, |
| 686 | &mut s.luma_weight_l0_flag, |
| 687 | &mut s.chroma_weight_l0_flag, |
| 688 | ) |
| 689 | } else { |
| 690 | ( |
| 691 | &mut s.luma_weight_l1, |
| 692 | &mut s.luma_offset_l1, |
| 693 | &mut s.chroma_weight_l1, |
| 694 | &mut s.chroma_offset_l1, |
| 695 | &mut s.luma_weight_l1_flag, |
| 696 | &mut s.chroma_weight_l1_flag, |
| 697 | ) |
| 698 | }; |
| 699 | for (i, entry) in entries.iter().take(32).enumerate() { |
| 700 | match entry.luma { |
| 701 | Some((weight, offset)) => { |
| 702 | *luma_flag = 1; |
| 703 | weights[i] = weight as i16; |
| 704 | offsets[i] = offset as i16; |
| 705 | } |
| 706 | None => { |
| 707 | weights[i] = luma_default; |
| 708 | offsets[i] = 0; |
| 709 | } |
| 710 | } |
| 711 | match entry.chroma { |
| 712 | Some(pair) => { |
| 713 | *chroma_flag = 1; |
| 714 | for c in 0..2 { |
| 715 | cweights[i][c] = pair[c].0 as i16; |
| 716 | coffsets[i][c] = pair[c].1 as i16; |
| 717 | } |
| 718 | } |
| 719 | None => { |
| 720 | for c in 0..2 { |
| 721 | cweights[i][c] = chroma_default; |
| 722 | coffsets[i][c] = 0; |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | } |
| 729 | |
| 730 | /// Feeds an Annex B stream through the H.264 parameter builders, with the SPS, |
| 731 | /// PPS and slice headers the real parser produces and a synthetic DPB of up to 15 |
| 732 | /// slots. No GPU: surface ids are plain numbers. Returns the number of slices built. |
| 733 | #[doc(hidden)] |
| 734 | pub fn fuzz_build_parameters(data: &[u8]) -> usize { |
| 735 | let mut sps_map: Vec<Option<Sps>> = std::iter::repeat_with(|| None).take(32).collect(); |
| 736 | let mut pps_map: Vec<Option<Pps>> = std::iter::repeat_with(|| None).take(256).collect(); |
| 737 | let mut built = 0usize; |
| 738 | for nal in AnnexBIter::new(data) { |
| 739 | let Some((&first, payload)) = nal.split_first() else { |
| 740 | continue; |
| 741 | }; |
| 742 | let Ok(header) = NalHeader::parse(first) else { |
| 743 | continue; |
| 744 | }; |
| 745 | let mut rbsp = Vec::new(); |
| 746 | unescape_rbsp(payload, &mut rbsp); |
| 747 | match header.unit_type { |
| 748 | NalUnitType::Sps => { |
| 749 | if let Ok(sps) = Sps::parse(&rbsp) |
| 750 | && let Some(slot) = sps_map.get_mut(usize::from(sps.id)) |
| 751 | { |
| 752 | *slot = Some(sps); |
| 753 | } |
| 754 | } |
| 755 | NalUnitType::Pps => { |
| 756 | let pps = Pps::parse(&rbsp, |id| { |
| 757 | sps_map.get(usize::from(id)).and_then(Option::as_ref) |
| 758 | }); |
| 759 | if let Ok(pps) = pps |
| 760 | && let Some(slot) = pps_map.get_mut(pps.id as usize) |
| 761 | { |
| 762 | *slot = Some(pps); |
| 763 | } |
| 764 | } |
| 765 | NalUnitType::Slice | NalUnitType::SliceIdr => { |
| 766 | let Ok(pps_id) = peek_pps_id(&rbsp) else { |
| 767 | continue; |
| 768 | }; |
| 769 | let Some(pps) = pps_map.get(pps_id as usize).and_then(Option::as_ref) else { |
| 770 | continue; |
| 771 | }; |
| 772 | let Some(sps) = sps_map |
| 773 | .get(usize::from(pps.sps_id)) |
| 774 | .and_then(Option::as_ref) |
| 775 | else { |
| 776 | continue; |
| 777 | }; |
| 778 | let Ok(sh) = SliceHeader::parse(&rbsp, header, sps, pps) else { |
| 779 | continue; |
| 780 | }; |
| 781 | let n = (data.len() % 16).max(1); |
| 782 | let refs: Vec<RefView> = (0..n) |
| 783 | .map(|i| RefView { |
| 784 | id: 0x100 + i as u32, |
| 785 | frame_num: i as u32, |
| 786 | long_term_frame_idx: (i % 4) as u32, |
| 787 | poc: i as i32 - (n as i32 / 2), |
| 788 | mark: match i % 3 { |
| 789 | 0 => Mark::Short, |
| 790 | 1 => Mark::Long, |
| 791 | _ => Mark::Unused, |
| 792 | }, |
| 793 | }) |
| 794 | .collect(); |
| 795 | let curr = CurrentView { |
| 796 | id: 0x200, |
| 797 | frame_num: sh.frame_num, |
| 798 | poc: data.len() as i32, |
| 799 | is_reference: header.ref_idc != 0, |
| 800 | }; |
| 801 | let mut lists = [RefList::default(), RefList::default()]; |
| 802 | if !sh.slice_type.is_intra() { |
| 803 | for i in (0..n).step_by(2) { |
| 804 | lists[0].push(i); |
| 805 | } |
| 806 | for i in (1..n).step_by(3) { |
| 807 | lists[1].push(i); |
| 808 | } |
| 809 | } |
| 810 | let pic = picture_parameters(sps, pps, &sh, header, curr, &refs); |
| 811 | let slice = slice_parameters(&sh, pps, nal, &lists, &refs); |
| 812 | std::hint::black_box((pic, slice)); |
| 813 | built += 1; |
| 814 | } |
| 815 | _ => {} |
| 816 | } |
| 817 | } |
| 818 | built |
| 819 | } |
| 820 | |
| 821 | #[cfg(test)] |
| 822 | mod tests { |
| 823 | use super::*; |
| 824 | |
| 825 | fn test_sps() -> Sps { |
| 826 | Sps { |
| 827 | profile_idc: 100, |
| 828 | constraint_flags: 0, |
| 829 | level_idc: 40, |
| 830 | id: 0, |
| 831 | chroma_format_idc: 1, |
| 832 | separate_colour_plane: false, |
| 833 | bit_depth_luma: 8, |
| 834 | bit_depth_chroma: 8, |
| 835 | transform_bypass: false, |
| 836 | scaling_lists: None, |
| 837 | log2_max_frame_num: 4, |
| 838 | pic_order_cnt_type: 0, |
| 839 | log2_max_pic_order_cnt_lsb: 4, |
| 840 | delta_pic_order_always_zero: false, |
| 841 | offset_for_non_ref_pic: 0, |
| 842 | offset_for_top_to_bottom_field: 0, |
| 843 | offsets_for_ref_frame: Vec::new(), |
| 844 | max_num_ref_frames: 4, |
| 845 | gaps_in_frame_num_allowed: true, |
| 846 | frame_mbs_only: true, |
| 847 | mb_adaptive_frame_field: false, |
| 848 | direct_8x8_inference: true, |
| 849 | crop: (0, 0, 0, 0), |
| 850 | vui: None, |
| 851 | mb_width: 120, |
| 852 | mb_height: 68, |
| 853 | coded_width: 1920, |
| 854 | coded_height: 1088, |
| 855 | width: 1920, |
| 856 | height: 1080, |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | #[test] |
| 861 | fn slice_type_codes_match_table_7_6() { |
| 862 | assert_eq!(slice_type_code(SliceType::P), 0); |
| 863 | assert_eq!(slice_type_code(SliceType::B), 1); |
| 864 | assert_eq!(slice_type_code(SliceType::I), 2); |
| 865 | assert_eq!(slice_type_code(SliceType::Sp), 3); |
| 866 | assert_eq!(slice_type_code(SliceType::Si), 4); |
| 867 | } |
| 868 | |
| 869 | #[test] |
| 870 | fn profiles_follow_the_stream_bit_depth() { |
| 871 | let mut sps = test_sps(); |
| 872 | sps.profile_idc = 100; |
| 873 | assert_eq!(profile_for(&sps).unwrap(), Profile::H264High); |
| 874 | sps.bit_depth_luma = 10; |
| 875 | assert_eq!(profile_for(&sps).unwrap(), Profile::H264High10); |
| 876 | sps.profile_idc = 66; |
| 877 | sps.bit_depth_luma = 8; |
| 878 | assert_eq!(profile_for(&sps).unwrap(), Profile::H264ConstrainedBaseline); |
| 879 | sps.profile_idc = 244; |
| 880 | assert!(profile_for(&sps).is_err()); |
| 881 | } |
| 882 | } |