forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs897 lines, 33.3 KiBHistoryRawDownload
1//! Stateful HEVC decoder: parameter sets, picture order count, reference
2//! picture sets, the decoded picture buffer and output order (ITU-T H.265
3//! clauses 8.1 to 8.3 and C.5.2).
4//!
5//! Scope is the base layer of Main, Main 10 and range extension streams. Every slice
6//! goes through [`cu_syntax::parse_slice_into`], which parses the slice data
7//! and pixel-decodes it. Inter slices write placeholder samples (see
8//! [`inter::placeholder_cu`]) until motion compensation lands. With pixel
9//! decode off ([`Decoder::set_pixel_decode`]) every slice is
10//! parsed and every picture is managed, but no samples are produced; that is
11//! the mode the picture-management tests use. [`Decoder::set_syntax_check`]
12//! adds the slice-data parse ([`cu_syntax::parse_slice`]) to that mode, for
13//! every slice type.
14//!
15//! Decoded: Main, Main 10 and the range extension formats (4:0:0, 4:2:0, 4:2:2, 4:4:4 at
16//! 8 to 12 bits) with transform-skip extensions, implicit and explicit RDPCM, persistent
17//! Rice adaptation, cross-component prediction, chroma QP offset lists and SAO offset
18//! scaling. Refused by name, never decoded wrong: separate colour planes, bit depths above
19//! 12, extended precision, CABAC bypass alignment, and the SCC,
20//! multilayer and 3D SPS/PPS extensions. NAL units with `nuh_layer_id > 0`
21//! are skipped silently, as a base-layer decoder must, so a multi-layer stream
22//! decodes its base layer; so are AUD, filler, reserved types and types 62 and 63
23//! (Dolby Vision RPU and enhancement layer).
24//!
25//! SEI NAL units are read for metadata only (see [`meta`]): the HDR static
26//! metadata, the decoded picture hash, and the SPS colour description go onto
27//! the frames. A malformed SEI is skipped, and the stream decodes on.
28
29pub mod amvp;
30pub mod cu_syntax;
31pub mod deblock;
32pub mod dpb;
33pub mod inter;
34pub mod mc;
35pub mod merge;
36pub mod meta;
37pub mod motion_field;
38pub mod pic;
39pub mod picjob;
40pub mod poc;
41pub mod recon;
42pub mod rext;
43pub mod rowfilter;
44pub mod rps;
45pub mod runner;
46pub mod sao;
47pub mod shared;
48pub mod slice_seg;
49pub mod tiles;
50pub mod trace;
51pub mod weighted;
52
53use std::collections::VecDeque;
54use std::sync::Arc;
55
56use dpb::{Dpb, DpbLimits, Marking};
57pub use dpb::{DpbPicture, Frame, PendingFrame};
58use ec_core::bitio::BitReader;
59use ec_core::error::{Error, Result};
60use ec_h265_syntax::nal::{NalHeader, NalUnitType, split_annex_b, unescape_rbsp};
61use ec_h265_syntax::sei::{SeiMessage, parse_sei_rbsp};
62use ec_h265_syntax::slice::{LongTermRef, ParsePositions, SliceHeader, SliceType};
63use ec_h265_syntax::{Pps, PpsRangeExt, ShortTermRefPicSet, Sps, SpsRangeExt, Vps};
64pub use meta::PictureMeta;
65use picjob::{PicJob, SliceJob};
66use rps::RpsInput;
67pub use rps::{RefEntry, RefPicLists, RefPicSet};
68use runner::{Budget, Checksum, Runner};
69use shared::SharedPic;
70use std::sync::Mutex;
71use std::thread::JoinHandle;
72
73/// What [`Decoder::push_nal`] did with a NAL unit.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum NalOutcome {
76 /// A VPS, SPS or PPS was stored.
77 ParameterSet,
78 /// A slice segment of a picture that is being decoded.
79 Slice,
80 /// A RASL picture of a random-access point that starts decoding (or a slice
81 /// of one): not decoded and not output, as 8.1.3 requires.
82 SkippedPicture,
83 /// A NAL unit a base-layer decoder ignores.
84 Skipped,
85 /// An end of sequence or end of bitstream NAL unit. The open picture is
86 /// finished; pending pictures wait for the next IRAP (C.5.2.2).
87 EndOfSequence,
88}
89
90/// The picture being decoded, from its first slice segment until the next
91/// picture starts or the stream ends.
92struct CurPicture {
93 sps: Arc<Sps>,
94 poc: i32,
95 au_index: u32,
96 output: bool,
97 rps: RefPicSet,
98 lists: RefPicLists,
99 /// Where the picture is decoded (see [`Runner`]).
100 runner: Runner,
101 /// The published picture (the samples and collocated motion that later pictures read).
102 shared: Arc<SharedPic>,
103 /// The motion checksum, set when the picture finishes.
104 checksum: Arc<Checksum>,
105 /// The header of the picture's latest independent slice segment; the
106 /// dependent segments after it take their values from it.
107 header: Option<SliceHeader>,
108 /// False once a slice of the picture is not an I slice.
109 all_intra: bool,
110 meta: PictureMeta,
111}
112
113/// The most worker threads the decoder uses.
114pub const MAX_THREADS: usize = 6;
115
116/// Pictures allowed in flight beyond the thread count, when the thread count fits the
117/// machine's cores. A picture waiting on the rows of a reference holds its thread, so with
118/// exactly `threads` pictures in flight the next picture cannot start until that wait ends.
119/// One spare picture lets it start. Measured on host b (4 cores), 1080p and 4K: 4 threads
120/// about 14% less wall time, 2 threads 20 to 28% less; 6 threads on 4 cores got 4 to 8%
121/// slower with a spare, so the spare is dropped there. Two spares are no faster at 4
122/// threads. The oldest live picture never waits on a younger one, so this cannot deadlock.
123const PICTURE_SLACK: usize = 1;
124
125/// The most pictures in flight for `threads` workers.
126fn 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/// The worker-thread budget: `EC_H265_THREADS` when it is a positive number, else
136/// the machine's available parallelism. Either way capped at [`MAX_THREADS`].
137pub 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/// Streaming HEVC decoder with the same surface as the H.264 one: feed NAL
147/// units (or a whole Annex-B buffer), then drain frames in display order.
148pub struct Decoder {
149 vps: Vec<Option<Vps>>,
150 sps: Vec<Option<Arc<Sps>>>,
151 pps: Vec<Option<Arc<Pps>>>,
152 pixel_decode: bool,
153 /// Worker threads for the in-loop filters (see [`configured_threads`]).
154 threads: usize,
155 /// The worker threads the pictures and their wavefront rows share.
156 budget: Arc<Budget>,
157 /// Parse every slice's data (all types) with [`cu_syntax`] when pixel decode is off.
158 syntax_check: bool,
159 dpb: Dpb,
160 cur: Option<CurPicture>,
161 /// Set while the slices of a skipped RASL picture go by.
162 skipping: bool,
163 seen_picture: bool,
164 after_eos: bool,
165 /// NoRaslOutputFlag of the most recent IRAP picture. RASL pictures follow
166 /// it; none has come yet, so the initial value skips them.
167 irap_no_rasl: bool,
168 /// POC of `prevTid0Pic` (8.3.1).
169 prev_tid0_poc: i32,
170 au_index: u32,
171 out: VecDeque<PendingFrame>,
172 /// HDR SEI that arrived since the last picture started (the access unit
173 /// being collected); folded into `hdr_persist` at the next picture start.
174 hdr_pending: PictureMeta,
175 /// The HDR SEI in force in the current coded video sequence.
176 hdr_persist: PictureMeta,
177 /// The motion checksum of the finished pictures (see [`Decoder::motion_checksum`]).
178 checksums: Mutex<ChecksumFold>,
179 /// Worker threads of the pictures that finished but may still run, oldest first.
180 in_flight: VecDeque<JoinHandle<()>>,
181 /// The most pictures in flight (see [`picture_limit`]).
182 max_in_flight: usize,
183}
184
185/// The motion checksum folded over the finished pictures in decoding order.
186#[derive(Default)]
187struct ChecksumFold {
188 /// The fold of every picture whose checksum has been waited for.
189 fold: u64,
190 /// The checksums of the finished pictures not yet folded, in decoding order.
191 pending: VecDeque<Arc<Checksum>>,
192}
193
194impl Default for Decoder {
195 fn default() -> Self {
196 Decoder::new()
197 }
198}
199
200impl Decoder {
201 /// A decoder with no parameter sets and pixel decode on.
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 /// Worker threads the in-loop filters may use (at least 1).
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 /// Turn pixel decode on or off. Off parses every slice and manages every
236 /// picture (RPS, POC, bumping) without producing samples; inter slices are
237 /// accepted in that mode.
238 pub fn set_pixel_decode(&mut self, on: bool) {
239 self.pixel_decode = on;
240 }
241
242 /// Whether pixel decode is on.
243 pub fn pixel_decode(&self) -> bool {
244 self.pixel_decode
245 }
246
247 /// A hash of the motion field of every picture finished so far, in decoding order.
248 /// Two decodes of the same stream give the same value; a change in any derived
249 /// motion vector, reference index or prediction flag changes it.
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 /// With pixel decode off, also parse every slice's data with the CU syntax
261 /// parser. A parse that does not reach `end_of_slice_segment_flag` at the
262 /// end of the slice is an error from [`Decoder::push_nal`].
263 pub fn set_syntax_check(&mut self, on: bool) {
264 self.syntax_check = on;
265 }
266
267 /// The VPS stored under `id`.
268 pub fn vps(&self, id: u32) -> Option<&Vps> {
269 self.vps.get(id as usize)?.as_ref()
270 }
271
272 /// The SPS stored under `id`.
273 pub fn sps(&self, id: u32) -> Option<&Sps> {
274 self.sps.get(id as usize)?.as_deref()
275 }
276
277 /// The PPS stored under `id`.
278 pub fn pps(&self, id: u32) -> Option<&Pps> {
279 self.pps.get(id as usize)?.as_deref()
280 }
281
282 /// `RefPicList0` and `RefPicList1` of the most recent slice of the picture
283 /// being decoded.
284 pub fn ref_pic_lists(&self) -> Option<&RefPicLists> {
285 self.cur.as_ref().map(|c| &c.lists)
286 }
287
288 /// The reference picture set of the picture being decoded.
289 pub fn ref_pic_set(&self) -> Option<&RefPicSet> {
290 self.cur.as_ref().map(|c| &c.rps)
291 }
292
293 /// A picture in the decoded picture buffer, by id.
294 pub fn picture(&self, id: u32) -> Option<&DpbPicture> {
295 self.dpb.get(id)
296 }
297
298 /// Feed one NAL unit: the two-byte header, then the payload, with no start
299 /// code. Emulation prevention bytes stay in.
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 /// Feed a whole Annex-B byte stream.
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 /// End of the current access unit: finish the open picture now instead of
314 /// at the next picture's first slice, so a no-reorder stream outputs it at once.
315 pub fn end_picture(&mut self) {
316 self.finish_picture();
317 }
318
319 /// End of stream: finish the open picture and output everything pending.
320 pub fn flush(&mut self) -> Result<()> {
321 self.finish_picture();
322 self.dpb.drain(&mut self.out);
323 // Every picture is complete now; a failed one reports its error here.
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 /// The next frame ready for output, in display (POC) order.
337 pub fn next_frame(&mut self) -> Option<Frame> {
338 // A frame whose picture failed is dropped here; `flush` reports the failure.
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 // 4:0:0 has no chroma samples; the unused planes follow the luma depth.
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 // A malformed SEI is skipped: it is metadata, and the pictures are
375 // unaffected. The picture hash is a suffix message (40) only.
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 // End of sequence or bitstream: the open picture is finished, but
383 // nothing is output here. The next IRAP applies C.5.2.2 to what is
384 // still pending (a CRA after EOS discards it, an IDR or BLA
385 // outputs it unless no_output_of_prior_pics_flag is set). `flush`
386 // outputs the rest at the true end of the stream.
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 // The first syntax elements locate the PPS (7.3.6.1).
398 let mut r = BitReader::new(&rbsp);
399 let first = r.read_bit()?;
400 if (16..=21).contains(&code) {
401 r.read_bit()?; // no_output_of_prior_pics_flag
402 }
403 let pps_id = r.read_ue()?;
404
405 if first {
406 self.finish_picture();
407 self.skipping = false;
408 // RASL pictures of an IRAP with NoRaslOutputFlag reference pictures
409 // that are not there: skip them (8.1.3).
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 /// The header a slice segment decodes with (7.4.7.1). An independent segment
453 /// is remembered for the dependent segments that follow it.
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 /// Fold the SEI of one NAL unit into the decoder state. Mastering display, content
471 /// light level and alternative transfer characteristics wait for the next picture
472 /// start. A picture hash goes to the open picture, and only from a suffix SEI.
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 /// Picture-level work at the first slice segment of a picture: POC, RPS,
492 /// the output and removal of buffered pictures (C.5.2.2).
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 // 8.3.1: prevTid0Pic excludes RASL, RADL and sub-layer non-reference pictures.
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 // 8.3.2: an IDR picture has no RPS; every other picture names one.
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 // C.5.2.2: output or discard what the new picture displaces.
543 let limits = DpbLimits::from_sps(sps);
544 if irap && no_rasl && !first_picture {
545 // C.5.2.2: a CRA here follows an end of sequence and its
546 // NoOutputOfPriorPicsFlag is 1 by definition, so pending pictures are
547 // discarded. An IDR or BLA discards them only when its flag says so.
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 // SEI state: a new coded video sequence starts from nothing, then this
559 // access unit's SEI applies from here on.
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 // Frame threads: at most `threads` pictures in flight, so wait for the oldest.
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 /// Build the slice's reference lists, then hand the slice data to the picture's
617 /// job. Nothing runs when pixel decode and the syntax check are both off.
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 /// C.5.2.3: store the open picture in the buffer and run the additional
688 /// bumping. Idempotent when no picture is open. The picture's samples may still be
689 /// being decoded (on its worker); output waits for them.
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/// Store a parameter set under its id, refusing ids the spec does not allow.
743/// The RBSP offsets, from the start of the RBSP, of the substreams after the first of a
744/// slice segment, from its entry points. The entry points count the escaped bytes of the
745/// NAL unit payload, so each one is mapped back past the emulation prevention bytes before
746/// it. Empty when the segment has no entry points, or when they do not fit the data.
747fn 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 // The escaped index of every emulation prevention byte, as unescape_rbsp drops it.
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 // Escaped index to RBSP index: the bytes removed before it are not in the RBSP.
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
785fn 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/// The extension flags this decoder refuses: bits 6 to 4 of the packed
794/// `extension_flags` (multilayer, 3D, SCC). The range extension (bit 7) is parsed, and
795/// its tools are refused one by one by [`unimplemented_sps_range`] and
796/// [`unimplemented_pps_range`]. `sps_extension_4bits` in the low
797/// nibble only says that extension data follows, which is skipped (7.4.3.2.1).
798const EXT_REFUSED: u8 = 0x70;
799
800/// The first refused extension in `flags`, named for the refusal message.
801fn 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/// Refuse an SPS this decoder does not implement, by name: separate colour planes, bit
816/// depths above 12, the multilayer, 3D and SCC extensions, and the range extension tools
817/// that cost more than they are worth (extended precision, CABAC bypass alignment).
818fn 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/// The first range extension tool of an SPS that this decoder does not implement.
860fn 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/// The first range extension tool of a PPS that this decoder does not implement. Every
877/// PPS range extension tool is implemented.
878fn unimplemented_pps_range(_r: &PpsRangeExt) -> Option<&'static str> {
879 None
880}
881
882/// Refuse a PPS that carries an extension this decoder does not implement.
883fn 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}