edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·2e2ed69·Tahinli·3 months ago·69 commits
| 1 | // Copyright 2023 The ChromiumOS Authors |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #[cfg(test)] |
| 6 | mod dummy; |
| 7 | #[cfg(feature = "vaapi")] |
| 8 | mod vaapi; |
| 9 | |
| 10 | use std::cell::RefCell; |
| 11 | use std::io::Cursor; |
| 12 | use std::os::fd::AsFd; |
| 13 | use std::os::fd::BorrowedFd; |
| 14 | use std::rc::Rc; |
| 15 | |
| 16 | use anyhow::anyhow; |
| 17 | use anyhow::Context; |
| 18 | |
| 19 | use crate::codec::h265::dpb::Dpb; |
| 20 | use crate::codec::h265::dpb::DpbEntry; |
| 21 | use crate::codec::h265::parser::Nalu; |
| 22 | use crate::codec::h265::parser::NaluType; |
| 23 | use crate::codec::h265::parser::Parser; |
| 24 | use crate::codec::h265::parser::Pps; |
| 25 | use crate::codec::h265::parser::ShortTermRefPicSet; |
| 26 | use crate::codec::h265::parser::Slice; |
| 27 | use crate::codec::h265::parser::SliceHeader; |
| 28 | use crate::codec::h265::parser::Sps; |
| 29 | use crate::codec::h265::picture::PictureData; |
| 30 | use crate::codec::h265::picture::Reference; |
| 31 | use crate::decoder::stateless::DecodeError; |
| 32 | use crate::decoder::stateless::DecodingState; |
| 33 | use crate::decoder::stateless::NewPictureResult; |
| 34 | use crate::decoder::stateless::StatelessBackendResult; |
| 35 | use crate::decoder::stateless::StatelessCodec; |
| 36 | use crate::decoder::stateless::StatelessDecoder; |
| 37 | use crate::decoder::stateless::StatelessDecoderBackend; |
| 38 | use crate::decoder::stateless::StatelessDecoderBackendPicture; |
| 39 | use crate::decoder::stateless::StatelessVideoDecoder; |
| 40 | use crate::decoder::BlockingMode; |
| 41 | use crate::decoder::DecodedHandle; |
| 42 | use crate::decoder::DecoderEvent; |
| 43 | use crate::decoder::StreamInfo; |
| 44 | use crate::Resolution; |
| 45 | |
| 46 | const MAX_DPB_SIZE: usize = 16; |
| 47 | /// Stateless backend methods specific to H.265. |
| 48 | pub trait StatelessH265DecoderBackend: |
| 49 | StatelessDecoderBackend + StatelessDecoderBackendPicture<H265> |
| 50 | { |
| 51 | /// Called when a new SPS is parsed. |
| 52 | fn new_sequence(&mut self, sps: &Sps) -> StatelessBackendResult<()>; |
| 53 | |
| 54 | /// Called when the decoder determines that a frame or field was found. |
| 55 | fn new_picture( |
| 56 | &mut self, |
| 57 | timestamp: u64, |
| 58 | alloc_cb: &mut dyn FnMut() -> Option< |
| 59 | <<Self as StatelessDecoderBackend>::Handle as DecodedHandle>::Frame, |
| 60 | >, |
| 61 | ) -> NewPictureResult<Self::Picture>; |
| 62 | |
| 63 | /// Called by the decoder for every frame or field found. |
| 64 | #[allow(clippy::too_many_arguments)] |
| 65 | fn begin_picture( |
| 66 | &mut self, |
| 67 | picture: &mut Self::Picture, |
| 68 | picture_data: &PictureData, |
| 69 | sps: &Sps, |
| 70 | pps: &Pps, |
| 71 | dpb: &Dpb<Self::Handle>, |
| 72 | rps: &RefPicSet<Self::Handle>, |
| 73 | slice: &Slice, |
| 74 | ) -> StatelessBackendResult<()>; |
| 75 | |
| 76 | /// Called to dispatch a decode operation to the backend. |
| 77 | #[allow(clippy::too_many_arguments)] |
| 78 | fn decode_slice( |
| 79 | &mut self, |
| 80 | picture: &mut Self::Picture, |
| 81 | slice: &Slice, |
| 82 | sps: &Sps, |
| 83 | pps: &Pps, |
| 84 | ref_pic_list0: &[Option<RefPicListEntry<Self::Handle>>; 16], |
| 85 | ref_pic_list1: &[Option<RefPicListEntry<Self::Handle>>; 16], |
| 86 | ) -> StatelessBackendResult<()>; |
| 87 | |
| 88 | /// Called when the decoder wants the backend to finish the decoding |
| 89 | /// operations for `picture`. At this point, `decode_slice` has been called |
| 90 | /// for all slices. |
| 91 | fn submit_picture(&mut self, picture: Self::Picture) -> StatelessBackendResult<Self::Handle>; |
| 92 | } |
| 93 | |
| 94 | /// An entry in the Reference Picture Lists. Unlike H.264, H.265 can use the |
| 95 | /// current picture itself as a reference. |
| 96 | #[derive(Clone)] |
| 97 | pub enum RefPicListEntry<T> { |
| 98 | CurrentPicture(PictureData), |
| 99 | DpbEntry(DpbEntry<T>), |
| 100 | } |
| 101 | |
| 102 | enum BumpingType { |
| 103 | BeforeDecoding, |
| 104 | AfterDecoding, |
| 105 | } |
| 106 | |
| 107 | enum RenegotiationType<'a> { |
| 108 | CurrentSps, |
| 109 | NewSps(&'a Sps), |
| 110 | } |
| 111 | |
| 112 | /// Keeps track of the last values seen for negotiation purposes. |
| 113 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 114 | struct NegotiationInfo { |
| 115 | /// The current coded resolution |
| 116 | coded_resolution: Resolution, |
| 117 | general_profile_idc: u8, |
| 118 | bit_depth_luma_minus8: u8, |
| 119 | bit_depth_chroma_minus8: u8, |
| 120 | chroma_format_idc: u8, |
| 121 | } |
| 122 | |
| 123 | impl From<&Sps> for NegotiationInfo { |
| 124 | fn from(sps: &Sps) -> Self { |
| 125 | NegotiationInfo { |
| 126 | coded_resolution: Resolution { width: sps.width().into(), height: sps.height().into() }, |
| 127 | general_profile_idc: sps.profile_tier_level.general_profile_idc, |
| 128 | bit_depth_luma_minus8: sps.bit_depth_luma_minus8, |
| 129 | bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8, |
| 130 | chroma_format_idc: sps.chroma_format_idc, |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | /// The RefPicSet data, derived once per picture. |
| 136 | #[derive(Clone, Debug)] |
| 137 | pub struct RefPicSet<T> { |
| 138 | curr_delta_poc_msb_present_flag: [bool; MAX_DPB_SIZE], |
| 139 | foll_delta_poc_msb_present_flag: [bool; MAX_DPB_SIZE], |
| 140 | |
| 141 | num_poc_st_curr_before: usize, |
| 142 | num_poc_st_curr_after: usize, |
| 143 | num_poc_st_foll: usize, |
| 144 | num_poc_lt_curr: usize, |
| 145 | num_poc_lt_foll: usize, |
| 146 | |
| 147 | poc_st_curr_before: [i32; MAX_DPB_SIZE], |
| 148 | poc_st_curr_after: [i32; MAX_DPB_SIZE], |
| 149 | poc_st_foll: [i32; MAX_DPB_SIZE], |
| 150 | poc_lt_curr: [i32; MAX_DPB_SIZE], |
| 151 | poc_lt_foll: [i32; MAX_DPB_SIZE], |
| 152 | |
| 153 | ref_pic_set_lt_curr: [Option<DpbEntry<T>>; MAX_DPB_SIZE], |
| 154 | ref_pic_set_st_curr_after: [Option<DpbEntry<T>>; MAX_DPB_SIZE], |
| 155 | ref_pic_set_st_curr_before: [Option<DpbEntry<T>>; MAX_DPB_SIZE], |
| 156 | ref_pic_set_st_foll: [Option<DpbEntry<T>>; MAX_DPB_SIZE], |
| 157 | ref_pic_set_lt_foll: [Option<DpbEntry<T>>; MAX_DPB_SIZE], |
| 158 | } |
| 159 | |
| 160 | impl<T> RefPicSet<T> |
| 161 | where |
| 162 | T: Clone, |
| 163 | { |
| 164 | // See 8.3.4. |
| 165 | // Builds the reference picture list for `hdr` for P and B slices. |
| 166 | fn build_ref_pic_lists( |
| 167 | &self, |
| 168 | hdr: &SliceHeader, |
| 169 | pps: &Pps, |
| 170 | cur_pic: &PictureData, |
| 171 | ) -> anyhow::Result<ReferencePicLists<T>> { |
| 172 | let mut ref_pic_lists = ReferencePicLists::default(); |
| 173 | |
| 174 | // I slices do not use inter prediction. |
| 175 | if !hdr.type_.is_p() && !hdr.type_.is_b() { |
| 176 | return Ok(ref_pic_lists); |
| 177 | } |
| 178 | |
| 179 | if self.num_poc_st_curr_before == 0 |
| 180 | && self.num_poc_st_curr_after == 0 |
| 181 | && self.num_poc_lt_curr == 0 |
| 182 | && pps.scc_extension_flag |
| 183 | && !pps.scc_extension.curr_pic_ref_enabled_flag |
| 184 | { |
| 185 | // Let's try and keep going, if it is a broken stream then maybe it |
| 186 | // will sort itself out as we go. In any case, we must not loop |
| 187 | // infinitely here. |
| 188 | log::error!("Bug or broken stream: out of pictures and can't build ref pic lists."); |
| 189 | return Ok(ref_pic_lists); |
| 190 | } |
| 191 | |
| 192 | let rplm = &hdr.ref_pic_list_modification; |
| 193 | |
| 194 | let num_rps_curr_temp_list0 = |
| 195 | std::cmp::max(u32::from(hdr.num_ref_idx_l0_active_minus1) + 1, hdr.num_pic_total_curr); |
| 196 | |
| 197 | // This could be simplified using a Vec, but lets not change the |
| 198 | // algorithm from the spec too much. |
| 199 | let mut ref_pic_list_temp0: [Option<RefPicListEntry<T>>; MAX_DPB_SIZE] = Default::default(); |
| 200 | |
| 201 | // Equation 8-8 |
| 202 | let mut r_idx = 0; |
| 203 | assert!(num_rps_curr_temp_list0 as usize <= MAX_DPB_SIZE); |
| 204 | while r_idx < num_rps_curr_temp_list0 { |
| 205 | let mut i = 0; |
| 206 | while i < self.num_poc_st_curr_before && r_idx < num_rps_curr_temp_list0 { |
| 207 | ref_pic_list_temp0[r_idx as usize] = |
| 208 | self.ref_pic_set_st_curr_before[i].clone().map(RefPicListEntry::DpbEntry); |
| 209 | |
| 210 | i += 1; |
| 211 | r_idx += 1; |
| 212 | } |
| 213 | |
| 214 | let mut i = 0; |
| 215 | while i < self.num_poc_st_curr_after && r_idx < num_rps_curr_temp_list0 { |
| 216 | ref_pic_list_temp0[r_idx as usize] = |
| 217 | self.ref_pic_set_st_curr_after[i].clone().map(RefPicListEntry::DpbEntry); |
| 218 | |
| 219 | i += 1; |
| 220 | r_idx += 1; |
| 221 | } |
| 222 | |
| 223 | let mut i = 0; |
| 224 | while i < self.num_poc_lt_curr && r_idx < num_rps_curr_temp_list0 { |
| 225 | ref_pic_list_temp0[r_idx as usize] = |
| 226 | self.ref_pic_set_lt_curr[i].clone().map(RefPicListEntry::DpbEntry); |
| 227 | |
| 228 | i += 1; |
| 229 | r_idx += 1; |
| 230 | } |
| 231 | |
| 232 | if pps.scc_extension.curr_pic_ref_enabled_flag { |
| 233 | ref_pic_list_temp0[r_idx as usize] = |
| 234 | Some(RefPicListEntry::CurrentPicture(cur_pic.clone())); |
| 235 | |
| 236 | r_idx += 1; |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // Equation 8-9 |
| 241 | for r_idx in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) { |
| 242 | let entry = if rplm.ref_pic_list_modification_flag_l0 { |
| 243 | let idx = rplm.list_entry_l0[r_idx]; |
| 244 | ref_pic_list_temp0[idx as usize].clone() |
| 245 | } else { |
| 246 | ref_pic_list_temp0[r_idx].clone() |
| 247 | }; |
| 248 | |
| 249 | ref_pic_lists.ref_pic_list0[r_idx] = entry; |
| 250 | } |
| 251 | |
| 252 | if pps.scc_extension.curr_pic_ref_enabled_flag |
| 253 | && !rplm.ref_pic_list_modification_flag_l0 |
| 254 | && num_rps_curr_temp_list0 > (u32::from(hdr.num_ref_idx_l0_active_minus1) + 1) |
| 255 | { |
| 256 | ref_pic_lists.ref_pic_list0[r_idx as usize] = |
| 257 | Some(RefPicListEntry::CurrentPicture(cur_pic.clone())); |
| 258 | } |
| 259 | |
| 260 | if hdr.type_.is_b() { |
| 261 | let mut ref_pic_list_temp1: [Option<RefPicListEntry<T>>; MAX_DPB_SIZE] = |
| 262 | Default::default(); |
| 263 | |
| 264 | let num_rps_curr_temp_list1 = std::cmp::max( |
| 265 | u32::from(hdr.num_ref_idx_l1_active_minus1) + 1, |
| 266 | hdr.num_pic_total_curr, |
| 267 | ); |
| 268 | |
| 269 | // Equation 8-10 |
| 270 | let mut r_idx = 0; |
| 271 | assert!(num_rps_curr_temp_list1 as usize <= MAX_DPB_SIZE); |
| 272 | while r_idx < num_rps_curr_temp_list1 { |
| 273 | let mut i = 0; |
| 274 | while i < self.num_poc_st_curr_after && r_idx < num_rps_curr_temp_list1 { |
| 275 | ref_pic_list_temp1[r_idx as usize] = |
| 276 | self.ref_pic_set_st_curr_after[i].clone().map(RefPicListEntry::DpbEntry); |
| 277 | i += 1; |
| 278 | r_idx += 1; |
| 279 | } |
| 280 | |
| 281 | let mut i = 0; |
| 282 | while i < self.num_poc_st_curr_before && r_idx < num_rps_curr_temp_list1 { |
| 283 | ref_pic_list_temp1[r_idx as usize] = |
| 284 | self.ref_pic_set_st_curr_before[i].clone().map(RefPicListEntry::DpbEntry); |
| 285 | i += 1; |
| 286 | r_idx += 1; |
| 287 | } |
| 288 | |
| 289 | let mut i = 0; |
| 290 | while i < self.num_poc_lt_curr && r_idx < num_rps_curr_temp_list1 { |
| 291 | ref_pic_list_temp1[r_idx as usize] = |
| 292 | self.ref_pic_set_lt_curr[i].clone().map(RefPicListEntry::DpbEntry); |
| 293 | i += 1; |
| 294 | r_idx += 1; |
| 295 | } |
| 296 | |
| 297 | if pps.scc_extension.curr_pic_ref_enabled_flag { |
| 298 | ref_pic_list_temp1[r_idx as usize] = |
| 299 | Some(RefPicListEntry::CurrentPicture(cur_pic.clone())); |
| 300 | |
| 301 | r_idx += 1; |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // Equation 8-11 |
| 306 | for r_idx in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) { |
| 307 | let entry = if rplm.ref_pic_list_modification_flag_l1 { |
| 308 | let idx = rplm.list_entry_l1[r_idx]; |
| 309 | ref_pic_list_temp1[idx as usize].clone() |
| 310 | } else { |
| 311 | ref_pic_list_temp1[r_idx].clone() |
| 312 | }; |
| 313 | |
| 314 | ref_pic_lists.ref_pic_list1[r_idx] = entry; |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | Ok(ref_pic_lists) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | impl<T: Clone> Default for RefPicSet<T> { |
| 323 | fn default() -> Self { |
| 324 | Self { |
| 325 | curr_delta_poc_msb_present_flag: Default::default(), |
| 326 | foll_delta_poc_msb_present_flag: Default::default(), |
| 327 | num_poc_st_curr_before: Default::default(), |
| 328 | num_poc_st_curr_after: Default::default(), |
| 329 | num_poc_st_foll: Default::default(), |
| 330 | num_poc_lt_curr: Default::default(), |
| 331 | num_poc_lt_foll: Default::default(), |
| 332 | poc_st_curr_before: Default::default(), |
| 333 | poc_st_curr_after: Default::default(), |
| 334 | poc_st_foll: Default::default(), |
| 335 | poc_lt_curr: Default::default(), |
| 336 | poc_lt_foll: Default::default(), |
| 337 | ref_pic_set_lt_curr: Default::default(), |
| 338 | ref_pic_set_st_curr_after: Default::default(), |
| 339 | ref_pic_set_st_curr_before: Default::default(), |
| 340 | ref_pic_set_st_foll: Default::default(), |
| 341 | ref_pic_set_lt_foll: Default::default(), |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// State of the picture being currently decoded. |
| 347 | /// |
| 348 | /// Stored between calls to [`StatelessDecoder::handle_slice`] that belong to the same picture. |
| 349 | struct CurrentPicState<H: DecodedHandle, P> { |
| 350 | /// Data for the current picture as extracted from the stream. |
| 351 | pic: PictureData, |
| 352 | /// Backend-specific data for that picture. |
| 353 | backend_pic: P, |
| 354 | /// List of reference pictures, used once per slice. |
| 355 | ref_pic_lists: ReferencePicLists<H>, |
| 356 | } |
| 357 | |
| 358 | /// All the reference picture lists used to decode a stream. |
| 359 | struct ReferencePicLists<T> { |
| 360 | /// Reference picture list 0 for P and B slices. Retains the same meaning as |
| 361 | /// in the specification. Points into the pictures stored in the DPB. |
| 362 | /// Derived once per slice. |
| 363 | ref_pic_list0: [Option<RefPicListEntry<T>>; MAX_DPB_SIZE], |
| 364 | /// Reference picture list 1 for B slices. Retains the same meaning as in |
| 365 | /// the specification. Points into the pictures stored in the DPB. Derived |
| 366 | /// once per slice. |
| 367 | ref_pic_list1: [Option<RefPicListEntry<T>>; MAX_DPB_SIZE], |
| 368 | } |
| 369 | |
| 370 | impl<T> Default for ReferencePicLists<T> { |
| 371 | fn default() -> Self { |
| 372 | Self { ref_pic_list0: Default::default(), ref_pic_list1: Default::default() } |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | pub struct H265DecoderState<H: DecodedHandle, P> { |
| 377 | /// A parser to extract bitstream metadata |
| 378 | parser: Parser, |
| 379 | |
| 380 | /// Keeps track of the last values seen for negotiation purposes. |
| 381 | negotiation_info: NegotiationInfo, |
| 382 | /// The set of reference pictures. |
| 383 | rps: RefPicSet<H>, |
| 384 | |
| 385 | /// The decoded picture buffer |
| 386 | dpb: Dpb<H>, |
| 387 | |
| 388 | /// The current active SPS id. |
| 389 | cur_sps_id: u8, |
| 390 | |
| 391 | /// Used to identify first picture in decoding order or first picture that |
| 392 | /// follows an EOS NALU. |
| 393 | first_picture_after_eos: bool, |
| 394 | |
| 395 | /// Whether this is the first picture in the bitstream in decoding order. |
| 396 | first_picture_in_bitstream: bool, |
| 397 | // Same as PrevTid0Pic in the specification. |
| 398 | prev_tid_0_pic: Option<PictureData>, |
| 399 | |
| 400 | /// A H.265 syntax element. |
| 401 | max_pic_order_cnt_lsb: i32, |
| 402 | /// The value of NoRaslOutputFlag for the last IRAP picture. |
| 403 | irap_no_rasl_output_flag: bool, |
| 404 | |
| 405 | /// We keep track of the last independent header so we can copy that into |
| 406 | /// dependent slices. |
| 407 | last_independent_slice_header: Option<SliceHeader>, |
| 408 | |
| 409 | /// The picture currently being decoded. We need to preserve it between |
| 410 | /// calls to `decode` because multiple slices will be processed in different |
| 411 | /// calls to `decode`. |
| 412 | current_pic: Option<CurrentPicState<H, P>>, |
| 413 | |
| 414 | pending_pps: Vec<Nalu<'static>>, |
| 415 | } |
| 416 | |
| 417 | impl<H, P> Default for H265DecoderState<H, P> |
| 418 | where |
| 419 | H: DecodedHandle + Clone, |
| 420 | { |
| 421 | fn default() -> Self { |
| 422 | H265DecoderState { |
| 423 | parser: Default::default(), |
| 424 | negotiation_info: Default::default(), |
| 425 | rps: Default::default(), |
| 426 | dpb: Default::default(), |
| 427 | cur_sps_id: Default::default(), |
| 428 | first_picture_after_eos: true, |
| 429 | first_picture_in_bitstream: true, |
| 430 | prev_tid_0_pic: Default::default(), |
| 431 | max_pic_order_cnt_lsb: Default::default(), |
| 432 | irap_no_rasl_output_flag: Default::default(), |
| 433 | last_independent_slice_header: Default::default(), |
| 434 | current_pic: Default::default(), |
| 435 | pending_pps: Default::default(), |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | /// [`StatelessCodec`] structure to use in order to create a H.265 stateless decoder. |
| 441 | /// |
| 442 | /// # Accepted input |
| 443 | /// |
| 444 | /// A decoder using this codec processes exactly one NAL unit of input per call to |
| 445 | /// [`StatelessDecoder::decode`], and returns the number of bytes until the end of this NAL unit. |
| 446 | /// This makes it possible to call [`Decode`](StatelessDecoder::decode) repeatedly on some unsplit |
| 447 | /// Annex B stream and shrinking it by the number of bytes processed after each call, until the |
| 448 | /// stream ends up being empty. |
| 449 | pub struct H265; |
| 450 | |
| 451 | impl StatelessCodec for H265 { |
| 452 | type FormatInfo = Sps; |
| 453 | type DecoderState<H: DecodedHandle, P> = H265DecoderState<H, P>; |
| 454 | } |
| 455 | |
| 456 | impl<B> StatelessDecoder<H265, B> |
| 457 | where |
| 458 | B: StatelessH265DecoderBackend, |
| 459 | B::Handle: Clone, |
| 460 | { |
| 461 | /// Whether the stream parameters have changed, indicating that a negotiation window has opened. |
| 462 | fn negotiation_possible( |
| 463 | sps: &Sps, |
| 464 | dpb: &Dpb<B::Handle>, |
| 465 | old_negotiation_info: &NegotiationInfo, |
| 466 | ) -> bool { |
| 467 | let negotiation_info = NegotiationInfo::from(sps); |
| 468 | let max_dpb_size = std::cmp::min(sps.max_dpb_size(), 16); |
| 469 | let prev_max_dpb_size = dpb.max_num_pics(); |
| 470 | |
| 471 | *old_negotiation_info != negotiation_info || prev_max_dpb_size != max_dpb_size |
| 472 | } |
| 473 | |
| 474 | /// Apply the parameters of `sps` to the decoder. |
| 475 | fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> { |
| 476 | self.drain()?; |
| 477 | self.codec.negotiation_info = NegotiationInfo::from(sps); |
| 478 | |
| 479 | let max_dpb_size = std::cmp::min(sps.max_dpb_size(), 16); |
| 480 | self.codec.dpb.set_max_num_pics(max_dpb_size); |
| 481 | self.coded_resolution = |
| 482 | Resolution { width: u32::from(sps.width()), height: u32::from(sps.height()) }; |
| 483 | Ok(()) |
| 484 | } |
| 485 | |
| 486 | // See 8.3.2, Note 2. |
| 487 | fn st_ref_pic_set<'a>(hdr: &'a SliceHeader, sps: &'a Sps) -> &'a ShortTermRefPicSet { |
| 488 | if hdr.curr_rps_idx == sps.num_short_term_ref_pic_sets { |
| 489 | &hdr.short_term_ref_pic_set |
| 490 | } else { |
| 491 | &sps.short_term_ref_pic_set[usize::from(hdr.curr_rps_idx)] |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | // See 8.3.2. |
| 496 | fn decode_rps( |
| 497 | &mut self, |
| 498 | slice: &Slice, |
| 499 | sps: &Sps, |
| 500 | cur_pic: &PictureData, |
| 501 | ) -> anyhow::Result<()> { |
| 502 | let hdr = &slice.header; |
| 503 | |
| 504 | if cur_pic.nalu_type.is_irap() && cur_pic.no_rasl_output_flag { |
| 505 | self.codec.dpb.mark_all_as_unused_for_ref(); |
| 506 | } |
| 507 | |
| 508 | if slice.nalu.header.type_.is_idr() { |
| 509 | self.codec.rps.poc_st_curr_before = Default::default(); |
| 510 | self.codec.rps.poc_st_curr_after = Default::default(); |
| 511 | self.codec.rps.poc_st_foll = Default::default(); |
| 512 | self.codec.rps.poc_lt_curr = Default::default(); |
| 513 | self.codec.rps.poc_lt_foll = Default::default(); |
| 514 | |
| 515 | self.codec.rps.num_poc_st_curr_before = 0; |
| 516 | self.codec.rps.num_poc_st_curr_after = 0; |
| 517 | self.codec.rps.num_poc_st_foll = 0; |
| 518 | self.codec.rps.num_poc_lt_curr = 0; |
| 519 | self.codec.rps.num_poc_lt_foll = 0; |
| 520 | } else { |
| 521 | let curr_st_rps = Self::st_ref_pic_set(hdr, sps); |
| 522 | let mut j = 0; |
| 523 | let mut k = 0; |
| 524 | for i in 0..usize::from(curr_st_rps.num_negative_pics) { |
| 525 | let poc = cur_pic.pic_order_cnt_val + curr_st_rps.delta_poc_s0[i]; |
| 526 | |
| 527 | if curr_st_rps.used_by_curr_pic_s0[i] { |
| 528 | self.codec.rps.poc_st_curr_before[j] = poc; |
| 529 | j += 1; |
| 530 | } else { |
| 531 | self.codec.rps.poc_st_foll[k] = poc; |
| 532 | k += 1; |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | self.codec.rps.num_poc_st_curr_before = j as _; |
| 537 | |
| 538 | let mut j = 0; |
| 539 | for i in 0..usize::from(curr_st_rps.num_positive_pics) { |
| 540 | let poc = cur_pic.pic_order_cnt_val + curr_st_rps.delta_poc_s1[i]; |
| 541 | |
| 542 | if curr_st_rps.used_by_curr_pic_s1[i] { |
| 543 | self.codec.rps.poc_st_curr_after[j] = poc; |
| 544 | j += 1; |
| 545 | } else { |
| 546 | self.codec.rps.poc_st_foll[k] = poc; |
| 547 | k += 1; |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | self.codec.rps.num_poc_st_curr_after = j as _; |
| 552 | self.codec.rps.num_poc_st_foll = k as _; |
| 553 | |
| 554 | let mut j = 0; |
| 555 | let mut k = 0; |
| 556 | for i in 0..usize::from(hdr.num_long_term_sps + hdr.num_long_term_pics) { |
| 557 | let mut poc_lt = hdr.poc_lsb_lt[i] as i32; |
| 558 | if hdr.delta_poc_msb_present_flag[i] { |
| 559 | poc_lt += cur_pic.pic_order_cnt_val; |
| 560 | let delta_poc = |
| 561 | hdr.delta_poc_msb_cycle_lt[i] as i32 * self.codec.max_pic_order_cnt_lsb; |
| 562 | |
| 563 | poc_lt -= delta_poc; |
| 564 | poc_lt -= cur_pic.pic_order_cnt_val & (self.codec.max_pic_order_cnt_lsb - 1); |
| 565 | } |
| 566 | |
| 567 | if hdr.used_by_curr_pic_lt[i] { |
| 568 | self.codec.rps.poc_lt_curr[j] = poc_lt; |
| 569 | self.codec.rps.curr_delta_poc_msb_present_flag[j] = |
| 570 | hdr.delta_poc_msb_present_flag[i]; |
| 571 | j += 1; |
| 572 | } else { |
| 573 | self.codec.rps.poc_lt_foll[k] = poc_lt; |
| 574 | self.codec.rps.foll_delta_poc_msb_present_flag[k] = |
| 575 | hdr.delta_poc_msb_present_flag[i]; |
| 576 | k += 1; |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | self.codec.rps.num_poc_lt_curr = j as _; |
| 581 | self.codec.rps.num_poc_lt_foll = k as _; |
| 582 | } |
| 583 | |
| 584 | self.derive_and_mark_rps()?; |
| 585 | Ok(()) |
| 586 | } |
| 587 | |
| 588 | // See the derivation process in the second half of 8.3.2. |
| 589 | fn derive_and_mark_rps(&mut self) -> anyhow::Result<()> { |
| 590 | let max_pic_order_cnt_lsb = self.codec.max_pic_order_cnt_lsb; |
| 591 | |
| 592 | // Equation 8-6 |
| 593 | for i in 0..self.codec.rps.num_poc_lt_curr { |
| 594 | if !self.codec.rps.curr_delta_poc_msb_present_flag[i] { |
| 595 | let poc = self.codec.rps.poc_lt_curr[i]; |
| 596 | let mask = max_pic_order_cnt_lsb - 1; |
| 597 | let reference = self.codec.dpb.find_ref_by_poc_masked(poc, mask); |
| 598 | |
| 599 | if reference.is_none() { |
| 600 | log::warn!("No reference found for poc {} and mask {}", poc, mask); |
| 601 | } |
| 602 | |
| 603 | self.codec.rps.ref_pic_set_lt_curr[i] = reference; |
| 604 | } else { |
| 605 | let poc = self.codec.rps.poc_lt_curr[i]; |
| 606 | let reference = self.codec.dpb.find_ref_by_poc(poc); |
| 607 | |
| 608 | if reference.is_none() { |
| 609 | log::warn!("No reference found for poc {}", poc); |
| 610 | } |
| 611 | |
| 612 | self.codec.rps.ref_pic_set_lt_curr[i] = reference; |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | for i in 0..self.codec.rps.num_poc_lt_foll { |
| 617 | if !self.codec.rps.foll_delta_poc_msb_present_flag[i] { |
| 618 | let poc = self.codec.rps.poc_lt_foll[i]; |
| 619 | let mask = max_pic_order_cnt_lsb - 1; |
| 620 | let reference = self.codec.dpb.find_ref_by_poc_masked(poc, mask); |
| 621 | |
| 622 | if reference.is_none() { |
| 623 | log::warn!("No reference found for poc {} and mask {}", poc, mask); |
| 624 | } |
| 625 | |
| 626 | self.codec.rps.ref_pic_set_lt_foll[i] = reference; |
| 627 | } else { |
| 628 | let poc = self.codec.rps.poc_lt_foll[i]; |
| 629 | let reference = self.codec.dpb.find_ref_by_poc(poc); |
| 630 | |
| 631 | if reference.is_none() { |
| 632 | log::warn!("No reference found for poc {}", poc); |
| 633 | } |
| 634 | |
| 635 | self.codec.rps.ref_pic_set_lt_foll[i] = reference; |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | for pic in self.codec.rps.ref_pic_set_lt_curr.iter().flatten() { |
| 640 | pic.0.borrow_mut().set_reference(Reference::LongTerm); |
| 641 | } |
| 642 | |
| 643 | for pic in self.codec.rps.ref_pic_set_lt_foll.iter().flatten() { |
| 644 | pic.0.borrow_mut().set_reference(Reference::LongTerm); |
| 645 | } |
| 646 | |
| 647 | // Equation 8-7 |
| 648 | for i in 0..self.codec.rps.num_poc_st_curr_before { |
| 649 | let poc = self.codec.rps.poc_st_curr_before[i]; |
| 650 | let reference = self.codec.dpb.find_short_term_ref_by_poc(poc); |
| 651 | |
| 652 | if reference.is_none() { |
| 653 | log::warn!("No reference found for poc {}", poc); |
| 654 | } |
| 655 | |
| 656 | self.codec.rps.ref_pic_set_st_curr_before[i] = reference; |
| 657 | } |
| 658 | |
| 659 | for i in 0..self.codec.rps.num_poc_st_curr_after { |
| 660 | let poc = self.codec.rps.poc_st_curr_after[i]; |
| 661 | let reference = self.codec.dpb.find_short_term_ref_by_poc(poc); |
| 662 | |
| 663 | if reference.is_none() { |
| 664 | log::warn!("No reference found for poc {}", poc); |
| 665 | } |
| 666 | |
| 667 | self.codec.rps.ref_pic_set_st_curr_after[i] = reference; |
| 668 | } |
| 669 | |
| 670 | for i in 0..self.codec.rps.num_poc_st_foll { |
| 671 | let poc = self.codec.rps.poc_st_foll[i]; |
| 672 | let reference = self.codec.dpb.find_short_term_ref_by_poc(poc); |
| 673 | |
| 674 | if reference.is_none() { |
| 675 | log::warn!("No reference found for poc {}", poc); |
| 676 | } |
| 677 | |
| 678 | self.codec.rps.ref_pic_set_st_foll[i] = reference; |
| 679 | } |
| 680 | |
| 681 | // 4. All reference pictures in the DPB that are not included in |
| 682 | // RefPicSetLtCurr, RefPicSetLtFoll, RefPicSetStCurrBefore, |
| 683 | // RefPicSetStCurrAfter, or RefPicSetStFoll and have nuh_layer_id equal |
| 684 | // to currPicLayerId are marked as "unused for reference" |
| 685 | for dpb_pic in self.codec.dpb.entries() { |
| 686 | let find_predicate = |p: &Option<DpbEntry<B::Handle>>| match p { |
| 687 | Some(p) => p.0.borrow().pic_order_cnt_val == dpb_pic.0.borrow().pic_order_cnt_val, |
| 688 | None => false, |
| 689 | }; |
| 690 | |
| 691 | if !self.codec.rps.ref_pic_set_lt_curr[0..self.codec.rps.num_poc_lt_curr] |
| 692 | .iter() |
| 693 | .any(find_predicate) |
| 694 | && !self.codec.rps.ref_pic_set_lt_foll[0..self.codec.rps.num_poc_lt_foll] |
| 695 | .iter() |
| 696 | .any(find_predicate) |
| 697 | && !self.codec.rps.ref_pic_set_st_curr_after |
| 698 | [0..self.codec.rps.num_poc_st_curr_after] |
| 699 | .iter() |
| 700 | .any(find_predicate) |
| 701 | && !self.codec.rps.ref_pic_set_st_curr_before |
| 702 | [0..self.codec.rps.num_poc_st_curr_before] |
| 703 | .iter() |
| 704 | .any(find_predicate) |
| 705 | && !self.codec.rps.ref_pic_set_st_foll[0..self.codec.rps.num_poc_st_foll] |
| 706 | .iter() |
| 707 | .any(find_predicate) |
| 708 | { |
| 709 | dpb_pic.0.borrow_mut().set_reference(Reference::None); |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | let total_rps_len = self.codec.rps.ref_pic_set_lt_curr[0..self.codec.rps.num_poc_lt_curr] |
| 714 | .len() |
| 715 | + self.codec.rps.ref_pic_set_lt_foll[0..self.codec.rps.num_poc_lt_foll].len() |
| 716 | + self.codec.rps.ref_pic_set_st_curr_after[0..self.codec.rps.num_poc_st_curr_after] |
| 717 | .len() |
| 718 | + self.codec.rps.ref_pic_set_st_curr_before[0..self.codec.rps.num_poc_st_curr_before] |
| 719 | .len() |
| 720 | + self.codec.rps.ref_pic_set_st_foll[0..self.codec.rps.num_poc_st_foll].len(); |
| 721 | |
| 722 | let dpb_len = self.codec.dpb.entries().len(); |
| 723 | if dpb_len != total_rps_len { |
| 724 | log::warn!( |
| 725 | "The total RPS length {} is not the same as the DPB length {}", |
| 726 | total_rps_len, |
| 727 | dpb_len |
| 728 | ); |
| 729 | log::warn!("A reference pic may be in more than one RPS list. This is against the specification. See 8.3.2. NOTE 5") |
| 730 | } |
| 731 | |
| 732 | // According to Chromium, unavailable reference pictures are handled by |
| 733 | // the accelerators internally. |
| 734 | Ok(()) |
| 735 | } |
| 736 | |
| 737 | /// Drain the decoder, processing all pending frames. |
| 738 | fn drain(&mut self) -> anyhow::Result<()> { |
| 739 | log::debug!("Draining the decoder"); |
| 740 | |
| 741 | // Finish the current picture if there is one pending. |
| 742 | if let Some(cur_pic) = self.codec.current_pic.take() { |
| 743 | self.finish_picture(cur_pic)?; |
| 744 | } |
| 745 | |
| 746 | let pics = self.codec.dpb.drain(); |
| 747 | |
| 748 | log::debug!( |
| 749 | "Adding POCs {:?} to the ready queue while draining", |
| 750 | pics.iter().map(|p| p.0.borrow().pic_order_cnt_val).collect::<Vec<_>>() |
| 751 | ); |
| 752 | |
| 753 | log::trace!("{:#?}", pics.iter().map(|p| p.0.borrow()).collect::<Vec<_>>()); |
| 754 | |
| 755 | self.ready_queue.extend(pics.into_iter().map(|h| h.1)); |
| 756 | self.codec.dpb.clear(); |
| 757 | |
| 758 | Ok(()) |
| 759 | } |
| 760 | |
| 761 | fn clear_ref_lists(&mut self) { |
| 762 | if let Some(pic) = self.codec.current_pic.as_mut() { |
| 763 | pic.ref_pic_lists = Default::default(); |
| 764 | } |
| 765 | |
| 766 | self.codec.rps.ref_pic_set_lt_curr = Default::default(); |
| 767 | self.codec.rps.ref_pic_set_st_curr_after = Default::default(); |
| 768 | self.codec.rps.ref_pic_set_st_curr_before = Default::default(); |
| 769 | |
| 770 | self.codec.rps.num_poc_lt_curr = Default::default(); |
| 771 | self.codec.rps.num_poc_lt_foll = Default::default(); |
| 772 | self.codec.rps.num_poc_st_curr_after = Default::default(); |
| 773 | self.codec.rps.num_poc_st_curr_before = Default::default(); |
| 774 | self.codec.rps.num_poc_st_foll = Default::default(); |
| 775 | } |
| 776 | |
| 777 | /// Bumps the DPB if needed. |
| 778 | fn bump_as_needed( |
| 779 | &mut self, |
| 780 | bumping_type: BumpingType, |
| 781 | ) -> anyhow::Result<Vec<DpbEntry<B::Handle>>> { |
| 782 | let mut pics = vec![]; |
| 783 | |
| 784 | let needs_bumping = match bumping_type { |
| 785 | BumpingType::BeforeDecoding => Dpb::<B::Handle>::needs_bumping, |
| 786 | BumpingType::AfterDecoding => Dpb::<B::Handle>::needs_additional_bumping, |
| 787 | }; |
| 788 | |
| 789 | let sps = self.codec.parser.get_sps(self.codec.cur_sps_id).context("Invalid SPS id")?; |
| 790 | |
| 791 | while needs_bumping(&mut self.codec.dpb, sps) { |
| 792 | match self.codec.dpb.bump(false) { |
| 793 | Some(pic) => pics.push(pic), |
| 794 | None => return Ok(pics), |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | Ok(pics) |
| 799 | } |
| 800 | |
| 801 | // See C.5.2.2 |
| 802 | fn update_dpb_before_decoding(&mut self, cur_pic: &PictureData) -> anyhow::Result<()> { |
| 803 | if cur_pic.nalu_type.is_irap() |
| 804 | && cur_pic.no_rasl_output_flag |
| 805 | && !self.codec.first_picture_after_eos |
| 806 | { |
| 807 | if cur_pic.no_output_of_prior_pics_flag { |
| 808 | self.codec.dpb.clear(); |
| 809 | } else { |
| 810 | self.drain()?; |
| 811 | } |
| 812 | } else { |
| 813 | self.codec.dpb.remove_unused(); |
| 814 | let bumped = self.bump_as_needed(BumpingType::BeforeDecoding)?; |
| 815 | |
| 816 | log::debug!( |
| 817 | "Adding POCs {:?} to the ready queue before decoding", |
| 818 | bumped.iter().map(|p| p.0.borrow().pic_order_cnt_val).collect::<Vec<_>>() |
| 819 | ); |
| 820 | |
| 821 | log::trace!("{:#?}", bumped.iter().map(|p| p.0.borrow()).collect::<Vec<_>>()); |
| 822 | |
| 823 | let bumped = bumped.into_iter().map(|p| p.1).collect::<Vec<_>>(); |
| 824 | self.ready_queue.extend(bumped); |
| 825 | } |
| 826 | |
| 827 | Ok(()) |
| 828 | } |
| 829 | |
| 830 | /// Called once per picture to start it. |
| 831 | #[allow(clippy::type_complexity)] |
| 832 | fn begin_picture( |
| 833 | &mut self, |
| 834 | timestamp: u64, |
| 835 | slice: &Slice, |
| 836 | alloc_cb: &mut dyn FnMut() -> Option<<B::Handle as DecodedHandle>::Frame>, |
| 837 | ) -> Result<Option<CurrentPicState<B::Handle, B::Picture>>, DecodeError> { |
| 838 | self.update_current_set_ids(slice.header.pic_parameter_set_id)?; |
| 839 | self.renegotiate_if_needed(RenegotiationType::CurrentSps)?; |
| 840 | // We renegotiated and must return the NALU and wait. |
| 841 | if matches!(self.decoding_state, DecodingState::AwaitingFormat(_)) { |
| 842 | return Err(DecodeError::CheckEvents); |
| 843 | } |
| 844 | |
| 845 | let mut backend_pic = self.backend.new_picture(timestamp, alloc_cb)?; |
| 846 | |
| 847 | let pic = PictureData::new_from_slice( |
| 848 | slice, |
| 849 | self.codec.first_picture_in_bitstream, |
| 850 | self.codec.first_picture_after_eos, |
| 851 | self.codec.prev_tid_0_pic.as_ref(), |
| 852 | self.codec.max_pic_order_cnt_lsb, |
| 853 | ); |
| 854 | |
| 855 | self.codec.first_picture_after_eos = false; |
| 856 | self.codec.first_picture_in_bitstream = false; |
| 857 | |
| 858 | if pic.nalu_type.is_irap() { |
| 859 | self.codec.irap_no_rasl_output_flag = pic.no_rasl_output_flag; |
| 860 | } else if pic.nalu_type.is_rasl() && self.codec.irap_no_rasl_output_flag { |
| 861 | // NOTE – All RASL pictures are leading pictures of an associated |
| 862 | // BLA or CRA picture. When the associated IRAP picture has |
| 863 | // NoRaslOutputFlag equal to 1, the RASL picture is not output and |
| 864 | // may not be correctly decodable, as the RASL picture may contain |
| 865 | // references to pictures that are not present in the bitstream. |
| 866 | // RASL pictures are not used as reference pictures for the decoding |
| 867 | // process of non-RASL pictures. |
| 868 | log::debug!( |
| 869 | "Dropping POC {}, as it may not be decodable according to the specification", |
| 870 | pic.pic_order_cnt_val |
| 871 | ); |
| 872 | |
| 873 | return Ok(None); |
| 874 | } |
| 875 | |
| 876 | log::debug!("Decode picture POC {}", pic.pic_order_cnt_val); |
| 877 | |
| 878 | let pps = self |
| 879 | .codec |
| 880 | .parser |
| 881 | .get_pps(slice.header.pic_parameter_set_id) |
| 882 | .context("invalid PPS ID")? |
| 883 | .clone(); |
| 884 | |
| 885 | self.decode_rps(slice, &pps.sps, &pic)?; |
| 886 | self.update_dpb_before_decoding(&pic)?; |
| 887 | |
| 888 | self.backend.begin_picture( |
| 889 | &mut backend_pic, |
| 890 | &pic, |
| 891 | pps.sps.as_ref(), |
| 892 | &pps, |
| 893 | &self.codec.dpb, |
| 894 | &self.codec.rps, |
| 895 | slice, |
| 896 | )?; |
| 897 | |
| 898 | Ok(Some(CurrentPicState { pic, backend_pic, ref_pic_lists: Default::default() })) |
| 899 | } |
| 900 | |
| 901 | fn update_current_set_ids(&mut self, pps_id: u8) -> anyhow::Result<()> { |
| 902 | let pps = self.codec.parser.get_pps(pps_id).context("Invalid PPS")?; |
| 903 | |
| 904 | self.codec.cur_sps_id = pps.seq_parameter_set_id; |
| 905 | Ok(()) |
| 906 | } |
| 907 | |
| 908 | /// Handle a slice. Called once per slice NALU. |
| 909 | fn handle_slice( |
| 910 | &mut self, |
| 911 | pic: &mut CurrentPicState<B::Handle, B::Picture>, |
| 912 | slice: &Slice, |
| 913 | ) -> anyhow::Result<()> { |
| 914 | // A dependent slice may refer to a previous SPS which |
| 915 | // is not the one currently in use. |
| 916 | self.update_current_set_ids(slice.header.pic_parameter_set_id)?; |
| 917 | |
| 918 | let pps = self |
| 919 | .codec |
| 920 | .parser |
| 921 | .get_pps(slice.header.pic_parameter_set_id) |
| 922 | .context("invalid PPS ID")?; |
| 923 | let sps = pps.sps.as_ref(); |
| 924 | |
| 925 | pic.ref_pic_lists = self.codec.rps.build_ref_pic_lists(&slice.header, pps, &pic.pic)?; |
| 926 | |
| 927 | // Make sure that no negotiation is possible mid-picture. How could it? |
| 928 | // We'd lose the context with the previous slices on it. |
| 929 | if Self::negotiation_possible(sps, &self.codec.dpb, &self.codec.negotiation_info) { |
| 930 | anyhow::bail!("invalid stream: mid-frame format negotiation requested"); |
| 931 | } |
| 932 | |
| 933 | self.backend.decode_slice( |
| 934 | &mut pic.backend_pic, |
| 935 | slice, |
| 936 | sps, |
| 937 | pps, |
| 938 | &pic.ref_pic_lists.ref_pic_list0, |
| 939 | &pic.ref_pic_lists.ref_pic_list1, |
| 940 | )?; |
| 941 | |
| 942 | Ok(()) |
| 943 | } |
| 944 | |
| 945 | fn finish_picture( |
| 946 | &mut self, |
| 947 | pic: CurrentPicState<B::Handle, B::Picture>, |
| 948 | ) -> anyhow::Result<()> { |
| 949 | log::debug!("Finishing picture POC {:?}", pic.pic.pic_order_cnt_val); |
| 950 | |
| 951 | // Submit the picture to the backend. |
| 952 | let handle = self.submit_picture(pic.backend_pic)?; |
| 953 | let pic = pic.pic; |
| 954 | |
| 955 | // 8.3.1 |
| 956 | if pic.valid_for_prev_tid0_pic { |
| 957 | self.codec.prev_tid_0_pic = Some(pic.clone()); |
| 958 | } |
| 959 | |
| 960 | self.clear_ref_lists(); |
| 961 | |
| 962 | // First store the current picture in the DPB, only then we should |
| 963 | // decide whether to bump. |
| 964 | self.codec |
| 965 | .dpb |
| 966 | .store_picture(Rc::new(RefCell::new(pic)), handle) |
| 967 | .map_err(|err| anyhow!(err))?; |
| 968 | let bumped = self.bump_as_needed(BumpingType::AfterDecoding)?; |
| 969 | |
| 970 | log::debug!( |
| 971 | "Adding POCs {:?} to the ready queue after decoding", |
| 972 | bumped.iter().map(|p| p.0.borrow().pic_order_cnt_val).collect::<Vec<_>>() |
| 973 | ); |
| 974 | |
| 975 | log::trace!("{:#?}", bumped.iter().map(|p| p.0.borrow()).collect::<Vec<_>>()); |
| 976 | |
| 977 | let bumped = bumped.into_iter().map(|p| p.1).collect::<Vec<_>>(); |
| 978 | self.ready_queue.extend(bumped); |
| 979 | |
| 980 | Ok(()) |
| 981 | } |
| 982 | |
| 983 | fn renegotiate_if_needed( |
| 984 | &mut self, |
| 985 | renegotiation_type: RenegotiationType, |
| 986 | ) -> anyhow::Result<()> { |
| 987 | let sps = match renegotiation_type { |
| 988 | RenegotiationType::CurrentSps => { |
| 989 | self.codec.parser.get_sps(self.codec.cur_sps_id).context("Invalid SPS")? |
| 990 | } |
| 991 | RenegotiationType::NewSps(sps) => sps, |
| 992 | }; |
| 993 | |
| 994 | if Self::negotiation_possible(sps, &self.codec.dpb, &self.codec.negotiation_info) { |
| 995 | // Make sure all the frames we decoded so far are in the ready queue. |
| 996 | self.drain()?; |
| 997 | let sps = match renegotiation_type { |
| 998 | RenegotiationType::CurrentSps => { |
| 999 | self.codec.parser.get_sps(self.codec.cur_sps_id).context("Invalid SPS")? |
| 1000 | } |
| 1001 | RenegotiationType::NewSps(sps) => sps, |
| 1002 | }; |
| 1003 | self.backend.new_sequence(sps)?; |
| 1004 | self.await_format_change(sps.clone()); |
| 1005 | } |
| 1006 | |
| 1007 | Ok(()) |
| 1008 | } |
| 1009 | |
| 1010 | fn process_nalu( |
| 1011 | &mut self, |
| 1012 | timestamp: u64, |
| 1013 | nalu: Nalu, |
| 1014 | alloc_cb: &mut dyn FnMut() -> Option<<B::Handle as DecodedHandle>::Frame>, |
| 1015 | ) -> Result<(), DecodeError> { |
| 1016 | log::debug!("Processing NALU {:?}, length is {}", nalu.header.type_, nalu.size); |
| 1017 | |
| 1018 | match nalu.header.type_ { |
| 1019 | NaluType::VpsNut => { |
| 1020 | self.codec |
| 1021 | .parser |
| 1022 | .parse_vps(&nalu) |
| 1023 | .map_err(|err| DecodeError::ParseFrameError(err))?; |
| 1024 | } |
| 1025 | NaluType::SpsNut => { |
| 1026 | let sps = self |
| 1027 | .codec |
| 1028 | .parser |
| 1029 | .parse_sps(&nalu) |
| 1030 | .map_err(|err| DecodeError::ParseFrameError(err))?; |
| 1031 | self.codec.max_pic_order_cnt_lsb = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4); |
| 1032 | |
| 1033 | let pending_pps = std::mem::take(&mut self.codec.pending_pps); |
| 1034 | |
| 1035 | // Try parsing the PPS again. |
| 1036 | for pps in pending_pps.into_iter() { |
| 1037 | if self.codec.parser.parse_pps(&pps).is_err() { |
| 1038 | // Failed to parse PPS add it again to pending |
| 1039 | self.codec.pending_pps.push(pps); |
| 1040 | } |
| 1041 | } |
| 1042 | } |
| 1043 | |
| 1044 | NaluType::PpsNut => { |
| 1045 | if self.codec.parser.parse_pps(&nalu).is_err() { |
| 1046 | self.codec.pending_pps.push(nalu.into_owned()) |
| 1047 | } |
| 1048 | } |
| 1049 | |
| 1050 | NaluType::BlaWLp |
| 1051 | | NaluType::BlaWRadl |
| 1052 | | NaluType::BlaNLp |
| 1053 | | NaluType::IdrWRadl |
| 1054 | | NaluType::IdrNLp |
| 1055 | | NaluType::TrailN |
| 1056 | | NaluType::TrailR |
| 1057 | | NaluType::TsaN |
| 1058 | | NaluType::TsaR |
| 1059 | | NaluType::StsaN |
| 1060 | | NaluType::StsaR |
| 1061 | | NaluType::RadlN |
| 1062 | | NaluType::RadlR |
| 1063 | | NaluType::RaslN |
| 1064 | | NaluType::RaslR |
| 1065 | | NaluType::CraNut => { |
| 1066 | let mut slice = self |
| 1067 | .codec |
| 1068 | .parser |
| 1069 | .parse_slice_header(nalu) |
| 1070 | .map_err(|err| DecodeError::ParseFrameError(err))?; |
| 1071 | |
| 1072 | let first_slice_segment_in_pic_flag = slice.header.first_slice_segment_in_pic_flag; |
| 1073 | |
| 1074 | if slice.header.dependent_slice_segment_flag { |
| 1075 | let previous_independent_header = self.codec.last_independent_slice_header.as_ref().ok_or(anyhow!("Cannot process an dependent slice without first processing and independent one"))?.clone(); |
| 1076 | slice |
| 1077 | .replace_header(previous_independent_header) |
| 1078 | .map_err(|err| DecodeError::ParseFrameError(err))?; |
| 1079 | } else { |
| 1080 | self.codec.last_independent_slice_header = Some(slice.header.clone()); |
| 1081 | } |
| 1082 | |
| 1083 | let cur_pic = match self.codec.current_pic.take() { |
| 1084 | // No current picture, start a new one. |
| 1085 | None => self.begin_picture(timestamp, &slice, alloc_cb)?, |
| 1086 | Some(cur_pic) if first_slice_segment_in_pic_flag => { |
| 1087 | self.finish_picture(cur_pic)?; |
| 1088 | self.begin_picture(timestamp, &slice, alloc_cb)? |
| 1089 | } |
| 1090 | Some(cur_pic) => Some(cur_pic), |
| 1091 | }; |
| 1092 | |
| 1093 | // Picture may have been dropped during begin_picture() |
| 1094 | if let Some(mut cur_pic) = cur_pic { |
| 1095 | self.handle_slice(&mut cur_pic, &slice)?; |
| 1096 | self.codec.current_pic = Some(cur_pic); |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | NaluType::EosNut => { |
| 1101 | self.codec.first_picture_after_eos = true; |
| 1102 | } |
| 1103 | |
| 1104 | NaluType::EobNut => { |
| 1105 | self.codec.first_picture_in_bitstream = true; |
| 1106 | } |
| 1107 | |
| 1108 | other => { |
| 1109 | log::debug!("Unsupported NAL unit type {:?}", other,); |
| 1110 | } |
| 1111 | } |
| 1112 | |
| 1113 | Ok(()) |
| 1114 | } |
| 1115 | |
| 1116 | /// Submits the picture to the accelerator. |
| 1117 | fn submit_picture(&mut self, backend_pic: B::Picture) -> Result<B::Handle, DecodeError> { |
| 1118 | let handle = self.backend.submit_picture(backend_pic)?; |
| 1119 | |
| 1120 | if self.blocking_mode == BlockingMode::Blocking { |
| 1121 | handle.sync()?; |
| 1122 | } |
| 1123 | |
| 1124 | Ok(handle) |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | impl<B> StatelessVideoDecoder for StatelessDecoder<H265, B> |
| 1129 | where |
| 1130 | B: StatelessH265DecoderBackend, |
| 1131 | B::Handle: Clone + 'static, |
| 1132 | { |
| 1133 | type Handle = B::Handle; |
| 1134 | |
| 1135 | fn decode( |
| 1136 | &mut self, |
| 1137 | timestamp: u64, |
| 1138 | bitstream: &[u8], |
| 1139 | alloc_cb: &mut dyn FnMut() -> Option< |
| 1140 | <<B as StatelessDecoderBackend>::Handle as DecodedHandle>::Frame, |
| 1141 | >, |
| 1142 | ) -> Result<usize, DecodeError> { |
| 1143 | let mut cursor = Cursor::new(bitstream); |
| 1144 | let nalu = Nalu::next(&mut cursor).map_err(|err| DecodeError::ParseFrameError(err))?; |
| 1145 | |
| 1146 | if nalu.header.type_ == NaluType::SpsNut { |
| 1147 | let sps = self |
| 1148 | .codec |
| 1149 | .parser |
| 1150 | .parse_sps(&nalu) |
| 1151 | .map_err(|err| DecodeError::ParseFrameError(err))? |
| 1152 | .clone(); |
| 1153 | if matches!(self.decoding_state, DecodingState::AwaitingStreamInfo) { |
| 1154 | // If more SPS come along we will renegotiate in begin_picture(). |
| 1155 | self.renegotiate_if_needed(RenegotiationType::NewSps(&sps))?; |
| 1156 | } else if matches!(self.decoding_state, DecodingState::Reset) { |
| 1157 | // We can resume decoding since the decoding parameters have not changed. |
| 1158 | self.decoding_state = DecodingState::Decoding; |
| 1159 | } |
| 1160 | } else if matches!(self.decoding_state, DecodingState::Reset) { |
| 1161 | let mut cursor = Cursor::new(bitstream); |
| 1162 | |
| 1163 | while let Ok(nalu) = Nalu::next(&mut cursor) { |
| 1164 | // In the Reset state we can resume decoding from any key frame. |
| 1165 | if nalu.header.type_.is_idr() { |
| 1166 | self.decoding_state = DecodingState::Decoding; |
| 1167 | break; |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | |
| 1172 | let nalu_len = nalu.offset + nalu.size; |
| 1173 | |
| 1174 | match &mut self.decoding_state { |
| 1175 | // Process parameter sets, but skip input until we get information |
| 1176 | // from the stream. |
| 1177 | DecodingState::AwaitingStreamInfo | DecodingState::Reset => { |
| 1178 | if matches!( |
| 1179 | nalu.header.type_, |
| 1180 | NaluType::VpsNut | NaluType::SpsNut | NaluType::PpsNut |
| 1181 | ) { |
| 1182 | self.process_nalu(timestamp, nalu, alloc_cb)?; |
| 1183 | } |
| 1184 | } |
| 1185 | // Ask the client to confirm the format before we can process this. |
| 1186 | DecodingState::FlushingForDRC | DecodingState::AwaitingFormat(_) => { |
| 1187 | // Start signaling the awaiting format event to process a format change. |
| 1188 | self.awaiting_format_event.write(1).unwrap(); |
| 1189 | return Err(DecodeError::CheckEvents); |
| 1190 | } |
| 1191 | DecodingState::Decoding => { |
| 1192 | self.process_nalu(timestamp, nalu, alloc_cb)?; |
| 1193 | } |
| 1194 | } |
| 1195 | |
| 1196 | Ok(nalu_len) |
| 1197 | } |
| 1198 | |
| 1199 | fn flush(&mut self) -> Result<(), DecodeError> { |
| 1200 | self.drain()?; |
| 1201 | self.decoding_state = DecodingState::Reset; |
| 1202 | |
| 1203 | Ok(()) |
| 1204 | } |
| 1205 | |
| 1206 | fn next_event(&mut self) -> Option<DecoderEvent<B::Handle>> { |
| 1207 | self.query_next_event(|decoder, sps| { |
| 1208 | // Apply the SPS settings to the decoder so we don't enter the AwaitingFormat state |
| 1209 | // on the next decode() call. |
| 1210 | // TODO: unwrap this for now, but ideally change this closure to return Result |
| 1211 | decoder.apply_sps(sps).unwrap(); |
| 1212 | }) |
| 1213 | } |
| 1214 | |
| 1215 | fn stream_info(&self) -> Option<&StreamInfo> { |
| 1216 | self.backend.stream_info() |
| 1217 | } |
| 1218 | |
| 1219 | fn poll_fd(&self) -> BorrowedFd { |
| 1220 | self.epoll_fd.0.as_fd() |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | #[cfg(test)] |
| 1225 | pub mod tests { |
| 1226 | |
| 1227 | use crate::bitstream_utils::NalIterator; |
| 1228 | use crate::codec::h265::parser::Nalu; |
| 1229 | use crate::decoder::stateless::h265::H265; |
| 1230 | use crate::decoder::stateless::tests::test_decode_stream; |
| 1231 | use crate::decoder::stateless::tests::TestStream; |
| 1232 | use crate::decoder::stateless::StatelessDecoder; |
| 1233 | use crate::decoder::BlockingMode; |
| 1234 | use crate::utils::simple_playback_loop; |
| 1235 | use crate::utils::simple_playback_loop_owned_frames; |
| 1236 | use crate::DecodedFormat; |
| 1237 | |
| 1238 | /// Run `test` using the dummy decoder, in both blocking and non-blocking modes. |
| 1239 | fn test_decoder_dummy(test: &TestStream, blocking_mode: BlockingMode) { |
| 1240 | let decoder = StatelessDecoder::<H265, _>::new_dummy(blocking_mode).unwrap(); |
| 1241 | |
| 1242 | test_decode_stream( |
| 1243 | |d, s, f| { |
| 1244 | simple_playback_loop( |
| 1245 | d, |
| 1246 | NalIterator::<Nalu>::new(s), |
| 1247 | f, |
| 1248 | &mut simple_playback_loop_owned_frames, |
| 1249 | DecodedFormat::NV12, |
| 1250 | blocking_mode, |
| 1251 | ) |
| 1252 | }, |
| 1253 | decoder, |
| 1254 | test, |
| 1255 | false, |
| 1256 | false, |
| 1257 | ); |
| 1258 | } |
| 1259 | |
| 1260 | /// A 64x64 progressive byte-stream encoded I-frame to make it easier to |
| 1261 | /// spot errors on the libva trace. |
| 1262 | /// Encoded with the following GStreamer pipeline: |
| 1263 | /// |
| 1264 | /// gst-launch-1.0 videotestsrc num-buffers=1 ! video/x-raw,format=I420,width=64,height=64 ! x265enc ! video/x-h265,profile=main ! filesink location="64x64-I.h265" |
| 1265 | pub const DECODE_64X64_PROGRESSIVE_I: TestStream = TestStream { |
| 1266 | stream: include_bytes!("../../codec/h265/test_data/64x64-I.h265"), |
| 1267 | crcs: include_str!("../../codec/h265/test_data/64x64-I.h265.crc"), |
| 1268 | }; |
| 1269 | |
| 1270 | #[test] |
| 1271 | fn test_64x64_progressive_i_block() { |
| 1272 | test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I, BlockingMode::Blocking); |
| 1273 | } |
| 1274 | |
| 1275 | #[test] |
| 1276 | fn test_64x64_progressive_i_nonblock() { |
| 1277 | test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I, BlockingMode::NonBlocking); |
| 1278 | } |
| 1279 | |
| 1280 | /// A 64x64 progressive byte-stream encoded I-frame and P-frame to make |
| 1281 | /// it easier to spot errors on the libva trace. |
| 1282 | /// Encoded with the following GStreamer pipeline: |
| 1283 | /// gst-launch-1.0 videotestsrc num-buffers=2 ! video/x-raw,format=I420,width=64,height=64 ! x265enc option-string="b-adapt=0" ! video/x-h265,profile=main ! filesink location="64x64-I-P.h265" |
| 1284 | pub const DECODE_64X64_PROGRESSIVE_I_P: TestStream = TestStream { |
| 1285 | stream: include_bytes!("../../codec/h265/test_data/64x64-I-P.h265"), |
| 1286 | crcs: include_str!("../../codec/h265/test_data/64x64-I-P.h265.crc"), |
| 1287 | }; |
| 1288 | |
| 1289 | #[test] |
| 1290 | fn test_64x64_progressive_i_p_block() { |
| 1291 | test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P, BlockingMode::Blocking); |
| 1292 | } |
| 1293 | |
| 1294 | #[test] |
| 1295 | fn test_64x64_progressive_i_p_nonblock() { |
| 1296 | test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P, BlockingMode::NonBlocking); |
| 1297 | } |
| 1298 | |
| 1299 | /// A 64x64 progressive byte-stream encoded I-P-B-P sequence to make it |
| 1300 | /// easier to it easier to spot errors on the libva trace. |
| 1301 | /// Encoded with the following GStreamer pipeline: |
| 1302 | /// gst-launch-1.0 videotestsrc num-buffers=3 ! video/x-raw,format=I420,width=64,height=64 ! x265enc option-string="b-adapt=0:bframes=1" ! video/x-h265,profile=main ! filesink location="64x64-I-P-B-P.h265" |
| 1303 | pub const DECODE_64X64_PROGRESSIVE_I_P_B_P: TestStream = TestStream { |
| 1304 | stream: include_bytes!("../../codec/h265/test_data/64x64-I-P-B-P.h265"), |
| 1305 | crcs: include_str!("../../codec/h265/test_data/64x64-I-P-B-P.h265.crc"), |
| 1306 | }; |
| 1307 | |
| 1308 | #[test] |
| 1309 | fn test_64x64_progressive_i_p_b_p_block() { |
| 1310 | test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P, BlockingMode::Blocking); |
| 1311 | } |
| 1312 | |
| 1313 | #[test] |
| 1314 | fn test_64x64_progressive_i_p_b_p_nonblock() { |
| 1315 | test_decoder_dummy(&DECODE_64X64_PROGRESSIVE_I_P_B_P, BlockingMode::NonBlocking); |
| 1316 | } |
| 1317 | |
| 1318 | /// Same as Chromium's test-25fps.h265 |
| 1319 | pub const DECODE_TEST_25FPS: TestStream = TestStream { |
| 1320 | stream: include_bytes!("../../codec/h265/test_data/test-25fps.h265"), |
| 1321 | crcs: include_str!("../../codec/h265/test_data/test-25fps.h265.crc"), |
| 1322 | }; |
| 1323 | |
| 1324 | #[test] |
| 1325 | fn test_25fps_block() { |
| 1326 | test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::Blocking); |
| 1327 | } |
| 1328 | |
| 1329 | #[test] |
| 1330 | fn test_25fps_nonblock() { |
| 1331 | test_decoder_dummy(&DECODE_TEST_25FPS, BlockingMode::NonBlocking); |
| 1332 | } |
| 1333 | |
| 1334 | /// Same as Chromium's bear.h265 |
| 1335 | pub const DECODE_BEAR: TestStream = TestStream { |
| 1336 | stream: include_bytes!("../../codec/h265/test_data/bear.h265"), |
| 1337 | crcs: include_str!("../../codec/h265/test_data/bear.h265.crc"), |
| 1338 | }; |
| 1339 | |
| 1340 | #[test] |
| 1341 | fn test_bear_block() { |
| 1342 | test_decoder_dummy(&DECODE_BEAR, BlockingMode::Blocking); |
| 1343 | } |
| 1344 | |
| 1345 | #[test] |
| 1346 | fn test_bear_nonblock() { |
| 1347 | test_decoder_dummy(&DECODE_BEAR, BlockingMode::NonBlocking); |
| 1348 | } |
| 1349 | |
| 1350 | /// Same as Chromium's bbb.h265 |
| 1351 | pub const DECODE_BBB: TestStream = TestStream { |
| 1352 | stream: include_bytes!("../../codec/h265/test_data/bbb.h265"), |
| 1353 | crcs: include_str!("../../codec/h265/test_data/bbb.h265.crc"), |
| 1354 | }; |
| 1355 | |
| 1356 | #[test] |
| 1357 | fn test_bbb_block() { |
| 1358 | test_decoder_dummy(&DECODE_BBB, BlockingMode::Blocking); |
| 1359 | } |
| 1360 | |
| 1361 | #[test] |
| 1362 | fn test_bbb_nonblock() { |
| 1363 | test_decoder_dummy(&DECODE_BBB, BlockingMode::NonBlocking); |
| 1364 | } |
| 1365 | } |