forge
Explore
Log in

Don't you dare go Hollow

The DPB fields a stateless hardware decode needs

Browse files at this commit

a3e5dd1124a39b838b987d051dd6fd6446ec9283Ahmet Kaan GümüşParent: c665d19
  • feat
    • the DPB fields a stateless hardware decode needs
Show full message
feat(h265-syntax): the DPB fields a stateless hardware decode needs

A software decoder derives its reference picture set as it goes; a
stateless one has to hand the driver finished picture lists, so the
parser now keeps what it used to walk past:

- `ShortTermRefPicSet` carries `DeltaPocS0`/`S1` and the used-by-current
  flags, including the inter-set prediction of 7.4.8, and the SPS keeps
  its sets so a slice that names one by index can resolve it.
- `SliceHeader` carries the resolved set, the long-term entries with
  their `DeltaPocMsbCycleLt` accumulation (7-52), the reference list
  modification entries and a parsed `pred_weight_table()` whose chroma
  offsets are derived per 7-56 rather than left as raw deltas.
- `SliceHeader::write_without_alignment` writes a header without its
  closing `byte_alignment()`, which is what a VA-API encoder submits as
  a packed header, and `write` keeps its old behaviour on top of it.

The fuzz suite caught an overflow in the weight derivation on the way
in: both terms come straight off the wire, so 7-56 is evaluated in 64
bits and clamped.
crates/ec-h265-syntax/src/lib.rsmodified+7 -2
@@ -36,6 +36,11 @@ pub mod slice;
36 pub mod vui;36 pub mod vui;
37 37
38 pub use nal::{AnnexBNal, NalHeader, NalUnitType, escape_rbsp, split_annex_b, unescape_rbsp};38 pub use nal::{AnnexBNal, NalHeader, NalUnitType, escape_rbsp, split_annex_b, unescape_rbsp};
39-pub use ps::{ConformanceWindow, Pps, ProfileTierLevel, ShortTermRefPicSet, Sps, Vps};39+pub use ps::{
40-pub use slice::{ParsePositions, SliceHeader, SliceType, count_emulation_prevention_bytes};40+ ConformanceWindow, MAX_ST_REF_PICS, Pps, ProfileTierLevel, ShortTermRefPicSet, Sps, Vps,
41+};
42+pub use slice::{
43+ LongTermRef, ParsePositions, PredWeightTable, SliceHeader, SliceType, WeightEntry,
44+ count_emulation_prevention_bytes,
45+};
41 pub use vui::{ColourDescription, VideoSignalType, VuiParameters};46 pub use vui::{ColourDescription, VideoSignalType, VuiParameters};
crates/ec-h265-syntax/src/ps.rsmodified+192 -38
@@ -312,10 +312,16 @@ pub struct Sps {
312 pub pcm: Option<(u32, u32, u32, u32, bool)>,312 pub pcm: Option<(u32, u32, u32, u32, bool)>,
313 /// `num_short_term_ref_pic_sets`.313 /// `num_short_term_ref_pic_sets`.
314 pub num_short_term_ref_pic_sets: u32,314 pub num_short_term_ref_pic_sets: u32,
315+ /// The sets themselves, in bitstream order: a slice header may name one by
316+ /// index instead of carrying it, and a decoder then needs it from here.
317+ pub short_term_ref_pic_sets: Vec<ShortTermRefPicSet>,
315 /// `long_term_ref_pics_present_flag`.318 /// `long_term_ref_pics_present_flag`.
316 pub long_term_ref_pics_present: bool,319 pub long_term_ref_pics_present: bool,
317 /// `num_long_term_ref_pics_sps`.320 /// `num_long_term_ref_pics_sps`.
318 pub num_long_term_ref_pics_sps: u32,321 pub num_long_term_ref_pics_sps: u32,
322+ /// `(lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag)` per SPS long
323+ /// term picture, which a slice header names by index.
324+ pub long_term_ref_pics_sps: Vec<(u32, bool)>,
319 /// `sps_temporal_mvp_enabled_flag`.325 /// `sps_temporal_mvp_enabled_flag`.
320 pub temporal_mvp_enabled: bool,326 pub temporal_mvp_enabled: bool,
321 /// `strong_intra_smoothing_enabled_flag`.327 /// `strong_intra_smoothing_enabled_flag`.
@@ -417,9 +423,16 @@ impl Sps {
417 w.write_bit(filter_off);423 w.write_bit(filter_off);
418 }424 }
419 w.write_ue(self.num_short_term_ref_pic_sets);425 w.write_ue(self.num_short_term_ref_pic_sets);
426+ for (i, set) in self.short_term_ref_pic_sets.iter().enumerate() {
427+ set.write(&mut w, i as u32);
428+ }
420 w.write_bit(self.long_term_ref_pics_present);429 w.write_bit(self.long_term_ref_pics_present);
421 if self.long_term_ref_pics_present {430 if self.long_term_ref_pics_present {
422 w.write_ue(self.num_long_term_ref_pics_sps);431 w.write_ue(self.num_long_term_ref_pics_sps);
432+ for &(poc_lsb_lt, used_by_curr) in &self.long_term_ref_pics_sps {
433+ w.write_bits(poc_lsb_lt, self.log2_max_poc_lsb_minus4 + 4);
434+ w.write_bit(used_by_curr);
435+ }
423 }436 }
424 w.write_bit(self.temporal_mvp_enabled);437 w.write_bit(self.temporal_mvp_enabled);
425 w.write_bit(self.strong_intra_smoothing);438 w.write_bit(self.strong_intra_smoothing);
@@ -546,6 +559,7 @@ impl Sps {
546 }559 }
547 let long_term_ref_pics_present = r.read_bit()?;560 let long_term_ref_pics_present = r.read_bit()?;
548 let mut num_long_term_ref_pics_sps = 0;561 let mut num_long_term_ref_pics_sps = 0;
562+ let mut long_term_ref_pics_sps = Vec::new();
549 if long_term_ref_pics_present {563 if long_term_ref_pics_present {
550 num_long_term_ref_pics_sps = r.read_ue()?;564 num_long_term_ref_pics_sps = r.read_ue()?;
551 if num_long_term_ref_pics_sps > 32 {565 if num_long_term_ref_pics_sps > 32 {
@@ -554,8 +568,9 @@ impl Sps {
554 )));568 )));
555 }569 }
556 for _ in 0..num_long_term_ref_pics_sps {570 for _ in 0..num_long_term_ref_pics_sps {
557- r.read_bits(log2_max_poc_lsb_minus4 + 4)?;571+ let poc_lsb_lt = r.read_bits(log2_max_poc_lsb_minus4 + 4)?;
558- r.read_bit()?;572+ let used_by_curr = r.read_bit()?;
573+ long_term_ref_pics_sps.push((poc_lsb_lt, used_by_curr));
559 }574 }
560 }575 }
561 let temporal_mvp_enabled = r.read_bit()?;576 let temporal_mvp_enabled = r.read_bit()?;
@@ -590,8 +605,10 @@ impl Sps {
590 pcm_enabled,605 pcm_enabled,
591 pcm,606 pcm,
592 num_short_term_ref_pic_sets,607 num_short_term_ref_pic_sets,
608+ short_term_ref_pic_sets: sets,
593 long_term_ref_pics_present,609 long_term_ref_pics_present,
594 num_long_term_ref_pics_sps,610 num_long_term_ref_pics_sps,
611+ long_term_ref_pics_sps,
595 temporal_mvp_enabled,612 temporal_mvp_enabled,
596 strong_intra_smoothing,613 strong_intra_smoothing,
597 ptl,614 ptl,
@@ -600,12 +617,18 @@ impl Sps {
600 }617 }
601 }618 }
602 619
603-/// One `st_ref_pic_set()` (7.3.7), kept only as far as re-parsing needs.620+/// Largest `st_ref_pic_set()` this crate carries in either direction; the spec
621+/// caps `NumNegativePics` and `NumPositivePics` at `sps_max_dec_pic_buffering`,
622+/// which itself cannot exceed 16.
623+pub const MAX_ST_REF_PICS: usize = 16;
624+
625+/// One `st_ref_pic_set()` (7.3.7), with the POC deltas a decoder needs.
604 ///626 ///
605-/// The delta values themselves are a decoder's reference-list problem; what a627+/// A *stateless hardware* decoder is the reason the deltas are here: the driver
606-/// *parser* has to get right is the number of pictures in each direction,628+/// is handed `RefPicSetStCurrBefore` / `StCurrAfter` as picture lists, so
607-/// because the next set's syntax depends on it.629+/// something has to turn `delta_poc_sX_minus1` into actual reference pictures,
608-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]630+/// and that something is the caller of this crate.
631+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609 pub struct ShortTermRefPicSet {632 pub struct ShortTermRefPicSet {
610 /// `NumNegativePics`.633 /// `NumNegativePics`.
611 pub num_negative: u32,634 pub num_negative: u32,
@@ -614,6 +637,28 @@ pub struct ShortTermRefPicSet {
614 /// How many of them have `used_by_curr_pic` set — the count that feeds637 /// How many of them have `used_by_curr_pic` set — the count that feeds
615 /// `NumPicTotalCurr`, which sizes the reference list modification syntax.638 /// `NumPicTotalCurr`, which sizes the reference list modification syntax.
616 pub num_used_by_curr: u32,639 pub num_used_by_curr: u32,
640+ /// `DeltaPocS0[i]`, negative, in decreasing order (7-59).
641+ pub delta_poc_s0: [i32; MAX_ST_REF_PICS],
642+ /// `UsedByCurrPicS0[i]`.
643+ pub used_s0: [bool; MAX_ST_REF_PICS],
644+ /// `DeltaPocS1[i]`, positive, in increasing order (7-60).
645+ pub delta_poc_s1: [i32; MAX_ST_REF_PICS],
646+ /// `UsedByCurrPicS1[i]`.
647+ pub used_s1: [bool; MAX_ST_REF_PICS],
648+}
649+
650+impl Default for ShortTermRefPicSet {
651+ fn default() -> ShortTermRefPicSet {
652+ ShortTermRefPicSet {
653+ num_negative: 0,
654+ num_positive: 0,
655+ num_used_by_curr: 0,
656+ delta_poc_s0: [0; MAX_ST_REF_PICS],
657+ used_s0: [false; MAX_ST_REF_PICS],
658+ delta_poc_s1: [0; MAX_ST_REF_PICS],
659+ used_s1: [false; MAX_ST_REF_PICS],
660+ }
661+ }
617 }662 }
618 663
619 impl ShortTermRefPicSet {664 impl ShortTermRefPicSet {
@@ -636,46 +681,153 @@ impl ShortTermRefPicSet {
636 let reference = *prev681 let reference = *prev
637 .get(ref_idx as usize)682 .get(ref_idx as usize)
638 .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: unknown reference set"))?;683 .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: unknown reference set"))?;
639- r.read_bit()?; // delta_rps_sign684+ let delta_rps_sign = r.read_bit()?;
640- r.read_ue()?; // abs_delta_rps_minus1685+ let abs_delta_rps_minus1 = r.read_ue()?;
641- let num_delta_pocs = reference.num_negative + reference.num_positive;686+ let delta_rps = if delta_rps_sign {
642- let mut kept = 0;687+ -((abs_delta_rps_minus1 + 1) as i32)
643- let mut used_by_curr = 0;688+ } else {
644- for _ in 0..=num_delta_pocs {689+ (abs_delta_rps_minus1 + 1) as i32
645- let used = r.read_bit()?;690+ };
646- if used {691+ let num_delta_pocs = (reference.num_negative + reference.num_positive) as usize;
647- kept += 1;692+ if num_delta_pocs >= MAX_ST_REF_PICS * 2 {
648- used_by_curr += 1;693+ return Err(Error::corrupt(
649- } else if r.read_bit()? {694+ "HEVC st_ref_pic_set: reference set too large",
650- kept += 1;695+ ));
696+ }
697+ let mut used_by_curr = [false; MAX_ST_REF_PICS * 2 + 1];
698+ let mut use_delta = [true; MAX_ST_REF_PICS * 2 + 1];
699+ for j in 0..=num_delta_pocs {
700+ used_by_curr[j] = r.read_bit()?;
701+ if !used_by_curr[j] {
702+ use_delta[j] = r.read_bit()?;
651 }703 }
652 }704 }
653- // Without reconstructing the POCs the split between negative and705+ Ok(reference.predict(delta_rps, &used_by_curr, &use_delta))
654- // positive is not knowable; the total is, and that is what the
655- // syntax of any following set depends on.
656- Ok(ShortTermRefPicSet {
657- num_negative: kept,
658- num_positive: 0,
659- num_used_by_curr: used_by_curr,
660- })
661 } else {706 } else {
662 let num_negative = r.read_ue()?;707 let num_negative = r.read_ue()?;
663 let num_positive = r.read_ue()?;708 let num_positive = r.read_ue()?;
664- if num_negative > 16 || num_positive > 16 {709+ if num_negative as usize > MAX_ST_REF_PICS || num_positive as usize > MAX_ST_REF_PICS {
665 return Err(Error::corrupt("HEVC st_ref_pic_set: too many pictures"));710 return Err(Error::corrupt("HEVC st_ref_pic_set: too many pictures"));
666 }711 }
667- let mut num_used_by_curr = 0;712+ let mut set = ShortTermRefPicSet {
668- for _ in 0..num_negative + num_positive {
669- r.read_ue()?; // delta_poc_sX_minus1
670- if r.read_bit()? {
671- num_used_by_curr += 1; // used_by_curr_pic_sX_flag
672- }
673- }
674- Ok(ShortTermRefPicSet {
675 num_negative,713 num_negative,
676 num_positive,714 num_positive,
677- num_used_by_curr,715+ ..ShortTermRefPicSet::default()
678- })716+ };
717+ let mut poc = 0i32;
718+ for i in 0..num_negative as usize {
719+ let delta = r.read_ue()? as i32 + 1;
720+ poc -= delta;
721+ set.delta_poc_s0[i] = poc;
722+ set.used_s0[i] = r.read_bit()?;
723+ if set.used_s0[i] {
724+ set.num_used_by_curr += 1;
725+ }
726+ }
727+ let mut poc = 0i32;
728+ for i in 0..num_positive as usize {
729+ let delta = r.read_ue()? as i32 + 1;
730+ poc += delta;
731+ set.delta_poc_s1[i] = poc;
732+ set.used_s1[i] = r.read_bit()?;
733+ if set.used_s1[i] {
734+ set.num_used_by_curr += 1;
735+ }
736+ }
737+ Ok(set)
738+ }
739+ }
740+
741+ /// Derive a set predicted from this one (7-61, 7-62).
742+ ///
743+ /// The two loops per direction are the spec's, and their order is what puts
744+ /// `DeltaPocS0` in decreasing and `DeltaPocS1` in increasing order without a
745+ /// sort: entries derived from the *other* direction of the reference set
746+ /// come first, then the reference picture itself, then the same direction.
747+ fn predict(
748+ &self,
749+ delta_rps: i32,
750+ used_by_curr: &[bool],
751+ use_delta: &[bool],
752+ ) -> ShortTermRefPicSet {
753+ let mut out = ShortTermRefPicSet::default();
754+ let neg = self.num_negative as usize;
755+ let pos = self.num_positive as usize;
756+ let num_delta_pocs = neg + pos;
757+
758+ let mut i = 0usize;
759+ for j in (0..pos).rev() {
760+ let d = self.delta_poc_s1[j] + delta_rps;
761+ if d < 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS {
762+ out.delta_poc_s0[i] = d;
763+ out.used_s0[i] = used_by_curr[neg + j];
764+ i += 1;
765+ }
766+ }
767+ if delta_rps < 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS {
768+ out.delta_poc_s0[i] = delta_rps;
769+ out.used_s0[i] = used_by_curr[num_delta_pocs];
770+ i += 1;
771+ }
772+ for j in 0..neg {
773+ let d = self.delta_poc_s0[j] + delta_rps;
774+ if d < 0 && use_delta[j] && i < MAX_ST_REF_PICS {
775+ out.delta_poc_s0[i] = d;
776+ out.used_s0[i] = used_by_curr[j];
777+ i += 1;
778+ }
779+ }
780+ out.num_negative = i as u32;
781+
782+ let mut i = 0usize;
783+ for j in (0..neg).rev() {
784+ let d = self.delta_poc_s0[j] + delta_rps;
785+ if d > 0 && use_delta[j] && i < MAX_ST_REF_PICS {
786+ out.delta_poc_s1[i] = d;
787+ out.used_s1[i] = used_by_curr[j];
788+ i += 1;
789+ }
790+ }
791+ if delta_rps > 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS {
792+ out.delta_poc_s1[i] = delta_rps;
793+ out.used_s1[i] = used_by_curr[num_delta_pocs];
794+ i += 1;
795+ }
796+ for j in 0..pos {
797+ let d = self.delta_poc_s1[j] + delta_rps;
798+ if d > 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS {
799+ out.delta_poc_s1[i] = d;
800+ out.used_s1[i] = used_by_curr[neg + j];
801+ i += 1;
802+ }
803+ }
804+ out.num_positive = i as u32;
805+ out.num_used_by_curr = out.used_s0[..out.num_negative as usize]
806+ .iter()
807+ .chain(out.used_s1[..out.num_positive as usize].iter())
808+ .filter(|&&u| u)
809+ .count() as u32;
810+ out
811+ }
812+
813+ /// Write the set in its non-predicted form (7.3.7), which is always legal.
814+ pub fn write(&self, w: &mut ec_core::BitWriter, idx: u32) {
815+ if idx != 0 {
816+ w.write_bit(false); // inter_ref_pic_set_prediction_flag
817+ }
818+ w.write_ue(self.num_negative);
819+ w.write_ue(self.num_positive);
820+ let mut prev = 0i32;
821+ for i in 0..self.num_negative as usize {
822+ w.write_ue((prev - self.delta_poc_s0[i] - 1).max(0) as u32);
823+ prev = self.delta_poc_s0[i];
824+ w.write_bit(self.used_s0[i]);
825+ }
826+ let mut prev = 0i32;
827+ for i in 0..self.num_positive as usize {
828+ w.write_ue((self.delta_poc_s1[i] - prev - 1).max(0) as u32);
829+ prev = self.delta_poc_s1[i];
830+ w.write_bit(self.used_s1[i]);
679 }831 }
680 }832 }
681 }833 }
@@ -988,8 +1140,10 @@ mod tests {
988 pcm_enabled: false,1140 pcm_enabled: false,
989 pcm: None,1141 pcm: None,
990 num_short_term_ref_pic_sets: 0,1142 num_short_term_ref_pic_sets: 0,
1143+ short_term_ref_pic_sets: Vec::new(),
991 long_term_ref_pics_present: false,1144 long_term_ref_pics_present: false,
992 num_long_term_ref_pics_sps: 0,1145 num_long_term_ref_pics_sps: 0,
1146+ long_term_ref_pics_sps: Vec::new(),
993 temporal_mvp_enabled: false,1147 temporal_mvp_enabled: false,
994 strong_intra_smoothing: true,1148 strong_intra_smoothing: true,
995 ptl: ProfileTierLevel::main(120),1149 ptl: ProfileTierLevel::main(120),
crates/ec-h265-syntax/src/slice.rsmodified+213 -46
@@ -37,6 +37,41 @@ impl SliceType {
37 }37 }
38 }38 }
39 39
40+/// One long-term reference picture named by a slice header (7.3.6.1).
41+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42+pub struct LongTermRef {
43+ /// `PocLsbLt`: the low bits of the reference's picture order count.
44+ pub poc_lsb_lt: u32,
45+ /// `UsedByCurrPicLt`: whether the current picture may predict from it.
46+ pub used_by_curr: bool,
47+ /// `delta_poc_msb_present_flag`.
48+ pub delta_poc_msb_present: bool,
49+ /// `DeltaPocMsbCycleLt`, accumulated as equation 7-52 requires.
50+ pub delta_poc_msb_cycle: u32,
51+}
52+
53+/// One entry of a `pred_weight_table()` (7.3.6.3).
54+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55+pub struct WeightEntry {
56+ /// `(delta_luma_weight, luma_offset)`, absent when the flag was 0.
57+ pub luma: Option<(i32, i32)>,
58+ /// `(delta_chroma_weight, ChromaOffset)` per chroma component.
59+ pub chroma: Option<[(i32, i32); 2]>,
60+}
61+
62+/// A parsed `pred_weight_table()` (7.3.6.3).
63+#[derive(Debug, Clone, PartialEq, Eq, Default)]
64+pub struct PredWeightTable {
65+ /// `luma_log2_weight_denom`.
66+ pub luma_log2_weight_denom: u32,
67+ /// `delta_chroma_log2_weight_denom`.
68+ pub delta_chroma_log2_weight_denom: i32,
69+ /// One entry per active list 0 reference.
70+ pub l0: Vec<WeightEntry>,
71+ /// One entry per active list 1 reference.
72+ pub l1: Vec<WeightEntry>,
73+}
74+
40 /// A slice segment header, as far as an intra encoder writes one and a75 /// A slice segment header, as far as an intra encoder writes one and a
41 /// stateless hardware decoder reads one.76 /// stateless hardware decoder reads one.
42 #[derive(Debug, Clone, PartialEq, Eq)]77 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -96,6 +131,22 @@ pub struct SliceHeader {
96 pub loop_filter_across_slices_enabled: bool,131 pub loop_filter_across_slices_enabled: bool,
97 /// Substream entry points: one per WPP CTB row (or tile) after the first.132 /// Substream entry points: one per WPP CTB row (or tile) after the first.
98 pub entry_point_offsets: Vec<u32>,133 pub entry_point_offsets: Vec<u32>,
134+ /// The short-term reference picture set in force, whether it came from the
135+ /// SPS by index or was written out in this header.
136+ ///
137+ /// This and the three fields after it are what a *stateless hardware*
138+ /// decoder needs and a software one derives on the fly: the driver is given
139+ /// `RefPicSetStCurrBefore` / `StCurrAfter` / `LtCurr` as picture lists, so
140+ /// the caller has to turn these deltas into reference pictures itself.
141+ pub short_term_ref_pic_set: ShortTermRefPicSet,
142+ /// True when the set above came from the SPS rather than this header.
143+ pub short_term_ref_pic_set_sps_flag: bool,
144+ /// The long-term reference pictures this slice names, in bitstream order.
145+ pub long_term: Vec<LongTermRef>,
146+ /// `list_entry_l0` / `list_entry_l1`; empty when the list is not modified.
147+ pub list_entry: [Vec<u32>; 2],
148+ /// `pred_weight_table()`, when the PPS turns weighted prediction on.
149+ pub pred_weight_table: Option<PredWeightTable>,
99 }150 }
100 151
101 impl SliceHeader {152 impl SliceHeader {
@@ -129,6 +180,11 @@ impl SliceHeader {
129 tc_offset_div2: 0,180 tc_offset_div2: 0,
130 loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled,181 loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled,
131 entry_point_offsets: Vec::new(),182 entry_point_offsets: Vec::new(),
183+ short_term_ref_pic_set: ShortTermRefPicSet::default(),
184+ short_term_ref_pic_set_sps_flag: true,
185+ long_term: Vec::new(),
186+ list_entry: [Vec::new(), Vec::new()],
187+ pred_weight_table: None,
132 }188 }
133 }189 }
134 190
@@ -138,6 +194,26 @@ impl SliceHeader {
138 /// encoder codes its substreams first and builds the header afterwards —194 /// encoder codes its substreams first and builds the header afterwards —
139 /// the offsets are not knowable any earlier.195 /// the offsets are not knowable any earlier.
140 pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) {196 pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) {
197+ self.write_without_alignment(w, sps, pps, nal_type);
198+ // byte_alignment(): a one bit then zeros.
199+ w.write_bit(true);
200+ w.align_to_byte();
201+ }
202+
203+ /// The header without its closing `byte_alignment()`.
204+ ///
205+ /// A VA-API encoder wants exactly this: the driver is told how many bits of
206+ /// header the application wrote and appends the alignment itself, so
207+ /// including it here leaves the alignment bit sitting where the driver
208+ /// expects slice data (measured on radeonsi: every P picture then decodes
209+ /// as `alignment_bit_equal_to_one = 0`).
210+ pub fn write_without_alignment(
211+ &self,
212+ w: &mut BitWriter,
213+ sps: &Sps,
214+ pps: &Pps,
215+ nal_type: NalUnitType,
216+ ) {
141 w.write_bit(self.first_slice_segment_in_pic);217 w.write_bit(self.first_slice_segment_in_pic);
142 if nal_type.is_irap() {218 if nal_type.is_irap() {
143 w.write_bit(self.no_output_of_prior_pics);219 w.write_bit(self.no_output_of_prior_pics);
@@ -159,11 +235,17 @@ impl SliceHeader {
159 }235 }
160 if !nal_type.is_idr() {236 if !nal_type.is_idr() {
161 w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4);237 w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4);
162- // An intra encoder writes no reference picture sets at all; a238+ w.write_bit(self.short_term_ref_pic_set_sps_flag);
163- // non-IDR picture from this family does not exist yet.239+ if self.short_term_ref_pic_set_sps_flag {
164- w.write_bit(true); // short_term_ref_pic_set_sps_flag240+ if sps.num_short_term_ref_pic_sets > 1 {
165- if sps.num_short_term_ref_pic_sets > 1 {241+ w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets));
166- w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets));242+ }
243+ } else {
244+ // Written out here, which is what a stream whose SPS carries
245+ // no sets must do — and what a hardware encoder's driver
246+ // does for its own single reference.
247+ self.short_term_ref_pic_set
248+ .write(w, sps.num_short_term_ref_pic_sets);
167 }249 }
168 if sps.temporal_mvp_enabled {250 if sps.temporal_mvp_enabled {
169 w.write_bit(self.temporal_mvp_enabled);251 w.write_bit(self.temporal_mvp_enabled);
@@ -210,9 +292,6 @@ impl SliceHeader {
210 }292 }
211 }293 }
212 }294 }
213- // byte_alignment(): a one bit then zeros.
214- w.write_bit(true);
215- w.align_to_byte();
216 }295 }
217 296
218 /// Parse a slice segment header out of an unescaped slice NAL payload.297 /// Parse a slice segment header out of an unescaped slice NAL payload.
@@ -250,20 +329,44 @@ impl SliceHeader {
250 if sps.separate_colour_plane {329 if sps.separate_colour_plane {
251 h.colour_plane_id = r.read_bits(2)? as u8;330 h.colour_plane_id = r.read_bits(2)? as u8;
252 }331 }
253- let mut st_rps = ShortTermRefPicSet::default();
254 let mut num_long_term = 0;332 let mut num_long_term = 0;
255 if !nal_type.is_idr() {333 if !nal_type.is_idr() {
256 h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?;334 h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?;
257 let from_sps = r.read_bit()?;335 let from_sps = r.read_bit()?;
336+ h.short_term_ref_pic_set_sps_flag = from_sps;
258 let before = r.bit_position();337 let before = r.bit_position();
259 if !from_sps {338 if !from_sps {
260- // The sets in the SPS are not kept, so an inter-set339+ // Written out here, possibly predicted from the SPS sets —
261- // predicted slice set cannot be resolved here.340+ // hence `num_short_term_ref_pic_sets` as this set's index
262- st_rps = ShortTermRefPicSet::parse(&mut r, 0, &[])?;341+ // and the SPS sets as the prediction source (7.3.7).
263- } else if sps.num_short_term_ref_pic_sets > 1 {342+ h.short_term_ref_pic_set = ShortTermRefPicSet::parse(
264- r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))?;343+ &mut r,
344+ sps.num_short_term_ref_pic_sets,
345+ &sps.short_term_ref_pic_sets,
346+ )?;
347+ } else {
348+ let idx = if sps.num_short_term_ref_pic_sets > 1 {
349+ r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))?
350+ } else {
351+ 0
352+ };
353+ h.short_term_ref_pic_set = sps
354+ .short_term_ref_pic_sets
355+ .get(idx as usize)
356+ .copied()
357+ .ok_or_else(|| {
358+ Error::corrupt(format!(
359+ "HEVC slice: short_term_ref_pic_set_idx {idx} is not in the SPS"
360+ ))
361+ })?;
265 }362 }
266- pos.st_rps_bits = (r.bit_position() - before) as u32;363+ // Only a set written *in the header* costs the driver bits to
364+ // skip; for an SPS-indexed one libva wants zero.
365+ pos.st_rps_bits = if from_sps {
366+ 0
367+ } else {
368+ (r.bit_position() - before) as u32
369+ };
267 if sps.long_term_ref_pics_present {370 if sps.long_term_ref_pics_present {
268 let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 {371 let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 {
269 r.read_ue()?372 r.read_ue()?
@@ -271,21 +374,42 @@ impl SliceHeader {
271 0374 0
272 };375 };
273 let num_long_term_pics = r.read_ue()?;376 let num_long_term_pics = r.read_ue()?;
377+ let mut prev_delta_msb = 0u32;
274 for i in 0..num_long_term_sps + num_long_term_pics {378 for i in 0..num_long_term_sps + num_long_term_pics {
379+ let mut entry = LongTermRef::default();
275 if i < num_long_term_sps {380 if i < num_long_term_sps {
276- if sps.num_long_term_ref_pics_sps > 1 {381+ let idx = if sps.num_long_term_ref_pics_sps > 1 {
277- r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))?;382+ r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))?
278- }383+ } else {
279- num_long_term += 1;384+ 0
385+ };
386+ let (poc_lsb_lt, used) = sps
387+ .long_term_ref_pics_sps
388+ .get(idx as usize)
389+ .copied()
390+ .unwrap_or((0, false));
391+ entry.poc_lsb_lt = poc_lsb_lt;
392+ entry.used_by_curr = used;
280 } else {393 } else {
281- r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; // poc_lsb_lt394+ entry.poc_lsb_lt = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?;
282- if r.read_bit()? {395+ entry.used_by_curr = r.read_bit()?;
283- num_long_term += 1; // used_by_curr_pic_lt_flag
284- }
285 }396 }
286- if r.read_bit()? {397+ if entry.used_by_curr {
287- r.read_ue()?; // delta_poc_msb_cycle_lt398+ num_long_term += 1;
399+ }
400+ entry.delta_poc_msb_present = r.read_bit()?;
401+ if entry.delta_poc_msb_present {
402+ // 7-52: coded as a delta against the previous entry,
403+ // except for the first of each kind.
404+ let delta = r.read_ue()?;
405+ entry.delta_poc_msb_cycle = if i == 0 || i == num_long_term_sps {
406+ delta
407+ } else {
408+ delta + prev_delta_msb
409+ };
410+ prev_delta_msb = entry.delta_poc_msb_cycle;
288 }411 }
412+ h.long_term.push(entry);
289 }413 }
290 }414 }
291 if sps.temporal_mvp_enabled {415 if sps.temporal_mvp_enabled {
@@ -307,17 +431,19 @@ impl SliceHeader {
307 h.num_ref_idx_l1_active_minus1 = r.read_ue()?;431 h.num_ref_idx_l1_active_minus1 = r.read_ue()?;
308 }432 }
309 }433 }
310- let num_pic_total_curr = st_rps.num_used_by_curr + num_long_term;434+ let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term;
311 if pps.lists_modification_present && num_pic_total_curr > 1 {435 if pps.lists_modification_present && num_pic_total_curr > 1 {
312 let bits = ceil_log2(num_pic_total_curr);436 let bits = ceil_log2(num_pic_total_curr);
313 if r.read_bit()? {437 if r.read_bit()? {
314 for _ in 0..=h.num_ref_idx_l0_active_minus1 {438 for _ in 0..=h.num_ref_idx_l0_active_minus1 {
315- r.read_bits(bits)?;439+ let entry = r.read_bits(bits)?;
440+ h.list_entry[0].push(entry);
316 }441 }
317 }442 }
318 if h.slice_type == SliceType::B && r.read_bit()? {443 if h.slice_type == SliceType::B && r.read_bit()? {
319 for _ in 0..=h.num_ref_idx_l1_active_minus1 {444 for _ in 0..=h.num_ref_idx_l1_active_minus1 {
320- r.read_bits(bits)?;445+ let entry = r.read_bits(bits)?;
446+ h.list_entry[1].push(entry);
321 }447 }
322 }448 }
323 }449 }
@@ -340,7 +466,7 @@ impl SliceHeader {
340 if (pps.weighted_pred && h.slice_type == SliceType::P)466 if (pps.weighted_pred && h.slice_type == SliceType::P)
341 || (pps.weighted_bipred && h.slice_type == SliceType::B)467 || (pps.weighted_bipred && h.slice_type == SliceType::B)
342 {468 {
343- skip_pred_weight_table(&mut r, &h, sps)?;469+ h.pred_weight_table = Some(parse_pred_weight_table(&mut r, &h, sps)?);
344 }470 }
345 h.five_minus_max_num_merge_cand = r.read_ue()?;471 h.five_minus_max_num_merge_cand = r.read_ue()?;
346 }472 }
@@ -464,13 +590,34 @@ pub fn count_emulation_prevention_bytes(escaped_payload: &[u8]) -> usize {
464 count590 count
465 }591 }
466 592
467-/// Walk past a `pred_weight_table()` (7.3.6.3).593+/// Parse a `pred_weight_table()` (7.3.6.3).
468-fn skip_pred_weight_table(r: &mut BitReader, h: &SliceHeader, sps: &Sps) -> Result<()> {594+///
469- r.read_ue()?; // luma_log2_weight_denom595+/// The chroma *offset* is derived, not coded: equation 7-56 turns
596+/// `delta_chroma_offset_lX` into `ChromaOffsetLX` against the weight, and a
597+/// decoder that forwards the raw delta to hardware shifts every weighted
598+/// chroma sample.
599+fn parse_pred_weight_table(
600+ r: &mut BitReader,
601+ h: &SliceHeader,
602+ sps: &Sps,
603+) -> Result<PredWeightTable> {
604+ let mut table = PredWeightTable {
605+ luma_log2_weight_denom: r.read_ue()?,
606+ ..PredWeightTable::default()
607+ };
470 let chroma = sps.chroma_format_idc != 0;608 let chroma = sps.chroma_format_idc != 0;
471 if chroma {609 if chroma {
472- r.read_se()?; // delta_chroma_log2_weight_denom610+ table.delta_chroma_log2_weight_denom = r.read_se()?;
473 }611 }
612+ let chroma_log2 = table.luma_log2_weight_denom as i32 + table.delta_chroma_log2_weight_denom;
613+ if !(0..=7).contains(&chroma_log2) {
614+ return Err(Error::corrupt(
615+ "HEVC pred_weight_table: ChromaLog2WeightDenom out of range",
616+ ));
617+ }
618+ // A fuzzed SPS can name any bit depth; the shift below has to survive it.
619+ let half_range = 1i64 << (sps.bit_depth_chroma_minus8.min(8) + 7);
620+
474 let lists: &[u32] = if h.slice_type == SliceType::B {621 let lists: &[u32] = if h.slice_type == SliceType::B {
475 &[622 &[
476 h.num_ref_idx_l0_active_minus1,623 h.num_ref_idx_l0_active_minus1,
@@ -479,32 +626,50 @@ fn skip_pred_weight_table(r: &mut BitReader, h: &SliceHeader, sps: &Sps) -> Resu
479 } else {626 } else {
480 &[h.num_ref_idx_l0_active_minus1]627 &[h.num_ref_idx_l0_active_minus1]
481 };628 };
482- for &active_minus1 in lists {629+ for (list, &active_minus1) in lists.iter().enumerate() {
483- let count = active_minus1 + 1;630+ let count = (active_minus1 + 1) as usize;
484- let mut luma_flags = Vec::with_capacity(count as usize);631+ let mut luma_flags = Vec::with_capacity(count);
485 for _ in 0..count {632 for _ in 0..count {
486 luma_flags.push(r.read_bit()?);633 luma_flags.push(r.read_bit()?);
487 }634 }
488- let mut chroma_flags = Vec::with_capacity(count as usize);635+ let mut chroma_flags = vec![false; count];
489 if chroma {636 if chroma {
490- for _ in 0..count {637+ for flag in chroma_flags.iter_mut() {
491- chroma_flags.push(r.read_bit()?);638+ *flag = r.read_bit()?;
492 }639 }
493 }640 }
494- for i in 0..count as usize {641+ let mut entries = Vec::with_capacity(count);
642+ for i in 0..count {
643+ let mut entry = WeightEntry::default();
495 if luma_flags[i] {644 if luma_flags[i] {
496- r.read_se()?; // delta_luma_weight645+ let delta_weight = r.read_se()?;
497- r.read_se()?; // luma_offset646+ let offset = r.read_se()?;
647+ entry.luma = Some((delta_weight, offset));
498 }648 }
499 if chroma && chroma_flags[i] {649 if chroma && chroma_flags[i] {
500- for _ in 0..2 {650+ let mut pair = [(0i32, 0i32); 2];
501- r.read_se()?; // delta_chroma_weight651+ for component in &mut pair {
502- r.read_se()?; // delta_chroma_offset652+ let delta_weight = r.read_se()?;
653+ let delta_offset = r.read_se()?;
654+ let weight = (1i64 << chroma_log2) + i64::from(delta_weight);
655+ // 7-56, in 64 bits because both terms come straight off the
656+ // wire and a corrupt stream must not overflow the derivation.
657+ let offset = (half_range + i64::from(delta_offset)
658+ - ((half_range * weight) >> chroma_log2))
659+ .clamp(-half_range, half_range - 1);
660+ *component = (delta_weight, offset as i32);
503 }661 }
662+ entry.chroma = Some(pair);
504 }663 }
664+ entries.push(entry);
665+ }
666+ if list == 0 {
667+ table.l0 = entries;
668+ } else {
669+ table.l1 = entries;
505 }670 }
506 }671 }
507- Ok(())672+ Ok(table)
508 }673 }
509 674
510 #[cfg(test)]675 #[cfg(test)]
@@ -538,8 +703,10 @@ mod tests {
538 pcm_enabled: false,703 pcm_enabled: false,
539 pcm: None,704 pcm: None,
540 num_short_term_ref_pic_sets: 0,705 num_short_term_ref_pic_sets: 0,
706+ short_term_ref_pic_sets: Vec::new(),
541 long_term_ref_pics_present: false,707 long_term_ref_pics_present: false,
542 num_long_term_ref_pics_sps: 0,708 num_long_term_ref_pics_sps: 0,
709+ long_term_ref_pics_sps: Vec::new(),
543 temporal_mvp_enabled: false,710 temporal_mvp_enabled: false,
544 strong_intra_smoothing: true,711 strong_intra_smoothing: true,
545 ptl: ProfileTierLevel::main(120),712 ptl: ProfileTierLevel::main(120),
crates/ec-h265-syntax/tests/fuzz.rsmodified+2 -0
@@ -65,8 +65,10 @@ fn reference_sps() -> Sps {
65 pcm_enabled: false,65 pcm_enabled: false,
66 pcm: None,66 pcm: None,
67 num_short_term_ref_pic_sets: 0,67 num_short_term_ref_pic_sets: 0,
68+ short_term_ref_pic_sets: Vec::new(),
68 long_term_ref_pics_present: false,69 long_term_ref_pics_present: false,
69 num_long_term_ref_pics_sps: 0,70 num_long_term_ref_pics_sps: 0,
71+ long_term_ref_pics_sps: Vec::new(),
70 temporal_mvp_enabled: true,72 temporal_mvp_enabled: true,
71 strong_intra_smoothing: true,73 strong_intra_smoothing: true,
72 ptl: ProfileTierLevel::main(120),74 ptl: ProfileTierLevel::main(120),
crates/ec-h265/src/encoder.rsmodified+2 -0
@@ -199,8 +199,10 @@ impl Encoder {
199 pcm_enabled: false,199 pcm_enabled: false,
200 pcm: None,200 pcm: None,
201 num_short_term_ref_pic_sets: 0,201 num_short_term_ref_pic_sets: 0,
202+ short_term_ref_pic_sets: Vec::new(),
202 long_term_ref_pics_present: false,203 long_term_ref_pics_present: false,
203 num_long_term_ref_pics_sps: 0,204 num_long_term_ref_pics_sps: 0,
205+ long_term_ref_pics_sps: Vec::new(),
204 temporal_mvp_enabled: false,206 temporal_mvp_enabled: false,
205 strong_intra_smoothing: true,207 strong_intra_smoothing: true,
206 ptl,208 ptl,