| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | pub mod amvp; |
| 30 | pub mod cu_syntax; |
| 31 | pub mod deblock; |
| 32 | pub mod dpb; |
| 33 | pub mod inter; |
| 34 | pub mod mc; |
| 35 | pub mod merge; |
| 36 | pub mod meta; |
| 37 | pub mod motion_field; |
| 38 | pub mod pic; |
| 39 | pub mod picjob; |
| 40 | pub mod poc; |
| 41 | pub mod recon; |
| 42 | pub mod rext; |
| 43 | pub mod rowfilter; |
| 44 | pub mod rps; |
| 45 | pub mod runner; |
| 46 | pub mod sao; |
| 47 | pub mod shared; |
| 48 | pub mod slice_seg; |
| 49 | pub mod tiles; |
| 50 | pub mod trace; |
| 51 | pub mod weighted; |
| 52 | |
| 53 | use std::collections::VecDeque; |
| 54 | use std::sync::Arc; |
| 55 | |
| 56 | use dpb::{Dpb, DpbLimits, Marking}; |
| 57 | pub use dpb::{DpbPicture, Frame, PendingFrame}; |
| 58 | use ec_core::bitio::BitReader; |
| 59 | use ec_core::error::{Error, Result}; |
| 60 | use ec_h265_syntax::nal::{NalHeader, NalUnitType, split_annex_b, unescape_rbsp}; |
| 61 | use ec_h265_syntax::sei::{SeiMessage, parse_sei_rbsp}; |
| 62 | use ec_h265_syntax::slice::{LongTermRef, ParsePositions, SliceHeader, SliceType}; |
| 63 | use ec_h265_syntax::{Pps, PpsRangeExt, ShortTermRefPicSet, Sps, SpsRangeExt, Vps}; |
| 64 | pub use meta::PictureMeta; |
| 65 | use picjob::{PicJob, SliceJob}; |
| 66 | use rps::RpsInput; |
| 67 | pub use rps::{RefEntry, RefPicLists, RefPicSet}; |
| 68 | use runner::{Budget, Checksum, Runner}; |
| 69 | use shared::SharedPic; |
| 70 | use std::sync::Mutex; |
| 71 | use std::thread::JoinHandle; |
| 72 | |
| 73 | |
| 74 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 75 | pub enum NalOutcome { |
| 76 | |
| 77 | ParameterSet, |
| 78 | |
| 79 | Slice, |
| 80 | |
| 81 | |
| 82 | SkippedPicture, |
| 83 | |
| 84 | Skipped, |
| 85 | |
| 86 | |
| 87 | EndOfSequence, |
| 88 | } |
| 89 | |
| 90 | |
| 91 | |
| 92 | struct CurPicture { |
| 93 | sps: Arc<Sps>, |
| 94 | poc: i32, |
| 95 | au_index: u32, |
| 96 | output: bool, |
| 97 | rps: RefPicSet, |
| 98 | lists: RefPicLists, |
| 99 | |
| 100 | runner: Runner, |
| 101 | |
| 102 | shared: Arc<SharedPic>, |
| 103 | |
| 104 | checksum: Arc<Checksum>, |
| 105 | |
| 106 | |
| 107 | header: Option<SliceHeader>, |
| 108 | |
| 109 | all_intra: bool, |
| 110 | meta: PictureMeta, |
| 111 | } |
| 112 | |
| 113 | |
| 114 | pub const MAX_THREADS: usize = 6; |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | const PICTURE_SLACK: usize = 1; |
| 124 | |
| 125 | |
| 126 | fn picture_limit(threads: usize) -> usize { |
| 127 | let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); |
| 128 | if threads <= cores { |
| 129 | threads + PICTURE_SLACK |
| 130 | } else { |
| 131 | threads |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | |
| 136 | |
| 137 | pub fn configured_threads() -> usize { |
| 138 | let requested = std::env::var("EC_H265_THREADS") |
| 139 | .ok() |
| 140 | .and_then(|v| v.trim().parse::<usize>().ok()) |
| 141 | .filter(|&n| n > 0) |
| 142 | .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())); |
| 143 | requested.min(MAX_THREADS) |
| 144 | } |
| 145 | |
| 146 | |
| 147 | |
| 148 | pub struct Decoder { |
| 149 | vps: Vec<Option<Vps>>, |
| 150 | sps: Vec<Option<Arc<Sps>>>, |
| 151 | pps: Vec<Option<Arc<Pps>>>, |
| 152 | pixel_decode: bool, |
| 153 | |
| 154 | threads: usize, |
| 155 | |
| 156 | budget: Arc<Budget>, |
| 157 | |
| 158 | syntax_check: bool, |
| 159 | dpb: Dpb, |
| 160 | cur: Option<CurPicture>, |
| 161 | |
| 162 | skipping: bool, |
| 163 | seen_picture: bool, |
| 164 | after_eos: bool, |
| 165 | |
| 166 | |
| 167 | irap_no_rasl: bool, |
| 168 | |
| 169 | prev_tid0_poc: i32, |
| 170 | au_index: u32, |
| 171 | out: VecDeque<PendingFrame>, |
| 172 | |
| 173 | |
| 174 | hdr_pending: PictureMeta, |
| 175 | |
| 176 | hdr_persist: PictureMeta, |
| 177 | |
| 178 | checksums: Mutex<ChecksumFold>, |
| 179 | |
| 180 | in_flight: VecDeque<JoinHandle<()>>, |
| 181 | |
| 182 | max_in_flight: usize, |
| 183 | } |
| 184 | |
| 185 | |
| 186 | #[derive(Default)] |
| 187 | struct ChecksumFold { |
| 188 | |
| 189 | fold: u64, |
| 190 | |
| 191 | pending: VecDeque<Arc<Checksum>>, |
| 192 | } |
| 193 | |
| 194 | impl Default for Decoder { |
| 195 | fn default() -> Self { |
| 196 | Decoder::new() |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | impl Decoder { |
| 201 | |
| 202 | pub fn new() -> Decoder { |
| 203 | Decoder { |
| 204 | vps: vec![None; 16], |
| 205 | sps: vec![None; 16], |
| 206 | pps: vec![None; 64], |
| 207 | pixel_decode: true, |
| 208 | threads: configured_threads(), |
| 209 | budget: Budget::new(configured_threads()), |
| 210 | syntax_check: false, |
| 211 | dpb: Dpb::new(), |
| 212 | cur: None, |
| 213 | skipping: false, |
| 214 | seen_picture: false, |
| 215 | after_eos: false, |
| 216 | irap_no_rasl: true, |
| 217 | prev_tid0_poc: 0, |
| 218 | au_index: 0, |
| 219 | out: VecDeque::new(), |
| 220 | hdr_pending: PictureMeta::default(), |
| 221 | hdr_persist: PictureMeta::default(), |
| 222 | checksums: Mutex::new(ChecksumFold::default()), |
| 223 | in_flight: VecDeque::new(), |
| 224 | max_in_flight: picture_limit(configured_threads()), |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | |
| 229 | pub fn set_threads(&mut self, threads: usize) { |
| 230 | self.threads = threads.clamp(1, MAX_THREADS); |
| 231 | self.max_in_flight = picture_limit(self.threads); |
| 232 | self.budget = Budget::new(self.threads); |
| 233 | } |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | pub fn set_pixel_decode(&mut self, on: bool) { |
| 239 | self.pixel_decode = on; |
| 240 | } |
| 241 | |
| 242 | |
| 243 | pub fn pixel_decode(&self) -> bool { |
| 244 | self.pixel_decode |
| 245 | } |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | pub fn motion_checksum(&self) -> u64 { |
| 251 | let mut fold = self.checksums.lock().unwrap_or_else(|e| e.into_inner()); |
| 252 | while let Some(slot) = fold.pending.pop_front() { |
| 253 | if let Some(sum) = slot.wait() { |
| 254 | fold.fold = (fold.fold ^ sum).wrapping_mul(0x0000_0100_0000_01b3); |
| 255 | } |
| 256 | } |
| 257 | fold.fold |
| 258 | } |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | pub fn set_syntax_check(&mut self, on: bool) { |
| 264 | self.syntax_check = on; |
| 265 | } |
| 266 | |
| 267 | |
| 268 | pub fn vps(&self, id: u32) -> Option<&Vps> { |
| 269 | self.vps.get(id as usize)?.as_ref() |
| 270 | } |
| 271 | |
| 272 | |
| 273 | pub fn sps(&self, id: u32) -> Option<&Sps> { |
| 274 | self.sps.get(id as usize)?.as_deref() |
| 275 | } |
| 276 | |
| 277 | |
| 278 | pub fn pps(&self, id: u32) -> Option<&Pps> { |
| 279 | self.pps.get(id as usize)?.as_deref() |
| 280 | } |
| 281 | |
| 282 | |
| 283 | |
| 284 | pub fn ref_pic_lists(&self) -> Option<&RefPicLists> { |
| 285 | self.cur.as_ref().map(|c| &c.lists) |
| 286 | } |
| 287 | |
| 288 | |
| 289 | pub fn ref_pic_set(&self) -> Option<&RefPicSet> { |
| 290 | self.cur.as_ref().map(|c| &c.rps) |
| 291 | } |
| 292 | |
| 293 | |
| 294 | pub fn picture(&self, id: u32) -> Option<&DpbPicture> { |
| 295 | self.dpb.get(id) |
| 296 | } |
| 297 | |
| 298 | |
| 299 | |
| 300 | pub fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> { |
| 301 | let header = NalHeader::parse(nal)?; |
| 302 | self.handle(header, &nal[2..]) |
| 303 | } |
| 304 | |
| 305 | |
| 306 | pub fn decode_annex_b(&mut self, data: &[u8]) -> Result<()> { |
| 307 | for nal in split_annex_b(data) { |
| 308 | self.handle(nal.header, nal.payload)?; |
| 309 | } |
| 310 | Ok(()) |
| 311 | } |
| 312 | |
| 313 | |
| 314 | |
| 315 | pub fn end_picture(&mut self) { |
| 316 | self.finish_picture(); |
| 317 | } |
| 318 | |
| 319 | |
| 320 | pub fn flush(&mut self) -> Result<()> { |
| 321 | self.finish_picture(); |
| 322 | self.dpb.drain(&mut self.out); |
| 323 | |
| 324 | for pending in &self.out { |
| 325 | pending.picture.wait_done()?; |
| 326 | } |
| 327 | let t = trace::now(); |
| 328 | for handle in self.in_flight.drain(..) { |
| 329 | let _ = handle.join(); |
| 330 | } |
| 331 | trace::since(trace::Phase::WaitJoin, t); |
| 332 | trace::report(); |
| 333 | Ok(()) |
| 334 | } |
| 335 | |
| 336 | |
| 337 | pub fn next_frame(&mut self) -> Option<Frame> { |
| 338 | |
| 339 | self.out |
| 340 | .pop_front() |
| 341 | .and_then(|pending| pending.resolve().ok()) |
| 342 | } |
| 343 | |
| 344 | fn handle(&mut self, header: NalHeader, payload: &[u8]) -> Result<NalOutcome> { |
| 345 | if header.layer_id > 0 { |
| 346 | return Ok(NalOutcome::Skipped); |
| 347 | } |
| 348 | match header.nal_type.code() { |
| 349 | code @ (0..=9 | 16..=21) => self.slice(header, code, payload), |
| 350 | 32 => { |
| 351 | let vps = Vps::parse(&unescape_rbsp(payload))?; |
| 352 | store(&mut self.vps, usize::from(vps.id), vps)?; |
| 353 | Ok(NalOutcome::ParameterSet) |
| 354 | } |
| 355 | 33 => { |
| 356 | let mut sps = Sps::parse(&unescape_rbsp(payload))?; |
| 357 | check_sps(&sps)?; |
| 358 | if sps.chroma_format_idc == 0 { |
| 359 | |
| 360 | sps.bit_depth_chroma_minus8 = sps.bit_depth_luma_minus8; |
| 361 | } |
| 362 | let id = sps.id as usize; |
| 363 | store(&mut self.sps, id, Arc::new(sps))?; |
| 364 | Ok(NalOutcome::ParameterSet) |
| 365 | } |
| 366 | 34 => { |
| 367 | let pps = Pps::parse(&unescape_rbsp(payload))?; |
| 368 | check_pps(&pps)?; |
| 369 | let id = pps.id as usize; |
| 370 | store(&mut self.pps, id, Arc::new(pps))?; |
| 371 | Ok(NalOutcome::ParameterSet) |
| 372 | } |
| 373 | 39 | 40 => { |
| 374 | |
| 375 | |
| 376 | if let Ok(msgs) = parse_sei_rbsp(&unescape_rbsp(payload)) { |
| 377 | self.take_sei(msgs, header.nal_type.code() == 40); |
| 378 | } |
| 379 | Ok(NalOutcome::Skipped) |
| 380 | } |
| 381 | 36 | 37 => { |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | self.finish_picture(); |
| 388 | self.after_eos = true; |
| 389 | Ok(NalOutcome::EndOfSequence) |
| 390 | } |
| 391 | _ => Ok(NalOutcome::Skipped), |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | fn slice(&mut self, header: NalHeader, code: u8, payload: &[u8]) -> Result<NalOutcome> { |
| 396 | let rbsp = unescape_rbsp(payload); |
| 397 | |
| 398 | let mut r = BitReader::new(&rbsp); |
| 399 | let first = r.read_bit()?; |
| 400 | if (16..=21).contains(&code) { |
| 401 | r.read_bit()?; |
| 402 | } |
| 403 | let pps_id = r.read_ue()?; |
| 404 | |
| 405 | if first { |
| 406 | self.finish_picture(); |
| 407 | self.skipping = false; |
| 408 | |
| 409 | |
| 410 | if matches!(code, 8 | 9) && self.irap_no_rasl { |
| 411 | self.skipping = true; |
| 412 | self.hdr_pending = PictureMeta::default(); |
| 413 | self.au_index += 1; |
| 414 | return Ok(NalOutcome::SkippedPicture); |
| 415 | } |
| 416 | } else if self.skipping { |
| 417 | return Ok(NalOutcome::SkippedPicture); |
| 418 | } |
| 419 | |
| 420 | let pps = self |
| 421 | .pps |
| 422 | .get(pps_id as usize) |
| 423 | .and_then(|p| p.clone()) |
| 424 | .ok_or_else(|| { |
| 425 | Error::corrupt(format!("HEVC slice: PPS {pps_id} was never received")) |
| 426 | })?; |
| 427 | let sps = self |
| 428 | .sps |
| 429 | .get(pps.sps_id as usize) |
| 430 | .and_then(|s| s.clone()) |
| 431 | .ok_or_else(|| { |
| 432 | Error::corrupt(format!( |
| 433 | "HEVC slice: SPS {} (for PPS {pps_id}) was never received", |
| 434 | pps.sps_id |
| 435 | )) |
| 436 | })?; |
| 437 | let (slice, pos) = SliceHeader::parse(&rbsp, &sps, &pps, NalUnitType::from_code(code))?; |
| 438 | |
| 439 | if first { |
| 440 | self.start_picture(&header, code, &slice, &sps); |
| 441 | } else if self.cur.is_none() { |
| 442 | return Err(Error::corrupt( |
| 443 | "HEVC slice: segment whose picture's first slice was never seen".to_string(), |
| 444 | )); |
| 445 | } |
| 446 | let slice = self.segment_header(slice)?; |
| 447 | let substreams = substream_starts(payload, &pos, &slice.entry_point_offsets, rbsp.len()); |
| 448 | self.decode_slice(&slice, &pos, rbsp, substreams, &sps, &pps)?; |
| 449 | Ok(NalOutcome::Slice) |
| 450 | } |
| 451 | |
| 452 | |
| 453 | |
| 454 | fn segment_header(&mut self, segment: SliceHeader) -> Result<SliceHeader> { |
| 455 | let cur = self |
| 456 | .cur |
| 457 | .as_mut() |
| 458 | .ok_or_else(|| Error::corrupt("HEVC slice: no picture is open".to_string()))?; |
| 459 | if segment.dependent_slice_segment { |
| 460 | let base = cur.header.as_ref().ok_or_else(|| { |
| 461 | Error::corrupt("HEVC slice: dependent slice segment before its slice".to_string()) |
| 462 | })?; |
| 463 | Ok(slice_seg::inherit(base, &segment)) |
| 464 | } else { |
| 465 | cur.header = Some(segment.clone()); |
| 466 | Ok(segment) |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | fn take_sei(&mut self, msgs: Vec<SeiMessage>, suffix: bool) { |
| 474 | for msg in msgs { |
| 475 | match msg { |
| 476 | SeiMessage::MasteringDisplay(m) => self.hdr_pending.mastering_display = Some(m), |
| 477 | SeiMessage::ContentLightLevel(c) => self.hdr_pending.content_light = Some(c), |
| 478 | SeiMessage::AlternativeTransferCharacteristics(a) => { |
| 479 | self.hdr_pending.alternative_transfer = Some(a); |
| 480 | } |
| 481 | SeiMessage::DecodedPictureHash(h) if suffix => { |
| 482 | if let Some(cur) = self.cur.as_mut() { |
| 483 | cur.meta.picture_hash = Some(h); |
| 484 | } |
| 485 | } |
| 486 | SeiMessage::DecodedPictureHash(_) | SeiMessage::Unknown { .. } => {} |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | |
| 492 | |
| 493 | fn start_picture(&mut self, nal: &NalHeader, code: u8, slice: &SliceHeader, sps: &Arc<Sps>) { |
| 494 | let first_picture = !self.seen_picture; |
| 495 | self.seen_picture = true; |
| 496 | let irap = (16..=21).contains(&code); |
| 497 | let idr = matches!(code, 19 | 20); |
| 498 | let cra = code == 21; |
| 499 | let no_rasl = irap && (idr || (16..=18).contains(&code) || first_picture || self.after_eos); |
| 500 | self.after_eos = false; |
| 501 | if irap { |
| 502 | self.irap_no_rasl = no_rasl; |
| 503 | } |
| 504 | |
| 505 | |
| 506 | let log2_max_poc_lsb = sps.log2_max_poc_lsb_minus4 + 4; |
| 507 | let poc = poc::derive_poc( |
| 508 | self.prev_tid0_poc, |
| 509 | log2_max_poc_lsb, |
| 510 | slice.poc_lsb, |
| 511 | irap && no_rasl, |
| 512 | ); |
| 513 | let sub_layer_non_ref = code <= 14 && code & 1 == 0; |
| 514 | let radl_or_rasl = (6..=9).contains(&code); |
| 515 | if nal.temporal_id == 0 && !radl_or_rasl && !sub_layer_non_ref { |
| 516 | self.prev_tid0_poc = poc; |
| 517 | } |
| 518 | |
| 519 | |
| 520 | let empty_st = ShortTermRefPicSet::default(); |
| 521 | let (st, lt): (&ShortTermRefPicSet, &[LongTermRef]) = if idr { |
| 522 | (&empty_st, &[]) |
| 523 | } else { |
| 524 | (&slice.short_term_ref_pic_set, &slice.long_term) |
| 525 | }; |
| 526 | let input = RpsInput { |
| 527 | poc, |
| 528 | log2_max_poc_lsb, |
| 529 | st, |
| 530 | lt, |
| 531 | irap_no_rasl: irap && no_rasl, |
| 532 | width: sps.pic_width_in_luma_samples as usize, |
| 533 | height: sps.pic_height_in_luma_samples as usize, |
| 534 | fill: self.pixel_decode.then_some(( |
| 535 | sps.bit_depth_luma_minus8 + 8, |
| 536 | sps.bit_depth_chroma_minus8 + 8, |
| 537 | )), |
| 538 | chroma_format_idc: sps.chroma_format_idc, |
| 539 | }; |
| 540 | let rps = self.dpb.apply_rps(&input); |
| 541 | |
| 542 | |
| 543 | let limits = DpbLimits::from_sps(sps); |
| 544 | if irap && no_rasl && !first_picture { |
| 545 | |
| 546 | |
| 547 | |
| 548 | if cra || slice.no_output_of_prior_pics { |
| 549 | self.dpb.clear(); |
| 550 | } else { |
| 551 | self.dpb.drain(&mut self.out); |
| 552 | } |
| 553 | } else { |
| 554 | self.dpb.remove_unneeded(); |
| 555 | while self.dpb.needs_bumping(&limits, true) && self.dpb.bump(&mut self.out) {} |
| 556 | } |
| 557 | |
| 558 | |
| 559 | |
| 560 | if irap && no_rasl { |
| 561 | self.hdr_persist = PictureMeta::default(); |
| 562 | } |
| 563 | let pending = std::mem::take(&mut self.hdr_pending); |
| 564 | self.hdr_persist.absorb_sei(&pending); |
| 565 | let mut meta = self.hdr_persist.clone(); |
| 566 | if let Some(vst) = sps.vui.as_ref().and_then(|v| v.video_signal_type) { |
| 567 | meta.colour_description = vst.colour_description; |
| 568 | meta.video_full_range_flag = Some(vst.video_full_range_flag); |
| 569 | } |
| 570 | |
| 571 | |
| 572 | let threaded = self.threads > 1 && self.pixel_decode; |
| 573 | if threaded { |
| 574 | let t = trace::now(); |
| 575 | while self.in_flight.len() >= self.max_in_flight { |
| 576 | if let Some(handle) = self.in_flight.pop_front() { |
| 577 | let _ = handle.join(); |
| 578 | } |
| 579 | } |
| 580 | trace::since(trace::Phase::WaitAdmit, t); |
| 581 | } |
| 582 | let shared = Arc::new(SharedPic::new( |
| 583 | poc, |
| 584 | sps.pic_width_in_luma_samples as usize, |
| 585 | sps.pic_height_in_luma_samples as usize, |
| 586 | ( |
| 587 | 8 + sps.bit_depth_luma_minus8, |
| 588 | 8 + sps.bit_depth_chroma_minus8, |
| 589 | ), |
| 590 | self.pixel_decode, |
| 591 | sps.chroma_format_idc, |
| 592 | )); |
| 593 | let checksum = Arc::new(Checksum::default()); |
| 594 | let runner = Runner::start( |
| 595 | PicJob::new(Arc::clone(&shared), Arc::clone(&self.budget)), |
| 596 | Arc::clone(&checksum), |
| 597 | threaded, |
| 598 | ); |
| 599 | self.cur = Some(CurPicture { |
| 600 | sps: Arc::clone(sps), |
| 601 | poc, |
| 602 | au_index: self.au_index, |
| 603 | header: None, |
| 604 | output: slice.pic_output_flag, |
| 605 | rps, |
| 606 | lists: RefPicLists::default(), |
| 607 | runner, |
| 608 | shared, |
| 609 | checksum, |
| 610 | all_intra: true, |
| 611 | meta, |
| 612 | }); |
| 613 | self.au_index += 1; |
| 614 | } |
| 615 | |
| 616 | |
| 617 | |
| 618 | fn decode_slice( |
| 619 | &mut self, |
| 620 | slice: &SliceHeader, |
| 621 | pos: &ParsePositions, |
| 622 | rbsp: Vec<u8>, |
| 623 | substreams: Vec<usize>, |
| 624 | sps: &Arc<Sps>, |
| 625 | pps: &Arc<Pps>, |
| 626 | ) -> Result<()> { |
| 627 | let pixel = self.pixel_decode; |
| 628 | let dpb = &self.dpb; |
| 629 | let cur = self |
| 630 | .cur |
| 631 | .as_mut() |
| 632 | .ok_or_else(|| Error::corrupt("HEVC decode: no picture is open".to_string()))?; |
| 633 | if !slice.dependent_slice_segment && slice.slice_type != SliceType::I { |
| 634 | cur.lists = rps::build_ref_lists(&cur.rps, slice)?; |
| 635 | } |
| 636 | if slice.slice_type != SliceType::I { |
| 637 | cur.all_intra = false; |
| 638 | } |
| 639 | if !pixel && !self.syntax_check { |
| 640 | return Ok(()); |
| 641 | } |
| 642 | let data_off = (pos.header_bits / 8) as usize; |
| 643 | if data_off > rbsp.len() { |
| 644 | return Err(Error::corrupt( |
| 645 | "HEVC slice: header runs past the RBSP".to_string(), |
| 646 | )); |
| 647 | } |
| 648 | let lookup = |entries: &[RefEntry]| -> Result<Vec<Arc<SharedPic>>> { |
| 649 | entries |
| 650 | .iter() |
| 651 | .map(|e| { |
| 652 | dpb.get(e.id) |
| 653 | .map(|p| Arc::clone(&p.picture)) |
| 654 | .ok_or_else(|| { |
| 655 | Error::corrupt( |
| 656 | "HEVC decode: a reference picture is missing from the buffer" |
| 657 | .to_string(), |
| 658 | ) |
| 659 | }) |
| 660 | }) |
| 661 | .collect() |
| 662 | }; |
| 663 | let refs = if pixel && slice.slice_type != SliceType::I { |
| 664 | [lookup(&cur.lists.l0)?, lookup(&cur.lists.l1)?] |
| 665 | } else { |
| 666 | [Vec::new(), Vec::new()] |
| 667 | }; |
| 668 | let col = motion_field::collocated(dpb, slice, &cur.lists); |
| 669 | let t = trace::now(); |
| 670 | let submitted = cur.runner.submit(SliceJob { |
| 671 | rbsp, |
| 672 | data_off, |
| 673 | header: slice.clone(), |
| 674 | sps: Arc::clone(sps), |
| 675 | pps: Arc::clone(pps), |
| 676 | lists: cur.lists.clone(), |
| 677 | refs, |
| 678 | col, |
| 679 | cur_poc: cur.poc, |
| 680 | pixel, |
| 681 | substreams, |
| 682 | }); |
| 683 | trace::since(trace::Phase::Decode, t); |
| 684 | submitted |
| 685 | } |
| 686 | |
| 687 | |
| 688 | |
| 689 | |
| 690 | fn finish_picture(&mut self) { |
| 691 | let t = trace::now(); |
| 692 | self.finish_picture_inner(); |
| 693 | trace::since(trace::Phase::Serial, t); |
| 694 | } |
| 695 | |
| 696 | fn finish_picture_inner(&mut self) { |
| 697 | let Some(cur) = self.cur.take() else { |
| 698 | return; |
| 699 | }; |
| 700 | let CurPicture { |
| 701 | sps, |
| 702 | poc, |
| 703 | au_index, |
| 704 | output, |
| 705 | runner, |
| 706 | shared, |
| 707 | checksum, |
| 708 | all_intra, |
| 709 | mut meta, |
| 710 | .. |
| 711 | } = cur; |
| 712 | meta.intra_only = all_intra; |
| 713 | self.checksums |
| 714 | .lock() |
| 715 | .unwrap_or_else(|e| e.into_inner()) |
| 716 | .pending |
| 717 | .push_back(checksum); |
| 718 | if let Some(handle) = runner.finish() { |
| 719 | self.in_flight.push_back(handle); |
| 720 | } |
| 721 | if output { |
| 722 | for p in self.dpb.pictures_mut() { |
| 723 | if p.needed_for_output && p.poc > poc { |
| 724 | p.latency += 1; |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | let id = self.dpb.insert( |
| 729 | poc, |
| 730 | Marking::ShortTerm, |
| 731 | output, |
| 732 | shared, |
| 733 | sps.conf_win, |
| 734 | au_index, |
| 735 | ); |
| 736 | self.dpb.set_meta(id, meta); |
| 737 | let limits = DpbLimits::from_sps(&sps); |
| 738 | while self.dpb.needs_bumping(&limits, false) && self.dpb.bump(&mut self.out) {} |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | |
| 746 | |
| 747 | fn substream_starts( |
| 748 | payload: &[u8], |
| 749 | pos: &ParsePositions, |
| 750 | entries: &[u32], |
| 751 | rbsp_len: usize, |
| 752 | ) -> Vec<usize> { |
| 753 | if entries.is_empty() { |
| 754 | return Vec::new(); |
| 755 | } |
| 756 | |
| 757 | let mut removed = Vec::new(); |
| 758 | let mut zeros = 0usize; |
| 759 | for (i, &b) in payload.iter().enumerate() { |
| 760 | if zeros >= 2 && b == 3 { |
| 761 | removed.push(i); |
| 762 | zeros = 0; |
| 763 | continue; |
| 764 | } |
| 765 | zeros = if b == 0 { zeros + 1 } else { 0 }; |
| 766 | } |
| 767 | let data_off = (pos.header_bits / 8) as usize; |
| 768 | let mut escaped = pos.slice_data_byte_offset(payload) - 2; |
| 769 | let mut starts = Vec::with_capacity(entries.len()); |
| 770 | for &size in entries { |
| 771 | escaped += size as usize; |
| 772 | |
| 773 | let before = removed.partition_point(|&r| r < escaped); |
| 774 | let Some(rbsp_at) = escaped.checked_sub(before) else { |
| 775 | return Vec::new(); |
| 776 | }; |
| 777 | if rbsp_at <= data_off || rbsp_at >= rbsp_len { |
| 778 | return Vec::new(); |
| 779 | } |
| 780 | starts.push(rbsp_at - data_off); |
| 781 | } |
| 782 | starts |
| 783 | } |
| 784 | |
| 785 | fn store<T>(table: &mut [Option<T>], id: usize, value: T) -> Result<()> { |
| 786 | let slot = table |
| 787 | .get_mut(id) |
| 788 | .ok_or_else(|| Error::corrupt(format!("HEVC parameter set id {id} is out of range")))?; |
| 789 | *slot = Some(value); |
| 790 | Ok(()) |
| 791 | } |
| 792 | |
| 793 | |
| 794 | |
| 795 | |
| 796 | |
| 797 | |
| 798 | const EXT_REFUSED: u8 = 0x70; |
| 799 | |
| 800 | |
| 801 | fn refused_extension(flags: u8) -> Option<&'static str> { |
| 802 | if flags & 0x80 != 0 { |
| 803 | Some("range extension (RExt tools)") |
| 804 | } else if flags & 0x40 != 0 { |
| 805 | Some("multi-layer extension (MV-HEVC, SHVC)") |
| 806 | } else if flags & 0x20 != 0 { |
| 807 | Some("3D extension (3D-HEVC)") |
| 808 | } else if flags & 0x10 != 0 { |
| 809 | Some("SCC extension (screen content coding)") |
| 810 | } else { |
| 811 | None |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | |
| 816 | |
| 817 | |
| 818 | fn check_sps(sps: &Sps) -> Result<()> { |
| 819 | if sps.chroma_format_idc > 3 { |
| 820 | return Err(Error::unsupported( |
| 821 | "HEVC decode: chroma format unknown", |
| 822 | "chroma_format_idc is 0 to 3", |
| 823 | )); |
| 824 | } |
| 825 | if sps.chroma_format_idc == 3 && sps.separate_colour_plane { |
| 826 | return Err(Error::unsupported( |
| 827 | "HEVC decode: chroma format 4:4:4 with separate_colour_plane_flag", |
| 828 | "the three colour planes coded as separate pictures are not implemented", |
| 829 | )); |
| 830 | } |
| 831 | let chroma_depth = |
| 832 | (sps.chroma_format_idc != 0).then_some(("chroma", sps.bit_depth_chroma_minus8)); |
| 833 | for (plane, minus8) in [("luma", sps.bit_depth_luma_minus8)] |
| 834 | .into_iter() |
| 835 | .chain(chroma_depth) |
| 836 | { |
| 837 | if minus8 > 4 { |
| 838 | return Err(Error::unsupported( |
| 839 | format!("HEVC decode: bit depth {} {plane}", minus8 + 8), |
| 840 | "only bit depths 8 to 12 are implemented", |
| 841 | )); |
| 842 | } |
| 843 | } |
| 844 | if let Some(name) = refused_extension(sps.extension_flags & EXT_REFUSED) { |
| 845 | return Err(Error::unsupported( |
| 846 | format!("HEVC decode: SPS {name}"), |
| 847 | "only Main, Main 10 and the range extension profiles are implemented", |
| 848 | )); |
| 849 | } |
| 850 | if let Some(name) = unimplemented_sps_range(&sps.range) { |
| 851 | return Err(Error::unsupported( |
| 852 | format!("HEVC decode: SPS {name}"), |
| 853 | "this range extension tool is not implemented", |
| 854 | )); |
| 855 | } |
| 856 | Ok(()) |
| 857 | } |
| 858 | |
| 859 | |
| 860 | fn unimplemented_sps_range(r: &SpsRangeExt) -> Option<&'static str> { |
| 861 | [ |
| 862 | ( |
| 863 | r.extended_precision_processing, |
| 864 | "extended_precision_processing_flag", |
| 865 | ), |
| 866 | ( |
| 867 | r.cabac_bypass_alignment_enabled, |
| 868 | "cabac_bypass_alignment_enabled_flag", |
| 869 | ), |
| 870 | ] |
| 871 | .into_iter() |
| 872 | .find(|&(on, _)| on) |
| 873 | .map(|(_, name)| name) |
| 874 | } |
| 875 | |
| 876 | |
| 877 | |
| 878 | fn unimplemented_pps_range(_r: &PpsRangeExt) -> Option<&'static str> { |
| 879 | None |
| 880 | } |
| 881 | |
| 882 | |
| 883 | fn check_pps(pps: &Pps) -> Result<()> { |
| 884 | if let Some(name) = refused_extension(pps.extension_flags & EXT_REFUSED) { |
| 885 | return Err(Error::unsupported( |
| 886 | format!("HEVC decode: PPS {name}"), |
| 887 | "only Main, Main 10 and Main 4:2:2 10 are implemented", |
| 888 | )); |
| 889 | } |
| 890 | if let Some(name) = unimplemented_pps_range(&pps.range) { |
| 891 | return Err(Error::unsupported( |
| 892 | format!("HEVC decode: PPS {name}"), |
| 893 | "this range extension tool is not implemented", |
| 894 | )); |
| 895 | } |
| 896 | Ok(()) |
| 897 | } |